api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strings"
  6. "proxmox-router/internal/firewall"
  7. "proxmox-router/internal/network"
  8. "proxmox-router/internal/routing"
  9. "proxmox-router/internal/system"
  10. "proxmox-router/internal/vpn"
  11. )
  12. type Server struct {
  13. netMgr *network.Manager
  14. persistMgr *network.PersistenceManager
  15. metaMgr *network.MetadataManager
  16. vpnMgr *vpn.Manager
  17. fwMgr *firewall.FirewallManager
  18. routingMgr *routing.RoutingManager
  19. mux *http.ServeMux
  20. fsHandler http.Handler
  21. }
  22. func NewServer(netMgr *network.Manager, persistMgr *network.PersistenceManager, metaMgr *network.MetadataManager, vpnMgr *vpn.Manager, fwMgr *firewall.FirewallManager, routingMgr *routing.RoutingManager, fsHandler http.Handler) *Server {
  23. s := &Server{
  24. netMgr: netMgr,
  25. persistMgr: persistMgr,
  26. metaMgr: metaMgr,
  27. vpnMgr: vpnMgr,
  28. fwMgr: fwMgr,
  29. routingMgr: routingMgr,
  30. mux: http.NewServeMux(),
  31. fsHandler: fsHandler,
  32. }
  33. s.registerRoutes()
  34. return s
  35. }
  36. func (s *Server) registerRoutes() {
  37. // API Endpoints
  38. s.mux.HandleFunc("GET /api/system/status", s.handleSystemStatus)
  39. // Routing & Policy Rules (/ip route & /ip route rule)
  40. s.mux.HandleFunc("GET /api/routes", s.handleListRoutes)
  41. s.mux.HandleFunc("POST /api/routes", s.handleSaveRoute)
  42. s.mux.HandleFunc("DELETE /api/routes/{id}", s.handleDeleteRoute)
  43. s.mux.HandleFunc("POST /api/routes/{id}/state", s.handleSetRouteState)
  44. s.mux.HandleFunc("GET /api/routing/rules", s.handleListPolicyRules)
  45. s.mux.HandleFunc("POST /api/routing/rules", s.handleSavePolicyRule)
  46. s.mux.HandleFunc("DELETE /api/routing/rules/{id}", s.handleDeletePolicyRule)
  47. s.mux.HandleFunc("GET /api/routing/tables", s.handleListRoutingTables)
  48. s.mux.HandleFunc("POST /api/routing/tables", s.handleSaveRoutingTable)
  49. // Firewall Endpoints (/ip firewall)
  50. s.mux.HandleFunc("GET /api/firewall/summary", s.handleFirewallSummary)
  51. s.mux.HandleFunc("POST /api/firewall/reset-counters", s.handleResetFirewallCounters)
  52. // Filter Rules
  53. s.mux.HandleFunc("GET /api/firewall/filter", s.handleListFilterRules)
  54. s.mux.HandleFunc("POST /api/firewall/filter", s.handleSaveFilterRule)
  55. s.mux.HandleFunc("DELETE /api/firewall/filter/{id}", s.handleDeleteFilterRule)
  56. s.mux.HandleFunc("POST /api/firewall/filter/{id}/move", s.handleMoveFilterRule)
  57. s.mux.HandleFunc("POST /api/firewall/filter/{id}/state", s.handleSetFilterRuleState)
  58. // NAT Rules
  59. s.mux.HandleFunc("GET /api/firewall/nat", s.handleListNATRules)
  60. s.mux.HandleFunc("POST /api/firewall/nat", s.handleSaveNATRule)
  61. s.mux.HandleFunc("DELETE /api/firewall/nat/{id}", s.handleDeleteNATRule)
  62. s.mux.HandleFunc("POST /api/firewall/nat/{id}/move", s.handleMoveNATRule)
  63. s.mux.HandleFunc("POST /api/firewall/nat/{id}/state", s.handleSetNATRuleState)
  64. // Mangle Rules
  65. s.mux.HandleFunc("GET /api/firewall/mangle", s.handleListMangleRules)
  66. s.mux.HandleFunc("POST /api/firewall/mangle", s.handleSaveMangleRule)
  67. s.mux.HandleFunc("DELETE /api/firewall/mangle/{id}", s.handleDeleteMangleRule)
  68. s.mux.HandleFunc("POST /api/firewall/mangle/{id}/move", s.handleMoveMangleRule)
  69. s.mux.HandleFunc("POST /api/firewall/mangle/{id}/state", s.handleSetMangleRuleState)
  70. // Address Lists
  71. s.mux.HandleFunc("GET /api/firewall/address-lists", s.handleListAddressLists)
  72. s.mux.HandleFunc("POST /api/firewall/address-lists", s.handleSaveAddressListEntry)
  73. s.mux.HandleFunc("DELETE /api/firewall/address-lists/{id}", s.handleDeleteAddressListEntry)
  74. // Active Connections
  75. s.mux.HandleFunc("GET /api/firewall/connections", s.handleListConnections)
  76. s.mux.HandleFunc("POST /api/firewall/connections/kill", s.handleKillConnection)
  77. s.mux.HandleFunc("GET /api/interfaces", s.handleListInterfaces)
  78. s.mux.HandleFunc("GET /api/interfaces/{name}", s.handleGetInterface)
  79. s.mux.HandleFunc("POST /api/interfaces/{name}/state", s.handleSetInterfaceState)
  80. s.mux.HandleFunc("POST /api/interfaces/{name}/mtu", s.handleSetInterfaceMTU)
  81. s.mux.HandleFunc("POST /api/interfaces/{name}/ip", s.handleAddInterfaceIP)
  82. s.mux.HandleFunc("DELETE /api/interfaces/{name}/ip", s.handleDeleteInterfaceIP)
  83. s.mux.HandleFunc("POST /api/interfaces/{name}/metadata", s.handleSetInterfaceMetadata)
  84. s.mux.HandleFunc("GET /api/vlans", s.handleListVLANs)
  85. s.mux.HandleFunc("POST /api/vlans", s.handleCreateVLAN)
  86. s.mux.HandleFunc("DELETE /api/vlans/{name}", s.handleDeleteVLAN)
  87. s.mux.HandleFunc("GET /api/debian/config", s.handleGetDebianConfig)
  88. s.mux.HandleFunc("POST /api/debian/apply", s.handleSaveDebianConfig)
  89. // VPN & WAN Endpoints
  90. s.mux.HandleFunc("GET /api/vpn/status", s.handleOverallVPNStatus)
  91. // PPPoE Multi-Instance
  92. s.mux.HandleFunc("GET /api/vpn/pppoe/clients", s.handleListPPPoE)
  93. s.mux.HandleFunc("POST /api/vpn/pppoe/clients", s.handleSavePPPoE)
  94. s.mux.HandleFunc("DELETE /api/vpn/pppoe/clients/{name}", s.handleDeletePPPoE)
  95. s.mux.HandleFunc("POST /api/vpn/pppoe/clients/{name}/state", s.handleSetPPPoEState)
  96. s.mux.HandleFunc("POST /api/vpn/pppoe/clients/{name}/connect", s.handleConnectPPPoE)
  97. s.mux.HandleFunc("POST /api/vpn/pppoe/clients/{name}/disconnect", s.handleDisconnectPPPoE)
  98. // WireGuard Multi-Interface & Multi-Peer
  99. s.mux.HandleFunc("GET /api/vpn/wireguard/interfaces", s.handleListWireGuardInterfaces)
  100. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces", s.handleSaveWireGuardInterface)
  101. s.mux.HandleFunc("DELETE /api/vpn/wireguard/interfaces/{name}", s.handleDeleteWireGuardInterface)
  102. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces/{name}/state", s.handleSetWireGuardInterfaceState)
  103. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces/{name}/start", s.handleStartWireGuardInterface)
  104. s.mux.HandleFunc("POST /api/vpn/wireguard/interfaces/{name}/stop", s.handleStopWireGuardInterface)
  105. s.mux.HandleFunc("GET /api/vpn/wireguard/peers", s.handleListWireGuardPeers)
  106. s.mux.HandleFunc("POST /api/vpn/wireguard/peers", s.handleSaveWireGuardPeer)
  107. s.mux.HandleFunc("DELETE /api/vpn/wireguard/peers/{iface}/{pubkey}", s.handleDeleteWireGuardPeer)
  108. s.mux.HandleFunc("POST /api/vpn/wireguard/genkeys", s.handleWireGuardGenKeys)
  109. // PPTP Multi-Instance
  110. s.mux.HandleFunc("GET /api/vpn/pptp/clients", s.handleListPPTP)
  111. s.mux.HandleFunc("POST /api/vpn/pptp/clients", s.handleSavePPTP)
  112. s.mux.HandleFunc("DELETE /api/vpn/pptp/clients/{name}", s.handleDeletePPTP)
  113. s.mux.HandleFunc("POST /api/vpn/pptp/clients/{name}/state", s.handleSetPPTPState)
  114. s.mux.HandleFunc("POST /api/vpn/pptp/clients/{name}/connect", s.handleConnectPPTP)
  115. s.mux.HandleFunc("POST /api/vpn/pptp/clients/{name}/disconnect", s.handleDisconnectPPTP)
  116. // L2TP Multi-Instance
  117. s.mux.HandleFunc("GET /api/vpn/l2tp/clients", s.handleListL2TP)
  118. s.mux.HandleFunc("POST /api/vpn/l2tp/clients", s.handleSaveL2TP)
  119. s.mux.HandleFunc("DELETE /api/vpn/l2tp/clients/{name}", s.handleDeleteL2TP)
  120. s.mux.HandleFunc("POST /api/vpn/l2tp/clients/{name}/state", s.handleSetL2TPState)
  121. s.mux.HandleFunc("POST /api/vpn/l2tp/clients/{name}/connect", s.handleConnectL2TP)
  122. s.mux.HandleFunc("POST /api/vpn/l2tp/clients/{name}/disconnect", s.handleDisconnectL2TP)
  123. // IPSec Multi-Tunnel
  124. s.mux.HandleFunc("GET /api/vpn/ipsec/tunnels", s.handleListIPSec)
  125. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels", s.handleSaveIPSecTunnel)
  126. s.mux.HandleFunc("DELETE /api/vpn/ipsec/tunnels/{name}", s.handleDeleteIPSecTunnel)
  127. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels/{name}/state", s.handleSetIPSecState)
  128. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels/{name}/start", s.handleInitiateIPSecTunnel)
  129. s.mux.HandleFunc("POST /api/vpn/ipsec/tunnels/{name}/stop", s.handleTerminateIPSecTunnel)
  130. // Web UI Static Files
  131. if s.fsHandler != nil {
  132. s.mux.Handle("/", s.fsHandler)
  133. }
  134. }
  135. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  136. // Enable CORS for local development/testing
  137. w.Header().Set("Access-Control-Allow-Origin", "*")
  138. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, PUT")
  139. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  140. if r.Method == http.MethodOptions {
  141. w.WriteHeader(http.StatusOK)
  142. return
  143. }
  144. s.mux.ServeHTTP(w, r)
  145. }
  146. func (s *Server) handleSystemStatus(w http.ResponseWriter, r *http.Request) {
  147. status, err := system.GetStatus()
  148. if err != nil {
  149. writeError(w, http.StatusInternalServerError, err.Error())
  150. return
  151. }
  152. ifaces, err := s.netMgr.ListInterfaces()
  153. if err == nil {
  154. status.TotalIfaces = len(ifaces)
  155. for _, iface := range ifaces {
  156. if iface.State == "UP" {
  157. status.UpIfaces++
  158. } else {
  159. status.DownIfaces++
  160. }
  161. if iface.IsVLAN {
  162. status.VlanIfaces++
  163. }
  164. }
  165. }
  166. writeJSON(w, http.StatusOK, status)
  167. }
  168. func (s *Server) handleRoutes(w http.ResponseWriter, r *http.Request) {
  169. routes, err := system.GetRoutingTable()
  170. if err != nil {
  171. writeError(w, http.StatusInternalServerError, err.Error())
  172. return
  173. }
  174. writeJSON(w, http.StatusOK, routes)
  175. }
  176. func (s *Server) handleListInterfaces(w http.ResponseWriter, r *http.Request) {
  177. ifaces, err := s.netMgr.ListInterfaces()
  178. if err != nil {
  179. writeError(w, http.StatusInternalServerError, err.Error())
  180. return
  181. }
  182. writeJSON(w, http.StatusOK, ifaces)
  183. }
  184. func (s *Server) handleGetInterface(w http.ResponseWriter, r *http.Request) {
  185. name := r.PathValue("name")
  186. iface, err := s.netMgr.GetInterface(name)
  187. if err != nil {
  188. writeError(w, http.StatusNotFound, err.Error())
  189. return
  190. }
  191. writeJSON(w, http.StatusOK, iface)
  192. }
  193. func (s *Server) handleSetInterfaceState(w http.ResponseWriter, r *http.Request) {
  194. name := r.PathValue("name")
  195. var req struct {
  196. State string `json:"state"` // "up" or "down"
  197. }
  198. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  199. writeError(w, http.StatusBadRequest, "invalid request body")
  200. return
  201. }
  202. up := strings.ToLower(req.State) == "up"
  203. if err := s.netMgr.SetInterfaceState(name, up); err != nil {
  204. writeError(w, http.StatusInternalServerError, err.Error())
  205. return
  206. }
  207. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "state": req.State})
  208. }
  209. func (s *Server) handleSetInterfaceMTU(w http.ResponseWriter, r *http.Request) {
  210. name := r.PathValue("name")
  211. var req struct {
  212. MTU int `json:"mtu"`
  213. }
  214. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  215. writeError(w, http.StatusBadRequest, "invalid request body")
  216. return
  217. }
  218. if err := s.netMgr.SetInterfaceMTU(name, req.MTU); err != nil {
  219. writeError(w, http.StatusInternalServerError, err.Error())
  220. return
  221. }
  222. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "mtu": req.MTU})
  223. }
  224. func (s *Server) handleAddInterfaceIP(w http.ResponseWriter, r *http.Request) {
  225. name := r.PathValue("name")
  226. var req network.AddIPRequest
  227. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.IP == "" {
  228. writeError(w, http.StatusBadRequest, "missing or invalid 'ip' parameter")
  229. return
  230. }
  231. if err := s.netMgr.AddInterfaceIP(name, req.IP); err != nil {
  232. writeError(w, http.StatusInternalServerError, err.Error())
  233. return
  234. }
  235. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "ip": req.IP})
  236. }
  237. func (s *Server) handleDeleteInterfaceIP(w http.ResponseWriter, r *http.Request) {
  238. name := r.PathValue("name")
  239. var req network.AddIPRequest
  240. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.IP == "" {
  241. writeError(w, http.StatusBadRequest, "missing or invalid 'ip' parameter")
  242. return
  243. }
  244. if err := s.netMgr.DeleteInterfaceIP(name, req.IP); err != nil {
  245. writeError(w, http.StatusInternalServerError, err.Error())
  246. return
  247. }
  248. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "ip": req.IP})
  249. }
  250. func (s *Server) handleSetInterfaceMetadata(w http.ResponseWriter, r *http.Request) {
  251. name := r.PathValue("name")
  252. var req struct {
  253. Role string `json:"role"`
  254. Description string `json:"description"`
  255. }
  256. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  257. writeError(w, http.StatusBadRequest, "invalid request body")
  258. return
  259. }
  260. if err := s.metaMgr.Set(name, req.Role, req.Description); err != nil {
  261. writeError(w, http.StatusInternalServerError, err.Error())
  262. return
  263. }
  264. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "role": req.Role, "description": req.Description})
  265. }
  266. func (s *Server) handleListVLANs(w http.ResponseWriter, r *http.Request) {
  267. vlans, err := s.netMgr.ListVLANs()
  268. if err != nil {
  269. writeError(w, http.StatusInternalServerError, err.Error())
  270. return
  271. }
  272. writeJSON(w, http.StatusOK, vlans)
  273. }
  274. func (s *Server) handleCreateVLAN(w http.ResponseWriter, r *http.Request) {
  275. var req network.CreateVLANRequest
  276. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  277. writeError(w, http.StatusBadRequest, "invalid request body")
  278. return
  279. }
  280. if req.ParentName == "" || req.VlanID <= 0 {
  281. writeError(w, http.StatusBadRequest, "parent_name and valid vlan_id (1-4094) are required")
  282. return
  283. }
  284. iface, err := s.netMgr.CreateVLAN(req)
  285. if err != nil {
  286. writeError(w, http.StatusInternalServerError, err.Error())
  287. return
  288. }
  289. writeJSON(w, http.StatusCreated, iface)
  290. }
  291. func (s *Server) handleDeleteVLAN(w http.ResponseWriter, r *http.Request) {
  292. name := r.PathValue("name")
  293. if err := s.netMgr.DeleteVLAN(name); err != nil {
  294. writeError(w, http.StatusInternalServerError, err.Error())
  295. return
  296. }
  297. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name})
  298. }
  299. func (s *Server) handleGetDebianConfig(w http.ResponseWriter, r *http.Request) {
  300. cfg, err := s.persistMgr.GenerateDebianConfig()
  301. if err != nil {
  302. writeError(w, http.StatusInternalServerError, err.Error())
  303. return
  304. }
  305. writeJSON(w, http.StatusOK, map[string]string{
  306. "path": network.DebianVlansCfgPath,
  307. "content": cfg,
  308. })
  309. }
  310. func (s *Server) handleSaveDebianConfig(w http.ResponseWriter, r *http.Request) {
  311. cfg, err := s.persistMgr.SaveDebianConfig()
  312. if err != nil {
  313. writeError(w, http.StatusInternalServerError, err.Error())
  314. return
  315. }
  316. writeJSON(w, http.StatusOK, map[string]any{
  317. "success": true,
  318. "path": network.DebianVlansCfgPath,
  319. "content": cfg,
  320. "message": "Configuration saved to " + network.DebianVlansCfgPath,
  321. })
  322. }
  323. func writeJSON(w http.ResponseWriter, status int, data any) {
  324. w.Header().Set("Content-Type", "application/json")
  325. w.WriteHeader(status)
  326. _ = json.NewEncoder(w).Encode(data)
  327. }
  328. func writeError(w http.ResponseWriter, status int, message string) {
  329. writeJSON(w, status, map[string]any{
  330. "error": true,
  331. "message": message,
  332. })
  333. }