api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. // EoIP (Ethernet over IP / GRETAP)
  131. s.mux.HandleFunc("GET /api/vpn/eoip", s.handleListEoIP)
  132. s.mux.HandleFunc("POST /api/vpn/eoip", s.handleSaveEoIP)
  133. s.mux.HandleFunc("DELETE /api/vpn/eoip/{id}", s.handleDeleteEoIP)
  134. s.mux.HandleFunc("POST /api/vpn/eoip/{id}/state", s.handleSetEoIPState)
  135. // PPP Profiles (/ppp profile)
  136. s.mux.HandleFunc("GET /api/vpn/ppp/profiles", s.handleListPPPProfiles)
  137. s.mux.HandleFunc("POST /api/vpn/ppp/profiles", s.handleSavePPPProfile)
  138. s.mux.HandleFunc("DELETE /api/vpn/ppp/profiles/{name}", s.handleDeletePPPProfile)
  139. // PPP Secrets (/ppp secret)
  140. s.mux.HandleFunc("GET /api/vpn/ppp/secrets", s.handleListPPPSecrets)
  141. s.mux.HandleFunc("POST /api/vpn/ppp/secrets", s.handleSavePPPSecret)
  142. s.mux.HandleFunc("DELETE /api/vpn/ppp/secrets/{id}", s.handleDeletePPPSecret)
  143. s.mux.HandleFunc("POST /api/vpn/ppp/secrets/{id}/state", s.handleSetPPPSecretState)
  144. // Active PPP Sessions (/ppp active)
  145. s.mux.HandleFunc("GET /api/vpn/ppp/active", s.handleListPPPSessions)
  146. s.mux.HandleFunc("DELETE /api/vpn/ppp/active/{iface}", s.handleDisconnectPPPSession)
  147. // VPN Server Settings
  148. s.mux.HandleFunc("GET /api/vpn/servers/pppoe", s.handleGetPPPoEServer)
  149. s.mux.HandleFunc("POST /api/vpn/servers/pppoe", s.handleSetPPPoEServer)
  150. s.mux.HandleFunc("GET /api/vpn/servers/pptp", s.handleGetPPTPServer)
  151. s.mux.HandleFunc("POST /api/vpn/servers/pptp", s.handleSetPPTPServer)
  152. s.mux.HandleFunc("GET /api/vpn/servers/l2tp", s.handleGetL2TPServer)
  153. s.mux.HandleFunc("POST /api/vpn/servers/l2tp", s.handleSetL2TPServer)
  154. s.mux.HandleFunc("GET /api/vpn/servers/ipsec", s.handleGetIPSecServer)
  155. s.mux.HandleFunc("POST /api/vpn/servers/ipsec", s.handleSetIPSecServer)
  156. // WireGuard Client Config Generator
  157. s.mux.HandleFunc("POST /api/vpn/wireguard/client-config", s.handleGenerateWGClientConfig)
  158. // Web UI Static Files
  159. if s.fsHandler != nil {
  160. s.mux.Handle("/", s.fsHandler)
  161. }
  162. }
  163. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  164. // Enable CORS for local development/testing
  165. w.Header().Set("Access-Control-Allow-Origin", "*")
  166. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, PUT")
  167. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  168. if r.Method == http.MethodOptions {
  169. w.WriteHeader(http.StatusOK)
  170. return
  171. }
  172. s.mux.ServeHTTP(w, r)
  173. }
  174. func (s *Server) handleSystemStatus(w http.ResponseWriter, r *http.Request) {
  175. status, err := system.GetStatus()
  176. if err != nil {
  177. writeError(w, http.StatusInternalServerError, err.Error())
  178. return
  179. }
  180. ifaces, err := s.netMgr.ListInterfaces()
  181. if err == nil {
  182. status.TotalIfaces = len(ifaces)
  183. for _, iface := range ifaces {
  184. if iface.State == "UP" {
  185. status.UpIfaces++
  186. } else {
  187. status.DownIfaces++
  188. }
  189. if iface.IsVLAN {
  190. status.VlanIfaces++
  191. }
  192. }
  193. }
  194. writeJSON(w, http.StatusOK, status)
  195. }
  196. func (s *Server) handleRoutes(w http.ResponseWriter, r *http.Request) {
  197. routes, err := system.GetRoutingTable()
  198. if err != nil {
  199. writeError(w, http.StatusInternalServerError, err.Error())
  200. return
  201. }
  202. writeJSON(w, http.StatusOK, routes)
  203. }
  204. func (s *Server) handleListInterfaces(w http.ResponseWriter, r *http.Request) {
  205. ifaces, err := s.netMgr.ListInterfaces()
  206. if err != nil {
  207. writeError(w, http.StatusInternalServerError, err.Error())
  208. return
  209. }
  210. writeJSON(w, http.StatusOK, ifaces)
  211. }
  212. func (s *Server) handleGetInterface(w http.ResponseWriter, r *http.Request) {
  213. name := r.PathValue("name")
  214. iface, err := s.netMgr.GetInterface(name)
  215. if err != nil {
  216. writeError(w, http.StatusNotFound, err.Error())
  217. return
  218. }
  219. writeJSON(w, http.StatusOK, iface)
  220. }
  221. func (s *Server) handleSetInterfaceState(w http.ResponseWriter, r *http.Request) {
  222. name := r.PathValue("name")
  223. var req struct {
  224. State string `json:"state"` // "up" or "down"
  225. }
  226. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  227. writeError(w, http.StatusBadRequest, "invalid request body")
  228. return
  229. }
  230. up := strings.ToLower(req.State) == "up"
  231. if err := s.netMgr.SetInterfaceState(name, up); err != nil {
  232. writeError(w, http.StatusInternalServerError, err.Error())
  233. return
  234. }
  235. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "state": req.State})
  236. }
  237. func (s *Server) handleSetInterfaceMTU(w http.ResponseWriter, r *http.Request) {
  238. name := r.PathValue("name")
  239. var req struct {
  240. MTU int `json:"mtu"`
  241. }
  242. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  243. writeError(w, http.StatusBadRequest, "invalid request body")
  244. return
  245. }
  246. if err := s.netMgr.SetInterfaceMTU(name, req.MTU); err != nil {
  247. writeError(w, http.StatusInternalServerError, err.Error())
  248. return
  249. }
  250. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "mtu": req.MTU})
  251. }
  252. func (s *Server) handleAddInterfaceIP(w http.ResponseWriter, r *http.Request) {
  253. name := r.PathValue("name")
  254. var req network.AddIPRequest
  255. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.IP == "" {
  256. writeError(w, http.StatusBadRequest, "missing or invalid 'ip' parameter")
  257. return
  258. }
  259. if err := s.netMgr.AddInterfaceIP(name, req.IP); err != nil {
  260. writeError(w, http.StatusInternalServerError, err.Error())
  261. return
  262. }
  263. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "ip": req.IP})
  264. }
  265. func (s *Server) handleDeleteInterfaceIP(w http.ResponseWriter, r *http.Request) {
  266. name := r.PathValue("name")
  267. var req network.AddIPRequest
  268. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.IP == "" {
  269. writeError(w, http.StatusBadRequest, "missing or invalid 'ip' parameter")
  270. return
  271. }
  272. if err := s.netMgr.DeleteInterfaceIP(name, req.IP); err != nil {
  273. writeError(w, http.StatusInternalServerError, err.Error())
  274. return
  275. }
  276. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "ip": req.IP})
  277. }
  278. func (s *Server) handleSetInterfaceMetadata(w http.ResponseWriter, r *http.Request) {
  279. name := r.PathValue("name")
  280. var req struct {
  281. Role string `json:"role"`
  282. Description string `json:"description"`
  283. }
  284. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  285. writeError(w, http.StatusBadRequest, "invalid request body")
  286. return
  287. }
  288. if err := s.metaMgr.Set(name, req.Role, req.Description); err != nil {
  289. writeError(w, http.StatusInternalServerError, err.Error())
  290. return
  291. }
  292. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name, "role": req.Role, "description": req.Description})
  293. }
  294. func (s *Server) handleListVLANs(w http.ResponseWriter, r *http.Request) {
  295. vlans, err := s.netMgr.ListVLANs()
  296. if err != nil {
  297. writeError(w, http.StatusInternalServerError, err.Error())
  298. return
  299. }
  300. writeJSON(w, http.StatusOK, vlans)
  301. }
  302. func (s *Server) handleCreateVLAN(w http.ResponseWriter, r *http.Request) {
  303. var req network.CreateVLANRequest
  304. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  305. writeError(w, http.StatusBadRequest, "invalid request body")
  306. return
  307. }
  308. if req.ParentName == "" || req.VlanID <= 0 {
  309. writeError(w, http.StatusBadRequest, "parent_name and valid vlan_id (1-4094) are required")
  310. return
  311. }
  312. iface, err := s.netMgr.CreateVLAN(req)
  313. if err != nil {
  314. writeError(w, http.StatusInternalServerError, err.Error())
  315. return
  316. }
  317. writeJSON(w, http.StatusCreated, iface)
  318. }
  319. func (s *Server) handleDeleteVLAN(w http.ResponseWriter, r *http.Request) {
  320. name := r.PathValue("name")
  321. if err := s.netMgr.DeleteVLAN(name); err != nil {
  322. writeError(w, http.StatusInternalServerError, err.Error())
  323. return
  324. }
  325. writeJSON(w, http.StatusOK, map[string]any{"success": true, "name": name})
  326. }
  327. func (s *Server) handleGetDebianConfig(w http.ResponseWriter, r *http.Request) {
  328. cfg, err := s.persistMgr.GenerateDebianConfig()
  329. if err != nil {
  330. writeError(w, http.StatusInternalServerError, err.Error())
  331. return
  332. }
  333. writeJSON(w, http.StatusOK, map[string]string{
  334. "path": network.DebianVlansCfgPath,
  335. "content": cfg,
  336. })
  337. }
  338. func (s *Server) handleSaveDebianConfig(w http.ResponseWriter, r *http.Request) {
  339. cfg, err := s.persistMgr.SaveDebianConfig()
  340. if err != nil {
  341. writeError(w, http.StatusInternalServerError, err.Error())
  342. return
  343. }
  344. writeJSON(w, http.StatusOK, map[string]any{
  345. "success": true,
  346. "path": network.DebianVlansCfgPath,
  347. "content": cfg,
  348. "message": "Configuration saved to " + network.DebianVlansCfgPath,
  349. })
  350. }
  351. func writeJSON(w http.ResponseWriter, status int, data any) {
  352. w.Header().Set("Content-Type", "application/json")
  353. w.WriteHeader(status)
  354. _ = json.NewEncoder(w).Encode(data)
  355. }
  356. func writeError(w http.ResponseWriter, status int, message string) {
  357. writeJSON(w, status, map[string]any{
  358. "error": true,
  359. "message": message,
  360. })
  361. }