network.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/gorilla/mux"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/logic"
  12. "github.com/gravitl/netmaker/models"
  13. "github.com/gravitl/netmaker/servercfg"
  14. "github.com/gravitl/netmaker/serverctl"
  15. )
  16. // ALL_NETWORK_ACCESS - represents all networks
  17. const ALL_NETWORK_ACCESS = "THIS_USER_HAS_ALL"
  18. // NO_NETWORKS_PRESENT - represents no networks
  19. const NO_NETWORKS_PRESENT = "THIS_USER_HAS_NONE"
  20. func networkHandlers(r *mux.Router) {
  21. r.HandleFunc("/api/networks", securityCheck(false, http.HandlerFunc(getNetworks))).Methods("GET")
  22. r.HandleFunc("/api/networks", securityCheck(true, http.HandlerFunc(createNetwork))).Methods("POST")
  23. r.HandleFunc("/api/networks/{networkname}", securityCheck(false, http.HandlerFunc(getNetwork))).Methods("GET")
  24. r.HandleFunc("/api/networks/{networkname}", securityCheck(false, http.HandlerFunc(updateNetwork))).Methods("PUT")
  25. r.HandleFunc("/api/networks/{networkname}/nodelimit", securityCheck(true, http.HandlerFunc(updateNetworkNodeLimit))).Methods("PUT")
  26. r.HandleFunc("/api/networks/{networkname}", securityCheck(true, http.HandlerFunc(deleteNetwork))).Methods("DELETE")
  27. r.HandleFunc("/api/networks/{networkname}/keyupdate", securityCheck(false, http.HandlerFunc(keyUpdate))).Methods("POST")
  28. r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(false, http.HandlerFunc(createAccessKey))).Methods("POST")
  29. r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(false, http.HandlerFunc(getAccessKeys))).Methods("GET")
  30. r.HandleFunc("/api/networks/{networkname}/keys/{name}", securityCheck(false, http.HandlerFunc(deleteAccessKey))).Methods("DELETE")
  31. }
  32. //simple get all networks function
  33. func getNetworks(w http.ResponseWriter, r *http.Request) {
  34. headerNetworks := r.Header.Get("networks")
  35. networksSlice := []string{}
  36. marshalErr := json.Unmarshal([]byte(headerNetworks), &networksSlice)
  37. if marshalErr != nil {
  38. returnErrorResponse(w, r, formatError(marshalErr, "internal"))
  39. return
  40. }
  41. allnetworks := []models.Network{}
  42. var err error
  43. if networksSlice[0] == ALL_NETWORK_ACCESS {
  44. allnetworks, err = logic.GetNetworks()
  45. if err != nil && !database.IsEmptyRecord(err) {
  46. returnErrorResponse(w, r, formatError(err, "internal"))
  47. return
  48. }
  49. } else {
  50. for _, network := range networksSlice {
  51. netObject, parentErr := logic.GetParentNetwork(network)
  52. if parentErr == nil {
  53. if netObject.IsComms != "yes" {
  54. allnetworks = append(allnetworks, netObject)
  55. }
  56. }
  57. }
  58. }
  59. if !servercfg.IsDisplayKeys() {
  60. for i, net := range allnetworks {
  61. net.AccessKeys = logic.RemoveKeySensitiveInfo(net.AccessKeys)
  62. allnetworks[i] = net
  63. }
  64. }
  65. logger.Log(2, r.Header.Get("user"), "fetched networks.")
  66. w.WriteHeader(http.StatusOK)
  67. json.NewEncoder(w).Encode(allnetworks)
  68. }
  69. // Simple get network function
  70. func getNetwork(w http.ResponseWriter, r *http.Request) {
  71. // set header.
  72. w.Header().Set("Content-Type", "application/json")
  73. var params = mux.Vars(r)
  74. netname := params["networkname"]
  75. if isCommsEdit(w, r, netname) {
  76. return
  77. }
  78. network, err := logic.GetNetwork(netname)
  79. if err != nil {
  80. returnErrorResponse(w, r, formatError(err, "internal"))
  81. return
  82. }
  83. if !servercfg.IsDisplayKeys() {
  84. network.AccessKeys = logic.RemoveKeySensitiveInfo(network.AccessKeys)
  85. }
  86. logger.Log(2, r.Header.Get("user"), "fetched network", netname)
  87. w.WriteHeader(http.StatusOK)
  88. json.NewEncoder(w).Encode(network)
  89. }
  90. func keyUpdate(w http.ResponseWriter, r *http.Request) {
  91. w.Header().Set("Content-Type", "application/json")
  92. var params = mux.Vars(r)
  93. netname := params["networkname"]
  94. if isCommsEdit(w, r, netname) {
  95. return
  96. }
  97. network, err := logic.KeyUpdate(netname)
  98. if err != nil {
  99. returnErrorResponse(w, r, formatError(err, "internal"))
  100. return
  101. }
  102. logger.Log(2, r.Header.Get("user"), "updated key on network", netname)
  103. w.WriteHeader(http.StatusOK)
  104. json.NewEncoder(w).Encode(network)
  105. nodes, err := logic.GetNetworkNodes(netname)
  106. if err != nil {
  107. logger.Log(2, "failed to retrieve network nodes for network", netname, err.Error())
  108. return
  109. }
  110. for _, node := range nodes {
  111. logger.Log(3, "updating node ", node.Name, " for a key update")
  112. runUpdates(&node, true)
  113. }
  114. }
  115. // Update a network
  116. func updateNetwork(w http.ResponseWriter, r *http.Request) {
  117. w.Header().Set("Content-Type", "application/json")
  118. var params = mux.Vars(r)
  119. var network models.Network
  120. netname := params["networkname"]
  121. if isCommsEdit(w, r, netname) {
  122. return
  123. }
  124. network, err := logic.GetParentNetwork(netname)
  125. if err != nil {
  126. returnErrorResponse(w, r, formatError(err, "internal"))
  127. return
  128. }
  129. var newNetwork models.Network
  130. err = json.NewDecoder(r.Body).Decode(&newNetwork)
  131. if err != nil {
  132. returnErrorResponse(w, r, formatError(err, "badrequest"))
  133. return
  134. }
  135. if !servercfg.GetRce() {
  136. newNetwork.DefaultPostDown = network.DefaultPostDown
  137. newNetwork.DefaultPostUp = network.DefaultPostUp
  138. }
  139. rangeupdate, localrangeupdate, holepunchupdate, err := logic.UpdateNetwork(&network, &newNetwork)
  140. if err != nil {
  141. returnErrorResponse(w, r, formatError(err, "badrequest"))
  142. return
  143. }
  144. // if newNetwork.IsDualStack != currentNetwork.IsDualStack && newNetwork.IsDualStack == "no" {
  145. // // Remove IPv6 address from network nodes
  146. // RemoveNetworkNodeIPv6Addresses(currentNetwork.NetID)
  147. // }
  148. if rangeupdate {
  149. err = logic.UpdateNetworkNodeAddresses(network.NetID)
  150. if err != nil {
  151. returnErrorResponse(w, r, formatError(err, "internal"))
  152. return
  153. }
  154. }
  155. if localrangeupdate {
  156. err = logic.UpdateNetworkLocalAddresses(network.NetID)
  157. if err != nil {
  158. returnErrorResponse(w, r, formatError(err, "internal"))
  159. return
  160. }
  161. }
  162. if holepunchupdate {
  163. err = logic.UpdateNetworkHolePunching(network.NetID, newNetwork.DefaultUDPHolePunch)
  164. if err != nil {
  165. returnErrorResponse(w, r, formatError(err, "internal"))
  166. return
  167. }
  168. }
  169. if rangeupdate || localrangeupdate || holepunchupdate {
  170. nodes, err := logic.GetNetworkNodes(network.NetID)
  171. if err != nil {
  172. returnErrorResponse(w, r, formatError(err, "internal"))
  173. return
  174. }
  175. for _, node := range nodes {
  176. runUpdates(&node, true)
  177. }
  178. }
  179. logger.Log(1, r.Header.Get("user"), "updated network", netname)
  180. w.WriteHeader(http.StatusOK)
  181. json.NewEncoder(w).Encode(newNetwork)
  182. }
  183. func updateNetworkNodeLimit(w http.ResponseWriter, r *http.Request) {
  184. w.Header().Set("Content-Type", "application/json")
  185. var params = mux.Vars(r)
  186. var network models.Network
  187. netname := params["networkname"]
  188. network, err := logic.GetParentNetwork(netname)
  189. if err != nil {
  190. returnErrorResponse(w, r, formatError(err, "internal"))
  191. return
  192. }
  193. var networkChange models.Network
  194. _ = json.NewDecoder(r.Body).Decode(&networkChange)
  195. if networkChange.NodeLimit != 0 {
  196. network.NodeLimit = networkChange.NodeLimit
  197. data, err := json.Marshal(&network)
  198. if err != nil {
  199. returnErrorResponse(w, r, formatError(err, "badrequest"))
  200. return
  201. }
  202. database.Insert(network.NetID, string(data), database.NETWORKS_TABLE_NAME)
  203. logger.Log(1, r.Header.Get("user"), "updated network node limit on", netname)
  204. }
  205. w.WriteHeader(http.StatusOK)
  206. json.NewEncoder(w).Encode(network)
  207. }
  208. // Delete a network
  209. // Will stop you if there's any nodes associated
  210. func deleteNetwork(w http.ResponseWriter, r *http.Request) {
  211. // Set header
  212. w.Header().Set("Content-Type", "application/json")
  213. var params = mux.Vars(r)
  214. network := params["networkname"]
  215. if isCommsEdit(w, r, network) {
  216. return
  217. }
  218. err := logic.DeleteNetwork(network)
  219. if err != nil {
  220. errtype := "badrequest"
  221. if strings.Contains(err.Error(), "Node check failed") {
  222. errtype = "forbidden"
  223. }
  224. returnErrorResponse(w, r, formatError(err, errtype))
  225. return
  226. }
  227. logger.Log(1, r.Header.Get("user"), "deleted network", network)
  228. w.WriteHeader(http.StatusOK)
  229. json.NewEncoder(w).Encode("success")
  230. }
  231. func createNetwork(w http.ResponseWriter, r *http.Request) {
  232. w.Header().Set("Content-Type", "application/json")
  233. var network models.Network
  234. // we decode our body request params
  235. err := json.NewDecoder(r.Body).Decode(&network)
  236. if err != nil {
  237. returnErrorResponse(w, r, formatError(err, "internal"))
  238. return
  239. }
  240. err = logic.CreateNetwork(network)
  241. if err != nil {
  242. returnErrorResponse(w, r, formatError(err, "badrequest"))
  243. return
  244. }
  245. if servercfg.IsClientMode() != "off" {
  246. var node models.Node
  247. node, err = logic.ServerJoin(&network)
  248. if err != nil {
  249. logic.DeleteNetwork(network.NetID)
  250. if err == nil {
  251. err = errors.New("Failed to add server to network " + network.NetID)
  252. }
  253. returnErrorResponse(w, r, formatError(err, "internal"))
  254. return
  255. }
  256. getServerAddrs(&node)
  257. }
  258. logger.Log(1, r.Header.Get("user"), "created network", network.NetID)
  259. w.WriteHeader(http.StatusOK)
  260. }
  261. // BEGIN KEY MANAGEMENT SECTION
  262. func createAccessKey(w http.ResponseWriter, r *http.Request) {
  263. w.Header().Set("Content-Type", "application/json")
  264. var params = mux.Vars(r)
  265. var accesskey models.AccessKey
  266. //start here
  267. netname := params["networkname"]
  268. if isCommsEdit(w, r, netname) {
  269. return
  270. }
  271. network, err := logic.GetParentNetwork(netname)
  272. if err != nil {
  273. returnErrorResponse(w, r, formatError(err, "internal"))
  274. return
  275. }
  276. err = json.NewDecoder(r.Body).Decode(&accesskey)
  277. if err != nil {
  278. returnErrorResponse(w, r, formatError(err, "internal"))
  279. return
  280. }
  281. key, err := logic.CreateAccessKey(accesskey, network)
  282. if err != nil {
  283. returnErrorResponse(w, r, formatError(err, "badrequest"))
  284. return
  285. }
  286. logger.Log(1, r.Header.Get("user"), "created access key", accesskey.Name, "on", netname)
  287. w.WriteHeader(http.StatusOK)
  288. json.NewEncoder(w).Encode(key)
  289. }
  290. // pretty simple get
  291. func getAccessKeys(w http.ResponseWriter, r *http.Request) {
  292. w.Header().Set("Content-Type", "application/json")
  293. var params = mux.Vars(r)
  294. network := params["networkname"]
  295. keys, err := logic.GetKeys(network)
  296. if err != nil {
  297. returnErrorResponse(w, r, formatError(err, "internal"))
  298. return
  299. }
  300. if !servercfg.IsDisplayKeys() {
  301. keys = logic.RemoveKeySensitiveInfo(keys)
  302. }
  303. logger.Log(2, r.Header.Get("user"), "fetched access keys on network", network)
  304. w.WriteHeader(http.StatusOK)
  305. json.NewEncoder(w).Encode(keys)
  306. }
  307. // delete key. Has to do a little funky logic since it's not a collection item
  308. func deleteAccessKey(w http.ResponseWriter, r *http.Request) {
  309. w.Header().Set("Content-Type", "application/json")
  310. var params = mux.Vars(r)
  311. keyname := params["name"]
  312. netname := params["networkname"]
  313. err := logic.DeleteKey(keyname, netname)
  314. if err != nil {
  315. returnErrorResponse(w, r, formatError(err, "badrequest"))
  316. return
  317. }
  318. logger.Log(1, r.Header.Get("user"), "deleted access key", keyname, "on network,", netname)
  319. w.WriteHeader(http.StatusOK)
  320. }
  321. func isCommsEdit(w http.ResponseWriter, r *http.Request, netname string) bool {
  322. if netname == serverctl.COMMS_NETID {
  323. returnErrorResponse(w, r, formatError(fmt.Errorf("cannot access comms network"), "internal"))
  324. return true
  325. }
  326. return false
  327. }