netmaker/controllers/ext_client.go

296 lines
8.9 KiB
Go
Raw Normal View History

2021-05-20 01:59:10 +08:00
package controller
import (
"encoding/json"
"errors"
"fmt"
2021-07-22 06:55:19 +08:00
"io"
2021-05-20 01:59:10 +08:00
"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"
"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")
r.HandleFunc("/api/extclients/{network}/{macaddress}", securityCheck(false, http.HandlerFunc(createExtClient))).Methods("POST")
2021-05-20 01:59:10 +08:00
}
func checkIngressExists(network string, macaddress string) bool {
2021-10-27 00:27:29 +08:00
node, err := logic.GetNodeByMacAddress(network, macaddress)
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
2021-10-27 00:27:29 +08:00
gwnode, err := logic.GetNodeByMacAddress(client.Network, client.IngressGatewayID)
2021-07-22 06:55:19 +08:00
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, fmt.Sprintf("%s %s %s", 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
}
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
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
}
2021-05-20 01:59:10 +08:00
config := fmt.Sprintf(`[Interface]
Address = %s
PrivateKey = %s
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
2021-07-22 06:55:19 +08:00
`, client.Address+"/32",
client.PrivateKey,
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"]
macaddress := params["macaddress"]
ingressExists := checkIngressExists(networkName, macaddress)
if !ingressExists {
returnErrorResponse(w, r, formatError(errors.New("ingress does not exist"), "internal"))
return
}
var extclient models.ExtClient
extclient.Network = networkName
extclient.IngressGatewayID = macaddress
2021-10-27 00:27:29 +08:00
node, err := logic.GetNodeByMacAddress(networkName, macaddress)
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)
err = json.NewDecoder(r.Body).Decode(&extclient)
2021-05-26 05:57:06 +08:00
if err != nil && !errors.Is(err, io.EOF) {
2021-05-20 01:59:10 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
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
}
w.WriteHeader(http.StatusOK)
}
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
}
2021-12-11 10:09:42 +08:00
newclient, err := logic.UpdateExtClient(newExtClient.ClientID, params["network"], &oldExtClient)
2021-07-22 06:55:19 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, r.Header.Get("user"), "updated client", newExtClient.ClientID)
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)
2021-12-08 01:46:55 +08:00
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
}
2021-12-07 04:31:08 +08:00
logger.Log(1, r.Header.Get("user"),
"Deleted extclient client", params["clientid"], "from network", params["network"])
2021-05-20 01:59:10 +08:00
returnSuccessResponse(w, r, params["clientid"]+" deleted.")
}