api.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. "time"
  10. "debtik/internal/auth"
  11. "debtik/internal/bridge"
  12. "debtik/internal/bwtest"
  13. "debtik/internal/certs"
  14. "debtik/internal/dhcp"
  15. "debtik/internal/dns"
  16. "debtik/internal/dynamicrouting"
  17. "debtik/internal/firewall"
  18. "debtik/internal/network"
  19. "debtik/internal/reverseproxy"
  20. "debtik/internal/routing"
  21. "debtik/internal/services"
  22. "debtik/internal/system"
  23. "debtik/internal/tools"
  24. "debtik/internal/vpn"
  25. "debtik/internal/vrrp"
  26. )
  27. type Server struct {
  28. aeroDraftMu sync.Mutex
  29. aeroDrafts map[string]aeroIdentityDraft
  30. netMgr *network.Manager
  31. persistMgr *network.PersistenceManager
  32. metaMgr *network.MetadataManager
  33. vpnMgr *vpn.Manager
  34. fwMgr *firewall.FirewallManager
  35. routingMgr *routing.RoutingManager
  36. dynRoutingMgr *dynamicrouting.Manager
  37. bridgeMgr *bridge.BridgeManager
  38. toolsMgr *tools.Manager
  39. dhcpMgr *dhcp.Manager
  40. dhcpServerMgr *dhcp.ServerManager
  41. vrrpMgr *vrrp.Manager
  42. bwtestMgr *bwtest.Manager
  43. dnsMgr *dns.Manager
  44. authMgr *auth.Manager
  45. servicesMgr *services.Manager
  46. certMgr *certs.CertManager
  47. proxyMgr *reverseproxy.Manager
  48. mux *http.ServeMux
  49. fsHandler http.Handler
  50. }
  51. func NewServer(netMgr *network.Manager, persistMgr *network.PersistenceManager, metaMgr *network.MetadataManager, vpnMgr *vpn.Manager, fwMgr *firewall.FirewallManager, routingMgr *routing.RoutingManager, dynRoutingMgr *dynamicrouting.Manager, bridgeMgr *bridge.BridgeManager, toolsMgr *tools.Manager, dhcpMgr *dhcp.Manager, dhcpServerMgr *dhcp.ServerManager, vrrpMgr *vrrp.Manager, bwtestMgr *bwtest.Manager, dnsMgr *dns.Manager, authMgr *auth.Manager, servicesMgr *services.Manager, certMgr *certs.CertManager, proxyMgr *reverseproxy.Manager, fsHandler http.Handler) *Server {
  52. s := &Server{
  53. netMgr: netMgr,
  54. persistMgr: persistMgr,
  55. metaMgr: metaMgr,
  56. vpnMgr: vpnMgr,
  57. fwMgr: fwMgr,
  58. routingMgr: routingMgr,
  59. dynRoutingMgr: dynRoutingMgr,
  60. bridgeMgr: bridgeMgr,
  61. toolsMgr: toolsMgr,
  62. dhcpMgr: dhcpMgr,
  63. dhcpServerMgr: dhcpServerMgr,
  64. vrrpMgr: vrrpMgr,
  65. bwtestMgr: bwtestMgr,
  66. dnsMgr: dnsMgr,
  67. authMgr: authMgr,
  68. servicesMgr: servicesMgr,
  69. certMgr: certMgr,
  70. proxyMgr: proxyMgr,
  71. mux: http.NewServeMux(),
  72. fsHandler: fsHandler,
  73. }
  74. s.registerRoutes()
  75. return s
  76. }
  77. func (s *Server) registerRoutes() {
  78. s.mux.HandleFunc("GET /api/update/status", s.handleUpdateStatus)
  79. s.mux.HandleFunc("POST /api/update/config", s.handleUpdateConfig)
  80. s.mux.HandleFunc("POST /api/update/check", s.handleUpdateCheck)
  81. s.mux.HandleFunc("POST /api/update/{action}", s.handleUpdateAction)
  82. // API Endpoints
  83. s.mux.HandleFunc("GET /api/system/status", s.handleSystemStatus)
  84. // Routing & Policy Rules (/ip route & /ip route rule)
  85. s.mux.HandleFunc("GET /api/routes", s.handleListRoutes)
  86. s.mux.HandleFunc("POST /api/routes", s.handleSaveRoute)
  87. s.mux.HandleFunc("DELETE /api/routes/{id}", s.handleDeleteRoute)
  88. s.mux.HandleFunc("POST /api/routes/{id}/state", s.handleSetRouteState)
  89. s.mux.HandleFunc("GET /api/routing/rules", s.handleListPolicyRules)
  90. s.mux.HandleFunc("POST /api/routing/rules", s.handleSavePolicyRule)
  91. s.mux.HandleFunc("DELETE /api/routing/rules/{id}", s.handleDeletePolicyRule)
  92. s.mux.HandleFunc("GET /api/routing/tables", s.handleListRoutingTables)
  93. s.mux.HandleFunc("POST /api/routing/tables", s.handleSaveRoutingTable)
  94. // Firewall Endpoints (/ip firewall)
  95. s.mux.HandleFunc("GET /api/firewall/capabilities", s.handleFirewallCapabilities)
  96. s.mux.HandleFunc("POST /api/firewall/{kind}/{id}/reset-counters", s.handleResetRuleCounters)
  97. s.mux.HandleFunc("GET /api/firewall/summary", s.handleFirewallSummary)
  98. s.mux.HandleFunc("POST /api/firewall/reset-counters", s.handleResetFirewallCounters)
  99. // Filter Rules
  100. s.mux.HandleFunc("GET /api/firewall/filter", s.handleListFilterRules)
  101. s.mux.HandleFunc("POST /api/firewall/filter", s.handleSaveFilterRule)
  102. s.mux.HandleFunc("DELETE /api/firewall/filter/{id}", s.handleDeleteFilterRule)
  103. s.mux.HandleFunc("POST /api/firewall/filter/{id}/move", s.handleMoveFilterRule)
  104. s.mux.HandleFunc("POST /api/firewall/filter/{id}/state", s.handleSetFilterRuleState)
  105. // NAT Rules
  106. s.mux.HandleFunc("GET /api/firewall/nat", s.handleListNATRules)
  107. s.mux.HandleFunc("POST /api/firewall/nat", s.handleSaveNATRule)
  108. s.mux.HandleFunc("DELETE /api/firewall/nat/{id}", s.handleDeleteNATRule)
  109. s.mux.HandleFunc("POST /api/firewall/nat/{id}/move", s.handleMoveNATRule)
  110. s.mux.HandleFunc("POST /api/firewall/nat/{id}/state", s.handleSetNATRuleState)
  111. // Mangle Rules
  112. s.mux.HandleFunc("GET /api/firewall/mangle", s.handleListMangleRules)
  113. s.mux.HandleFunc("POST /api/firewall/mangle", s.handleSaveMangleRule)
  114. s.mux.HandleFunc("DELETE /api/firewall/mangle/{id}", s.handleDeleteMangleRule)
  115. s.mux.HandleFunc("POST /api/firewall/mangle/{id}/move", s.handleMoveMangleRule)
  116. s.mux.HandleFunc("POST /api/firewall/mangle/{id}/state", s.handleSetMangleRuleState)
  117. // Address Lists
  118. s.mux.HandleFunc("GET /api/firewall/address-lists", s.handleListAddressLists)
  119. s.mux.HandleFunc("POST /api/firewall/address-lists", s.handleSaveAddressListEntry)
  120. s.mux.HandleFunc("DELETE /api/firewall/address-lists/{id}", s.handleDeleteAddressListEntry)
  121. s.mux.HandleFunc("POST /api/firewall/address-lists/{id}/state", s.handleSetAddressListEntryState)
  122. // Geo-Location
  123. s.mux.HandleFunc("GET /api/firewall/geoip/status", s.handleGeoIPStatus)
  124. s.mux.HandleFunc("POST /api/firewall/geoip/config", s.handleGeoIPConfig)
  125. s.mux.HandleFunc("GET /api/firewall/geoip/countries", s.handleListGeoCountries)
  126. s.mux.HandleFunc("POST /api/firewall/geoip/countries/{code}/toggle", s.handleToggleGeoCountry)
  127. s.mux.HandleFunc("POST /api/firewall/geoip/countries/{code}/update", s.handleUpdateGeoCountry)
  128. s.mux.HandleFunc("POST /api/firewall/geoip/update-now", s.handleGeoIPUpdateNow)
  129. s.mux.HandleFunc("POST /api/firewall/geoip/batch-toggle", s.handleGeoIPBatchToggle)
  130. s.mux.HandleFunc("GET /api/firewall/geoip/countries/{code}/subnets", s.handleGeoCountrySubnets)
  131. // Active Connections
  132. s.mux.HandleFunc("GET /api/firewall/connections", s.handleListConnections)
  133. s.mux.HandleFunc("POST /api/firewall/connections/kill", s.handleKillConnection)
  134. s.mux.HandleFunc("GET /api/interfaces", s.handleListInterfaces)
  135. s.mux.HandleFunc("GET /api/interfaces/traffic/stream", s.handleInterfacesTrafficStream)
  136. s.mux.HandleFunc("GET /api/interfaces/traffic/rates", s.handleInterfacesTrafficRates)
  137. s.mux.HandleFunc("GET /api/interfaces/rates", s.handleInterfacesTrafficRates)
  138. s.mux.HandleFunc("GET /api/roles", s.handleListRoleTags)
  139. s.mux.HandleFunc("POST /api/roles", s.handleSaveRoleTag)
  140. s.mux.HandleFunc("PUT /api/roles/{id}", s.handleSaveRoleTag)
  141. s.mux.HandleFunc("DELETE /api/roles/{id}", s.handleDeleteRoleTag)
  142. s.mux.HandleFunc("GET /api/interfaces/roles", s.handleListRoleTags)
  143. s.mux.HandleFunc("GET /api/interfaces/{name}", s.handleGetInterface)
  144. s.mux.HandleFunc("POST /api/interfaces/{name}/state", s.handleSetInterfaceState)
  145. s.mux.HandleFunc("POST /api/interfaces/{name}/mtu", s.handleSetInterfaceMTU)
  146. s.mux.HandleFunc("POST /api/interfaces/{name}/ip", s.handleAddInterfaceIP)
  147. s.mux.HandleFunc("DELETE /api/interfaces/{name}/ip", s.handleDeleteInterfaceIP)
  148. s.mux.HandleFunc("POST /api/interfaces/{name}/metadata", s.handleSetInterfaceMetadata)
  149. s.mux.HandleFunc("POST /api/interfaces/{name}/rename", s.handleRenameInterface)
  150. s.mux.HandleFunc("GET /api/vlans", s.handleListVLANs)
  151. s.mux.HandleFunc("POST /api/vlans", s.handleCreateVLAN)
  152. s.mux.HandleFunc("DELETE /api/vlans/{name}", s.handleDeleteVLAN)
  153. // Bridge Management (/interface bridge)
  154. s.mux.HandleFunc("GET /api/bridge/summary", s.handleBridgeSummary)
  155. s.mux.HandleFunc("GET /api/bridge/bridges", s.handleListBridges)
  156. s.mux.HandleFunc("POST /api/bridge/bridges", s.handleSaveBridge)
  157. s.mux.HandleFunc("DELETE /api/bridge/bridges/{id}", s.handleDeleteBridge)
  158. s.mux.HandleFunc("POST /api/bridge/bridges/{id}/state", s.handleSetBridgeState)
  159. s.mux.HandleFunc("POST /api/bridge/bridges/{id}/ip", s.handleAddBridgeIP)
  160. s.mux.HandleFunc("DELETE /api/bridge/bridges/{id}/ip", s.handleDeleteBridgeIP)
  161. s.mux.HandleFunc("GET /api/bridge/ports", s.handleListBridgePorts)
  162. s.mux.HandleFunc("POST /api/bridge/ports", s.handleSaveBridgePort)
  163. s.mux.HandleFunc("DELETE /api/bridge/ports/{id}", s.handleDeleteBridgePort)
  164. s.mux.HandleFunc("POST /api/bridge/ports/{id}/state", s.handleSetBridgePortState)
  165. s.mux.HandleFunc("GET /api/bridge/vlans", s.handleListBridgeVLANs)
  166. s.mux.HandleFunc("POST /api/bridge/vlans", s.handleSaveBridgeVLAN)
  167. s.mux.HandleFunc("DELETE /api/bridge/vlans/{id}", s.handleDeleteBridgeVLAN)
  168. s.mux.HandleFunc("POST /api/bridge/vlans/{id}/state", s.handleSetBridgeVLANState)
  169. s.mux.HandleFunc("GET /api/bridge/hosts", s.handleListBridgeHosts)
  170. s.mux.HandleFunc("POST /api/bridge/hosts/flush", s.handleFlushBridgeHosts)
  171. s.mux.HandleFunc("GET /api/debian/config", s.handleGetDebianConfig)
  172. s.mux.HandleFunc("POST /api/debian/apply", s.handleSaveDebianConfig)
  173. // VPN & WAN Endpoints
  174. s.mux.HandleFunc("GET /api/vpn/status", s.handleOverallVPNStatus)
  175. // PPPoE Multi-Instance
  176. s.mux.HandleFunc("GET /api/vpn/pppoe/clients", s.handleListPPPoE)
  177. s.mux.HandleFunc("POST /api/vpn/pppoe/clients", s.handleSavePPPoE)
  178. s.mux.HandleFunc("DELETE /api/vpn/pppoe/clients/{name}", s.handleDeletePPPoE)
  179. s.mux.HandleFunc("POST /api/vpn/pppoe/clients/{name}/state", s.handleSetPPPoEState)
  180. s.mux.HandleFunc("POST /api/vpn/pppoe/clients/{name}/connect", s.handleConnectPPPoE)
  181. s.mux.HandleFunc("POST /api/vpn/pppoe/clients/{name}/disconnect", s.handleDisconnectPPPoE)
  182. // WireGuard Multi-Interface & Multi-Peer
  183. s.mux.HandleFunc("GET /api/vpn/wireguard/interfaces", s.handleListWireGuardInterfaces)
  184. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces", s.handleSaveWireGuardInterface)
  185. s.mux.HandleFunc("DELETE /api/vpn/wireguard/interfaces/{name}", s.handleDeleteWireGuardInterface)
  186. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces/{name}/state", s.handleSetWireGuardInterfaceState)
  187. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces/{name}/start", s.handleStartWireGuardInterface)
  188. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces/{name}/stop", s.handleStopWireGuardInterface)
  189. s.mux.HandleFunc("GET /api/vpn/wireguard/peers", s.handleListWireGuardPeers)
  190. s.mux.HandleFunc("POST /api/vpn/wireguard/peers", s.handleSaveWireGuardPeer)
  191. s.mux.HandleFunc("POST /api/vpn/wireguard/peers/state", s.handleSetWireGuardPeerState)
  192. s.mux.HandleFunc("POST /api/vpn/wireguard/peers/delete", s.handleDeleteWireGuardPeer)
  193. s.mux.HandleFunc("DELETE /api/vpn/wireguard/peers", s.handleDeleteWireGuardPeer)
  194. s.mux.HandleFunc("DELETE /api/vpn/wireguard/peers/{iface}/{pubkey...}", s.handleDeleteWireGuardPeer)
  195. s.mux.HandleFunc("POST /api/vpn/wireguard/genkeys", s.handleWireGuardGenKeys)
  196. s.mux.HandleFunc("POST /api/vpn/wireguard/calc-pubkey", s.handleWireGuardCalcPubKey)
  197. // PPTP Multi-Instance
  198. s.mux.HandleFunc("GET /api/vpn/pptp/clients", s.handleListPPTP)
  199. s.mux.HandleFunc("POST /api/vpn/pptp/clients", s.handleSavePPTP)
  200. s.mux.HandleFunc("DELETE /api/vpn/pptp/clients/{name}", s.handleDeletePPTP)
  201. s.mux.HandleFunc("POST /api/vpn/pptp/clients/{name}/state", s.handleSetPPTPState)
  202. s.mux.HandleFunc("POST /api/vpn/pptp/clients/{name}/connect", s.handleConnectPPTP)
  203. s.mux.HandleFunc("POST /api/vpn/pptp/clients/{name}/disconnect", s.handleDisconnectPPTP)
  204. // L2TP Multi-Instance
  205. s.mux.HandleFunc("GET /api/vpn/l2tp/clients", s.handleListL2TP)
  206. s.mux.HandleFunc("POST /api/vpn/l2tp/clients", s.handleSaveL2TP)
  207. s.mux.HandleFunc("DELETE /api/vpn/l2tp/clients/{name}", s.handleDeleteL2TP)
  208. s.mux.HandleFunc("POST /api/vpn/l2tp/clients/{name}/state", s.handleSetL2TPState)
  209. s.mux.HandleFunc("POST /api/vpn/l2tp/clients/{name}/connect", s.handleConnectL2TP)
  210. s.mux.HandleFunc("POST /api/vpn/l2tp/clients/{name}/disconnect", s.handleDisconnectL2TP)
  211. // IPSec Multi-Tunnel
  212. s.mux.HandleFunc("GET /api/vpn/ipsec/tunnels", s.handleListIPSec)
  213. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels", s.handleSaveIPSecTunnel)
  214. s.mux.HandleFunc("DELETE /api/vpn/ipsec/tunnels/{name}", s.handleDeleteIPSecTunnel)
  215. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels/{name}/state", s.handleSetIPSecState)
  216. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels/{name}/start", s.handleInitiateIPSecTunnel)
  217. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels/{name}/stop", s.handleTerminateIPSecTunnel)
  218. // EoIP (Ethernet over IP / GRETAP)
  219. s.mux.HandleFunc("GET /api/vpn/eoip", s.handleListEoIP)
  220. s.mux.HandleFunc("POST /api/vpn/eoip", s.handleSaveEoIP)
  221. s.mux.HandleFunc("DELETE /api/vpn/eoip/{id}", s.handleDeleteEoIP)
  222. s.mux.HandleFunc("POST /api/vpn/eoip/{id}/state", s.handleSetEoIPState)
  223. // AeroTUN (High-speed ChaCha20-Poly1305 + LZ4 Encrypted UDP Tunnel)
  224. s.mux.HandleFunc("GET /api/vpn/aerotun/tunnels", s.handleListAeroTUNTunnels)
  225. s.mux.HandleFunc("POST /api/vpn/aerotun/tunnels", s.handleSaveAeroTUNTunnel)
  226. s.mux.HandleFunc("DELETE /api/vpn/aerotun/tunnels/{id}", s.handleDeleteAeroTUNTunnel)
  227. s.mux.HandleFunc("POST /api/vpn/aerotun/tunnels/{id}/state", s.handleSetAeroTUNTunnelState)
  228. s.mux.HandleFunc("POST /api/vpn/aerotun/tunnels/{id}/start", s.handleStartAeroTUNTunnel)
  229. s.mux.HandleFunc("POST /api/vpn/aerotun/tunnels/{id}/stop", s.handleStopAeroTUNTunnel)
  230. s.mux.HandleFunc("GET /api/vpn/aerotun/genkey", s.handleGenerateAeroTUNKey)
  231. s.mux.HandleFunc("POST /api/vpn/aerotun/identity-drafts", s.handleCreateAeroIdentityDraft)
  232. s.mux.HandleFunc("DELETE /api/vpn/aerotun/identity-drafts/{id}", s.handleDeleteAeroIdentityDraft)
  233. s.mux.HandleFunc("GET /api/vpn/aerotun/stats", s.handleGetAeroTUNStats)
  234. s.mux.HandleFunc("GET /api/vpn/aerotun/health", s.handleAeroTUNHealth)
  235. s.mux.HandleFunc("POST /api/vpn/aerotun/tunnels/{id}/health-check", s.handleAeroTUNHealthCheck)
  236. // PPP Profiles (/ppp profile)
  237. s.mux.HandleFunc("GET /api/vpn/ppp/profiles", s.handleListPPPProfiles)
  238. s.mux.HandleFunc("POST /api/vpn/ppp/profiles", s.handleSavePPPProfile)
  239. s.mux.HandleFunc("DELETE /api/vpn/ppp/profiles/{name}", s.handleDeletePPPProfile)
  240. // PPP Secrets (/ppp secret)
  241. s.mux.HandleFunc("GET /api/vpn/ppp/secrets", s.handleListPPPSecrets)
  242. s.mux.HandleFunc("POST /api/vpn/ppp/secrets", s.handleSavePPPSecret)
  243. s.mux.HandleFunc("DELETE /api/vpn/ppp/secrets/{id}", s.handleDeletePPPSecret)
  244. s.mux.HandleFunc("POST /api/vpn/ppp/secrets/{id}/state", s.handleSetPPPSecretState)
  245. // Active PPP Sessions (/ppp active)
  246. s.mux.HandleFunc("GET /api/vpn/ppp/active", s.handleListPPPSessions)
  247. s.mux.HandleFunc("DELETE /api/vpn/ppp/active/{iface}", s.handleDisconnectPPPSession)
  248. // VPN Server Settings
  249. s.mux.HandleFunc("GET /api/vpn/servers/pppoe", s.handleGetPPPoEServer)
  250. s.mux.HandleFunc("POST /api/vpn/servers/pppoe", s.handleSetPPPoEServer)
  251. s.mux.HandleFunc("GET /api/vpn/servers/pptp", s.handleGetPPTPServer)
  252. s.mux.HandleFunc("POST /api/vpn/servers/pptp", s.handleSetPPTPServer)
  253. s.mux.HandleFunc("GET /api/vpn/servers/l2tp", s.handleGetL2TPServer)
  254. s.mux.HandleFunc("POST /api/vpn/servers/l2tp", s.handleSetL2TPServer)
  255. s.mux.HandleFunc("GET /api/vpn/servers/ipsec", s.handleGetIPSecServer)
  256. s.mux.HandleFunc("POST /api/vpn/servers/ipsec", s.handleSetIPSecServer)
  257. // WireGuard Client Config Generator
  258. s.mux.HandleFunc("POST /api/vpn/wireguard/client-config", s.handleGenerateWGClientConfig)
  259. // Dynamic Routing (BGP & OSPF)
  260. s.mux.HandleFunc("GET /api/routing/dynamic/summary", s.handleDynamicRoutingSummary)
  261. // BGP
  262. s.mux.HandleFunc("GET /api/routing/bgp/instance", s.handleGetBGPInstance)
  263. s.mux.HandleFunc("POST /api/routing/bgp/instance", s.handleUpdateBGPInstance)
  264. s.mux.HandleFunc("GET /api/routing/bgp/peers", s.handleListBGPPeers)
  265. s.mux.HandleFunc("POST /api/routing/bgp/peers", s.handleSaveBGPPeer)
  266. s.mux.HandleFunc("DELETE /api/routing/bgp/peers/{id}", s.handleDeleteBGPPeer)
  267. s.mux.HandleFunc("POST /api/routing/bgp/peers/{id}/state", s.handleSetBGPPeerState)
  268. s.mux.HandleFunc("GET /api/routing/bgp/networks", s.handleListBGPNetworks)
  269. s.mux.HandleFunc("POST /api/routing/bgp/networks", s.handleSaveBGPNetwork)
  270. s.mux.HandleFunc("DELETE /api/routing/bgp/networks/{id}", s.handleDeleteBGPNetwork)
  271. s.mux.HandleFunc("GET /api/routing/bgp/routes", s.handleGetBGPRoutes)
  272. // OSPF (RouterOS v7 Multi-Instance OSPF)
  273. s.mux.HandleFunc("GET /api/routing/ospf/instances", s.handleListOSPFInstances)
  274. s.mux.HandleFunc("POST /api/routing/ospf/instances", s.handleSaveOSPFInstance)
  275. s.mux.HandleFunc("DELETE /api/routing/ospf/instances/{id}", s.handleDeleteOSPFInstance)
  276. s.mux.HandleFunc("POST /api/routing/ospf/instances/{id}/state", s.handleSetOSPFInstanceState)
  277. s.mux.HandleFunc("GET /api/routing/ospf/instance", s.handleGetOSPFInstance)
  278. s.mux.HandleFunc("POST /api/routing/ospf/instance", s.handleUpdateOSPFInstance)
  279. s.mux.HandleFunc("GET /api/routing/ospf/areas", s.handleListOSPFAreas)
  280. s.mux.HandleFunc("POST /api/routing/ospf/areas", s.handleSaveOSPFArea)
  281. s.mux.HandleFunc("DELETE /api/routing/ospf/areas/{id}", s.handleDeleteOSPFArea)
  282. s.mux.HandleFunc("POST /api/routing/ospf/areas/{id}/state", s.handleSetOSPFAreaState)
  283. s.mux.HandleFunc("GET /api/routing/ospf/area-ranges", s.handleListOSPFAreaRanges)
  284. s.mux.HandleFunc("POST /api/routing/ospf/area-ranges", s.handleSaveOSPFAreaRange)
  285. s.mux.HandleFunc("DELETE /api/routing/ospf/area-ranges/{id}", s.handleDeleteOSPFAreaRange)
  286. s.mux.HandleFunc("GET /api/routing/ospf/templates", s.handleListOSPFInterfaces)
  287. s.mux.HandleFunc("POST /api/routing/ospf/templates", s.handleSaveOSPFInterface)
  288. s.mux.HandleFunc("DELETE /api/routing/ospf/templates/{id}", s.handleDeleteOSPFInterface)
  289. s.mux.HandleFunc("POST /api/routing/ospf/templates/{id}/state", s.handleSetOSPFInterfaceState)
  290. s.mux.HandleFunc("GET /api/routing/ospf/interfaces", s.handleListOSPFInterfaces)
  291. s.mux.HandleFunc("POST /api/routing/ospf/interfaces", s.handleSaveOSPFInterface)
  292. s.mux.HandleFunc("DELETE /api/routing/ospf/interfaces/{id}", s.handleDeleteOSPFInterface)
  293. s.mux.HandleFunc("POST /api/routing/ospf/interfaces/{id}/state", s.handleSetOSPFInterfaceState)
  294. s.mux.HandleFunc("GET /api/routing/ospf/interfaces-live", s.handleGetOSPFInterfacesLive)
  295. s.mux.HandleFunc("GET /api/routing/ospf/static-neighbors", s.handleListOSPFStaticNeighbors)
  296. s.mux.HandleFunc("POST /api/routing/ospf/static-neighbors", s.handleSaveOSPFStaticNeighbor)
  297. s.mux.HandleFunc("DELETE /api/routing/ospf/static-neighbors/{id}", s.handleDeleteOSPFStaticNeighbor)
  298. s.mux.HandleFunc("GET /api/routing/ospf/neighbors", s.handleGetOSPFNeighbors)
  299. s.mux.HandleFunc("GET /api/routing/ospf/lsa", s.handleGetOSPFLSA)
  300. s.mux.HandleFunc("GET /api/routing/ospf/routes", s.handleGetOSPFRoutes)
  301. // Routing Filters (/routing filter)
  302. s.mux.HandleFunc("GET /api/routing/filters", s.handleListRoutingFilters)
  303. s.mux.HandleFunc("POST /api/routing/filters", s.handleSaveRoutingFilter)
  304. s.mux.HandleFunc("DELETE /api/routing/filters/{id}", s.handleDeleteRoutingFilter)
  305. s.mux.HandleFunc("POST /api/routing/filters/{id}/state", s.handleSetRoutingFilterState)
  306. s.mux.HandleFunc("GET /api/routing/filters/rules", s.handleListRoutingFilters)
  307. s.mux.HandleFunc("POST /api/routing/filters/rules", s.handleSaveRoutingFilter)
  308. s.mux.HandleFunc("DELETE /api/routing/filters/rules/{id}", s.handleDeleteRoutingFilter)
  309. s.mux.HandleFunc("POST /api/routing/filters/rules/{id}/state", s.handleSetRoutingFilterState)
  310. s.mux.HandleFunc("GET /api/routing/filters/community-lists", s.handleListCommunityLists)
  311. s.mux.HandleFunc("POST /api/routing/filters/community-lists", s.handleSaveCommunityList)
  312. s.mux.HandleFunc("DELETE /api/routing/filters/community-lists/{id}", s.handleDeleteCommunityList)
  313. s.mux.HandleFunc("POST /api/routing/filters/community-lists/{id}/state", s.handleSetCommunityListState)
  314. s.mux.HandleFunc("GET /api/routing/filters/as-lists", s.handleListASLists)
  315. s.mux.HandleFunc("POST /api/routing/filters/as-lists", s.handleSaveASList)
  316. s.mux.HandleFunc("DELETE /api/routing/filters/as-lists/{id}", s.handleDeleteASList)
  317. s.mux.HandleFunc("POST /api/routing/filters/as-lists/{id}/state", s.handleSetASListState)
  318. // Troubleshooting Tools (/tool ping, traceroute, mtr, dns, port-probe)
  319. s.mux.HandleFunc("POST /api/tools/ping", s.handleToolsPing)
  320. s.mux.HandleFunc("POST /api/tools/ping/stream", s.handleToolsPingStream)
  321. s.mux.HandleFunc("GET /api/tools/ping/stream", s.handleToolsPingStream)
  322. s.mux.HandleFunc("POST /api/tools/traceroute", s.handleToolsTraceroute)
  323. s.mux.HandleFunc("POST /api/tools/traceroute/stream", s.handleToolsTracerouteStream)
  324. s.mux.HandleFunc("GET /api/tools/traceroute/stream", s.handleToolsTracerouteStream)
  325. s.mux.HandleFunc("POST /api/tools/dns", s.handleToolsDNS)
  326. s.mux.HandleFunc("POST /api/tools/port-probe", s.handleToolsPortProbe)
  327. s.mux.HandleFunc("POST /api/tools/mtr", s.handleToolsMTR)
  328. // Bandwidth Test Tool (/tool bandwidth-test / BwTest)
  329. s.mux.HandleFunc("GET /api/tools/bwtest/server", s.handleGetBwTestServer)
  330. s.mux.HandleFunc("POST /api/tools/bwtest/server", s.handleUpdateBwTestServer)
  331. s.mux.HandleFunc("POST /api/tools/bwtest/start", s.handleStartBwTest)
  332. s.mux.HandleFunc("POST /api/tools/bwtest/stop", s.handleStopBwTest)
  333. s.mux.HandleFunc("GET /api/tools/bwtest/status", s.handleGetBwTestStatus)
  334. s.mux.HandleFunc("GET /api/tools/bwtest/stream", s.handleStreamBwTest)
  335. s.mux.HandleFunc("GET /api/tools/bwtest/history", s.handleGetBwTestHistory)
  336. // DHCP Client (/ip dhcp-client)
  337. s.mux.HandleFunc("GET /api/dhcp/clients", s.handleListDHCPClients)
  338. s.mux.HandleFunc("GET /api/dhcp/clients/summary", s.handleGetDHCPSummary)
  339. s.mux.HandleFunc("POST /api/dhcp/clients", s.handleCreateDHCPClient)
  340. s.mux.HandleFunc("PUT /api/dhcp/clients/{id}", s.handleUpdateDHCPClient)
  341. s.mux.HandleFunc("DELETE /api/dhcp/clients/{id}", s.handleDeleteDHCPClient)
  342. s.mux.HandleFunc("POST /api/dhcp/clients/{id}/state", s.handleToggleDHCPClientState)
  343. s.mux.HandleFunc("POST /api/dhcp/clients/{id}/renew", s.handleRenewDHCPClient)
  344. s.mux.HandleFunc("POST /api/dhcp/clients/{id}/release", s.handleReleaseDHCPClient)
  345. // DHCP Server (/ip dhcp-server)
  346. s.mux.HandleFunc("GET /api/dhcp-server/summary", s.handleGetDHCPServerSummary)
  347. s.mux.HandleFunc("GET /api/dhcp-server/servers", s.handleListDHCPServers)
  348. s.mux.HandleFunc("POST /api/dhcp-server/servers", s.handleSaveDHCPServer)
  349. s.mux.HandleFunc("DELETE /api/dhcp-server/servers/{id}", s.handleDeleteDHCPServer)
  350. s.mux.HandleFunc("POST /api/dhcp-server/servers/{id}/state", s.handleSetDHCPServerState)
  351. s.mux.HandleFunc("GET /api/dhcp-server/networks", s.handleListDHCPNetworks)
  352. s.mux.HandleFunc("POST /api/dhcp-server/networks", s.handleSaveDHCPNetwork)
  353. s.mux.HandleFunc("DELETE /api/dhcp-server/networks/{id}", s.handleDeleteDHCPNetwork)
  354. s.mux.HandleFunc("GET /api/dhcp-server/leases", s.handleListDHCPLeases)
  355. s.mux.HandleFunc("POST /api/dhcp-server/leases/static", s.handleSaveDHCPStaticLease)
  356. s.mux.HandleFunc("DELETE /api/dhcp-server/leases/{id}", s.handleDeleteDHCPStaticLease)
  357. s.mux.HandleFunc("POST /api/dhcp-server/leases/make-static", s.handleMakeDHCPStaticLease)
  358. s.mux.HandleFunc("GET /api/dhcp-server/options", s.handleListDHCPOptions)
  359. s.mux.HandleFunc("POST /api/dhcp-server/options", s.handleSaveDHCPOption)
  360. s.mux.HandleFunc("DELETE /api/dhcp-server/options/{id}", s.handleDeleteDHCPOption)
  361. s.mux.HandleFunc("POST /api/dhcp-server/setup", s.handleRunDHCPSetup)
  362. // VRRP Redundancy & High Availability
  363. s.mux.HandleFunc("GET /api/vrrp/summary", s.handleGetVRRPSummary)
  364. s.mux.HandleFunc("GET /api/vrrp/instances", s.handleListVRRPInstances)
  365. s.mux.HandleFunc("POST /api/vrrp/instances", s.handleSaveVRRPInstance)
  366. s.mux.HandleFunc("DELETE /api/vrrp/instances/{id}", s.handleDeleteVRRPInstance)
  367. s.mux.HandleFunc("POST /api/vrrp/instances/{id}/state", s.handleToggleVRRPState)
  368. // Router DNS & Settings (/ip dns)
  369. s.mux.HandleFunc("GET /api/dns/settings", s.handleGetDNSSettings)
  370. s.mux.HandleFunc("POST /api/dns/settings", s.handleSaveDNSSettings)
  371. s.mux.HandleFunc("GET /api/dns/static", s.handleListDNSStatic)
  372. s.mux.HandleFunc("POST /api/dns/static", s.handleSaveDNSStatic)
  373. s.mux.HandleFunc("DELETE /api/dns/static/{id}", s.handleDeleteDNSStatic)
  374. s.mux.HandleFunc("POST /api/dns/static/{id}/state", s.handleSetDNSStaticState)
  375. s.mux.HandleFunc("POST /api/dns/flush", s.handleFlushDNSCache)
  376. s.mux.HandleFunc("GET /api/dns/status", s.handleGetDNSStatus)
  377. // System Settings (/system identity & clock)
  378. s.mux.HandleFunc("GET /api/system/settings", s.handleGetSystemSettings)
  379. s.mux.HandleFunc("POST /api/system/settings", s.handleSaveSystemSettings)
  380. // Management Services (/ip service)
  381. s.mux.HandleFunc("GET /api/system/services", s.handleListServices)
  382. s.mux.HandleFunc("POST /api/system/services/{name}", s.handleUpdateService)
  383. s.mux.HandleFunc("PUT /api/system/services/{name}", s.handleUpdateService)
  384. s.mux.HandleFunc("POST /api/system/services/{name}/state", s.handleSetServiceState)
  385. // Certificate Management (/certificate)
  386. s.mux.HandleFunc("GET /api/certificates", s.handleListCertificates)
  387. s.mux.HandleFunc("POST /api/certificates/ca", s.handleCreateCA)
  388. s.mux.HandleFunc("POST /api/certificates/generate", s.handleCreateCertificate)
  389. s.mux.HandleFunc("POST /api/certificates/import", s.handleImportCertificate)
  390. s.mux.HandleFunc("POST /api/certificates/letsencrypt", s.handleIssueLetsEncrypt)
  391. s.mux.HandleFunc("GET /api/certificates/{name}", s.handleGetCertificate)
  392. s.mux.HandleFunc("GET /api/certificates/{name}/export", s.handleExportCertificate)
  393. s.mux.HandleFunc("DELETE /api/certificates/{name}", s.handleDeleteCertificate)
  394. // Reverse Proxy & Application Gateway (/reverse-proxy)
  395. s.mux.HandleFunc("GET /api/proxy/config", s.handleGetProxyConfig)
  396. s.mux.HandleFunc("POST /api/proxy/config", s.handleUpdateProxyConfig)
  397. s.mux.HandleFunc("GET /api/proxy/rules", s.handleListProxyRules)
  398. s.mux.HandleFunc("POST /api/proxy/rules", s.handleSaveProxyRule)
  399. s.mux.HandleFunc("GET /api/proxy/rules/{id}", s.handleGetProxyRule)
  400. s.mux.HandleFunc("PUT /api/proxy/rules/{id}", s.handleSaveProxyRule)
  401. s.mux.HandleFunc("DELETE /api/proxy/rules/{id}", s.handleDeleteProxyRule)
  402. s.mux.HandleFunc("POST /api/proxy/rules/{id}/state", s.handleSetProxyRuleState)
  403. s.mux.HandleFunc("GET /api/proxy/status", s.handleGetProxyStatus)
  404. // ACME HTTP-01 Challenge responder for Let's Encrypt
  405. s.mux.HandleFunc("GET /.well-known/acme-challenge/{token}", s.handleACMEChallenge)
  406. // Logging (/log)
  407. s.mux.HandleFunc("GET /api/system/logs", s.handleListLogs)
  408. // Authentication & User Management
  409. s.mux.HandleFunc("POST /api/auth/login", s.handleLogin)
  410. s.mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
  411. s.mux.HandleFunc("GET /api/auth/me", s.handleGetMe)
  412. s.mux.HandleFunc("POST /api/auth/change-password", s.handleChangePassword)
  413. s.mux.HandleFunc("GET /api/users", s.handleListUsers)
  414. s.mux.HandleFunc("POST /api/users", s.handleCreateUser)
  415. s.mux.HandleFunc("PUT /api/users/{username}", s.handleUpdateUser)
  416. s.mux.HandleFunc("DELETE /api/users/{username}", s.handleDeleteUser)
  417. s.mux.HandleFunc("POST /api/users/{username}/password", s.handleAdminResetPassword)
  418. // Web UI Static Files
  419. if s.fsHandler != nil {
  420. s.mux.Handle("/", s.fsHandler)
  421. }
  422. }
  423. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  424. // Enable CORS for local development/testing
  425. w.Header().Set("Access-Control-Allow-Origin", "*")
  426. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, PUT")
  427. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  428. if r.Method == http.MethodOptions {
  429. w.WriteHeader(http.StatusOK)
  430. return
  431. }
  432. path := r.URL.Path
  433. // 1. ACME challenge responder MUST always be accessible on port 80
  434. if strings.HasPrefix(path, "/.well-known/acme-challenge/") {
  435. s.mux.ServeHTTP(w, r)
  436. return
  437. }
  438. // 2. Reverse Proxy interceptor (prior to management checks, auth and static handlers)
  439. if s.proxyMgr != nil && s.proxyMgr.IsEnabled() {
  440. isMgmtAPI := strings.HasPrefix(path, "/api/")
  441. if !isMgmtAPI {
  442. if s.proxyMgr.HandleHTTP(w, r) {
  443. return
  444. }
  445. }
  446. }
  447. // 3. HTTP and HTTPS independent management service settings for DebTik Web UI / API
  448. if s.servicesMgr != nil {
  449. service := "www"
  450. if r.TLS != nil {
  451. service = "www-ssl"
  452. }
  453. if www, ok := s.servicesMgr.GetService(service); ok && www.Disabled {
  454. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  455. w.WriteHeader(http.StatusServiceUnavailable)
  456. _, _ = fmt.Fprintf(w, "503 Service Unavailable: %s management service is disabled\n", service)
  457. return
  458. }
  459. }
  460. // Authentication protection for API routes
  461. if strings.HasPrefix(path, "/api/") {
  462. // Public endpoint: Login
  463. if path != "/api/auth/login" {
  464. token := extractToken(r)
  465. sess, err := s.authMgr.ValidateSession(token)
  466. if err != nil {
  467. writeJSON(w, http.StatusUnauthorized, map[string]any{
  468. "error": true,
  469. "message": "Authentication required",
  470. "login_required": true,
  471. })
  472. return
  473. }
  474. // Admin privileges required for /api/users management
  475. if strings.HasPrefix(path, "/api/users") && sess.Role != auth.RoleFull {
  476. writeJSON(w, http.StatusForbidden, map[string]any{
  477. "error": true,
  478. "message": "Administrative privileges required",
  479. })
  480. return
  481. }
  482. // Read-only role protection: forbid mutating operations (except logout & self password change)
  483. if sess.Role == auth.RoleRead && r.Method != http.MethodGet && r.Method != http.MethodHead {
  484. if path != "/api/auth/logout" && path != "/api/auth/change-password" {
  485. writeJSON(w, http.StatusForbidden, map[string]any{
  486. "error": true,
  487. "message": "Read-only account cannot perform configuration modifications",
  488. })
  489. return
  490. }
  491. }
  492. // Inject session into request context
  493. ctx := context.WithValue(r.Context(), sessionContextKey, sess)
  494. r = r.WithContext(ctx)
  495. }
  496. }
  497. s.mux.ServeHTTP(w, r)
  498. }
  499. func (s *Server) handleSystemStatus(w http.ResponseWriter, r *http.Request) {
  500. status, err := system.GetStatus()
  501. if err != nil {
  502. writeError(w, http.StatusInternalServerError, err.Error())
  503. return
  504. }
  505. ifaces, err := s.netMgr.ListInterfaces()
  506. if err == nil {
  507. status.TotalIfaces = len(ifaces)
  508. for _, iface := range ifaces {
  509. if iface.State == "UP" {
  510. status.UpIfaces++
  511. } else {
  512. status.DownIfaces++
  513. }
  514. if iface.IsVLAN {
  515. status.VlanIfaces++
  516. }
  517. }
  518. }
  519. writeJSON(w, http.StatusOK, status)
  520. }
  521. func (s *Server) handleRoutes(w http.ResponseWriter, r *http.Request) {
  522. routes, err := system.GetRoutingTable()
  523. if err != nil {
  524. writeError(w, http.StatusInternalServerError, err.Error())
  525. return
  526. }
  527. writeJSON(w, http.StatusOK, routes)
  528. }
  529. func (s *Server) handleListInterfaces(w http.ResponseWriter, r *http.Request) {
  530. ifaces, err := s.netMgr.ListInterfaces()
  531. if err != nil {
  532. writeError(w, http.StatusInternalServerError, err.Error())
  533. return
  534. }
  535. writeJSON(w, http.StatusOK, ifaces)
  536. }
  537. func (s *Server) handleInterfacesTrafficStream(w http.ResponseWriter, r *http.Request) {
  538. flusher, ok := w.(http.Flusher)
  539. if !ok {
  540. http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
  541. return
  542. }
  543. w.Header().Set("Content-Type", "text/event-stream")
  544. w.Header().Set("Cache-Control", "no-cache")
  545. w.Header().Set("Connection", "keep-alive")
  546. w.Header().Set("Access-Control-Allow-Origin", "*")
  547. ch := s.netMgr.SubscribeTraffic()
  548. defer s.netMgr.UnsubscribeTraffic(ch)
  549. // Send immediate initial snapshot
  550. initSnap := s.netMgr.GetLatestTrafficSnapshot()
  551. if initSnap != nil {
  552. data, _ := json.Marshal(initSnap)
  553. fmt.Fprintf(w, "data: %s\n\n", data)
  554. flusher.Flush()
  555. }
  556. notify := r.Context().Done()
  557. for {
  558. select {
  559. case <-notify:
  560. return
  561. case snap, ok := <-ch:
  562. if !ok {
  563. return
  564. }
  565. data, _ := json.Marshal(snap)
  566. fmt.Fprintf(w, "data: %s\n\n", data)
  567. flusher.Flush()
  568. }
  569. }
  570. }
  571. func (s *Server) handleInterfacesTrafficRates(w http.ResponseWriter, r *http.Request) {
  572. snap := s.netMgr.GetLatestTrafficSnapshot()
  573. if snap == nil {
  574. snap = &network.TrafficSnapshot{
  575. Timestamp: time.Now().Unix(),
  576. Interfaces: make(map[string]network.InterfaceLiveRate),
  577. }
  578. }
  579. writeJSON(w, http.StatusOK, snap)
  580. }
  581. func (s *Server) handleGetInterface(w http.ResponseWriter, r *http.Request) {
  582. name := r.PathValue("name")
  583. iface, err := s.netMgr.GetInterface(name)
  584. if err != nil {
  585. writeError(w, http.StatusNotFound, err.Error())
  586. return
  587. }
  588. writeJSON(w, http.StatusOK, iface)
  589. }
  590. func (s *Server) handleSetInterfaceState(w http.ResponseWriter, r *http.Request) {
  591. name := r.PathValue("name")
  592. var req struct {
  593. State string `json:"state"` // "up" or "down"
  594. }
  595. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  596. writeError(w, http.StatusBadRequest, "invalid request body")
  597. return
  598. }
  599. up := strings.ToLower(req.State) == "up"
  600. if err := s.netMgr.SetInterfaceState(name, up); err != nil {
  601. writeError(w, http.StatusInternalServerError, err.Error())
  602. return
  603. }
  604. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "state": req.State})
  605. }
  606. func (s *Server) handleSetInterfaceMTU(w http.ResponseWriter, r *http.Request) {
  607. name := r.PathValue("name")
  608. var req struct {
  609. MTU int `json:"mtu"`
  610. }
  611. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  612. writeError(w, http.StatusBadRequest, "invalid request body")
  613. return
  614. }
  615. if err := s.netMgr.SetInterfaceMTU(name, req.MTU); err != nil {
  616. writeError(w, http.StatusInternalServerError, err.Error())
  617. return
  618. }
  619. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "mtu": req.MTU})
  620. }
  621. func (s *Server) handleAddInterfaceIP(w http.ResponseWriter, r *http.Request) {
  622. name := r.PathValue("name")
  623. var req network.AddIPRequest
  624. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.IP == "" {
  625. writeError(w, http.StatusBadRequest, "missing or invalid 'ip' parameter")
  626. return
  627. }
  628. if err := s.netMgr.AddInterfaceIP(name, req.IP); err != nil {
  629. writeError(w, http.StatusInternalServerError, err.Error())
  630. return
  631. }
  632. // If this interface is a bridge, also sync to BridgeManager persistent config
  633. if s.bridgeMgr != nil {
  634. _ = s.bridgeMgr.AddBridgeIP(name, req.IP)
  635. }
  636. // Persist to Debian network configuration
  637. if s.persistMgr != nil {
  638. if _, err := s.persistMgr.SaveDebianConfig(); err != nil {
  639. writeError(w, 500, "Live change applied but persistence failed: "+err.Error())
  640. return
  641. }
  642. }
  643. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "ip": req.IP})
  644. }
  645. func (s *Server) handleDeleteInterfaceIP(w http.ResponseWriter, r *http.Request) {
  646. name := r.PathValue("name")
  647. var req network.AddIPRequest
  648. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.IP == "" {
  649. writeError(w, http.StatusBadRequest, "missing or invalid 'ip' parameter")
  650. return
  651. }
  652. if err := s.netMgr.DeleteInterfaceIP(name, req.IP); err != nil {
  653. writeError(w, http.StatusInternalServerError, err.Error())
  654. return
  655. }
  656. // If this interface is a bridge, also delete from BridgeManager persistent config
  657. if s.bridgeMgr != nil {
  658. _ = s.bridgeMgr.DeleteBridgeIP(name, req.IP)
  659. }
  660. // Persist to Debian network configuration
  661. if s.persistMgr != nil {
  662. if _, err := s.persistMgr.SaveDebianConfig(); err != nil {
  663. writeError(w, 500, "Live change applied but persistence failed: "+err.Error())
  664. return
  665. }
  666. }
  667. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "ip": req.IP})
  668. }
  669. func (s *Server) handleSetInterfaceMetadata(w http.ResponseWriter, r *http.Request) {
  670. name := r.PathValue("name")
  671. var req struct {
  672. Role string `json:"role"`
  673. Description string `json:"description"`
  674. }
  675. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  676. writeError(w, http.StatusBadRequest, "invalid request body")
  677. return
  678. }
  679. previous := s.metaMgr.Get(name)
  680. if err := s.metaMgr.Set(name, req.Role, req.Description); err != nil {
  681. writeError(w, http.StatusInternalServerError, err.Error())
  682. return
  683. }
  684. if s.fwMgr != nil {
  685. if err := s.fwMgr.Reapply(); err != nil {
  686. _ = s.metaMgr.Set(name, previous.Role, previous.Description)
  687. _ = s.fwMgr.Reapply()
  688. writeError(w, 500, "Interface role update rolled back: "+err.Error())
  689. return
  690. }
  691. }
  692. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "role": req.Role, "description": req.Description})
  693. }
  694. func (s *Server) handleListRoleTags(w http.ResponseWriter, r *http.Request) {
  695. roles := s.metaMgr.GetRolesWithUsage()
  696. writeJSON(w, http.StatusOK, roles)
  697. }
  698. func (s *Server) handleSaveRoleTag(w http.ResponseWriter, r *http.Request) {
  699. var req network.RoleTag
  700. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  701. writeError(w, http.StatusBadRequest, "invalid request body")
  702. return
  703. }
  704. id := r.PathValue("id")
  705. if id != "" {
  706. req.ID = id
  707. }
  708. saved, err := s.metaMgr.SaveRole(req)
  709. if err != nil {
  710. writeError(w, http.StatusBadRequest, err.Error())
  711. return
  712. }
  713. writeJSON(w, http.StatusOK, saved)
  714. }
  715. func (s *Server) handleDeleteRoleTag(w http.ResponseWriter, r *http.Request) {
  716. id := r.PathValue("id")
  717. if id == "" {
  718. writeError(w, http.StatusBadRequest, "missing role ID")
  719. return
  720. }
  721. if err := s.metaMgr.DeleteRole(id); err != nil {
  722. writeError(w, http.StatusBadRequest, err.Error())
  723. return
  724. }
  725. writeJSON(w, http.StatusOK, map[string]string{"status": "deleted", "id": id})
  726. }
  727. func (s *Server) handleRenameInterface(w http.ResponseWriter, r *http.Request) {
  728. name := r.PathValue("name")
  729. var req struct {
  730. Name string `json:"name"`
  731. NewName string `json:"new_name"`
  732. }
  733. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  734. writeError(w, http.StatusBadRequest, "invalid request body")
  735. return
  736. }
  737. targetName := req.NewName
  738. if targetName == "" {
  739. targetName = req.Name
  740. }
  741. targetName = strings.TrimSpace(targetName)
  742. if targetName == "" {
  743. writeError(w, http.StatusBadRequest, "new interface name is required")
  744. return
  745. }
  746. info, err := s.netMgr.RenameInterface(name, targetName)
  747. if err != nil {
  748. writeError(w, http.StatusInternalServerError, err.Error())
  749. return
  750. }
  751. // Propagate rename to all referencing subsystems
  752. if s.bridgeMgr != nil {
  753. s.bridgeMgr.RenameInterface(name, targetName)
  754. }
  755. if s.dhcpMgr != nil {
  756. s.dhcpMgr.RenameInterface(name, targetName)
  757. }
  758. if s.dhcpServerMgr != nil {
  759. s.dhcpServerMgr.RenameInterface(name, targetName)
  760. }
  761. if s.vrrpMgr != nil {
  762. s.vrrpMgr.RenameInterface(name, targetName)
  763. }
  764. if s.routingMgr != nil {
  765. s.routingMgr.RenameInterface(name, targetName)
  766. }
  767. if s.fwMgr != nil {
  768. s.fwMgr.RenameInterface(name, targetName)
  769. }
  770. if s.vpnMgr != nil {
  771. s.vpnMgr.RenameInterface(name, targetName)
  772. }
  773. if s.persistMgr != nil {
  774. if _, err := s.persistMgr.SaveDebianConfig(); err != nil {
  775. writeError(w, 500, "Live change applied but persistence failed: "+err.Error())
  776. return
  777. }
  778. }
  779. writeJSON(w, http.StatusOK, map[string]any{
  780. "success": true,
  781. "old_name": name,
  782. "new_name": targetName,
  783. "interface": info,
  784. })
  785. }
  786. func (s *Server) handleListVLANs(w http.ResponseWriter, r *http.Request) {
  787. vlans, err := s.netMgr.ListVLANs()
  788. if err != nil {
  789. writeError(w, http.StatusInternalServerError, err.Error())
  790. return
  791. }
  792. writeJSON(w, http.StatusOK, vlans)
  793. }
  794. func (s *Server) handleCreateVLAN(w http.ResponseWriter, r *http.Request) {
  795. var req network.CreateVLANRequest
  796. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  797. writeError(w, http.StatusBadRequest, "invalid request body")
  798. return
  799. }
  800. if req.ParentName == "" || req.VlanID <= 0 {
  801. writeError(w, http.StatusBadRequest, "parent_name and valid vlan_id (1-4094) are required")
  802. return
  803. }
  804. iface, err := s.netMgr.CreateVLAN(req)
  805. if err != nil {
  806. writeError(w, http.StatusInternalServerError, err.Error())
  807. return
  808. }
  809. writeJSON(w, http.StatusCreated, iface)
  810. }
  811. func (s *Server) handleDeleteVLAN(w http.ResponseWriter, r *http.Request) {
  812. name := r.PathValue("name")
  813. if err := s.netMgr.DeleteVLAN(name); err != nil {
  814. writeError(w, http.StatusInternalServerError, err.Error())
  815. return
  816. }
  817. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name})
  818. }
  819. func (s *Server) handleGetDebianConfig(w http.ResponseWriter, r *http.Request) {
  820. cfg, err := s.persistMgr.GenerateDebianConfig()
  821. if err != nil {
  822. writeError(w, http.StatusInternalServerError, err.Error())
  823. return
  824. }
  825. writeJSON(w, http.StatusOK, map[string]string{
  826. "path": network.DebianVlansCfgPath,
  827. "content": cfg,
  828. })
  829. }
  830. func (s *Server) handleSaveDebianConfig(w http.ResponseWriter, r *http.Request) {
  831. cfg, err := s.persistMgr.SaveDebianConfig()
  832. if err != nil {
  833. writeError(w, http.StatusInternalServerError, err.Error())
  834. return
  835. }
  836. writeJSON(w, http.StatusOK, map[string]any{
  837. "success": true,
  838. "path": network.DebianVlansCfgPath,
  839. "content": cfg,
  840. "message": "Configuration saved to " + network.DebianVlansCfgPath,
  841. })
  842. }
  843. func writeJSON(w http.ResponseWriter, status int, data any) {
  844. w.Header().Set("Content-Type", "application/json")
  845. w.WriteHeader(status)
  846. _ = json.NewEncoder(w).Encode(data)
  847. }
  848. func writeError(w http.ResponseWriter, status int, message string) {
  849. writeJSON(w, status, map[string]any{
  850. "error": true,
  851. "message": message,
  852. })
  853. }