api.go 39 KB

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