netmaker/controllers/ext_client.go

352 lines
11 KiB
Go
Raw Normal View History

2021-05-20 01:59:10 +08:00
package controller
import (
"encoding/json"
"errors"
"fmt"
"net/http"
2021-05-20 07:27:22 +08:00
"strconv"
2021-05-20 01:59:10 +08:00
"github.com/gorilla/mux"
2021-07-22 06:55:19 +08:00
"github.com/gravitl/netmaker/database"
2021-05-20 01:59:10 +08:00
"github.com/gravitl/netmaker/functions"
2021-12-07 04:31:08 +08:00
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/logic"
2021-05-20 01:59:10 +08:00
"github.com/gravitl/netmaker/models"
2022-02-07 02:06:07 +08:00
"github.com/gravitl/netmaker/mq"
2021-05-20 01:59:10 +08:00
"github.com/skip2/go-qrcode"
)
func extClientHandlers(r *mux.Router) {
2021-08-10 05:04:16 +08:00
r.HandleFunc("/api/extclients", securityCheck(false, http.HandlerFunc(getAllExtClients))).Methods("GET")
2021-07-03 11:25:36 +08:00
r.HandleFunc("/api/extclients/{network}", securityCheck(false, http.HandlerFunc(getNetworkExtClients))).Methods("GET")
r.HandleFunc("/api/extclients/{network}/{clientid}", securityCheck(false, http.HandlerFunc(getExtClient))).Methods("GET")
r.HandleFunc("/api/extclients/{network}/{clientid}/{type}", securityCheck(false, http.HandlerFunc(getExtClientConf))).Methods("GET")
r.HandleFunc("/api/extclients/{network}/{clientid}", securityCheck(false, http.HandlerFunc(updateExtClient))).Methods("PUT")
r.HandleFunc("/api/extclients/{network}/{clientid}", securityCheck(false, http.HandlerFunc(deleteExtClient))).Methods("DELETE")
2022-01-11 06:52:21 +08:00
r.HandleFunc("/api/extclients/{network}/{nodeid}", securityCheck(false, http.HandlerFunc(createExtClient))).Methods("POST")
2021-05-20 01:59:10 +08:00
}
2022-01-11 06:52:21 +08:00
func checkIngressExists(nodeID string) bool {
node, err := logic.GetNodeByID(nodeID)
2021-05-20 01:59:10 +08:00
if err != nil {
return false
}
2021-07-27 00:24:36 +08:00
return node.IsIngressGateway == "yes"
2021-05-20 01:59:10 +08:00
}
//Gets all extclients associated with network, including pending extclients
func getNetworkExtClients(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var extclients []models.ExtClient
var params = mux.Vars(r)
2021-12-08 01:46:55 +08:00
extclients, err := logic.GetNetworkExtClients(params["network"])
2021-05-20 01:59:10 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
//Returns all the extclients in JSON format
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(extclients)
}
//A separate function to get all extclients, not just extclients for a particular network.
//Not quite sure if this is necessary. Probably necessary based on front end but may want to review after iteration 1 if it's being used or not
func getAllExtClients(w http.ResponseWriter, r *http.Request) {
2021-08-10 05:04:16 +08:00
2021-05-20 01:59:10 +08:00
w.Header().Set("Content-Type", "application/json")
2021-08-10 05:04:16 +08:00
headerNetworks := r.Header.Get("networks")
networksSlice := []string{}
marshalErr := json.Unmarshal([]byte(headerNetworks), &networksSlice)
if marshalErr != nil {
returnErrorResponse(w, r, formatError(marshalErr, "internal"))
2021-05-20 01:59:10 +08:00
return
}
2021-08-10 05:04:16 +08:00
clients := []models.ExtClient{}
err := errors.New("Networks Error")
if networksSlice[0] == ALL_NETWORK_ACCESS {
clients, err = functions.GetAllExtClients()
if err != nil && !database.IsEmptyRecord(err) {
2021-08-10 05:04:16 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
} else {
for _, network := range networksSlice {
2021-12-08 01:46:55 +08:00
extclients, err := logic.GetNetworkExtClients(network)
2021-08-10 05:04:16 +08:00
if err == nil {
clients = append(clients, extclients...)
}
}
}
2021-05-20 01:59:10 +08:00
//Return all the extclients in JSON format
w.WriteHeader(http.StatusOK)
2021-08-10 05:04:16 +08:00
json.NewEncoder(w).Encode(clients)
2021-05-20 01:59:10 +08:00
}
//Get an individual extclient. Nothin fancy here folks.
func getExtClient(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
2021-07-22 06:55:19 +08:00
clientid := params["clientid"]
network := params["network"]
2021-12-08 01:46:55 +08:00
client, err := logic.GetExtClient(clientid, network)
2021-05-20 01:59:10 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
w.WriteHeader(http.StatusOK)
2021-07-22 06:55:19 +08:00
json.NewEncoder(w).Encode(client)
2021-05-20 01:59:10 +08:00
}
2021-07-22 06:55:19 +08:00
//Get an individual extclient. Nothin fancy here folks.
func getExtClientConf(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
2021-05-20 01:59:10 +08:00
2021-07-22 06:55:19 +08:00
var params = mux.Vars(r)
clientid := params["clientid"]
networkid := params["network"]
2021-12-08 01:46:55 +08:00
client, err := logic.GetExtClient(clientid, networkid)
2021-07-22 06:55:19 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-05-20 01:59:10 +08:00
2022-01-11 06:52:21 +08:00
gwnode, err := logic.GetNodeByID(client.IngressGatewayID)
2021-07-22 06:55:19 +08:00
if err != nil {
2022-02-11 00:07:21 +08:00
logger.Log(1, r.Header.Get("user"), "Could not retrieve Ingress Gateway Node", client.IngressGatewayID)
2021-07-22 06:55:19 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-05-20 01:59:10 +08:00
2021-10-27 00:27:29 +08:00
network, err := logic.GetParentNetwork(client.Network)
2021-07-22 06:55:19 +08:00
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, r.Header.Get("user"), "Could not retrieve Ingress Gateway Network", client.Network)
2021-05-20 01:59:10 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
2021-07-22 06:55:19 +08:00
return
}
2022-04-20 04:18:03 +08:00
addrString := client.Address
if addrString != "" {
addrString += "/32"
}
if client.Address6 != "" {
if addrString != "" {
addrString += ","
}
addrString += client.Address6 + "/128"
}
2021-05-20 07:27:22 +08:00
keepalive := ""
if network.DefaultKeepalive != 0 {
keepalive = "PersistentKeepalive = " + strconv.Itoa(int(network.DefaultKeepalive))
}
gwendpoint := gwnode.Endpoint + ":" + strconv.Itoa(int(gwnode.ListenPort))
newAllowedIPs := network.AddressRange
if newAllowedIPs != "" && network.AddressRange6 != "" {
2022-04-21 23:02:44 +08:00
newAllowedIPs += ","
2022-04-21 22:56:10 +08:00
}
if network.AddressRange6 != "" {
newAllowedIPs += network.AddressRange6
}
2021-10-27 00:27:29 +08:00
if egressGatewayRanges, err := logic.GetEgressRangesOnNetwork(&client); err == nil {
for _, egressGatewayRange := range egressGatewayRanges {
newAllowedIPs += "," + egressGatewayRange
}
}
defaultDNS := ""
if network.DefaultExtClientDNS != "" {
defaultDNS = "DNS = " + network.DefaultExtClientDNS
}
2022-03-15 21:16:15 +08:00
defaultMTU := 1420
if gwnode.MTU != 0 {
defaultMTU = int(gwnode.MTU)
}
2021-05-20 01:59:10 +08:00
config := fmt.Sprintf(`[Interface]
Address = %s
PrivateKey = %s
2022-03-15 21:16:15 +08:00
MTU = %d
2021-08-26 05:59:40 +08:00
%s
2021-05-20 01:59:10 +08:00
[Peer]
PublicKey = %s
AllowedIPs = %s
Endpoint = %s
2021-05-20 10:09:48 +08:00
%s
2021-05-20 01:59:10 +08:00
2022-04-20 04:18:03 +08:00
`, addrString,
2021-07-22 06:55:19 +08:00
client.PrivateKey,
2022-03-15 21:16:15 +08:00
defaultMTU,
2021-08-26 05:59:40 +08:00
defaultDNS,
2021-07-22 06:55:19 +08:00
gwnode.PublicKey,
newAllowedIPs,
2021-07-22 06:55:19 +08:00
gwendpoint,
2021-08-26 05:59:40 +08:00
keepalive)
2021-05-20 01:59:10 +08:00
if params["type"] == "qr" {
bytes, err := qrcode.Encode(config, qrcode.Medium, 220)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
w.Header().Set("Content-Type", "image/png")
w.WriteHeader(http.StatusOK)
_, err = w.Write(bytes)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
return
}
if params["type"] == "file" {
2021-07-22 06:55:19 +08:00
name := client.ClientID + ".conf"
w.Header().Set("Content-Type", "application/config")
w.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
2021-05-20 01:59:10 +08:00
w.WriteHeader(http.StatusOK)
_, err := fmt.Fprint(w, config)
if err != nil {
2021-07-22 06:55:19 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
2021-05-20 01:59:10 +08:00
}
return
}
2021-12-07 04:31:08 +08:00
logger.Log(2, r.Header.Get("user"), "retrieved ext client config")
2021-07-22 06:55:19 +08:00
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(client)
2021-05-20 01:59:10 +08:00
}
2021-08-10 00:43:09 +08:00
/**
* To create a extclient
* Must have valid key and be unique
*/
2021-05-20 01:59:10 +08:00
func createExtClient(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
networkName := params["network"]
2022-01-11 06:52:21 +08:00
nodeid := params["nodeid"]
ingressExists := checkIngressExists(nodeid)
2021-05-20 01:59:10 +08:00
if !ingressExists {
returnErrorResponse(w, r, formatError(errors.New("ingress does not exist"), "internal"))
return
}
var extclient models.ExtClient
extclient.Network = networkName
2022-01-11 06:52:21 +08:00
extclient.IngressGatewayID = nodeid
2022-02-02 10:50:11 +08:00
node, err := logic.GetNodeByID(nodeid)
if err != nil {
2021-07-22 06:55:19 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-05-26 06:05:14 +08:00
extclient.IngressGatewayEndpoint = node.Endpoint + ":" + strconv.FormatInt(int64(node.ListenPort), 10)
2022-03-11 22:41:14 +08:00
extclient.Enabled = true
parentNetwork, err := logic.GetNetwork(networkName)
if err == nil { // check if parent network default ACL is enabled (yes) or not (no)
extclient.Enabled = parentNetwork.DefaultACL == "yes"
}
2021-12-11 10:09:42 +08:00
err = logic.CreateExtClient(&extclient)
2021-05-20 01:59:10 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
logger.Log(0, r.Header.Get("user"), "created new ext client on network", networkName)
2021-05-20 01:59:10 +08:00
w.WriteHeader(http.StatusOK)
2022-02-07 02:27:24 +08:00
err = mq.PublishExtPeerUpdate(&node)
2022-02-07 02:06:07 +08:00
if err != nil {
logger.Log(1, "error setting ext peers on "+nodeid+": "+err.Error())
}
2021-05-20 01:59:10 +08:00
}
func updateExtClient(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
var newExtClient models.ExtClient
var oldExtClient models.ExtClient
_ = json.NewDecoder(r.Body).Decode(&newExtClient)
2021-08-10 00:43:09 +08:00
2021-10-27 00:27:29 +08:00
key, err := logic.GetRecordKey(params["clientid"], params["network"])
2021-05-20 01:59:10 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-07-22 06:55:19 +08:00
data, err := database.FetchRecord(database.EXT_CLIENT_TABLE_NAME, key)
2021-05-20 01:59:10 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-07-22 06:55:19 +08:00
if err = json.Unmarshal([]byte(data), &oldExtClient); err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2022-03-11 22:41:14 +08:00
var changedEnabled = newExtClient.Enabled != oldExtClient.Enabled // indicates there was a change in enablement
newclient, err := logic.UpdateExtClient(newExtClient.ClientID, params["network"], newExtClient.Enabled, &oldExtClient)
2021-07-22 06:55:19 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
logger.Log(0, r.Header.Get("user"), "updated ext client", newExtClient.ClientID)
2022-03-11 22:41:14 +08:00
if changedEnabled { // need to send a peer update to the ingress node as enablement of one of it's clients has changed
if ingressNode, err := logic.GetNodeByID(newclient.IngressGatewayID); err == nil {
if err = mq.PublishExtPeerUpdate(&ingressNode); err != nil {
logger.Log(1, "error setting ext peers on", ingressNode.ID, ":", err.Error())
2022-03-11 22:41:14 +08:00
}
}
}
2021-05-20 01:59:10 +08:00
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(newclient)
}
2021-05-20 01:59:10 +08:00
//Delete a extclient
//Pretty straightforward
func deleteExtClient(w http.ResponseWriter, r *http.Request) {
// Set header
w.Header().Set("Content-Type", "application/json")
// get params
var params = mux.Vars(r)
2022-02-07 02:27:24 +08:00
extclient, err := logic.GetExtClient(params["clientid"], params["network"])
if err != nil {
err = errors.New("Could not delete extclient " + params["clientid"])
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
ingressnode, err := logic.GetNodeByID(extclient.IngressGatewayID)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
err = logic.DeleteExtClient(params["network"], params["clientid"])
2021-05-20 01:59:10 +08:00
if err != nil {
err = errors.New("Could not delete extclient " + params["clientid"])
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2022-02-07 02:27:24 +08:00
err = mq.PublishExtPeerUpdate(&ingressnode)
if err != nil {
logger.Log(1, "error setting ext peers on "+ingressnode.ID+": "+err.Error())
}
logger.Log(0, r.Header.Get("user"),
2021-12-07 04:31:08 +08:00
"Deleted extclient client", params["clientid"], "from network", params["network"])
2021-05-20 01:59:10 +08:00
returnSuccessResponse(w, r, params["clientid"]+" deleted.")
}