api.go 43 KB

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