api.go 37 KB

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