api.go 38 KB

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