api.go 42 KB

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