2
0
Эх сурвалжийг харах

Merge branch 'relays' into NET-137

Matthew R Kasun 2 жил өмнө
parent
commit
238920f50d
51 өөрчлөгдсөн 853 нэмэгдсэн , 709 устгасан
  1. 1 0
      .github/ISSUE_TEMPLATE/bug-report.yml
  2. 1 1
      Dockerfile
  3. 1 1
      Dockerfile-quick
  4. 1 1
      README.md
  5. 3 1
      auth/host_session.go
  6. 18 2
      cli/cmd/ext_client/create.go
  7. 8 27
      cli/cmd/ext_client/update.go
  8. 0 2
      cli/cmd/network/create.go
  9. 0 1
      cli/cmd/network/flags.go
  10. 3 9
      cli/functions/ext_client.go
  11. 4 73
      compose/docker-compose-emqx.yml
  12. 22 123
      compose/docker-compose.ee.yml
  13. 1 1
      compose/docker-compose.netclient.yml
  14. 0 122
      compose/docker-compose.reference.yml
  15. 52 54
      compose/docker-compose.yml
  16. 1 1
      controllers/docs.go
  17. 78 44
      controllers/ext_client.go
  18. 2 3
      controllers/hosts.go
  19. 2 3
      controllers/network.go
  20. 12 26
      controllers/node.go
  21. 15 3
      controllers/regex.go
  22. 51 0
      controllers/regex_test.go
  23. 9 9
      docker/Caddyfile
  24. 11 11
      docker/Caddyfile-EE
  25. 1 2
      functions/helpers_test.go
  26. 4 4
      go.mod
  27. 8 8
      go.sum
  28. 1 1
      k8s/client/netclient-daemonset.yaml
  29. 1 1
      k8s/client/netclient.yaml
  30. 1 1
      k8s/server/netmaker-server.yaml
  31. 1 1
      k8s/server/netmaker-ui.yaml
  32. 24 25
      logic/extpeers.go
  33. 3 2
      logic/gateway.go
  34. 10 12
      logic/peers.go
  35. 1 1
      logic/relay.go
  36. 1 1
      main.go
  37. 3 0
      models/api_node.go
  38. 11 1
      models/extclient.go
  39. 16 5
      models/host.go
  40. 10 5
      models/mqtt.go
  41. 0 1
      models/network.go
  42. 1 0
      models/node.go
  43. 6 6
      models/structs.go
  44. 16 3
      mq/handlers.go
  45. 148 5
      mq/publishers.go
  46. 5 4
      release.md
  47. 82 0
      scripts/netmaker.env
  48. 4 4
      scripts/nm-certs.sh
  49. 197 96
      scripts/nm-quick.sh
  50. 1 1
      scripts/nm-upgrade-0-17-1-to-0-19-0.sh
  51. 1 1
      swagger.yaml

+ 1 - 0
.github/ISSUE_TEMPLATE/bug-report.yml

@@ -31,6 +31,7 @@ body:
       label: Version
       label: Version
       description: What version are you running?
       description: What version are you running?
       options:
       options:
+        - v0.20.0
         - v0.19.0
         - v0.19.0
         - v0.18.7
         - v0.18.7
         - v0.18.6
         - v0.18.6

+ 1 - 1
Dockerfile

@@ -6,7 +6,7 @@ COPY . .
 
 
 RUN GOOS=linux CGO_ENABLED=1 go build -ldflags="-s -w " -tags ${tags} .
 RUN GOOS=linux CGO_ENABLED=1 go build -ldflags="-s -w " -tags ${tags} .
 # RUN go build -tags=ee . -o netmaker main.go
 # RUN go build -tags=ee . -o netmaker main.go
-FROM alpine:3.17.3
+FROM alpine:3.18.0
 
 
 # add a c lib
 # add a c lib
 # set the working directory
 # set the working directory

+ 1 - 1
Dockerfile-quick

@@ -1,5 +1,5 @@
 #first stage - builder
 #first stage - builder
-FROM alpine:3.17.3
+FROM alpine:3.18.0
 ARG version 
 ARG version 
 WORKDIR /app
 WORKDIR /app
 COPY ./netmaker /root/netmaker
 COPY ./netmaker /root/netmaker

+ 1 - 1
README.md

@@ -17,7 +17,7 @@
 
 
 <p align="center">
 <p align="center">
   <a href="https://github.com/gravitl/netmaker/releases">
   <a href="https://github.com/gravitl/netmaker/releases">
-    <img src="https://img.shields.io/badge/Version-0.19.0-informational?style=flat-square" />
+    <img src="https://img.shields.io/badge/Version-0.20.0-informational?style=flat-square" />
   </a>
   </a>
   <a href="https://hub.docker.com/r/gravitl/netmaker/tags">
   <a href="https://hub.docker.com/r/gravitl/netmaker/tags">
     <img src="https://img.shields.io/docker/pulls/gravitl/netmaker?label=downloads" />
     <img src="https://img.shields.io/docker/pulls/gravitl/netmaker?label=downloads" />

+ 3 - 1
auth/host_session.go

@@ -237,7 +237,9 @@ func CheckNetRegAndHostUpdate(networks []string, h *models.Host) {
 				Host:   *h,
 				Host:   *h,
 				Node:   *newNode,
 				Node:   *newNode,
 			})
 			})
-			//mq.PublishPeerAction(h)
+			if servercfg.IsMessageQueueBackend() {
+				mq.BroadcastAddOrUpdatePeer(h, newNode, false)
+			}
 		}
 		}
 	}
 	}
 	if servercfg.IsMessageQueueBackend() {
 	if servercfg.IsMessageQueueBackend() {

+ 18 - 2
cli/cmd/ext_client/create.go

@@ -4,10 +4,16 @@ import (
 	"fmt"
 	"fmt"
 
 
 	"github.com/gravitl/netmaker/cli/functions"
 	"github.com/gravitl/netmaker/cli/functions"
+	"github.com/gravitl/netmaker/models"
 	"github.com/spf13/cobra"
 	"github.com/spf13/cobra"
 )
 )
 
 
-var extClientID string
+var (
+	extClientID string
+	publicKey   string
+	dns         string
+	allowedips  []string
+)
 
 
 var extClientCreateCmd = &cobra.Command{
 var extClientCreateCmd = &cobra.Command{
 	Use:   "create [NETWORK NAME] [NODE ID]",
 	Use:   "create [NETWORK NAME] [NODE ID]",
@@ -15,12 +21,22 @@ var extClientCreateCmd = &cobra.Command{
 	Short: "Create an External Client",
 	Short: "Create an External Client",
 	Long:  `Create an External Client`,
 	Long:  `Create an External Client`,
 	Run: func(cmd *cobra.Command, args []string) {
 	Run: func(cmd *cobra.Command, args []string) {
-		functions.CreateExtClient(args[0], args[1], extClientID)
+		extClient := models.CustomExtClient{
+			ClientID:        extClientID,
+			PublicKey:       publicKey,
+			DNS:             dns,
+			ExtraAllowedIPs: allowedips,
+		}
+
+		functions.CreateExtClient(args[0], args[1], extClient)
 		fmt.Println("Success")
 		fmt.Println("Success")
 	},
 	},
 }
 }
 
 
 func init() {
 func init() {
 	extClientCreateCmd.Flags().StringVar(&extClientID, "id", "", "ID of the external client")
 	extClientCreateCmd.Flags().StringVar(&extClientID, "id", "", "ID of the external client")
+	extClientCreateCmd.Flags().StringVar(&publicKey, "public_key", "", "updated public key of the external client")
+	extClientCreateCmd.Flags().StringVar(&dns, "dns", "", "updated DNS of the external client")
+	extClientCreateCmd.Flags().StringSliceVar(&allowedips, "allowedips", []string{}, "updated extra allowed IPs of the external client")
 	rootCmd.AddCommand(extClientCreateCmd)
 	rootCmd.AddCommand(extClientCreateCmd)
 }
 }

+ 8 - 27
cli/cmd/ext_client/update.go

@@ -11,15 +11,7 @@ import (
 )
 )
 
 
 var (
 var (
-	extClientUpdateFile    string
-	description            string
-	privateKey             string
-	publicKey              string
-	address                string
-	address6               string
-	ingressGatewayID       string
-	ingressGatewayEndpoint string
-	ownerID                string
+	extClientUpdateFile string
 )
 )
 
 
 var extClientUpdateCmd = &cobra.Command{
 var extClientUpdateCmd = &cobra.Command{
@@ -31,7 +23,7 @@ var extClientUpdateCmd = &cobra.Command{
 		var (
 		var (
 			network   = args[0]
 			network   = args[0]
 			clientID  = args[1]
 			clientID  = args[1]
-			extClient = &models.ExtClient{}
+			extClient = &models.CustomExtClient{}
 		)
 		)
 		if extClientUpdateFile != "" {
 		if extClientUpdateFile != "" {
 			content, err := os.ReadFile(extClientUpdateFile)
 			content, err := os.ReadFile(extClientUpdateFile)
@@ -42,30 +34,19 @@ var extClientUpdateCmd = &cobra.Command{
 				log.Fatal(err)
 				log.Fatal(err)
 			}
 			}
 		} else {
 		} else {
-			extClient.ClientID = clientID
-			extClient.Description = description
-			extClient.PrivateKey = privateKey
+			extClient.ClientID = extClientID
 			extClient.PublicKey = publicKey
 			extClient.PublicKey = publicKey
-			extClient.Network = network
-			extClient.Address = address
-			extClient.Address6 = address6
-			extClient.IngressGatewayID = ingressGatewayID
-			extClient.IngressGatewayEndpoint = ingressGatewayEndpoint
-			extClient.OwnerID = ownerID
+			extClient.DNS = dns
 		}
 		}
 		functions.PrettyPrint(functions.UpdateExtClient(network, clientID, extClient))
 		functions.PrettyPrint(functions.UpdateExtClient(network, clientID, extClient))
 	},
 	},
 }
 }
 
 
 func init() {
 func init() {
+	extClientUpdateCmd.Flags().StringVar(&extClientID, "id", "", "updated ID of the external client")
 	extClientUpdateCmd.Flags().StringVar(&extClientUpdateFile, "file", "", "Filepath of updated external client definition in JSON")
 	extClientUpdateCmd.Flags().StringVar(&extClientUpdateFile, "file", "", "Filepath of updated external client definition in JSON")
-	extClientUpdateCmd.Flags().StringVar(&description, "desc", "", "Description of the external client")
-	extClientUpdateCmd.Flags().StringVar(&privateKey, "private_key", "", "Filepath of updated external client definition in JSON")
-	extClientUpdateCmd.Flags().StringVar(&publicKey, "public_key", "", "Filepath of updated external client definition in JSON")
-	extClientUpdateCmd.Flags().StringVar(&address, "ipv4_addr", "", "IPv4 address of the external client")
-	extClientUpdateCmd.Flags().StringVar(&address6, "ipv6_addr", "", "IPv6 address of the external client")
-	extClientUpdateCmd.Flags().StringVar(&ingressGatewayID, "ingress_gateway_id", "", "ID of the ingress gateway")
-	extClientUpdateCmd.Flags().StringVar(&ingressGatewayEndpoint, "ingress_gateway_endpoint", "", "Endpoint of the ingress gateway")
-	extClientUpdateCmd.Flags().StringVar(&ownerID, "owner_id", "", "External Client owner's ID")
+	extClientUpdateCmd.Flags().StringVar(&publicKey, "public_key", "", "updated public key of the external client")
+	extClientUpdateCmd.Flags().StringVar(&dns, "dns", "", "updated DNS of the external client")
+	extClientUpdateCmd.Flags().StringSliceVar(&allowedips, "allowedips", []string{}, "updated extra allowed IPs of the external client")
 	rootCmd.AddCommand(extClientUpdateCmd)
 	rootCmd.AddCommand(extClientUpdateCmd)
 }
 }

+ 0 - 2
cli/cmd/network/create.go

@@ -45,7 +45,6 @@ var networkCreateCmd = &cobra.Command{
 			if allowManualSignUp {
 			if allowManualSignUp {
 				network.AllowManualSignUp = "yes"
 				network.AllowManualSignUp = "yes"
 			}
 			}
-			network.DefaultExtClientDNS = defaultExtClientDNS
 			network.DefaultMTU = int32(defaultMTU)
 			network.DefaultMTU = int32(defaultMTU)
 		}
 		}
 		functions.PrettyPrint(functions.CreateNetwork(network))
 		functions.PrettyPrint(functions.CreateNetwork(network))
@@ -61,7 +60,6 @@ func init() {
 	networkCreateCmd.Flags().BoolVar(&udpHolePunch, "udp_hole_punch", false, "Enable UDP Hole Punching ?")
 	networkCreateCmd.Flags().BoolVar(&udpHolePunch, "udp_hole_punch", false, "Enable UDP Hole Punching ?")
 	networkCreateCmd.Flags().BoolVar(&defaultACL, "default_acl", false, "Enable default Access Control List ?")
 	networkCreateCmd.Flags().BoolVar(&defaultACL, "default_acl", false, "Enable default Access Control List ?")
 	networkCreateCmd.Flags().StringVar(&defaultInterface, "interface", "", "Name of the network interface")
 	networkCreateCmd.Flags().StringVar(&defaultInterface, "interface", "", "Name of the network interface")
-	networkCreateCmd.Flags().StringVar(&defaultExtClientDNS, "ext_client_dns", "", "IPv4 address of DNS server to be used by external clients")
 	networkCreateCmd.Flags().IntVar(&defaultListenPort, "listen_port", 51821, "Default wireguard port each node will attempt to use")
 	networkCreateCmd.Flags().IntVar(&defaultListenPort, "listen_port", 51821, "Default wireguard port each node will attempt to use")
 	networkCreateCmd.Flags().IntVar(&nodeLimit, "node_limit", 999999999, "Maximum number of nodes that can be associated with this network")
 	networkCreateCmd.Flags().IntVar(&nodeLimit, "node_limit", 999999999, "Maximum number of nodes that can be associated with this network")
 	networkCreateCmd.Flags().IntVar(&defaultKeepalive, "keep_alive", 20, "Keep Alive in seconds")
 	networkCreateCmd.Flags().IntVar(&defaultKeepalive, "keep_alive", 20, "Keep Alive in seconds")

+ 0 - 1
cli/cmd/network/flags.go

@@ -12,6 +12,5 @@ var (
 	nodeLimit                 int
 	nodeLimit                 int
 	defaultKeepalive          int
 	defaultKeepalive          int
 	allowManualSignUp         bool
 	allowManualSignUp         bool
-	defaultExtClientDNS       string
 	defaultMTU                int
 	defaultMTU                int
 )
 )

+ 3 - 9
cli/functions/ext_client.go

@@ -28,14 +28,8 @@ func GetExtClientConfig(networkName, clientID string) string {
 }
 }
 
 
 // CreateExtClient - create an external client
 // CreateExtClient - create an external client
-func CreateExtClient(networkName, nodeID, extClientID string) {
-	if extClientID != "" {
-		request[any](http.MethodPost, fmt.Sprintf("/api/extclients/%s/%s", networkName, nodeID), &models.CustomExtClient{
-			ClientID: extClientID,
-		})
-	} else {
-		request[any](http.MethodPost, fmt.Sprintf("/api/extclients/%s/%s", networkName, nodeID), nil)
-	}
+func CreateExtClient(networkName, nodeID string, extClient models.CustomExtClient) {
+	request[any](http.MethodPost, fmt.Sprintf("/api/extclients/%s/%s", networkName, nodeID), extClient)
 }
 }
 
 
 // DeleteExtClient - delete an external client
 // DeleteExtClient - delete an external client
@@ -44,6 +38,6 @@ func DeleteExtClient(networkName, clientID string) *models.SuccessResponse {
 }
 }
 
 
 // UpdateExtClient - update an external client
 // UpdateExtClient - update an external client
-func UpdateExtClient(networkName, clientID string, payload *models.ExtClient) *models.ExtClient {
+func UpdateExtClient(networkName, clientID string, payload *models.CustomExtClient) *models.ExtClient {
 	return request[models.ExtClient](http.MethodPut, fmt.Sprintf("/api/extclients/%s/%s", networkName, clientID), payload)
 	return request[models.ExtClient](http.MethodPut, fmt.Sprintf("/api/extclients/%s/%s", networkName, clientID), payload)
 }
 }

+ 4 - 73
compose/docker-compose-emqx.yml

@@ -1,86 +1,17 @@
 version: "3.4"
 version: "3.4"
 
 
 services:
 services:
-  netmaker:
-    container_name: netmaker
-    image: gravitl/netmaker:v0.19.0
-    restart: on-failure
-    volumes:
-      - dnsconfig:/root/config/dnsconfig
-      - sqldata:/root/data
-    environment:
-      BROKER_ENDPOINT: "wss://broker.NETMAKER_BASE_DOMAIN/mqtt"
-      BROKER_TYPE: "emqx"
-      EMQX_REST_ENDPOINT: "http://mq:18083"
-      SERVER_NAME: "NETMAKER_BASE_DOMAIN"
-      STUN_LIST: "stun.NETMAKER_BASE_DOMAIN:3478,stun1.netmaker.io:3478,stun2.netmaker.io:3478,stun1.l.google.com:19302,stun2.l.google.com:19302"
-      SERVER_HOST: "SERVER_PUBLIC_IP"
-      SERVER_API_CONN_STRING: "api.NETMAKER_BASE_DOMAIN:443"
-      COREDNS_ADDR: "SERVER_PUBLIC_IP"
-      DNS_MODE: "on"
-      SERVER_HTTP_HOST: "api.NETMAKER_BASE_DOMAIN"
-      NETCLIENT_AUTO_UPDATE: "enabled"
-      API_PORT: "8081"
-      MASTER_KEY: "REPLACE_MASTER_KEY"
-      CORS_ALLOWED_ORIGIN: "*"
-      DISPLAY_KEYS: "on"
-      DATABASE: "sqlite"
-      NODE_ID: "netmaker-server-1"
-      SERVER_BROKER_ENDPOINT: "ws://mq:8083/mqtt"
-      STUN_PORT: "3478"      
-      VERBOSITY: "1"
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD"
-      MQ_USERNAME: "REPLACE_MQ_USERNAME"
-      DEFAULT_PROXY_MODE: "off"
-    ports:
-      - "3478:3478/udp"
-  netmaker-ui:
-    container_name: netmaker-ui
-    image: gravitl/netmaker-ui:v0.19.0
-    depends_on:
-      - netmaker
-    links:
-      - "netmaker:api"
-    restart: always
-    environment:
-      BACKEND_URL: "https://api.NETMAKER_BASE_DOMAIN"
-  caddy:
-    image: caddy:2.6.2
-    container_name: caddy
-    restart: unless-stopped
-    volumes:
-      - /root/Caddyfile:/etc/caddy/Caddyfile
-      - /root/certs:/root/certs
-      - caddy_data:/data
-      - caddy_conf:/config
-    ports:
-      - "80:80"
-      - "443:443"
-  coredns:
-    container_name: coredns
-    image: coredns/coredns
-    command: -conf /root/dnsconfig/Corefile
-    depends_on:
-      - netmaker
-    restart: always
-    volumes:
-      - dnsconfig:/root/dnsconfig
   mq:
   mq:
     container_name: mq
     container_name: mq
     image: emqx/emqx:5.0.9
     image: emqx/emqx:5.0.9
     restart: unless-stopped
     restart: unless-stopped
     environment:
     environment:
-      EMQX_NAME: "emqx"
-      EMQX_DASHBOARD__DEFAULT_PASSWORD: "REPLACE_MQ_PASSWORD"
-      EMQX_DASHBOARD__DEFAULT_USERNAME: "REPLACE_MQ_USERNAME"
+      - EMQX_NAME: "emqx"
+      - EMQX_DASHBOARD__DEFAULT_PASSWORD=${MQ_PASSWORD}
+      - EMQX_DASHBOARD__DEFAULT_USERNAME=${MQ_USERNAME}
     ports:
     ports:
       - "1883:1883" # MQTT
       - "1883:1883" # MQTT
       - "8883:8883" # SSL MQTT
       - "8883:8883" # SSL MQTT
       - "8083:8083" # Websockets
       - "8083:8083" # Websockets
       - "18083:18083" # Dashboard/REST_API
       - "18083:18083" # Dashboard/REST_API
-volumes:
-  caddy_data: {}
-  caddy_conf: {}
-  sqldata: {}
-  dnsconfig: {}
-  mosquitto_logs: {}
+

+ 22 - 123
compose/docker-compose.ee.yml

@@ -1,109 +1,29 @@
 version: "3.4"
 version: "3.4"
 
 
 services:
 services:
-  netmaker:
-    container_name: netmaker
-    image: gravitl/netmaker:REPLACE_SERVER_IMAGE_TAG
-    restart: on-failure
-    volumes:
-      - dnsconfig:/root/config/dnsconfig
-      - sqldata:/root/data
-    environment:
-      BROKER_ENDPOINT: "wss://broker.NETMAKER_BASE_DOMAIN"
-      SERVER_NAME: "NETMAKER_BASE_DOMAIN"
-      STUN_LIST: "stun.NETMAKER_BASE_DOMAIN:3478,stun1.netmaker.io:3478,stun2.netmaker.io:3478,stun1.l.google.com:19302,stun2.l.google.com:19302"
-      SERVER_HOST: "SERVER_PUBLIC_IP"
-      SERVER_API_CONN_STRING: "api.NETMAKER_BASE_DOMAIN:443"
-      COREDNS_ADDR: "SERVER_PUBLIC_IP"
-      DNS_MODE: "on"
-      SERVER_HTTP_HOST: "api.NETMAKER_BASE_DOMAIN"
-      NETCLIENT_AUTO_UPDATE: "enabled"
-      API_PORT: "8081"
-      MASTER_KEY: "REPLACE_MASTER_KEY"
-      CORS_ALLOWED_ORIGIN: "*"
-      DISPLAY_KEYS: "on"
-      DATABASE: "sqlite"
-      NODE_ID: "netmaker-server-1"
-      SERVER_BROKER_ENDPOINT: "ws://mq:1883"
-      MQ_USERNAME: "REPLACE_MQ_USERNAME"
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD"
-      STUN_PORT: "3478"
-      VERBOSITY: "1"
-      METRICS_EXPORTER: "on"
-      LICENSE_KEY: "YOUR_LICENSE_KEY"
-      NETMAKER_ACCOUNT_ID: "YOUR_ACCOUNT_ID"
-      DEFAULT_PROXY_MODE: "off"
-      TURN_SERVER_HOST: "turn.NETMAKER_BASE_DOMAIN"
-      TURN_SERVER_API_HOST: "https://turnapi.NETMAKER_BASE_DOMAIN"
-      TURN_PORT: "3479"
-      TURN_USERNAME: "REPLACE_TURN_USERNAME"
-      TURN_PASSWORD: "REPLACE_TURN_PASSWORD"
-      USE_TURN: "true"
-    ports:
-      - "3478:3478/udp"
-  netmaker-ui:
-    container_name: netmaker-ui
-    image: gravitl/netmaker-ui:REPLACE_UI_IMAGE_TAG
-    depends_on:
-      - netmaker
-    links:
-      - "netmaker:api"
-    restart: always
-    environment:
-      BACKEND_URL: "https://api.NETMAKER_BASE_DOMAIN"
-  caddy:
-    image: caddy:2.6.2
-    container_name: caddy
-    restart: unless-stopped
-    volumes:
-      - /root/Caddyfile:/etc/caddy/Caddyfile
-      - /root/certs:/root/certs
-      - caddy_data:/data
-      - caddy_conf:/config
-    ports:
-      - "80:80"
-      - "443:443"
-  coredns:
-    container_name: coredns
-    image: coredns/coredns
-    command: -conf /root/dnsconfig/Corefile
-    depends_on:
-      - netmaker
-    restart: always
-    volumes:
-      - dnsconfig:/root/dnsconfig
-  mq:
-    container_name: mq
-    image: eclipse-mosquitto:2.0.15-openssl
-    depends_on:
-      - netmaker
-    restart: unless-stopped
-    command: ["/mosquitto/config/wait.sh"]
-    environment:
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD"
-      MQ_USERNAME: "REPLACE_MQ_USERNAME"
-    volumes:
-      - /root/mosquitto.conf:/mosquitto/config/mosquitto.conf
-      - /root/wait.sh:/mosquitto/config/wait.sh
-      - mosquitto_logs:/mosquitto/log
+
   prometheus:
   prometheus:
     container_name: prometheus
     container_name: prometheus
     image: gravitl/netmaker-prometheus:latest
     image: gravitl/netmaker-prometheus:latest
+    env_file: ./netmaker.env
     environment:
     environment:
-      NETMAKER_METRICS_TARGET: "netmaker-exporter.NETMAKER_BASE_DOMAIN"
-      LICENSE_KEY: "YOUR_LICENSE_KEY"
+      # config-dependant vars
+      - NETMAKER_METRICS_TARGET=netmaker-exporter.${NM_DOMAIN}
     restart: always
     restart: always
     volumes:
     volumes:
       - prometheus_data:/prometheus
       - prometheus_data:/prometheus
     depends_on:
     depends_on:
       - netmaker
       - netmaker
+
   grafana:
   grafana:
     container_name: grafana
     container_name: grafana
     image: gravitl/netmaker-grafana:latest
     image: gravitl/netmaker-grafana:latest
+    env_file: ./netmaker.env
     environment:
     environment:
-      PROMETHEUS_HOST: "prometheus.NETMAKER_BASE_DOMAIN"
-      NETMAKER_METRICS_TARGET: "netmaker-exporter.NETMAKER_BASE_DOMAIN"
-      LICENSE_KEY: "YOUR_LICENSE_KEY"
+      # config-dependant vars
+      # TODO unify with netmaker-exporter
+      - PROMETHEUS_HOST=prometheus.${NM_DOMAIN}
+      - NETMAKER_METRICS_TARGET=netmaker-exporter.${NM_DOMAIN}
     volumes:
     volumes:
       - grafana_data:/var/lib/grafana
       - grafana_data:/var/lib/grafana
     restart: always
     restart: always
@@ -112,43 +32,22 @@ services:
     depends_on:
     depends_on:
       - prometheus
       - prometheus
       - netmaker
       - netmaker
+
   netmaker-exporter:
   netmaker-exporter:
     container_name: netmaker-exporter
     container_name: netmaker-exporter
     image: gravitl/netmaker-exporter:latest
     image: gravitl/netmaker-exporter:latest
+    env_file: ./netmaker.env
+    environment:
+      # config-dependant vars
+      # TODO unify with grafana
+      - PROMETHEUS_HOST=https://prometheus.${NM_DOMAIN}
+      # The domain/host IP indicating the mq broker address
+      - BROKER_ENDPOINT=wss://broker.${NM_DOMAIN}
+      - API_PORT=${EXPORTER_API_PORT}
     restart: always
     restart: always
     depends_on:
     depends_on:
       - netmaker
       - netmaker
-    environment:
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD"
-      MQ_USERNAME: "REPLACE_MQ_USERNAME"
-      SERVER_BROKER_ENDPOINT: "ws://mq:1883"
-      BROKER_ENDPOINT: "wss://broker.NETMAKER_BASE_DOMAIN"
-      PROMETHEUS: "on"
-      VERBOSITY: "1"
-      API_PORT: "8085"
-      LICENSE_KEY: "YOUR_LICENSE_KEY"
-      PROMETHEUS_HOST: https://prometheus.NETMAKER_BASE_DOMAIN
-  turn:
-    container_name: turn
-    image: gravitl/turnserver:v1.0.0
-    network_mode: "host"
-    volumes:
-      - turn_server:/etc/config
-    environment:
-      DEBUG_MODE: "off"
-      VERBOSITY: "1"
-      TURN_PORT: "3479"
-      TURN_API_PORT: "8089"
-      CORS_ALLOWED_ORIGIN: "*"
-      TURN_SERVER_HOST: "turn.NETMAKER_BASE_DOMAIN"
-      USERNAME: "REPLACE_TURN_USERNAME"
-      PASSWORD: "REPLACE_TURN_PASSWORD"
+
 volumes:
 volumes:
-  caddy_data: {}
-  caddy_conf: {}
-  sqldata: {}
-  dnsconfig: {}
-  mosquitto_logs: {}
-  prometheus_data: {}
-  grafana_data: {}
-  turn_server: {}
+  prometheus_data: { }
+  grafana_data: { }

+ 1 - 1
compose/docker-compose.netclient.yml

@@ -3,7 +3,7 @@ version: "3.4"
 services:
 services:
   netclient:
   netclient:
     container_name: netclient
     container_name: netclient
-    image: 'gravitl/netclient:v0.19.0'
+    image: 'gravitl/netclient:v0.20.0'
     hostname: netmaker-1
     hostname: netmaker-1
     network_mode: host
     network_mode: host
     restart: on-failure
     restart: on-failure

+ 0 - 122
compose/docker-compose.reference.yml

@@ -1,122 +0,0 @@
-version: "3.4"
-
-services:
-  netmaker: # The Primary Server for running Netmaker
-    container_name: netmaker
-    image: gravitl/netmaker:REPLACE_SERVER_IMAGE_TAG
-    restart: on-failure
-    volumes: # Volume mounts necessary for sql, coredns, and mqtt
-      - dnsconfig:/root/config/dnsconfig
-      - sqldata:/root/data
-      - shared_certs:/etc/netmaker
-    environment: # Necessary capabilities to set iptables when running in container
-      BROKER_ENDPOINT: "wss://broker.NETMAKER_BASE_DOMAIN" # The domain/host IP indicating the mq broker address
-      SERVER_NAME: "NETMAKER_BASE_DOMAIN" # The base domain of netmaker
-      SERVER_HOST: "SERVER_PUBLIC_IP" # Set to public IP of machine.
-      SERVER_HTTP_HOST: "api.NETMAKER_BASE_DOMAIN" # Overrides SERVER_HOST if set. Useful for making HTTP available via different interfaces/networks.
-      NETCLIENT_AUTO_UPDATE: "enabled" # Enable auto update of netclient ? ENUM:- enabled,disabled | default: enabled
-      SERVER_API_CONN_STRING: "api.NETMAKER_BASE_DOMAIN:443"
-      COREDNS_ADDR: "SERVER_PUBLIC_IP" # Address of the CoreDNS server. Defaults to SERVER_HOST
-      DNS_MODE: "on" # Enables DNS Mode, meaning all nodes will set hosts file for private dns settings.
-      API_PORT: "8081" # The HTTP API port for Netmaker. Used for API calls / communication from front end. If changed, need to change port of BACKEND_URL for netmaker-ui.
-      REST_BACKEND: "on" # Enables the REST backend (API running on API_PORT at SERVER_HTTP_HOST). Change to "off" to turn off.
-      DISABLE_REMOTE_IP_CHECK: "off" # If turned "on", Server will not set Host based on remote IP check. This is already overridden if SERVER_HOST is set. Turned "off" by default.
-      TELEMETRY: "on" # Whether or not to send telemetry data to help improve Netmaker. Switch to "off" to opt out of sending telemetry.
-      MASTER_KEY: "REPLACE_MASTER_KEY" # The admin master key for accessing the API. Change this in any production installation.
-      CORS_ALLOWED_ORIGIN: "*" # The "allowed origin" for API requests. Change to restrict where API requests can come from with comma-separated URLs. ex:- https://dashboard.netmaker.domain1.com,https://dashboard.netmaker.domain2.com
-      DISPLAY_KEYS: "on" # Show keys permanently in UI (until deleted) as opposed to 1-time display.
-      DATABASE: "sqlite" # Database to use - sqlite, postgres, or rqlite
-      NODE_ID: "netmaker-server-1" # used for HA - identifies this server vs other servers
-      SERVER_BROKER_ENDPOINT: ""ws://mq:1883""  # the address of the mq server. If running from docker compose it will be "mq". Otherwise, need to input address. If using "host networking", it will find and detect the IP of the mq container.
-      MQ_USERNAME: "REPLACE_MQ_USERNAME" # the username to set for MQ access
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD" # the password to set for MQ access
-      STUN_PORT: "3478" # the reachable port of STUN on the server
-      VERBOSITY: "1" # logging verbosity level - 1, 2, or 3
-      # this section is for OAuth
-      AUTH_PROVIDER: "" # "<azure-ad|github|google|oidc>"
-      CLIENT_ID: "" # "<client id of your oauth provider>"
-      CLIENT_SECRET: "" # "<client secret of your oauth provider>"
-      FRONTEND_URL: "" # "https://dashboard.<netmaker base domain>"
-      AZURE_TENANT: "" # "<only for azure, you may optionally specify the tenant for the OAuth>"
-      OIDC_ISSUER: "" # https://oidc.yourprovider.com - URL of oidc provider
-      DEFAULT_PROXY_MODE: "off" # if ON, all new clients will enable proxy by default if OFF, all new clients will disable proxy by default, if AUTO, stick with the existing logic for NAT detection
-      TURN_SERVER_HOST: "turn.NETMAKER_BASE_DOMAIN" # domain for your turn server
-      TURN_SERVER_API_HOST: "https://turnapi.NETMAKER_BASE_DOMAIN" # domain of the turn api server
-      TURN_PORT: "3479" #  port to access turn server
-      TURN_USERNAME: "REPLACE_TURN_USERNAME"  # the username to set for turn api access
-      TURN_PASSWORD: "REPLACE_TURN_PASSWORD" #  the password to set for turn api access
-      USE_TURN: "true" #config for using turn, accepts either true/false
-    ports:
-      - "3478:3478/udp" # the stun port
-  netmaker-ui:  # The Netmaker UI Component
-    container_name: netmaker-ui
-    image: gravitl/netmaker-ui:REPLACE_UI_IMAGE_TAG
-    depends_on:
-      - netmaker
-    links:
-      - "netmaker:api"
-    restart: always
-    environment:
-      BACKEND_URL: "https://api.NETMAKER_BASE_DOMAIN" # URL where UI will send API requests. Change based on SERVER_HOST, SERVER_HTTP_HOST, and API_PORT
-  caddy: # The reverse proxy that manages traffic for Netmaker
-    image: caddy:2.6.2
-    container_name: caddy
-    restart: unless-stopped
-    volumes:
-      - /root/Caddyfile:/etc/caddy/Caddyfile # Config file for Caddy
-      - /root/certs:/root/certs
-      - caddy_data:/data
-      - caddy_conf:/config
-    ports:
-      - "80:80"
-      - "443:443"
-  coredns: # The DNS Server. CoreDNS can be removed unless doing special advanced use cases
-    container_name: coredns
-    image: coredns/coredns
-    command: -conf /root/dnsconfig/Corefile
-    depends_on:
-      - netmaker
-    restart: always
-    volumes:
-      - dnsconfig:/root/dnsconfig
-  mq: # the mqtt broker for netmaker
-    container_name: mq
-    image: eclipse-mosquitto:2.0.15-openssl
-    depends_on:
-      - netmaker
-    restart: unless-stopped
-    command: ["/mosquitto/config/wait.sh"]
-    environment:
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD" # must be same value as in netmaker env 
-      MQ_USERNAME: "REPLACE_MQ_USERNAME" # must be same value as in netmaker env
-    volumes:
-      - /root/mosquitto.conf:/mosquitto/config/mosquitto.conf
-      - /root/wait.sh:/mosquitto/config/wait.sh
-      - mosquitto_logs:/mosquitto/log
-    ports:
-      - "1883:1883"
-      - "8883:8883"
-  turn:
-    container_name: turn
-    image: gravitl/turnserver:v1.0.0
-    network_mode: "host"
-    volumes:
-      - turn_server:/etc/config
-    environment:
-      DEBUG_MODE: "off"
-      VERBOSITY: "1"
-      TURN_PORT: "3479"
-      TURN_API_PORT: "8089"
-      CORS_ALLOWED_ORIGIN: "*"
-      TURN_SERVER_HOST: "turn.NETMAKER_BASE_DOMAIN"
-      USERNAME: "REPLACE_TURN_USERNAME"
-      PASSWORD: "REPLACE_TURN_PASSWORD"
-      USE_TURN: "true"
-volumes:
-  caddy_data: {} # runtime data for caddy
-  caddy_conf: {} # configuration file for Caddy
-  shared_certs: {} # netmaker certs generated for MQ comms - used by nodes/servers
-  sqldata: {} # storage for embedded sqlite
-  dnsconfig: {} # storage for coredns
-  mosquitto_logs: {} # storage for mqtt logs
-  turn_server: {}

+ 52 - 54
compose/docker-compose.yml

@@ -1,71 +1,69 @@
 version: "3.4"
 version: "3.4"
 
 
 services:
 services:
+
   netmaker:
   netmaker:
     container_name: netmaker
     container_name: netmaker
-    image: gravitl/netmaker:REPLACE_SERVER_IMAGE_TAG
+    image: gravitl/netmaker:$SERVER_IMAGE_TAG
+    env_file: ./netmaker.env
     restart: on-failure
     restart: on-failure
     volumes:
     volumes:
       - dnsconfig:/root/config/dnsconfig
       - dnsconfig:/root/config/dnsconfig
       - sqldata:/root/data
       - sqldata:/root/data
     environment:
     environment:
-      BROKER_ENDPOINT: "wss://broker.NETMAKER_BASE_DOMAIN"
-      SERVER_NAME: "NETMAKER_BASE_DOMAIN"
-      STUN_LIST: "stun.NETMAKER_BASE_DOMAIN:3478,stun1.netmaker.io:3478,stun2.netmaker.io:3478,stun1.l.google.com:19302,stun2.l.google.com:19302"
-      SERVER_HOST: "SERVER_PUBLIC_IP"
-      SERVER_API_CONN_STRING: "api.NETMAKER_BASE_DOMAIN:443"
-      COREDNS_ADDR: "SERVER_PUBLIC_IP"
-      DNS_MODE: "on"
-      SERVER_HTTP_HOST: "api.NETMAKER_BASE_DOMAIN"
-      NETCLIENT_AUTO_UPDATE: "enabled"
-      API_PORT: "8081"
-      MASTER_KEY: "REPLACE_MASTER_KEY"
-      CORS_ALLOWED_ORIGIN: "*"
-      DISPLAY_KEYS: "on"
-      DATABASE: "sqlite"
-      NODE_ID: "netmaker-server-1"
-      SERVER_BROKER_ENDPOINT: "ws://mq:1883"
-      VERBOSITY: "1"
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD"
-      MQ_USERNAME: "REPLACE_MQ_USERNAME"
-      STUN_PORT: "3478"
-      DEFAULT_PROXY_MODE: "off"
-      TURN_SERVER_HOST: "turn.NETMAKER_BASE_DOMAIN"
-      TURN_SERVER_API_HOST: "https://turnapi.NETMAKER_BASE_DOMAIN"
-      TURN_PORT: "3479"
-      TURN_USERNAME: "REPLACE_TURN_USERNAME"
-      TURN_PASSWORD: "REPLACE_TURN_PASSWORD"
-      USE_TURN: "true"
+      # config-dependant vars
+      - STUN_LIST=stun.${NM_DOMAIN}:${STUN_PORT},stun1.netmaker.io:3478,stun2.netmaker.io:3478,stun1.l.google.com:19302,stun2.l.google.com:19302
+      # The domain/host IP indicating the mq broker address
+      - BROKER_ENDPOINT=wss://broker.${NM_DOMAIN}
+      # The base domain of netmaker
+      - SERVER_NAME=${NM_DOMAIN}
+      - SERVER_API_CONN_STRING=api.${NM_DOMAIN}:443
+      # Address of the CoreDNS server. Defaults to SERVER_HOST
+      - COREDNS_ADDR=${SERVER_HOST}
+      # Overrides SERVER_HOST if set. Useful for making HTTP available via different interfaces/networks.
+      - SERVER_HTTP_HOST=api.${NM_DOMAIN}
+      # domain for your turn server
+      - TURN_SERVER_HOST=turn.${NM_DOMAIN}
+      # domain of the turn api server
+      - TURN_SERVER_API_HOST=https://turnapi.${NM_DOMAIN}
     ports:
     ports:
       - "3478:3478/udp"
       - "3478:3478/udp"
+
   netmaker-ui:
   netmaker-ui:
     container_name: netmaker-ui
     container_name: netmaker-ui
-    image: gravitl/netmaker-ui:REPLACE_UI_IMAGE_TAG
+    image: gravitl/netmaker-ui:$UI_IMAGE_TAG
+    env_file: ./netmaker.env
+    environment:
+      # config-dependant vars
+      # URL where UI will send API requests. Change based on SERVER_HOST, SERVER_HTTP_HOST, and API_PORT
+      BACKEND_URL: "https://api.${NM_DOMAIN}"
     depends_on:
     depends_on:
       - netmaker
       - netmaker
     links:
     links:
       - "netmaker:api"
       - "netmaker:api"
     restart: always
     restart: always
-    environment:
-      BACKEND_URL: "https://api.NETMAKER_BASE_DOMAIN"
+
   caddy:
   caddy:
     image: caddy:2.6.2
     image: caddy:2.6.2
     container_name: caddy
     container_name: caddy
+    env_file: ./netmaker.env
     restart: unless-stopped
     restart: unless-stopped
     extra_hosts:
     extra_hosts:
       - "host.docker.internal:host-gateway"
       - "host.docker.internal:host-gateway"
     volumes:
     volumes:
-      - /root/Caddyfile:/etc/caddy/Caddyfile
-      - /root/certs:/root/certs
+      - ./Caddyfile:/etc/caddy/Caddyfile
+      - ./certs:/root/certs
       - caddy_data:/data
       - caddy_data:/data
       - caddy_conf:/config
       - caddy_conf:/config
     ports:
     ports:
       - "80:80"
       - "80:80"
       - "443:443"
       - "443:443"
+
   coredns:
   coredns:
     container_name: coredns
     container_name: coredns
     image: coredns/coredns
     image: coredns/coredns
     command: -conf /root/dnsconfig/Corefile
     command: -conf /root/dnsconfig/Corefile
+    env_file: ./netmaker.env
     depends_on:
     depends_on:
       - netmaker
       - netmaker
     restart: always
     restart: always
@@ -74,36 +72,36 @@ services:
   mq:
   mq:
     container_name: mq
     container_name: mq
     image: eclipse-mosquitto:2.0.15-openssl
     image: eclipse-mosquitto:2.0.15-openssl
+    env_file: ./netmaker.env
     depends_on:
     depends_on:
       - netmaker
       - netmaker
     restart: unless-stopped
     restart: unless-stopped
-    command: ["/mosquitto/config/wait.sh"]
-    environment:
-      MQ_PASSWORD: "REPLACE_MQ_PASSWORD"
-      MQ_USERNAME: "REPLACE_MQ_USERNAME"
+    command: [ "/mosquitto/config/wait.sh" ]
     volumes:
     volumes:
-      - /root/mosquitto.conf:/mosquitto/config/mosquitto.conf
-      - /root/wait.sh:/mosquitto/config/wait.sh
+      - ./mosquitto.conf:/mosquitto/config/mosquitto.conf
+      - ./wait.sh:/mosquitto/config/wait.sh
       - mosquitto_logs:/mosquitto/log
       - mosquitto_logs:/mosquitto/log
+      - mosquitto_data:/mosquitto/data
+
   turn:
   turn:
     container_name: turn
     container_name: turn
     image: gravitl/turnserver:v1.0.0
     image: gravitl/turnserver:v1.0.0
+    env_file: ./netmaker.env
+    environment:
+      # config-dependant vars
+      - USERNAME=${TURN_USERNAME}
+      - PASSWORD=${TURN_PASSWORD}
+      # domain for your turn server
+      - TURN_SERVER_HOST=turn.${NM_DOMAIN}
     network_mode: "host"
     network_mode: "host"
     volumes:
     volumes:
       - turn_server:/etc/config
       - turn_server:/etc/config
-    environment:
-      DEBUG_MODE: "off"
-      VERBOSITY: "1"
-      TURN_PORT: "3479"
-      TURN_API_PORT: "8089"
-      CORS_ALLOWED_ORIGIN: "*"
-      TURN_SERVER_HOST: "turn.NETMAKER_BASE_DOMAIN"
-      USERNAME: "REPLACE_TURN_USERNAME"
-      PASSWORD: "REPLACE_TURN_PASSWORD"
+
 volumes:
 volumes:
-  caddy_data: {}
-  caddy_conf: {}
-  sqldata: {}
-  dnsconfig: {}
-  mosquitto_logs: {}
-  turn_server: {}
+  caddy_data: { } # runtime data for caddy
+  caddy_conf: { } # configuration file for Caddy
+  sqldata: { }
+  dnsconfig: { } # storage for coredns
+  mosquitto_logs: { } # storage for mqtt logs
+  mosquitto_data: { } # storage for mqtt data
+  turn_server: { }

+ 1 - 1
controllers/docs.go

@@ -10,7 +10,7 @@
 //
 //
 //	Schemes: https
 //	Schemes: https
 //	BasePath: /
 //	BasePath: /
-//	Version: 0.19.0
+//	Version: 0.20.0
 //	Host: netmaker.io
 //	Host: netmaker.io
 //
 //
 //	Consumes:
 //	Consumes:

+ 78 - 44
controllers/ext_client.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"encoding/json"
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
+	"net"
 	"net/http"
 	"net/http"
 	"strconv"
 	"strconv"
 
 
@@ -230,8 +231,10 @@ func getExtClientConf(w http.ResponseWriter, r *http.Request) {
 		}
 		}
 	}
 	}
 	defaultDNS := ""
 	defaultDNS := ""
-	if network.DefaultExtClientDNS != "" {
-		defaultDNS = "DNS = " + network.DefaultExtClientDNS
+	if client.DNS != "" {
+		defaultDNS = "DNS = " + client.DNS
+	} else if gwnode.IngressDNS != "" {
+		defaultDNS = "DNS = " + gwnode.IngressDNS
 	}
 	}
 
 
 	defaultMTU := 1420
 	defaultMTU := 1420
@@ -321,20 +324,13 @@ func createExtClient(w http.ResponseWriter, r *http.Request) {
 	var extclient models.ExtClient
 	var extclient models.ExtClient
 	var customExtClient models.CustomExtClient
 	var customExtClient models.CustomExtClient
 
 
-	err := json.NewDecoder(r.Body).Decode(&customExtClient)
-	if err == nil {
-		if customExtClient.ClientID != "" && !validName(customExtClient.ClientID) {
-			logic.ReturnErrorResponse(w, r, logic.FormatError(errInvalidExtClientID, "badrequest"))
-			return
-		}
-		extclient.ClientID = customExtClient.ClientID
-		if len(customExtClient.PublicKey) > 0 {
-			if _, err := wgtypes.ParseKey(customExtClient.PublicKey); err != nil {
-				logic.ReturnErrorResponse(w, r, logic.FormatError(errInvalidExtClientPubKey, "badrequest"))
-				return
-			}
-			extclient.PublicKey = customExtClient.PublicKey
-		}
+	if err := json.NewDecoder(r.Body).Decode(&customExtClient); err != nil {
+		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
+		return
+	}
+	if err := validateExtClient(&extclient, &customExtClient); err != nil {
+		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
+		return
 	}
 	}
 
 
 	extclient.Network = networkName
 	extclient.Network = networkName
@@ -392,7 +388,7 @@ func createExtClient(w http.ResponseWriter, r *http.Request) {
 				logger.Log(0, "failed to associate client", extclient.ClientID, "to user", userID)
 				logger.Log(0, "failed to associate client", extclient.ClientID, "to user", userID)
 			}
 			}
 			extclient.OwnerID = userID
 			extclient.OwnerID = userID
-			if _, err := logic.UpdateExtClient(extclient.ClientID, extclient.Network, extclient.Enabled, &extclient, extclient.ACLs); err != nil {
+			if err := logic.SaveExtClient(&extclient); err != nil {
 				logger.Log(0, "failed to add owner id", userID, "to client", extclient.ClientID)
 				logger.Log(0, "failed to add owner id", userID, "to client", extclient.ClientID)
 			}
 			}
 		}
 		}
@@ -401,9 +397,7 @@ func createExtClient(w http.ResponseWriter, r *http.Request) {
 	logger.Log(0, r.Header.Get("user"), "created new ext client on network", networkName)
 	logger.Log(0, r.Header.Get("user"), "created new ext client on network", networkName)
 	w.WriteHeader(http.StatusOK)
 	w.WriteHeader(http.StatusOK)
 	go func() {
 	go func() {
-		if err := mq.PublishPeerUpdate(); err != nil {
-			logger.Log(1, "error setting ext peers on "+nodeid+": "+err.Error())
-		}
+		mq.BroadcastExtClient(host, &node)
 		if err := mq.PublishExtCLientDNS(&extclient); err != nil {
 		if err := mq.PublishExtCLientDNS(&extclient); err != nil {
 			logger.Log(1, "error publishing extclient dns", err.Error())
 			logger.Log(1, "error publishing extclient dns", err.Error())
 		}
 		}
@@ -426,9 +420,9 @@ func updateExtClient(w http.ResponseWriter, r *http.Request) {
 
 
 	var params = mux.Vars(r)
 	var params = mux.Vars(r)
 
 
-	var newExtClient models.ExtClient
+	var update models.CustomExtClient
 	var oldExtClient models.ExtClient
 	var oldExtClient models.ExtClient
-	err := json.NewDecoder(r.Body).Decode(&newExtClient)
+	err := json.NewDecoder(r.Body).Decode(&update)
 	if err != nil {
 	if err != nil {
 		logger.Log(0, r.Header.Get("user"), "error decoding request body: ",
 		logger.Log(0, r.Header.Get("user"), "error decoding request body: ",
 			err.Error())
 			err.Error())
@@ -445,8 +439,8 @@ func updateExtClient(w http.ResponseWriter, r *http.Request) {
 		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
 		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
 		return
 		return
 	}
 	}
-	if !validName(newExtClient.ClientID) {
-		logic.ReturnErrorResponse(w, r, logic.FormatError(errInvalidExtClientID, "badrequest"))
+	if err := validateExtClient(&oldExtClient, &update); err != nil {
+		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
 		return
 		return
 	}
 	}
 	data, err := database.FetchRecord(database.EXT_CLIENT_TABLE_NAME, key)
 	data, err := database.FetchRecord(database.EXT_CLIENT_TABLE_NAME, key)
@@ -466,7 +460,7 @@ func updateExtClient(w http.ResponseWriter, r *http.Request) {
 
 
 	// == PRO ==
 	// == PRO ==
 	networkName := params["network"]
 	networkName := params["network"]
-	var changedID = newExtClient.ClientID != oldExtClient.ClientID
+	var changedID = update.ClientID != oldExtClient.ClientID
 	if r.Header.Get("ismaster") != "yes" {
 	if r.Header.Get("ismaster") != "yes" {
 		userID := r.Header.Get("user")
 		userID := r.Header.Get("user")
 		_, doesOwn := doesUserOwnClient(userID, params["clientid"], networkName)
 		_, doesOwn := doesUserOwnClient(userID, params["clientid"], networkName)
@@ -479,17 +473,16 @@ func updateExtClient(w http.ResponseWriter, r *http.Request) {
 		if err := pro.DissociateNetworkUserClient(oldExtClient.OwnerID, networkName, oldExtClient.ClientID); err != nil {
 		if err := pro.DissociateNetworkUserClient(oldExtClient.OwnerID, networkName, oldExtClient.ClientID); err != nil {
 			logger.Log(0, "failed to dissociate client", oldExtClient.ClientID, "from user", oldExtClient.OwnerID)
 			logger.Log(0, "failed to dissociate client", oldExtClient.ClientID, "from user", oldExtClient.OwnerID)
 		}
 		}
-		if err := pro.AssociateNetworkUserClient(oldExtClient.OwnerID, networkName, newExtClient.ClientID); err != nil {
-			logger.Log(0, "failed to associate client", newExtClient.ClientID, "to user", oldExtClient.OwnerID)
+		if err := pro.AssociateNetworkUserClient(oldExtClient.OwnerID, networkName, update.ClientID); err != nil {
+			logger.Log(0, "failed to associate client", update.ClientID, "to user", oldExtClient.OwnerID)
 		}
 		}
 	}
 	}
 	// == END PRO ==
 	// == END PRO ==
 
 
-	var changedEnabled = (newExtClient.Enabled != oldExtClient.Enabled) || // indicates there was a change in enablement
-		len(newExtClient.ACLs) != len(oldExtClient.ACLs)
+	var changedEnabled = (update.Enabled != oldExtClient.Enabled) // indicates there was a change in enablement
 	// extra var need as logic.Update changes oldExtClient
 	// extra var need as logic.Update changes oldExtClient
 	currentClient := oldExtClient
 	currentClient := oldExtClient
-	newclient, err := logic.UpdateExtClient(newExtClient.ClientID, params["network"], newExtClient.Enabled, &oldExtClient, newExtClient.ACLs)
+	newclient, replaceOldClient, err := logic.UpdateExtClient(&oldExtClient, &update)
 	if err != nil {
 	if err != nil {
 		logger.Log(0, r.Header.Get("user"),
 		logger.Log(0, r.Header.Get("user"),
 			fmt.Sprintf("failed to update ext client [%s], network [%s]: %v",
 			fmt.Sprintf("failed to update ext client [%s], network [%s]: %v",
@@ -497,23 +490,30 @@ func updateExtClient(w http.ResponseWriter, r *http.Request) {
 		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
 		logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
 		return
 		return
 	}
 	}
-	logger.Log(0, r.Header.Get("user"), "updated ext client", newExtClient.ClientID)
-	if changedEnabled { // need to send a peer update to the ingress node as enablement of one of it's clients has changed
+	logger.Log(0, r.Header.Get("user"), "updated ext client", update.ClientID)
+
+	w.WriteHeader(http.StatusOK)
+	json.NewEncoder(w).Encode(newclient)
+
+	go func() {
 		if ingressNode, err := logic.GetNodeByID(newclient.IngressGatewayID); err == nil {
 		if ingressNode, err := logic.GetNodeByID(newclient.IngressGatewayID); err == nil {
-			if err = mq.PublishPeerUpdate(); err != nil {
-				logger.Log(1, "error setting ext peers on", ingressNode.ID.String(), ":", err.Error())
+			if ingressHost, err := logic.GetHost(ingressNode.HostID.String()); err == nil {
+				if replaceOldClient || !update.Enabled {
+					mq.BroadcastDelExtClient(ingressHost, &ingressNode, []models.ExtClient{currentClient})
+				}
+				if replaceOldClient || changedEnabled {
+					// broadcast update
+					mq.BroadcastExtClient(ingressHost, &ingressNode)
+				}
 			}
 			}
 		}
 		}
-	}
-	w.WriteHeader(http.StatusOK)
-	json.NewEncoder(w).Encode(newclient)
-	if changedID {
-		go func() {
-			if err := mq.PublishExtClientDNSUpdate(currentClient, newExtClient, networkName); err != nil {
+		if changedID {
+			if err := mq.PublishExtClientDNSUpdate(currentClient, *newclient, networkName); err != nil {
 				logger.Log(1, "error pubishing dns update for extcient update", err.Error())
 				logger.Log(1, "error pubishing dns update for extcient update", err.Error())
 			}
 			}
-		}()
-	}
+		}
+	}()
+
 }
 }
 
 
 // swagger:route DELETE /api/extclients/{network}/{clientid} ext_client deleteExtClient
 // swagger:route DELETE /api/extclients/{network}/{clientid} ext_client deleteExtClient
@@ -579,9 +579,11 @@ func deleteExtClient(w http.ResponseWriter, r *http.Request) {
 	}
 	}
 
 
 	go func() {
 	go func() {
-		if err := mq.PublishDeletedClientPeerUpdate(&extclient); err != nil {
-			logger.Log(1, "error setting ext peers on "+ingressnode.ID.String()+": "+err.Error())
+		ingressHost, err := logic.GetHost(ingressnode.HostID.String())
+		if err == nil {
+			go mq.BroadcastDelExtClient(ingressHost, &ingressnode, []models.ExtClient{extclient})
 		}
 		}
+
 		if err = mq.PublishDeleteExtClientDNS(&extclient); err != nil {
 		if err = mq.PublishDeleteExtClientDNS(&extclient); err != nil {
 			logger.Log(1, "error publishing dns update for extclient deletion", err.Error())
 			logger.Log(1, "error publishing dns update for extclient deletion", err.Error())
 		}
 		}
@@ -648,3 +650,35 @@ func doesUserOwnClient(username, clientID, network string) (bool, bool) {
 
 
 	return false, logic.StringSliceContains(netUser.Clients, clientID)
 	return false, logic.StringSliceContains(netUser.Clients, clientID)
 }
 }
+
+// validateExtClient	Validates the extclient object
+func validateExtClient(extclient *models.ExtClient, customExtClient *models.CustomExtClient) error {
+	//validate clientid
+	if customExtClient.ClientID != "" && !validName(customExtClient.ClientID) {
+		return errInvalidExtClientID
+	}
+	extclient.ClientID = customExtClient.ClientID
+	if len(customExtClient.PublicKey) > 0 {
+		if _, err := wgtypes.ParseKey(customExtClient.PublicKey); err != nil {
+			return errInvalidExtClientPubKey
+		}
+		extclient.PublicKey = customExtClient.PublicKey
+	}
+	//validate extra ips
+	if len(customExtClient.ExtraAllowedIPs) > 0 {
+		for _, ip := range customExtClient.ExtraAllowedIPs {
+			if _, _, err := net.ParseCIDR(ip); err != nil {
+				return errInvalidExtClientExtraIP
+			}
+		}
+		extclient.ExtraAllowedIPs = customExtClient.ExtraAllowedIPs
+	}
+	//validate DNS
+	if customExtClient.DNS != "" {
+		if ip := net.ParseIP(customExtClient.DNS); ip == nil {
+			return errInvalidExtClientDNS
+		}
+		extclient.DNS = customExtClient.DNS
+	}
+	return nil
+}

+ 2 - 3
controllers/hosts.go

@@ -263,6 +263,7 @@ func addHostToNetwork(w http.ResponseWriter, r *http.Request) {
 			Action: models.RequestAck,
 			Action: models.RequestAck,
 			Host:   *currHost,
 			Host:   *currHost,
 		})
 		})
+		go mq.BroadcastAddOrUpdatePeer(currHost, newNode, false)
 	}
 	}
 
 
 	logger.Log(2, r.Header.Get("user"), fmt.Sprintf("added host %s to network %s", currHost.Name, network))
 	logger.Log(2, r.Header.Get("user"), fmt.Sprintf("added host %s to network %s", currHost.Name, network))
@@ -314,9 +315,7 @@ func deleteHostFromNetwork(w http.ResponseWriter, r *http.Request) {
 
 
 	runUpdates(node, false)
 	runUpdates(node, false)
 	go func() { // notify of peer change
 	go func() { // notify of peer change
-		if err := mq.PublishPeerUpdate(); err != nil {
-			logger.Log(1, "error publishing peer update ", err.Error())
-		}
+		mq.BroadcastDelPeer(currHost, network)
 		if err := mq.PublishDNSDelete(node, currHost); err != nil {
 		if err := mq.PublishDNSDelete(node, currHost); err != nil {
 			logger.Log(1, "error publishing dns update", err.Error())
 			logger.Log(1, "error publishing dns update", err.Error())
 		}
 		}

+ 2 - 3
controllers/network.go

@@ -144,9 +144,8 @@ func updateNetworkACL(w http.ResponseWriter, r *http.Request) {
 
 
 	// send peer updates
 	// send peer updates
 	if servercfg.IsMessageQueueBackend() {
 	if servercfg.IsMessageQueueBackend() {
-		if err = mq.PublishPeerUpdate(); err != nil {
-			logger.Log(0, "failed to publish peer update after ACL update on", netname)
-		}
+		go mq.BroadcastAclUpdate(netname)
+
 	}
 	}
 	w.WriteHeader(http.StatusOK)
 	w.WriteHeader(http.StatusOK)
 	json.NewEncoder(w).Encode(newNetACL)
 	json.NewEncoder(w).Encode(newNetACL)

+ 12 - 26
controllers/node.go

@@ -520,13 +520,10 @@ func createIngressGateway(w http.ResponseWriter, r *http.Request) {
 	w.Header().Set("Content-Type", "application/json")
 	w.Header().Set("Content-Type", "application/json")
 	nodeid := params["nodeid"]
 	nodeid := params["nodeid"]
 	netid := params["network"]
 	netid := params["network"]
-	type failoverData struct {
-		Failover bool `json:"failover"`
-	}
-	var failoverReqBody failoverData
-	json.NewDecoder(r.Body).Decode(&failoverReqBody)
+	var request models.IngressRequest
+	json.NewDecoder(r.Body).Decode(&request)
 
 
-	node, err := logic.CreateIngressGateway(netid, nodeid, failoverReqBody.Failover)
+	node, err := logic.CreateIngressGateway(netid, nodeid, request)
 	if err != nil {
 	if err != nil {
 		logger.Log(0, r.Header.Get("user"),
 		logger.Log(0, r.Header.Get("user"),
 			fmt.Sprintf("failed to create ingress gateway on node [%s] on network [%s]: %v",
 			fmt.Sprintf("failed to create ingress gateway on node [%s] on network [%s]: %v",
@@ -535,7 +532,7 @@ func createIngressGateway(w http.ResponseWriter, r *http.Request) {
 		return
 		return
 	}
 	}
 
 
-	if servercfg.Is_EE && failoverReqBody.Failover {
+	if servercfg.Is_EE && request.Failover {
 		if err = logic.EnterpriseResetFailoverFunc(node.Network); err != nil {
 		if err = logic.EnterpriseResetFailoverFunc(node.Network); err != nil {
 			logger.Log(1, "failed to reset failover list during failover create", node.ID.String(), node.Network)
 			logger.Log(1, "failed to reset failover list during failover create", node.ID.String(), node.Network)
 		}
 		}
@@ -588,12 +585,7 @@ func deleteIngressGateway(w http.ResponseWriter, r *http.Request) {
 	if len(removedClients) > 0 {
 	if len(removedClients) > 0 {
 		host, err := logic.GetHost(node.HostID.String())
 		host, err := logic.GetHost(node.HostID.String())
 		if err == nil {
 		if err == nil {
-			go mq.PublishSingleHostPeerUpdate(
-				context.Background(),
-				host,
-				nil,
-				removedClients[:],
-			)
+			mq.BroadcastDelExtClient(host, &node, removedClients)
 		}
 		}
 	}
 	}
 
 
@@ -687,11 +679,7 @@ func updateNode(w http.ResponseWriter, r *http.Request) {
 	json.NewEncoder(w).Encode(apiNode)
 	json.NewEncoder(w).Encode(apiNode)
 	runUpdates(newNode, ifaceDelta)
 	runUpdates(newNode, ifaceDelta)
 	go func(aclUpdate bool, newNode *models.Node) {
 	go func(aclUpdate bool, newNode *models.Node) {
-		if aclUpdate {
-			if err := mq.PublishPeerUpdate(); err != nil {
-				logger.Log(0, "error during node ACL update for node", newNode.ID.String())
-			}
-		}
+		mq.BroadcastAddOrUpdatePeer(host, newNode, true)
 		if err := mq.PublishReplaceDNS(&currentNode, newNode, host); err != nil {
 		if err := mq.PublishReplaceDNS(&currentNode, newNode, host); err != nil {
 			logger.Log(1, "failed to publish dns update", err.Error())
 			logger.Log(1, "failed to publish dns update", err.Error())
 		}
 		}
@@ -746,19 +734,17 @@ func deleteNode(w http.ResponseWriter, r *http.Request) {
 	}
 	}
 	go func(deletedNode *models.Node, fromNode bool) { // notify of peer change
 	go func(deletedNode *models.Node, fromNode bool) { // notify of peer change
 		var err error
 		var err error
-		if fromNode {
-			err = mq.PublishDeletedNodePeerUpdate(deletedNode)
-		} else {
-			err = mq.PublishPeerUpdate()
-		}
+		host, err := logic.GetHost(node.HostID.String())
 		if err != nil {
 		if err != nil {
-			logger.Log(1, "error publishing peer update ", err.Error())
+			logger.Log(1, "failed to retrieve host for node", node.ID.String(), err.Error())
+			return
 		}
 		}
 
 
-		host, err := logic.GetHost(node.HostID.String())
+		err = mq.BroadcastDelPeer(host, deletedNode.Network)
 		if err != nil {
 		if err != nil {
-			logger.Log(1, "failed to retrieve host for node", node.ID.String(), err.Error())
+			logger.Log(1, "error publishing peer update ", err.Error())
 		}
 		}
+
 		if err := mq.PublishDNSDelete(&node, host); err != nil {
 		if err := mq.PublishDNSDelete(&node, host); err != nil {
 			logger.Log(1, "error publishing dns update", err.Error())
 			logger.Log(1, "error publishing dns update", err.Error())
 		}
 		}

+ 15 - 3
controllers/regex.go

@@ -6,11 +6,23 @@ import (
 )
 )
 
 
 var (
 var (
-	errInvalidExtClientPubKey = errors.New("incorrect ext client public key")
-	errInvalidExtClientID     = errors.New("ext client ID must be alphanumderic and/or dashes")
+	errInvalidExtClientPubKey  = errors.New("incorrect ext client public key")
+	errInvalidExtClientID      = errors.New("ext client ID must be alphanumderic and/or dashes and less that 15 chars")
+	errInvalidExtClientExtraIP = errors.New("ext client extra ip must be a valid cidr")
+	errInvalidExtClientDNS     = errors.New("ext client dns must be a valid ip address")
 )
 )
 
 
 // allow only dashes and alphaneumeric for ext client and node names
 // allow only dashes and alphaneumeric for ext client and node names
 func validName(name string) bool {
 func validName(name string) bool {
-	return regexp.MustCompile("^[a-zA-Z0-9-]+$").MatchString(name)
+	reg, err := regexp.Compile("^[a-zA-Z0-9-]+$")
+	if err != nil {
+		return false
+	}
+	if !reg.MatchString(name) {
+		return false
+	}
+	if len(name) > 15 {
+		return false
+	}
+	return true
 }
 }

+ 51 - 0
controllers/regex_test.go

@@ -0,0 +1,51 @@
+package controller
+
+import "testing"
+
+// TestValidName tests the validName function
+func TestValidName(t *testing.T) {
+	type args struct {
+		Name string
+	}
+	tests := []struct {
+		Name string
+		Args args
+		Want bool
+	}{
+		{
+			Name: "validName",
+			Args: args{
+				Name: "TestvalidName",
+			},
+			Want: true,
+		},
+		{
+			Name: "invalidName",
+			Args: args{
+				Name: "Test*Name",
+			},
+			Want: false,
+		},
+		{
+			Name: "nametoolong",
+			Args: args{
+				Name: "TestvalidNameTestvalidName",
+			},
+			Want: false,
+		},
+		{
+			Name: "maxlength",
+			Args: args{
+				Name: "123456789012345",
+			},
+			Want: true,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.Name, func(t *testing.T) {
+			if got := validName(tt.Args.Name); got != tt.Want {
+				t.Errorf("validName() = %v, want %v", got, tt.Want)
+			}
+		})
+	}
+}

+ 9 - 9
docker/Caddyfile

@@ -1,10 +1,10 @@
 # Dashboard
 # Dashboard
-https://dashboard.NETMAKER_BASE_DOMAIN {
+https://dashboard.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	# Apply basic security headers
 	# Apply basic security headers
 	header {
 	header {
-		# Enable cross origin access to *.NETMAKER_BASE_DOMAIN
-		Access-Control-Allow-Origin *.NETMAKER_BASE_DOMAIN
+		# Enable cross origin access to *.{$NM_DOMAIN}
+		Access-Control-Allow-Origin *.{$NM_DOMAIN}
 		# Enable HTTP Strict Transport Security (HSTS)
 		# Enable HTTP Strict Transport Security (HSTS)
 		Strict-Transport-Security "max-age=31536000;"
 		Strict-Transport-Security "max-age=31536000;"
 		# Enable cross-site filter (XSS) and tell browser to block detected attacks
 		# Enable cross-site filter (XSS) and tell browser to block detected attacks
@@ -21,31 +21,31 @@ https://dashboard.NETMAKER_BASE_DOMAIN {
 }
 }
 
 
 # API
 # API
-https://api.NETMAKER_BASE_DOMAIN {
+https://api.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy http://netmaker:8081
 	reverse_proxy http://netmaker:8081
 }
 }
 
 
 # STUN
 # STUN
-https://stun.NETMAKER_BASE_DOMAIN {
+https://stun.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy netmaker:3478
 	reverse_proxy netmaker:3478
 }
 }
 
 
 # TURN
 # TURN
-https://turn.NETMAKER_BASE_DOMAIN {
+https://turn.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy host.docker.internal:3479
 	reverse_proxy host.docker.internal:3479
 }
 }
 
 
 # TURN API
 # TURN API
-https://turnapi.NETMAKER_BASE_DOMAIN {
+https://turnapi.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
-    reverse_proxy http://host.docker.internal:8089
+	reverse_proxy http://host.docker.internal:8089
 }
 }
 
 
 # MQ
 # MQ
-wss://broker.NETMAKER_BASE_DOMAIN {
+wss://broker.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy ws://mq:8883 # For EMQX websockets use `reverse_proxy ws://mq:8083`
 	reverse_proxy ws://mq:8883 # For EMQX websockets use `reverse_proxy ws://mq:8083`
 }
 }

+ 11 - 11
docker/Caddyfile-EE

@@ -1,10 +1,10 @@
 # Dashboard
 # Dashboard
-https://dashboard.NETMAKER_BASE_DOMAIN {
+https://dashboard.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	# Apply basic security headers
 	# Apply basic security headers
 	header {
 	header {
-		# Enable cross origin access to *.NETMAKER_BASE_DOMAIN
-		Access-Control-Allow-Origin *.NETMAKER_BASE_DOMAIN
+		# Enable cross origin access to *.{$NM_DOMAIN}
+		Access-Control-Allow-Origin *.{$NM_DOMAIN}
 		# Enable HTTP Strict Transport Security (HSTS)
 		# Enable HTTP Strict Transport Security (HSTS)
 		Strict-Transport-Security "max-age=31536000;"
 		Strict-Transport-Security "max-age=31536000;"
 		# Enable cross-site filter (XSS) and tell browser to block detected attacks
 		# Enable cross-site filter (XSS) and tell browser to block detected attacks
@@ -21,49 +21,49 @@ https://dashboard.NETMAKER_BASE_DOMAIN {
 }
 }
 
 
 # Netmaker Exporter
 # Netmaker Exporter
-https://netmaker-exporter.NETMAKER_BASE_DOMAIN {
+https://netmaker-exporter.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy http://netmaker-exporter:8085
 	reverse_proxy http://netmaker-exporter:8085
 }
 }
 
 
 # Prometheus
 # Prometheus
-https://prometheus.NETMAKER_BASE_DOMAIN {
+https://prometheus.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy http://prometheus:9090
 	reverse_proxy http://prometheus:9090
 }
 }
 
 
 # Grafana
 # Grafana
-https://grafana.NETMAKER_BASE_DOMAIN {
+https://grafana.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy http://grafana:3000
 	reverse_proxy http://grafana:3000
 }
 }
 
 
 # API
 # API
-https://api.NETMAKER_BASE_DOMAIN {
+https://api.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy http://netmaker:8081
 	reverse_proxy http://netmaker:8081
 }
 }
 
 
 # STUN
 # STUN
-https://stun.NETMAKER_BASE_DOMAIN {
+https://stun.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy netmaker:3478
 	reverse_proxy netmaker:3478
 }
 }
 
 
 # TURN
 # TURN
-https://turn.NETMAKER_BASE_DOMAIN {
+https://turn.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy host.docker.internal:3479
 	reverse_proxy host.docker.internal:3479
 }
 }
 
 
 # TURN API
 # TURN API
-https://turnapi.NETMAKER_BASE_DOMAIN {
+https://turnapi.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy http://host.docker.internal:8089
 	reverse_proxy http://host.docker.internal:8089
 }
 }
 
 
 # MQ
 # MQ
-wss://broker.NETMAKER_BASE_DOMAIN {
+wss://broker.{$NM_DOMAIN} {
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	tls /root/certs/fullchain.pem /root/certs/privkey.pem
 	reverse_proxy ws://mq:8883
 	reverse_proxy ws://mq:8883
 }
 }

+ 1 - 2
functions/helpers_test.go

@@ -18,8 +18,7 @@ var (
 		NetID: "not-a-network",
 		NetID: "not-a-network",
 	}
 	}
 	testExternalClient = &models.ExtClient{
 	testExternalClient = &models.ExtClient{
-		ClientID:    "testExtClient",
-		Description: "ext client for testing",
+		ClientID: "testExtClient",
 	}
 	}
 )
 )
 
 

+ 4 - 4
go.mod

@@ -15,10 +15,10 @@ require (
 	github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
 	github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
 	github.com/stretchr/testify v1.8.2
 	github.com/stretchr/testify v1.8.2
 	github.com/txn2/txeh v1.4.0
 	github.com/txn2/txeh v1.4.0
-	golang.org/x/crypto v0.8.0
-	golang.org/x/net v0.9.0 // indirect
-	golang.org/x/oauth2 v0.7.0
-	golang.org/x/sys v0.7.0 // indirect
+	golang.org/x/crypto v0.9.0
+	golang.org/x/net v0.10.0 // indirect
+	golang.org/x/oauth2 v0.8.0
+	golang.org/x/sys v0.8.0 // indirect
 	golang.org/x/text v0.9.0 // indirect
 	golang.org/x/text v0.9.0 // indirect
 	golang.zx2c4.com/wireguard v0.0.0-20220920152132-bb719d3a6e2c // indirect
 	golang.zx2c4.com/wireguard v0.0.0-20220920152132-bb719d3a6e2c // indirect
 	golang.zx2c4.com/wireguard/wgctrl v0.0.0-20220324164955-056925b7df31
 	golang.zx2c4.com/wireguard/wgctrl v0.0.0-20220324164955-056925b7df31

+ 8 - 8
go.sum

@@ -134,8 +134,8 @@ golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8U
 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20220208050332-20e1d8d225ab/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
 golang.org/x/crypto v0.0.0-20220208050332-20e1d8d225ab/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
-golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
-golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
+golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
+golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
 golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
 golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
 golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
 golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
 golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
 golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
@@ -151,11 +151,11 @@ golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su
 golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
 golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
 golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
 golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
 golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
 golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
-golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
-golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
+golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
+golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
 golang.org/x/oauth2 v0.3.0/go.mod h1:rQrIauxkUhJ6CuwEXwymO2/eh4xz2ZWF1nBkcxS+tGk=
 golang.org/x/oauth2 v0.3.0/go.mod h1:rQrIauxkUhJ6CuwEXwymO2/eh4xz2ZWF1nBkcxS+tGk=
-golang.org/x/oauth2 v0.7.0 h1:qe6s0zUXlPX80/dITx3440hWZ7GwMwgDDyrSGTPJG/g=
-golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4=
+golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8=
+golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE=
 golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -176,8 +176,8 @@ golang.org/x/sys v0.0.0-20220207234003-57398862261d/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
-golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
 golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
 golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=

+ 1 - 1
k8s/client/netclient-daemonset.yaml

@@ -16,7 +16,7 @@ spec:
       hostNetwork: true
       hostNetwork: true
       containers:
       containers:
       - name: netclient
       - name: netclient
-        image: gravitl/netclient:v0.19.0
+        image: gravitl/netclient:v0.20.0
         env:
         env:
         - name: TOKEN
         - name: TOKEN
           value: "TOKEN_VALUE"
           value: "TOKEN_VALUE"

+ 1 - 1
k8s/client/netclient.yaml

@@ -28,7 +28,7 @@ spec:
       #           - "<node label value>"
       #           - "<node label value>"
       containers:
       containers:
       - name: netclient
       - name: netclient
-        image: gravitl/netclient:v0.19.0
+        image: gravitl/netclient:v0.20.0
         env:
         env:
         - name: TOKEN
         - name: TOKEN
           value: "TOKEN_VALUE"
           value: "TOKEN_VALUE"

+ 1 - 1
k8s/server/netmaker-server.yaml

@@ -79,7 +79,7 @@ spec:
           value: "Kubernetes"
           value: "Kubernetes"
         - name: VERBOSITY
         - name: VERBOSITY
           value: "3"
           value: "3"
-        image: gravitl/netmaker:v0.19.0
+        image: gravitl/netmaker:v0.20.0
         imagePullPolicy: Always
         imagePullPolicy: Always
         name: netmaker
         name: netmaker
         ports:
         ports:

+ 1 - 1
k8s/server/netmaker-ui.yaml

@@ -15,7 +15,7 @@ spec:
     spec:
     spec:
       containers:
       containers:
       - name: netmaker-ui
       - name: netmaker-ui
-        image: gravitl/netmaker-ui:v0.19.0
+        image: gravitl/netmaker-ui:v0.20.0
         ports:
         ports:
         - containerPort: 443
         - containerPort: 443
         env:
         env:

+ 24 - 25
logic/extpeers.go

@@ -174,6 +174,11 @@ func CreateExtClient(extclient *models.ExtClient) error {
 	}
 	}
 
 
 	extclient.LastModified = time.Now().Unix()
 	extclient.LastModified = time.Now().Unix()
+	return SaveExtClient(extclient)
+}
+
+// SaveExtClient - saves an ext client to database
+func SaveExtClient(extclient *models.ExtClient) error {
 	key, err := GetRecordKey(extclient.ClientID, extclient.Network)
 	key, err := GetRecordKey(extclient.ClientID, extclient.Network)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
@@ -188,35 +193,29 @@ func CreateExtClient(extclient *models.ExtClient) error {
 	return SetNetworkNodesLastModified(extclient.Network)
 	return SetNetworkNodesLastModified(extclient.Network)
 }
 }
 
 
-// UpdateExtClient - only supports name changes right now
-func UpdateExtClient(newclientid string, network string, enabled bool, client *models.ExtClient, newACLs map[string]struct{}) (*models.ExtClient, error) {
-	err := DeleteExtClient(network, client.ClientID)
+// UpdateExtClient - updates an ext client with new values
+func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) (*models.ExtClient, bool, error) {
+	new := old
+	replaceOldClient := false
+	err := DeleteExtClient(old.Network, old.ClientID)
 	if err != nil {
 	if err != nil {
-		return client, err
+		return new, replaceOldClient, err
 	}
 	}
-	if newclientid != client.ClientID { // name change only
-		client.ClientID = newclientid
-		client.LastModified = time.Now().Unix()
-		data, err := json.Marshal(&client)
-		if err != nil {
-			return nil, err
-		}
-		key, err := GetRecordKey(client.ClientID, client.Network)
-		if err != nil {
-			return nil, err
-		}
-		if err = database.Insert(key, string(data), database.EXT_CLIENT_TABLE_NAME); err != nil {
-			return client, err
-		}
-		return client, nil
+	new.ClientID = update.ClientID
+	if update.PublicKey != "" && old.PublicKey != update.PublicKey {
+		replaceOldClient = true
+		new.PublicKey = update.PublicKey
+	}
+	if update.DNS != "" && update.DNS != old.DNS {
+		new.DNS = update.DNS
+	}
+	if update.Enabled != old.Enabled {
+		new.Enabled = update.Enabled
 	}
 	}
-	client.ClientID = newclientid
-	client.Enabled = enabled
-	SetClientACLs(client, newACLs)
-	if err = CreateExtClient(client); err != nil {
-		return client, err
+	if update.ExtraAllowedIPs != nil && StringDifference(old.ExtraAllowedIPs, update.ExtraAllowedIPs) != nil {
+		new.ExtraAllowedIPs = update.ExtraAllowedIPs
 	}
 	}
-	return client, err
+	return new, replaceOldClient, CreateExtClient(new)
 }
 }
 
 
 // GetExtClientsByID - gets the clients of attached gateway
 // GetExtClientsByID - gets the clients of attached gateway

+ 3 - 2
logic/gateway.go

@@ -96,7 +96,7 @@ func DeleteEgressGateway(network, nodeid string) (models.Node, error) {
 }
 }
 
 
 // CreateIngressGateway - creates an ingress gateway
 // CreateIngressGateway - creates an ingress gateway
-func CreateIngressGateway(netid string, nodeid string, failover bool) (models.Node, error) {
+func CreateIngressGateway(netid string, nodeid string, ingress models.IngressRequest) (models.Node, error) {
 
 
 	node, err := GetNodeByID(nodeid)
 	node, err := GetNodeByID(nodeid)
 	if err != nil {
 	if err != nil {
@@ -120,8 +120,9 @@ func CreateIngressGateway(netid string, nodeid string, failover bool) (models.No
 	node.IsIngressGateway = true
 	node.IsIngressGateway = true
 	node.IngressGatewayRange = network.AddressRange
 	node.IngressGatewayRange = network.AddressRange
 	node.IngressGatewayRange6 = network.AddressRange6
 	node.IngressGatewayRange6 = network.AddressRange6
+	node.IngressDNS = ingress.ExtclientDNS
 	node.SetLastModified()
 	node.SetLastModified()
-	if failover && servercfg.Is_EE {
+	if ingress.Failover && servercfg.Is_EE {
 		node.Failover = true
 		node.Failover = true
 	}
 	}
 	data, err := json.Marshal(&node)
 	data, err := json.Marshal(&node)

+ 10 - 12
logic/peers.go

@@ -124,7 +124,7 @@ func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host
 	peerIndexMap := make(map[string]int)
 	peerIndexMap := make(map[string]int)
 	for _, nodeID := range host.Nodes {
 	for _, nodeID := range host.Nodes {
 		nodeID := nodeID
 		nodeID := nodeID
-		node, err := GetNodeByID(nodeID)
+		node, err := GetNodeByID(nodeID) (should be simple change)
 		if err != nil {
 		if err != nil {
 			continue
 			continue
 		}
 		}
@@ -205,7 +205,7 @@ func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host
 
 
 				if node.IsIngressGateway || node.IsEgressGateway {
 				if node.IsIngressGateway || node.IsEgressGateway {
 					if peer.IsIngressGateway {
 					if peer.IsIngressGateway {
-						_, extPeerIDAndAddrs, err := getExtPeers(&peer)
+						_, extPeerIDAndAddrs, err := GetExtPeers(&peer)
 						if err == nil {
 						if err == nil {
 							for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
 							for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
 								extPeerIdAndAddr := extPeerIdAndAddr
 								extPeerIdAndAddr := extPeerIdAndAddr
@@ -276,7 +276,7 @@ func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host
 					hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()] = models.IDandAddr{
 					hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()] = models.IDandAddr{
 						ID:              peer.ID.String(),
 						ID:              peer.ID.String(),
 						Address:         peer.PrimaryAddress(),
 						Address:         peer.PrimaryAddress(),
-						Name:            peerHost.Name,
+						Name:            peerHost.Name, (should be simple change)
 						Network:         peer.Network,
 						Network:         peer.Network,
 						ProxyListenPort: peerHost.ProxyListenPort,
 						ProxyListenPort: peerHost.ProxyListenPort,
 					}
 					}
@@ -287,7 +287,7 @@ func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host
 		var extPeers []wgtypes.PeerConfig
 		var extPeers []wgtypes.PeerConfig
 		var extPeerIDAndAddrs []models.IDandAddr
 		var extPeerIDAndAddrs []models.IDandAddr
 		if node.IsIngressGateway {
 		if node.IsIngressGateway {
-			extPeers, extPeerIDAndAddrs, err = getExtPeers(&node)
+			extPeers, extPeerIDAndAddrs, err = GetExtPeers(&node)
 			if err == nil {
 			if err == nil {
 				for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
 				for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
 					extPeerIdAndAddr := extPeerIdAndAddr
 					extPeerIdAndAddr := extPeerIdAndAddr
@@ -371,7 +371,7 @@ func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host
 			deletedClient := deletedClients[i]
 			deletedClient := deletedClients[i]
 			key, err := wgtypes.ParseKey(deletedClient.PublicKey)
 			key, err := wgtypes.ParseKey(deletedClient.PublicKey)
 			if err == nil {
 			if err == nil {
-				hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, wgtypes.PeerConfig{
+				hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, wgtypes.PeerConfig{ (should be simple change)
 					PublicKey: key,
 					PublicKey: key,
 					Remove:    true,
 					Remove:    true,
 				})
 				})
@@ -385,14 +385,12 @@ func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host
 // GetPeerListenPort - given a host, retrieve it's appropriate listening port
 // GetPeerListenPort - given a host, retrieve it's appropriate listening port
 func GetPeerListenPort(host *models.Host) int {
 func GetPeerListenPort(host *models.Host) int {
 	peerPort := host.ListenPort
 	peerPort := host.ListenPort
+	if host.ProxyEnabled && host.ProxyListenPort != 0 {
+		peerPort = host.ProxyListenPort
+	}
 	if host.PublicListenPort != 0 {
 	if host.PublicListenPort != 0 {
 		peerPort = host.PublicListenPort
 		peerPort = host.PublicListenPort
 	}
 	}
-	if host.ProxyEnabled {
-		if host.ProxyListenPort != 0 {
-			peerPort = host.ProxyListenPort
-		}
-	}
 	return peerPort
 	return peerPort
 }
 }
 
 
@@ -405,7 +403,7 @@ func GetProxyListenPort(host *models.Host) int {
 	return proxyPort
 	return proxyPort
 }
 }
 
 
-func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, error) {
+func GetExtPeers(node *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, error) {
 	var peers []wgtypes.PeerConfig
 	var peers []wgtypes.PeerConfig
 	var idsAndAddr []models.IDandAddr
 	var idsAndAddr []models.IDandAddr
 	extPeers, err := GetNetworkExtClients(node.Network)
 	extPeers, err := GetNetworkExtClients(node.Network)
@@ -540,7 +538,7 @@ func GetAllowedIPs(node, peer *models.Node, metrics *models.Metrics) []net.IPNet
 
 
 	// handle ingress gateway peers
 	// handle ingress gateway peers
 	if peer.IsIngressGateway {
 	if peer.IsIngressGateway {
-		extPeers, _, err := getExtPeers(peer)
+		extPeers, _, err := GetExtPeers(peer)
 		if err != nil {
 		if err != nil {
 			logger.Log(2, "could not retrieve ext peers for ", peer.ID.String(), err.Error())
 			logger.Log(2, "could not retrieve ext peers for ", peer.ID.String(), err.Error())
 		}
 		}

+ 1 - 1
logic/relay.go

@@ -30,7 +30,6 @@ func CreateRelay(relay models.RelayRequest) ([]models.Client, models.Node, error
 		return relayedClients, models.Node{}, err
 		return relayedClients, models.Node{}, err
 	}
 	}
 	node.IsRelay = true
 	node.IsRelay = true
-
 	node.RelayedNodes = relay.RelayedNodes
 	node.RelayedNodes = relay.RelayedNodes
 	node.SetLastModified()
 	node.SetLastModified()
 	nodeData, err := json.Marshal(&node)
 	nodeData, err := json.Marshal(&node)
@@ -113,6 +112,7 @@ func DeleteRelay(network, nodeid string) ([]models.Client, models.Node, error) {
 	if err != nil {
 	if err != nil {
 		return returnClients, models.Node{}, err
 		return returnClients, models.Node{}, err
 	}
 	}
+
 	returnClients = SetRelayedNodes(false, nodeid, node.RelayedNodes)
 	returnClients = SetRelayedNodes(false, nodeid, node.RelayedNodes)
 	node.IsRelay = false
 	node.IsRelay = false
 	node.RelayedNodes = []string{}
 	node.RelayedNodes = []string{}

+ 1 - 1
main.go

@@ -28,7 +28,7 @@ import (
 	stunserver "github.com/gravitl/netmaker/stun-server"
 	stunserver "github.com/gravitl/netmaker/stun-server"
 )
 )
 
 
-var version = "v0.19.1"
+var version = "v0.20.0"
 
 
 // Start DB Connection and start API Request Handler
 // Start DB Connection and start API Request Handler
 func main() {
 func main() {

+ 3 - 0
models/api_node.go

@@ -33,6 +33,7 @@ type ApiNode struct {
 	EgressGatewayNatEnabled bool     `json:"egressgatewaynatenabled"`
 	EgressGatewayNatEnabled bool     `json:"egressgatewaynatenabled"`
 	FailoverNode            string   `json:"failovernode"`
 	FailoverNode            string   `json:"failovernode"`
 	DNSOn                   bool     `json:"dnson"`
 	DNSOn                   bool     `json:"dnson"`
+	IngressDns              string   `json:"ingressdns"`
 	Server                  string   `json:"server"`
 	Server                  string   `json:"server"`
 	InternetGateway         string   `json:"internetgateway"`
 	InternetGateway         string   `json:"internetgateway"`
 	Connected               bool     `json:"connected"`
 	Connected               bool     `json:"connected"`
@@ -64,6 +65,7 @@ func (a *ApiNode) ConvertToServerNode(currentNode *Node) *Node {
 	convertedNode.IngressGatewayRange = currentNode.IngressGatewayRange
 	convertedNode.IngressGatewayRange = currentNode.IngressGatewayRange
 	convertedNode.IngressGatewayRange6 = currentNode.IngressGatewayRange6
 	convertedNode.IngressGatewayRange6 = currentNode.IngressGatewayRange6
 	convertedNode.DNSOn = a.DNSOn
 	convertedNode.DNSOn = a.DNSOn
+	convertedNode.IngressDNS = a.IngressDns
 	convertedNode.EgressGatewayRequest = currentNode.EgressGatewayRequest
 	convertedNode.EgressGatewayRequest = currentNode.EgressGatewayRequest
 	convertedNode.EgressGatewayNatEnabled = currentNode.EgressGatewayNatEnabled
 	convertedNode.EgressGatewayNatEnabled = currentNode.EgressGatewayNatEnabled
 	convertedNode.PersistentKeepalive = time.Second * time.Duration(a.PersistentKeepalive)
 	convertedNode.PersistentKeepalive = time.Second * time.Duration(a.PersistentKeepalive)
@@ -152,6 +154,7 @@ func (nm *Node) ConvertToAPINode() *ApiNode {
 		apiNode.FailoverNode = ""
 		apiNode.FailoverNode = ""
 	}
 	}
 	apiNode.DNSOn = nm.DNSOn
 	apiNode.DNSOn = nm.DNSOn
+	apiNode.IngressDns = nm.IngressDNS
 	apiNode.Server = nm.Server
 	apiNode.Server = nm.Server
 	apiNode.InternetGateway = nm.InternetGateway.String()
 	apiNode.InternetGateway = nm.InternetGateway.String()
 	if isEmptyAddr(apiNode.InternetGateway) {
 	if isEmptyAddr(apiNode.InternetGateway) {

+ 11 - 1
models/extclient.go

@@ -3,12 +3,13 @@ package models
 // ExtClient - struct for external clients
 // ExtClient - struct for external clients
 type ExtClient struct {
 type ExtClient struct {
 	ClientID               string              `json:"clientid" bson:"clientid"`
 	ClientID               string              `json:"clientid" bson:"clientid"`
-	Description            string              `json:"description" bson:"description"`
 	PrivateKey             string              `json:"privatekey" bson:"privatekey"`
 	PrivateKey             string              `json:"privatekey" bson:"privatekey"`
 	PublicKey              string              `json:"publickey" bson:"publickey"`
 	PublicKey              string              `json:"publickey" bson:"publickey"`
 	Network                string              `json:"network" bson:"network"`
 	Network                string              `json:"network" bson:"network"`
+	DNS                    string              `json:"dns" bson:"dns"`
 	Address                string              `json:"address" bson:"address"`
 	Address                string              `json:"address" bson:"address"`
 	Address6               string              `json:"address6" bson:"address6"`
 	Address6               string              `json:"address6" bson:"address6"`
+	ExtraAllowedIPs        []string            `json:"extraallowedips" bson:"extraallowedips"`
 	IngressGatewayID       string              `json:"ingressgatewayid" bson:"ingressgatewayid"`
 	IngressGatewayID       string              `json:"ingressgatewayid" bson:"ingressgatewayid"`
 	IngressGatewayEndpoint string              `json:"ingressgatewayendpoint" bson:"ingressgatewayendpoint"`
 	IngressGatewayEndpoint string              `json:"ingressgatewayendpoint" bson:"ingressgatewayendpoint"`
 	LastModified           int64               `json:"lastmodified" bson:"lastmodified"`
 	LastModified           int64               `json:"lastmodified" bson:"lastmodified"`
@@ -16,3 +17,12 @@ type ExtClient struct {
 	OwnerID                string              `json:"ownerid" bson:"ownerid"`
 	OwnerID                string              `json:"ownerid" bson:"ownerid"`
 	ACLs                   map[string]struct{} `json:"acls,omitempty" bson:"acls,omitempty"`
 	ACLs                   map[string]struct{} `json:"acls,omitempty" bson:"acls,omitempty"`
 }
 }
+
+// CustomExtClient - struct for CustomExtClient params
+type CustomExtClient struct {
+	ClientID        string   `json:"clientid,omitempty"`
+	PublicKey       string   `json:"publickey,omitempty"`
+	DNS             string   `json:"dns,omitempty"`
+	ExtraAllowedIPs []string `json:"extraallowedips,omitempty"`
+	Enabled         bool     `json:"enabled,omitempty"`
+}

+ 16 - 5
models/host.go

@@ -123,6 +123,16 @@ const (
 	UpdateKeys = "UPDATE_KEYS"
 	UpdateKeys = "UPDATE_KEYS"
 )
 )
 
 
+// SignalAction - turn peer signal action
+type SignalAction string
+
+const (
+	// Disconnect - action to stop using turn connection
+	Disconnect SignalAction = "DISCONNECT"
+	// ConnNegotiation - action to negotiate connection between peers
+	ConnNegotiation SignalAction = "CONNECTION_NEGOTIATION"
+)
+
 // HostUpdate - struct for host update
 // HostUpdate - struct for host update
 type HostUpdate struct {
 type HostUpdate struct {
 	Action HostMqAction
 	Action HostMqAction
@@ -139,11 +149,12 @@ type HostTurnRegister struct {
 
 
 // Signal - struct for signalling peer
 // Signal - struct for signalling peer
 type Signal struct {
 type Signal struct {
-	Server            string `json:"server"`
-	FromHostPubKey    string `json:"from_host_pubkey"`
-	TurnRelayEndpoint string `json:"turn_relay_addr"`
-	ToHostPubKey      string `json:"to_host_pubkey"`
-	Reply             bool   `json:"reply"`
+	Server            string       `json:"server"`
+	FromHostPubKey    string       `json:"from_host_pubkey"`
+	TurnRelayEndpoint string       `json:"turn_relay_addr"`
+	ToHostPubKey      string       `json:"to_host_pubkey"`
+	Reply             bool         `json:"reply"`
+	Action            SignalAction `json:"action"`
 }
 }
 
 
 // RegisterMsg - login message struct for hosts to join via SSO login
 // RegisterMsg - login message struct for hosts to join via SSO login

+ 10 - 5
models/mqtt.go

@@ -61,15 +61,20 @@ type KeyUpdate struct {
 	Interface string `json:"interface" bson:"interface"`
 	Interface string `json:"interface" bson:"interface"`
 }
 }
 
 
-type PeerActionType string
+// PeerMqActionType - peer update action type
+type PeerMqActionType string
 
 
 const (
 const (
-	AddPeer    PeerActionType = "ADD_PEER"
-	UpdatePeer PeerActionType = "UPDATE_PEER"
-	RemovePeer PeerActionType = "REMOVE_PEER"
+	// AddPeer - peer mq action type for adding peers
+	AddPeer PeerMqActionType = "ADD_PEER"
+	// UpdatePeer - peer mq action type for updating peers
+	UpdatePeer PeerMqActionType = "UPDATE_PEER"
+	// RemovePeer - peer mq action type for removing peers
+	RemovePeer PeerMqActionType = "REMOVE_PEER"
 )
 )
 
 
+// PeerAction - struct for mq peer actions
 type PeerAction struct {
 type PeerAction struct {
-	Action PeerActionType       `json:"action"`
+	Action PeerMqActionType     `json:"action"`
 	Peers  []wgtypes.PeerConfig `json:"peers"`
 	Peers  []wgtypes.PeerConfig `json:"peers"`
 }
 }

+ 0 - 1
models/network.go

@@ -23,7 +23,6 @@ type Network struct {
 	IsIPv4              string                `json:"isipv4" bson:"isipv4" validate:"checkyesorno"`
 	IsIPv4              string                `json:"isipv4" bson:"isipv4" validate:"checkyesorno"`
 	IsIPv6              string                `json:"isipv6" bson:"isipv6" validate:"checkyesorno"`
 	IsIPv6              string                `json:"isipv6" bson:"isipv6" validate:"checkyesorno"`
 	DefaultUDPHolePunch string                `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"`
 	DefaultUDPHolePunch string                `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"`
-	DefaultExtClientDNS string                `json:"defaultextclientdns" bson:"defaultextclientdns"`
 	DefaultMTU          int32                 `json:"defaultmtu" bson:"defaultmtu"`
 	DefaultMTU          int32                 `json:"defaultmtu" bson:"defaultmtu"`
 	DefaultACL          string                `json:"defaultacl" bson:"defaultacl" yaml:"defaultacl" validate:"checkyesorno"`
 	DefaultACL          string                `json:"defaultacl" bson:"defaultacl" yaml:"defaultacl" validate:"checkyesorno"`
 	ProSettings         *promodels.ProNetwork `json:"prosettings,omitempty" bson:"prosettings,omitempty" yaml:"prosettings,omitempty"`
 	ProSettings         *promodels.ProNetwork `json:"prosettings,omitempty" bson:"prosettings,omitempty" yaml:"prosettings,omitempty"`

+ 1 - 0
models/node.go

@@ -69,6 +69,7 @@ type CommonNode struct {
 	IsEgressGateway     bool          `json:"isegressgateway" yaml:"isegressgateway"`
 	IsEgressGateway     bool          `json:"isegressgateway" yaml:"isegressgateway"`
 	EgressGatewayRanges []string      `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
 	EgressGatewayRanges []string      `json:"egressgatewayranges" bson:"egressgatewayranges" yaml:"egressgatewayranges"`
 	IsIngressGateway    bool          `json:"isingressgateway" yaml:"isingressgateway"`
 	IsIngressGateway    bool          `json:"isingressgateway" yaml:"isingressgateway"`
+	IngressDNS          string        `json:"ingressdns" yaml:"ingressdns"`
 	IsRelayed           bool          `json:"isrelayed" bson:"isrelayed" yaml:"isrelayed"`
 	IsRelayed           bool          `json:"isrelayed" bson:"isrelayed" yaml:"isrelayed"`
 	RelayedBy           string        `json:"relayedby" bson:"relayedby" yaml:"relayedby"`
 	RelayedBy           string        `json:"relayedby" bson:"relayedby" yaml:"relayedby"`
 	IsRelay             bool          `json:"isrelay" bson:"isrelay" yaml:"isrelay"`
 	IsRelay             bool          `json:"isrelay" bson:"isrelay" yaml:"isrelay"`

+ 6 - 6
models/structs.go

@@ -14,12 +14,6 @@ const (
 	PLACEHOLDER_TOKEN_TEXT = "ACCESS_TOKEN"
 	PLACEHOLDER_TOKEN_TEXT = "ACCESS_TOKEN"
 )
 )
 
 
-// CustomExtClient - struct for CustomExtClient params
-type CustomExtClient struct {
-	ClientID  string `json:"clientid"`
-	PublicKey string `json:"publickey,omitempty"`
-}
-
 // AuthParams - struct for auth params
 // AuthParams - struct for auth params
 type AuthParams struct {
 type AuthParams struct {
 	MacAddress string `json:"macaddress"`
 	MacAddress string `json:"macaddress"`
@@ -170,6 +164,12 @@ type HostRelayRequest struct {
 	RelayedHosts []string `json:"relayed_hosts"`
 	RelayedHosts []string `json:"relayed_hosts"`
 }
 }
 
 
+// IngressRequest - ingress request struct
+type IngressRequest struct {
+	ExtclientDNS string `json:"extclientdns"`
+	Failover     bool   `json:"failover"`
+}
+
 // ServerUpdateData - contains data to configure server
 // ServerUpdateData - contains data to configure server
 // and if it should set peers
 // and if it should set peers
 type ServerUpdateData struct {
 type ServerUpdateData struct {

+ 16 - 3
mq/handlers.go

@@ -59,9 +59,17 @@ func UpdateNode(client mqtt.Client, msg mqtt.Message) {
 		return
 		return
 	}
 	}
 	if ifaceDelta { // reduce number of unneeded updates, by only sending on iface changes
 	if ifaceDelta { // reduce number of unneeded updates, by only sending on iface changes
-		if err = PublishPeerUpdate(); err != nil {
+		h, err := logic.GetHost(newNode.HostID.String())
+		if err != nil {
+			return
+		}
+		if err = BroadcastAddOrUpdatePeer(h, &newNode, true); err != nil {
 			logger.Log(0, "error updating peers when node", currentNode.ID.String(), "informed the server of an interface change", err.Error())
 			logger.Log(0, "error updating peers when node", currentNode.ID.String(), "informed the server of an interface change", err.Error())
 		}
 		}
+		if nodes, err := logic.GetNetworkNodes(newNode.Network); err == nil {
+			FlushNetworkPeersToHost(h, &newNode, nodes)
+		}
+
 	}
 	}
 
 
 	logger.Log(1, "updated node", id, newNode.ID.String())
 	logger.Log(1, "updated node", id, newNode.ID.String())
@@ -107,10 +115,15 @@ func UpdateHost(client mqtt.Client, msg mqtt.Message) {
 						return
 						return
 					}
 					}
 				}
 				}
-				if err = PublishSingleHostPeerUpdate(context.Background(), currentHost, nil, nil); err != nil {
-					logger.Log(0, "failed peers publish after join acknowledged", hostUpdate.Host.Name, currentHost.ID.String(), err.Error())
+				// flush peers to host
+				nodes, err := logic.GetNetworkNodes(hu.Node.Network)
+				if err != nil {
 					return
 					return
 				}
 				}
+				err = FlushNetworkPeersToHost(&hu.Host, &hu.Node, nodes)
+				if err != nil {
+					logger.Log(0, "failed to flush peers to host: ", err.Error())
+				}
 				if err = handleNewNodeDNS(&hu.Host, &hu.Node); err != nil {
 				if err = handleNewNodeDNS(&hu.Host, &hu.Node); err != nil {
 					logger.Log(0, "failed to send dns update after node,", hu.Node.ID.String(), ", added to host", hu.Host.Name, err.Error())
 					logger.Log(0, "failed to send dns update after node,", hu.Node.ID.String(), ", added to host", hu.Host.Name, err.Error())
 					return
 					return

+ 148 - 5
mq/publishers.go

@@ -10,6 +10,7 @@ import (
 
 
 	"github.com/gravitl/netmaker/logger"
 	"github.com/gravitl/netmaker/logger"
 	"github.com/gravitl/netmaker/logic"
 	"github.com/gravitl/netmaker/logic"
+	"github.com/gravitl/netmaker/logic/acls/nodeacls"
 	"github.com/gravitl/netmaker/models"
 	"github.com/gravitl/netmaker/models"
 	"github.com/gravitl/netmaker/servercfg"
 	"github.com/gravitl/netmaker/servercfg"
 	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
 	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
@@ -110,8 +111,75 @@ func PublishSingleHostPeerUpdate(ctx context.Context, host *models.Host, deleted
 	return publish(host, fmt.Sprintf("peers/host/%s/%s", host.ID.String(), servercfg.GetServer()), data)
 	return publish(host, fmt.Sprintf("peers/host/%s/%s", host.ID.String(), servercfg.GetServer()), data)
 }
 }
 
 
-func BroadCastDelPeer(host *models.Host, network string) error {
-	//relatedHosts := logic.GetRelatedHosts(host.ID.String())
+// FlushNetworkPeersToHost - sends all the peers in the network to the host.
+func FlushNetworkPeersToHost(host *models.Host, hNode *models.Node, networkNodes []models.Node) error {
+	logger.Log(0, "flushing network peers to host: ", host.ID.String(), hNode.Network)
+	addPeerAction := models.PeerAction{
+		Action: models.AddPeer,
+		Peers:  []wgtypes.PeerConfig{},
+	}
+	rmPeerAction := models.PeerAction{
+		Action: models.RemovePeer,
+		Peers:  []wgtypes.PeerConfig{},
+	}
+	for _, node := range networkNodes {
+		if node.ID == hNode.ID {
+			// skip self
+			continue
+		}
+		peerHost, err := logic.GetHost(node.HostID.String())
+		if err != nil {
+			continue
+		}
+
+		if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(hNode.ID.String()), nodeacls.NodeID(node.ID.String())) ||
+			hNode.Action == models.NODE_DELETE || hNode.PendingDelete || !hNode.Connected {
+			// remove peer if not allowed
+			rmPeerAction.Peers = append(rmPeerAction.Peers, wgtypes.PeerConfig{
+				PublicKey: peerHost.PublicKey,
+				Remove:    true,
+			})
+			continue
+
+		}
+		peerCfg := wgtypes.PeerConfig{
+			PublicKey: peerHost.PublicKey,
+			Endpoint: &net.UDPAddr{
+				IP:   peerHost.EndpointIP,
+				Port: logic.GetPeerListenPort(peerHost),
+			},
+			PersistentKeepaliveInterval: &node.PersistentKeepalive,
+			ReplaceAllowedIPs:           true,
+			AllowedIPs:                  logic.GetAllowedIPs(hNode, &node, nil),
+		}
+		addPeerAction.Peers = append(addPeerAction.Peers, peerCfg)
+	}
+	if hNode.IsIngressGateway {
+		extPeers, _, err := logic.GetExtPeers(hNode)
+		if err == nil {
+			addPeerAction.Peers = append(addPeerAction.Peers, extPeers...)
+		}
+
+	}
+	if len(rmPeerAction.Peers) > 0 {
+		data, err := json.Marshal(rmPeerAction)
+		if err != nil {
+			return err
+		}
+		publish(host, fmt.Sprintf("peer/host/%s/%s", host.ID.String(), servercfg.GetServer()), data)
+	}
+	if len(addPeerAction.Peers) > 0 {
+		data, err := json.Marshal(addPeerAction)
+		if err != nil {
+			return err
+		}
+		publish(host, fmt.Sprintf("peer/host/%s/%s", host.ID.String(), servercfg.GetServer()), data)
+	}
+	return nil
+}
+
+// BroadcastDelPeer - notifys all the hosts in the network to remove peer
+func BroadcastDelPeer(host *models.Host, network string) error {
 	nodes, err := logic.GetNetworkNodes(network)
 	nodes, err := logic.GetNetworkNodes(network)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
@@ -130,19 +198,40 @@ func BroadCastDelPeer(host *models.Host, network string) error {
 		return err
 		return err
 	}
 	}
 	for _, nodeI := range nodes {
 	for _, nodeI := range nodes {
+		if nodeI.HostID == host.ID {
+			// skip self...
+			continue
+		}
 		peerHost, err := logic.GetHost(nodeI.HostID.String())
 		peerHost, err := logic.GetHost(nodeI.HostID.String())
 		if err == nil {
 		if err == nil {
-			publish(peerHost, fmt.Sprintf("peer/host/%s/%s", host.ID.String(), servercfg.GetServer()), data)
+			publish(peerHost, fmt.Sprintf("peer/host/%s/%s", peerHost.ID.String(), servercfg.GetServer()), data)
 		}
 		}
 	}
 	}
 	return nil
 	return nil
 }
 }
 
 
-func BroadCastAddPeer(host *models.Host, node *models.Node, network string, update bool) error {
+// BroadcastAclUpdate - sends new acl updates to peers
+func BroadcastAclUpdate(network string) error {
 	nodes, err := logic.GetNetworkNodes(network)
 	nodes, err := logic.GetNetworkNodes(network)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
+	for _, nodeI := range nodes {
+		nodeI := nodeI
+		h, err := logic.GetHost(nodeI.HostID.String())
+		if err == nil {
+			go FlushNetworkPeersToHost(h, &nodeI, nodes)
+		}
+	}
+	return err
+}
+
+// BroadcastAddOrUpdatePeer - notifys the hosts in the network to add or update peer.
+func BroadcastAddOrUpdatePeer(host *models.Host, node *models.Node, update bool) error {
+	nodes, err := logic.GetNetworkNodes(node.Network)
+	if err != nil {
+		return err
+	}
 
 
 	p := models.PeerAction{
 	p := models.PeerAction{
 		Action: models.AddPeer,
 		Action: models.AddPeer,
@@ -162,20 +251,74 @@ func BroadCastAddPeer(host *models.Host, node *models.Node, network string, upda
 		p.Action = models.UpdatePeer
 		p.Action = models.UpdatePeer
 	}
 	}
 	for _, nodeI := range nodes {
 	for _, nodeI := range nodes {
+		if nodeI.ID.String() == node.ID.String() {
+			// skip self...
+			continue
+		}
 		// update allowed ips, according to the peer node
 		// update allowed ips, according to the peer node
 		p.Peers[0].AllowedIPs = logic.GetAllowedIPs(&nodeI, node, nil)
 		p.Peers[0].AllowedIPs = logic.GetAllowedIPs(&nodeI, node, nil)
+		if update && (!nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(nodeI.ID.String())) ||
+			node.Action == models.NODE_DELETE || node.PendingDelete || !node.Connected) {
+			// remove peer
+			p.Action = models.RemovePeer
+			p.Peers[0].Remove = true
+		}
 		data, err := json.Marshal(p)
 		data, err := json.Marshal(p)
 		if err != nil {
 		if err != nil {
 			continue
 			continue
 		}
 		}
 		peerHost, err := logic.GetHost(nodeI.HostID.String())
 		peerHost, err := logic.GetHost(nodeI.HostID.String())
 		if err == nil {
 		if err == nil {
-			publish(peerHost, fmt.Sprintf("peer/host/%s/%s", host.ID.String(), servercfg.GetServer()), data)
+			publish(peerHost, fmt.Sprintf("peer/host/%s/%s", peerHost.ID.String(), servercfg.GetServer()), data)
 		}
 		}
 	}
 	}
 	return nil
 	return nil
 }
 }
 
 
+// BroadcastExtClient - publishes msg to add/updates ext client in the network
+func BroadcastExtClient(ingressHost *models.Host, ingressNode *models.Node) error {
+
+	nodes, err := logic.GetNetworkNodes(ingressNode.Network)
+	if err != nil {
+		return err
+	}
+	//flush peers to ingress host
+	go FlushNetworkPeersToHost(ingressHost, ingressNode, nodes)
+	// broadcast to update ingress peer to other hosts
+	go BroadcastAddOrUpdatePeer(ingressHost, ingressNode, true)
+	// TODO - send fw update
+	return nil
+}
+
+// BroadcastDelExtClient - published msg to remove ext client from network
+func BroadcastDelExtClient(ingressHost *models.Host, ingressNode *models.Node, extclients []models.ExtClient) error {
+	// TODO - send fw update
+	go BroadcastAddOrUpdatePeer(ingressHost, ingressNode, true)
+	peers := []wgtypes.PeerConfig{}
+	for _, extclient := range extclients {
+		extPubKey, err := wgtypes.ParseKey(extclient.PublicKey)
+		if err != nil {
+			continue
+		}
+		peers = append(peers, wgtypes.PeerConfig{
+			PublicKey: extPubKey,
+			Remove:    true,
+		})
+
+	}
+	p := models.PeerAction{
+		Action: models.RemovePeer,
+		Peers:  peers,
+	}
+
+	data, err := json.Marshal(p)
+	if err != nil {
+		return err
+	}
+	publish(ingressHost, fmt.Sprintf("peer/host/%s/%s", ingressHost.ID.String(), servercfg.GetServer()), data)
+	return nil
+}
+
 // NodeUpdate -- publishes a node update
 // NodeUpdate -- publishes a node update
 func NodeUpdate(node *models.Node) error {
 func NodeUpdate(node *models.Node) error {
 	host, err := logic.GetHost(node.HostID.String())
 	host, err := logic.GetHost(node.HostID.String())

+ 5 - 4
release.md

@@ -1,14 +1,15 @@
 
 
-# Netmaker v0.19.1
+# Netmaker v0.20.0
 
 
 ## whats new
 ## whats new
-- 
+- New UI
+- revamped compose-files and install scripts
+- TURN
     
     
 ## whats fixed
 ## whats fixed
-- status code for exceeding free tier limits  
+- Caddy does not handle netmaker exporter well for EE
 
 
 ## known issues
 ## known issues
-- Caddy does not handle netmaker exporter well for EE
 - Migration causes a listen port of 0 for some upgraded hosts
 - Migration causes a listen port of 0 for some upgraded hosts
 - Docker clients can not re-join after deletion
 - Docker clients can not re-join after deletion
 - Innacurate Ext Client Metrics 
 - Innacurate Ext Client Metrics 

+ 82 - 0
scripts/netmaker.env

@@ -0,0 +1,82 @@
+# Email used for SSL certificates
+NM_EMAIL=
+# The base domain of netmaker
+NM_DOMAIN=
+# Public IP of machine
+SERVER_HOST=
+# The admin master key for accessing the API. Change this in any production installation.
+MASTER_KEY=
+# The username to set for turn api access
+TURN_USERNAME=
+# The password to set for turn api access
+TURN_PASSWORD=
+# The username to set for MQ access
+MQ_USERNAME=
+# The password to set for MQ access
+MQ_PASSWORD=
+INSTALL_TYPE=
+NETMAKER_ACCOUNT_ID=
+LICENSE_KEY=
+SERVER_IMAGE_TAG=
+UI_IMAGE_TAG=
+# used for HA - identifies this server vs other servers
+NODE_ID="netmaker-server-1"
+METRICS_EXPORTER="off"
+PROMETHEUS="off"
+# Enables DNS Mode, meaning all nodes will set hosts file for private dns settings
+DNS_MODE="on"
+# Enable auto update of netclient ? ENUM:- enabled,disabled | default=enabled
+NETCLIENT_AUTO_UPDATE="enabled"
+# The HTTP API port for Netmaker. Used for API calls / communication from front end.
+# If changed, need to change port of BACKEND_URL for netmaker-ui.
+API_PORT="8081"
+EXPORTER_API_PORT="8085"
+# The "allowed origin" for API requests. Change to restrict where API requests can come from with comma-separated
+# URLs. ex:- https://dashboard.netmaker.domain1.com,https://dashboard.netmaker.domain2.com
+CORS_ALLOWED_ORIGIN="*"
+# Show keys permanently in UI (until deleted) as opposed to 1-time display.
+DISPLAY_KEYS="on"
+# Database to use - sqlite, postgres, or rqlite
+DATABASE="sqlite"
+# The address of the mq server. If running from docker compose it will be "mq". Otherwise, need to input address.
+# If using "host networking", it will find and detect the IP of the mq container.
+SERVER_BROKER_ENDPOINT="ws://mq:1883"
+# The reachable port of STUN on the server
+STUN_PORT="3478"
+# Logging verbosity level - 1, 2, or 3
+VERBOSITY="1"
+# If ON, all new clients will enable proxy by default
+# If OFF, all new clients will disable proxy by default
+# If AUTO, stick with the existing logic for NAT detection
+DEFAULT_PROXY_MODE="off"
+# Port to access turn server
+TURN_PORT="3479"
+# Config for using turn, accepts either true/false
+USE_TURN="true"
+DEBUG_MODE="off"
+TURN_API_PORT="8089"
+# Enables the REST backend (API running on API_PORT at SERVER_HTTP_HOST).
+# Change to "off" to turn off.
+REST_BACKEND="on"
+# If turned "on", Server will not set Host based on remote IP check.
+# This is already overridden if SERVER_HOST is set. Turned "off" by default.
+DISABLE_REMOTE_IP_CHECK="off"
+# Whether or not to send telemetry data to help improve Netmaker. Switch to "off" to opt out of sending telemetry.
+TELEMETRY="on"
+###
+#
+# OAuth section
+#
+###
+# "<azure-ad|github|google|oidc>"
+AUTH_PROVIDER=
+# "<client id of your oauth provider>"
+CLIENT_ID=
+# "<client secret of your oauth provider>"
+CLIENT_SECRET=
+# "https://dashboard.<netmaker base domain>"
+FRONTEND_URL=
+# "<only for azure, you may optionally specify the tenant for the OAuth>"
+AZURE_TENANT=
+# https://oidc.yourprovider.com - URL of oidc provider
+OIDC_ISSUER=

+ 4 - 4
scripts/nm-certs.sh

@@ -64,8 +64,8 @@ sudo docker run -it --rm --name certbot \
 	--entrypoint "/opt/certbot/certbot-entry.sh" \
 	--entrypoint "/opt/certbot/certbot-entry.sh" \
 	certbot/certbot
 	certbot/certbot
 
 
-# clean up TODO enable
-#rm "$SCRIPT_DIR/certbot-entry.sh"
+# clean up
+rm "$SCRIPT_DIR/certbot-entry.sh"
 
 
 # check if successful
 # check if successful
 if [ ! -f "$CERT_DIR"/fullchain.pem ]; then
 if [ ! -f "$CERT_DIR"/fullchain.pem ]; then
@@ -84,8 +84,8 @@ fi
 
 
 # copy for mounting
 # copy for mounting
 mkdir -p certs
 mkdir -p certs
-cp -L "$CERT_DIR/fullchain.pem" /root/certs/fullchain.pem
-cp -L "$CERT_DIR/privkey.pem" /root/certs/privkey.pem
+cp -L "$CERT_DIR/fullchain.pem" "$SCRIPT_DIR/certs/fullchain.pem"
+cp -L "$CERT_DIR/privkey.pem" "$SCRIPT_DIR/certs/privkey.pem"
 
 
 echo "SSL certificates ready"
 echo "SSL certificates ready"
 
 

+ 197 - 96
scripts/nm-quick.sh

@@ -148,13 +148,13 @@ set_buildinfo() {
 # install_yq - install yq if not present
 # install_yq - install yq if not present
 install_yq() {
 install_yq() {
 	if ! command -v yq &>/dev/null; then
 	if ! command -v yq &>/dev/null; then
-		wget -O /usr/bin/yq https://github.com/mikefarah/yq/releases/download/v4.31.1/yq_linux_$(dpkg --print-architecture)
+		wget -qO /usr/bin/yq https://github.com/mikefarah/yq/releases/download/v4.31.1/yq_linux_$(dpkg --print-architecture)
 		chmod +x /usr/bin/yq
 		chmod +x /usr/bin/yq
 	fi
 	fi
 	set +e
 	set +e
 	if ! command -v yq &>/dev/null; then
 	if ! command -v yq &>/dev/null; then
 		set -e
 		set -e
-		wget -O /usr/bin/yq https://github.com/mikefarah/yq/releases/download/v4.31.1/yq_linux_amd64
+		wget -qO /usr/bin/yq https://github.com/mikefarah/yq/releases/download/v4.31.1/yq_linux_amd64
 		chmod +x /usr/bin/yq
 		chmod +x /usr/bin/yq
 	fi
 	fi
 	set -e
 	set -e
@@ -172,21 +172,44 @@ setup_netclient() {
 	netclient uninstall
 	netclient uninstall
 	set -e
 	set -e
 
 
-	wget -O netclient https://github.com/gravitl/netclient/releases/download/$LATEST/netclient-linux-amd64
+	# TODO arm support
+	wget -qO netclient https://github.com/gravitl/netclient/releases/download/$LATEST/netclient-linux-amd64
 	chmod +x netclient
 	chmod +x netclient
 	./netclient install
 	./netclient install
+	echo "Register token: $TOKEN"
 	netclient register -t $TOKEN
 	netclient register -t $TOKEN
 
 
-	echo "waiting for client to become available"
-	wait_seconds 10
+	echo "waiting for netclient to become available"
+	local found=false
+	local file=/etc/netclient/nodes.yml
+	for ((a = 1; a <= 90; a++)); do
+		if [ -f "$file" ]; then
+			found=true
+			break
+		fi
+		sleep 1
+	done
+
+	if [ "$found" = false ]; then
+		echo "Error - $file not present"
+		exit 1
+	fi
 }
 }
 
 
 # configure_netclient - configures server's netclient as a default host and an ingress gateway
 # configure_netclient - configures server's netclient as a default host and an ingress gateway
 configure_netclient() {
 configure_netclient() {
 
 
 	NODE_ID=$(sudo cat /etc/netclient/nodes.yml | yq -r .netmaker.commonnode.id)
 	NODE_ID=$(sudo cat /etc/netclient/nodes.yml | yq -r .netmaker.commonnode.id)
+	if [ "$NODE_ID" = "" ] || [ "$NODE_ID" = "null" ]; then
+		echo "Error obtaining NODE_ID for the new network"
+		exit 1
+	fi
 	echo "register complete. New node ID: $NODE_ID"
 	echo "register complete. New node ID: $NODE_ID"
 	HOST_ID=$(sudo cat /etc/netclient/netclient.yml | yq -r .host.id)
 	HOST_ID=$(sudo cat /etc/netclient/netclient.yml | yq -r .host.id)
+	if [ "$HOST_ID" = "" ] || [ "$HOST_ID" = "null" ]; then
+		echo "Error obtaining HOST_ID for the new network"
+		exit 1
+	fi
 	echo "making host a default"
 	echo "making host a default"
 	echo "Host ID: $HOST_ID"
 	echo "Host ID: $HOST_ID"
 	# set as a default host
 	# set as a default host
@@ -200,7 +223,15 @@ configure_netclient() {
 # setup_nmctl - pulls nmctl and makes it executable
 # setup_nmctl - pulls nmctl and makes it executable
 setup_nmctl() {
 setup_nmctl() {
 
 
-	wget -O /usr/bin/nmctl https://github.com/gravitl/netmaker/releases/download/$LATEST/nmctl-linux-amd64
+	# TODO arm support
+	local URL="https://github.com/gravitl/netmaker/releases/download/$LATEST/nmctl-linux-amd64"
+	echo "Downloading nmctl..."
+	wget -qO /usr/bin/nmctl "$URL"
+
+	if [ ! -f /usr/bin/nmctl ]; then
+		echo "Error downloading nmctl from '$URL'"
+		exit 1
+	fi
 
 
 	chmod +x /usr/bin/nmctl
 	chmod +x /usr/bin/nmctl
 	echo "using server api.$NETMAKER_BASE_DOMAIN"
 	echo "using server api.$NETMAKER_BASE_DOMAIN"
@@ -247,48 +278,107 @@ confirm() { (
 save_config() { (
 save_config() { (
 	echo "Saving the config to $CONFIG_PATH"
 	echo "Saving the config to $CONFIG_PATH"
 	touch "$CONFIG_PATH"
 	touch "$CONFIG_PATH"
-	# email
-	if grep -q "^NM_EMAIL=" "$CONFIG_PATH"; then
-		sed -i "s/NM_EMAIL=.*/NM_EMAIL=$EMAIL/" "$CONFIG_PATH"
+	save_config_item NM_EMAIL "$EMAIL"
+	save_config_item NM_DOMAIN "$NETMAKER_BASE_DOMAIN"
+	save_config_item UI_IMAGE_TAG "$IMAGE_TAG"
+	if [ "$BUILD_TYPE" = "local" ]; then
+		save_config_item UI_IMAGE_TAG "$LATEST"
+	else
+		save_config_item UI_IMAGE_TAG "$IMAGE_TAG"
+	fi
+	# version-specific entries
+	if [ "$INSTALL_TYPE" = "ee" ]; then
+		save_config_item NETMAKER_ACCOUNT_ID "$ACCOUNT_ID"
+		save_config_item LICENSE_KEY "$LICENSE_KEY"
+		save_config_item METRICS_EXPORTER "on"
+		save_config_item PROMETHEUS "on"
+		if [ "$BUILD_TYPE" = "version" ]; then
+			save_config_item SERVER_IMAGE_TAG "$IMAGE_TAG-ee"
+		else
+			save_config_item SERVER_IMAGE_TAG "$IMAGE_TAG"
+		fi
 	else
 	else
-		echo "NM_EMAIL=$EMAIL" >>"$CONFIG_PATH"
+		save_config_item METRICS_EXPORTER "off"
+		save_config_item PROMETHEUS "off"
+		save_config_item SERVER_IMAGE_TAG "$IMAGE_TAG"
+	fi
+	# copy entries from the previous config
+	local toCopy=("SERVER_HOST" "MASTER_KEY" "TURN_USERNAME" "MQ_USERNAME" "MQ_PASSWORD"
+		"INSTALL_TYPE" "NODE_ID" "METRICS_EXPORTER" "PROMETHEUS" "DNS_MODE" "NETCLIENT_AUTO_UPDATE" "API_PORT"
+		"CORS_ALLOWED_ORIGIN" "DISPLAY_KEYS" "DATABASE" "SERVER_BROKER_ENDPOINT" "STUN_PORT" "VERBOSITY"
+		"DEFAULT_PROXY_MODE" "TURN_PORT" "USE_TURN" "DEBUG_MODE" "TURN_API_PORT" "REST_BACKEND" "DISABLE_REMOTE_IP_CHECK"
+		"TELEMETRY" "AUTH_PROVIDER" "CLIENT_ID" "CLIENT_SECRET" "FRONTEND_URL" "AZURE_TENANT" "OIDC_ISSUER"
+		"EXPORTER_API_PORT")
+	for name in "${toCopy[@]}"; do
+		save_config_item $name "${!name}"
+	done
+	# preserve debug entries
+	if test -n "$NM_SKIP_BUILD"; then
+		save_config_item NM_SKIP_BUILD "$NM_SKIP_BUILD"
+	fi
+	if test -n "$NM_SKIP_CLONE"; then
+		save_config_item NM_SKIP_CLONE "$NM_SKIP_CLONE"
 	fi
 	fi
-	# domain
-	if grep -q "^NM_DOMAIN=" "$CONFIG_PATH"; then
-		sed -i "s/NM_DOMAIN=.*/NM_DOMAIN=$NETMAKER_BASE_DOMAIN/" "$CONFIG_PATH"
+	if test -n "$NM_SKIP_DEPS"; then
+		save_config_item NM_SKIP_DEPS "$NM_SKIP_DEPS"
+	fi
+); }
+
+save_config_item() { (
+	local NAME="$1"
+	local VALUE="$2"
+	# echo "NAME $NAME"
+	# echo "VALUE $VALUE"
+	if grep -q "^$NAME=" "$CONFIG_PATH"; then
+		# TODO escape | in the value
+		sed -i "s|$NAME=.*|$NAME=$VALUE|" "$CONFIG_PATH"
 	else
 	else
-		echo "NM_DOMAIN=$NETMAKER_BASE_DOMAIN" >>"$CONFIG_PATH"
+		echo "$NAME=\"$VALUE\"" >>"$CONFIG_PATH"
 	fi
 	fi
 ); }
 ); }
 
 
 # local_install_setup - builds artifacts based on specified branch locally to use in install
 # local_install_setup - builds artifacts based on specified branch locally to use in install
 local_install_setup() { (
 local_install_setup() { (
-	rm -rf netmaker-tmp
-	mkdir netmaker-tmp
-	cd netmaker-tmp
-	git clone --single-branch --depth=1 --branch=$BUILD_TAG https://www.github.com/gravitl/netmaker
+	if test -z "$NM_SKIP_CLONE"; then
+		rm -rf netmaker-tmp
+		mkdir netmaker-tmp
+		cd netmaker-tmp
+		git clone --single-branch --depth=1 --branch=$BUILD_TAG https://www.github.com/gravitl/netmaker
+	else
+		cd netmaker-tmp
+		echo "Skipping git clone on NM_SKIP_CLONE"
+	fi
 	cd netmaker
 	cd netmaker
 	if test -z "$NM_SKIP_BUILD"; then
 	if test -z "$NM_SKIP_BUILD"; then
 		docker build --no-cache --build-arg version=$IMAGE_TAG -t gravitl/netmaker:$IMAGE_TAG .
 		docker build --no-cache --build-arg version=$IMAGE_TAG -t gravitl/netmaker:$IMAGE_TAG .
 	else
 	else
 		echo "Skipping build on NM_SKIP_BUILD"
 		echo "Skipping build on NM_SKIP_BUILD"
 	fi
 	fi
+	cp compose/docker-compose.yml "$SCRIPT_DIR/docker-compose.yml"
 	if [ "$INSTALL_TYPE" = "ee" ]; then
 	if [ "$INSTALL_TYPE" = "ee" ]; then
-		cp compose/docker-compose.ee.yml /root/docker-compose.yml
-		cp docker/Caddyfile-EE /root/Caddyfile
+		cp compose/docker-compose.ee.yml "$SCRIPT_DIR/docker-compose.override.yml"
+		cp docker/Caddyfile-EE "$SCRIPT_DIR/Caddyfile"
 	else
 	else
-		cp compose/docker-compose.yml /root/docker-compose.yml
-		cp docker/Caddyfile /root/Caddyfile
+		cp docker/Caddyfile "$SCRIPT_DIR/Caddyfile"
 	fi
 	fi
-	cp scripts/nm-certs.sh /root/nm-certs.sh
-	cp docker/mosquitto.conf /root/mosquitto.conf
-	cp docker/wait.sh /root/wait.sh
+	cp scripts/nm-certs.sh "$SCRIPT_DIR/nm-certs.sh"
+	cp scripts/netmaker.env "$SCRIPT_DIR/netmaker.env"
+	ln -fs "$SCRIPT_DIR/netmaker.env" "$SCRIPT_DIR/.env"
+	cp docker/mosquitto.conf "$SCRIPT_DIR/mosquitto.conf"
+	cp docker/wait.sh "$SCRIPT_DIR/wait.sh"
 	cd ../../
 	cd ../../
-	rm -rf netmaker-tmp
+	if test -z "$NM_SKIP_CLONE"; then
+		rm -rf netmaker-tmp
+	fi
 ); }
 ); }
 
 
 # install_dependencies - install necessary packages to run netmaker
 # install_dependencies - install necessary packages to run netmaker
 install_dependencies() {
 install_dependencies() {
+
+	if test -n "$NM_SKIP_DEPS"; then
+		return
+	fi
+
 	echo "checking dependencies..."
 	echo "checking dependencies..."
 
 
 	OS=$(uname)
 	OS=$(uname)
@@ -399,9 +489,7 @@ set_install_vars() {
 	fi
 	fi
 
 
 	NETMAKER_BASE_DOMAIN=nm.$(echo $IP_ADDR | tr . -).nip.io
 	NETMAKER_BASE_DOMAIN=nm.$(echo $IP_ADDR | tr . -).nip.io
-	# TODO dead code?
-	# COREDNS_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
-	SERVER_PUBLIC_IP=$IP_ADDR
+	SERVER_HOST=$IP_ADDR
 	MASTER_KEY=$(
 	MASTER_KEY=$(
 		tr -dc A-Za-z0-9 </dev/urandom | head -c 30
 		tr -dc A-Za-z0-9 </dev/urandom | head -c 30
 		echo ''
 		echo ''
@@ -409,7 +497,7 @@ set_install_vars() {
 	DOMAIN_TYPE=""
 	DOMAIN_TYPE=""
 	echo "-----------------------------------------------------"
 	echo "-----------------------------------------------------"
 	echo "Would you like to use your own domain for netmaker, or an auto-generated domain?"
 	echo "Would you like to use your own domain for netmaker, or an auto-generated domain?"
-	echo "To use your own domain, add a Wildcard DNS record (e.x: *.netmaker.example.com) pointing to $SERVER_PUBLIC_IP"
+	echo "To use your own domain, add a Wildcard DNS record (e.x: *.netmaker.example.com) pointing to $SERVER_HOST"
 	echo "IMPORTANT: Due to the high volume of requests, the auto-generated domain has been rate-limited by the certificate provider."
 	echo "IMPORTANT: Due to the high volume of requests, the auto-generated domain has been rate-limited by the certificate provider."
 	echo "For this reason, we STRONGLY RECOMMEND using your own domain. Using the auto-generated domain may lead to a failed installation due to rate limiting."
 	echo "For this reason, we STRONGLY RECOMMEND using your own domain. Using the auto-generated domain may lead to a failed installation due to rate limiting."
 	echo "-----------------------------------------------------"
 	echo "-----------------------------------------------------"
@@ -425,7 +513,7 @@ set_install_vars() {
 				break
 				break
 				;;
 				;;
 			2)
 			2)
-				read -p "Enter Custom Domain (make sure  *.domain points to $SERVER_PUBLIC_IP first): " domain
+				read -p "Enter Custom Domain (make sure  *.domain points to $SERVER_HOST first): " domain
 				NETMAKER_BASE_DOMAIN=$domain
 				NETMAKER_BASE_DOMAIN=$domain
 				echo "using $NETMAKER_BASE_DOMAIN"
 				echo "using $NETMAKER_BASE_DOMAIN"
 				DOMAIN_TYPE="custom"
 				DOMAIN_TYPE="custom"
@@ -456,7 +544,7 @@ set_install_vars() {
 	echo "-----------------------------------------------------"
 	echo "-----------------------------------------------------"
 
 
 	if [[ "$DOMAIN_TYPE" == "custom" ]]; then
 	if [[ "$DOMAIN_TYPE" == "custom" ]]; then
-		echo "before continuing, confirm DNS is configured correctly, with records pointing to $SERVER_PUBLIC_IP"
+		echo "before continuing, confirm DNS is configured correctly, with records pointing to $SERVER_HOST"
 		confirm
 		confirm
 	fi
 	fi
 
 
@@ -603,7 +691,7 @@ set_install_vars() {
 	echo "-----------------------------------------------------------------"
 	echo "-----------------------------------------------------------------"
 	echo "        domain: $NETMAKER_BASE_DOMAIN"
 	echo "        domain: $NETMAKER_BASE_DOMAIN"
 	echo "         email: $EMAIL"
 	echo "         email: $EMAIL"
-	echo "     public ip: $SERVER_PUBLIC_IP"
+	echo "     public ip: $SERVER_HOST"
 	if [ "$INSTALL_TYPE" = "ee" ]; then
 	if [ "$INSTALL_TYPE" = "ee" ]; then
 		echo "       license: $LICENSE_KEY"
 		echo "       license: $LICENSE_KEY"
 		echo "    account id: $ACCOUNT_ID"
 		echo "    account id: $ACCOUNT_ID"
@@ -612,9 +700,11 @@ set_install_vars() {
 	echo "Confirm Settings for Installation"
 	echo "Confirm Settings for Installation"
 	echo "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
 	echo "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
 
 
-	confirm
+	if [ ! "$BUILD_TYPE" = "local" ]; then
+		IMAGE_TAG="$LATEST"
+	fi
 
 
-	save_config
+	confirm
 }
 }
 
 
 # install_netmaker - sets the config files and starts docker-compose
 # install_netmaker - sets the config files and starts docker-compose
@@ -626,55 +716,39 @@ install_netmaker() {
 
 
 	wait_seconds 3
 	wait_seconds 3
 
 
-	# TODO extract wgets to setup(), mirror local_setup()
 	echo "Pulling config files..."
 	echo "Pulling config files..."
 
 
-	COMPOSE_URL="https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/compose/docker-compose.yml"
-	CADDY_URL="https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/docker/Caddyfile"
-	if [ "$INSTALL_TYPE" = "ee" ]; then
-		COMPOSE_URL="https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/compose/docker-compose.ee.yml"
-		CADDY_URL="https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/docker/Caddyfile-EE"
-	fi
+	if [ "$BUILD_TYPE" = "local" ]; then
+		local_install_setup
+	else
+		local BASE_URL="https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG"
 
 
-	if [ ! "$BUILD_TYPE" = "local" ]; then
-		wget -qO /root/docker-compose.yml $COMPOSE_URL
-		wget -qO /root/Caddyfile $CADDY_URL
-		wget -qO /root/mosquitto.conf "https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/docker/mosquitto.conf"
-		wget -qO /root/nm-certs.sh "https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/scripts/nm-certs.sh"
-		wget -qO /root/wait.sh "https://raw.githubusercontent.com/gravitl/netmaker/$BUILD_TAG/docker/wait.sh"
+		local COMPOSE_URL="$BASE_URL/compose/docker-compose.yml"
+		local CADDY_URL="$BASE_URL/docker/Caddyfile"
+		if [ "$INSTALL_TYPE" = "ee" ]; then
+			local COMPOSE_OVERRIDE_URL="$BASE_URL/compose/docker-compose.ee.yml"
+			local CADDY_URL="$BASE_URL/docker/Caddyfile-EE"
+		fi
+		wget -qO "$SCRIPT_DIR"/docker-compose.yml $COMPOSE_URL
+		if test -n "$COMPOSE_OVERRIDE_URL"; then
+			wget -qO "$SCRIPT_DIR"/docker-compose.override.yml $COMPOSE_OVERRIDE_URL
+		fi
+		wget -qO "$SCRIPT_DIR"/Caddyfile "$CADDY_URL"
+		wget -qO "$SCRIPT_DIR"/netmaker.env "$BASE_URL/scripts/netmaker.env"
+		ln -fs "$SCRIPT_DIR/netmaker.env" "$SCRIPT_DIR/.env"
+		wget -qO "$SCRIPT_DIR"/mosquitto.conf "$BASE_URL/docker/mosquitto.conf"
+		wget -qO "$SCRIPT_DIR"/nm-certs.sh "$BASE_URL/scripts/nm-certs.sh"
+		wget -qO "$SCRIPT_DIR"/wait.sh "$BASE_URL/docker/wait.sh"
 	fi
 	fi
 
 
-	chmod +x /root/wait.sh
+	chmod +x "$SCRIPT_DIR"/wait.sh
 	mkdir -p /etc/netmaker
 	mkdir -p /etc/netmaker
 
 
-	echo "Setting docker-compose and Caddyfile..."
-
-	sed -i "s/SERVER_PUBLIC_IP/$SERVER_PUBLIC_IP/g" /root/docker-compose.yml
-	sed -i "s/NETMAKER_BASE_DOMAIN/$NETMAKER_BASE_DOMAIN/g" /root/Caddyfile
-	sed -i "s/NETMAKER_BASE_DOMAIN/$NETMAKER_BASE_DOMAIN/g" /root/docker-compose.yml
-	sed -i "s/REPLACE_MASTER_KEY/$MASTER_KEY/g" /root/docker-compose.yml
-	sed -i "s/YOUR_EMAIL/$EMAIL/g" /root/Caddyfile
-	sed -i "s/REPLACE_MQ_USERNAME/$MQ_USERNAME/g" /root/docker-compose.yml
-	sed -i "s/REPLACE_MQ_PASSWORD/$MQ_PASSWORD/g" /root/docker-compose.yml
-	sed -i "s/REPLACE_TURN_USERNAME/$TURN_USERNAME/g" /root/docker-compose.yml
-	sed -i "s/REPLACE_TURN_PASSWORD/$TURN_PASSWORD/g" /root/docker-compose.yml
-
-	if [ "$INSTALL_TYPE" = "ee" ]; then
-		sed -i "s~YOUR_LICENSE_KEY~$LICENSE_KEY~g" /root/docker-compose.yml
-		sed -i "s/YOUR_ACCOUNT_ID/$ACCOUNT_ID/g" /root/docker-compose.yml
-	fi
-
-	if [ "$BUILD_TYPE" = "version" ] && [ "$INSTALL_TYPE" = "ee" ]; then
-		sed -i "s/REPLACE_SERVER_IMAGE_TAG/$IMAGE_TAG-ee/g" /root/docker-compose.yml
-	else
-		sed -i "s/REPLACE_SERVER_IMAGE_TAG/$IMAGE_TAG/g" /root/docker-compose.yml
-	fi
+	save_config
 
 
-	if [ "$BUILD_TYPE" = "local" ]; then
-		sed -i "s/REPLACE_UI_IMAGE_TAG/$LATEST/g" /root/docker-compose.yml
-	else
-		sed -i "s/REPLACE_UI_IMAGE_TAG/$IMAGE_TAG/g" /root/docker-compose.yml
-	fi
+	# Fetch / update certs using certbot
+	chmod +x "$SCRIPT_DIR"/nm-certs.sh
+	"$SCRIPT_DIR"/nm-certs.sh
 
 
 	echo "Starting containers..."
 	echo "Starting containers..."
 
 
@@ -683,7 +757,7 @@ install_netmaker() {
 	export COMPOSE_HTTP_TIMEOUT=120
 	export COMPOSE_HTTP_TIMEOUT=120
 
 
 	# start docker and rebuild containers / networks
 	# start docker and rebuild containers / networks
-	docker-compose -f /root/docker-compose.yml up -d --force-recreate
+	docker-compose -f "$SCRIPT_DIR"/docker-compose.yml up -d --force-recreate
 
 
 	wait_seconds 2
 	wait_seconds 2
 
 
@@ -720,16 +794,28 @@ setup_mesh() {
 
 
 	wait_seconds 5
 	wait_seconds 5
 
 
-	echo "Creating netmaker network (10.101.0.0/16)"
+	local networkCount=$(nmctl network list -o json | jq '. | length')
 
 
-	nmctl network create --name netmaker --ipv4_addr 10.101.0.0/16
+	# add a network if none present
+	if [ "$networkCount" -lt 1 ]; then
+		echo "Creating netmaker network (10.101.0.0/16)"
 
 
-	wait_seconds 5
+		# TODO causes "Error Status: 400 Response: {"Code":400,"Message":"could not find any records"}"
+		nmctl network create --name netmaker --ipv4_addr 10.101.0.0/16
+
+		wait_seconds 5
+	fi
 
 
-	echo "Creating netmaker enrollment key"
+	echo "Obtaining a netmaker enrollment key..."
 
 
-	tokenJson=$(nmctl enrollment_key create --unlimited --networks netmaker)
+	local tokenJson=$(nmctl enrollment_key create --unlimited --networks netmaker)
 	TOKEN=$(jq -r '.token' <<<${tokenJson})
 	TOKEN=$(jq -r '.token' <<<${tokenJson})
+	if test -z "$TOKEN"; then
+		echo "Error creating an enrollment key"
+		exit 1
+	else
+		echo "Enrollment key ready"
+	fi
 
 
 	wait_seconds 3
 	wait_seconds 3
 
 
@@ -745,6 +831,32 @@ print_success() {
 	echo "-----------------------------------------------------------------"
 	echo "-----------------------------------------------------------------"
 }
 }
 
 
+cleanup() {
+	# remove the existing netclient's instance from the existing network
+	if command -v nmctl >/dev/null 2>&1; then
+		local node_id=$(netclient list | jq '.[0].node_id' 2>/dev/null)
+		# trim doublequotes
+		node_id="${node_id//\"/}"
+		if test -n "$node_id"; then
+			echo "De-registering the existing netclient..."
+			nmctl node delete netmaker $node_id >/dev/null 2>&1
+		fi
+	fi
+
+	echo "Stopping all containers..."
+	local containers=("mq" "netmaker-ui" "coredns" "turn" "caddy" "netmaker" "netmaker-exporter" "prometheus" "grafana")
+	for name in "${containers[@]}"; do
+		local running=$(docker ps | grep -w "$name")
+		local exists=$(docker ps -a | grep -w "$name")
+		if test -n "$running"; then
+			docker stop "$name" 1>/dev/null
+		fi
+		if test -n "$exists"; then
+			docker rm "$name" 1>/dev/null
+		fi
+	done
+}
+
 # 1. print netmaker logo
 # 1. print netmaker logo
 print_logo
 print_logo
 
 
@@ -759,25 +871,14 @@ install_dependencies
 # 4. install yq if necessary
 # 4. install yq if necessary
 install_yq
 install_yq
 
 
-# 5. if running a local build, clone git and build artifacts
-if [ "$BUILD_TYPE" = "local" ]; then
-	local_install_setup
-fi
-
 set -e
 set -e
 
 
 # 6. get user input for variables
 # 6. get user input for variables
 set_install_vars
 set_install_vars
 
 
-# stop
-for name in "mq" "netmaker-ui" "coredns" "turn" "caddy" "netmaker"; do
-	if test -n "$(docker ps | grep name)"; then
-		docker stop $name
-	fi
-done
-
-# Fetch / update certs using certbot
-"$SCRIPT_DIR"/nm-certs.sh
+set +e
+cleanup
+set -e
 
 
 # 7. get and set config files, startup docker-compose
 # 7. get and set config files, startup docker-compose
 install_netmaker
 install_netmaker

+ 1 - 1
scripts/nm-upgrade-0-17-1-to-0-19-0.sh

@@ -1,6 +1,6 @@
 #!/bin/bash
 #!/bin/bash
 
 
-LATEST="v0.19.0"
+LATEST="v0.20.0"
 INSTALL_PATH="/root"
 INSTALL_PATH="/root"
 
 
 trap restore_old_netmaker_instructions
 trap restore_old_netmaker_instructions

+ 1 - 1
swagger.yaml

@@ -704,7 +704,7 @@ info:
 
 
         API calls must be authenticated via a header of the format -H “Authorization: Bearer <YOUR_SECRET_KEY>” There are two methods to obtain YOUR_SECRET_KEY: 1. Using the masterkey. By default, this value is “secret key,” but you should change this on your instance and keep it secure. This value can be set via env var at startup or in a config file (config/environments/< env >.yaml). See the [Netmaker](https://docs.netmaker.org/index.html) documentation for more details. 2. Using a JWT received for a node. This can be retrieved by calling the /api/nodes/<network>/authenticate endpoint, as documented below.
         API calls must be authenticated via a header of the format -H “Authorization: Bearer <YOUR_SECRET_KEY>” There are two methods to obtain YOUR_SECRET_KEY: 1. Using the masterkey. By default, this value is “secret key,” but you should change this on your instance and keep it secure. This value can be set via env var at startup or in a config file (config/environments/< env >.yaml). See the [Netmaker](https://docs.netmaker.org/index.html) documentation for more details. 2. Using a JWT received for a node. This can be retrieved by calling the /api/nodes/<network>/authenticate endpoint, as documented below.
     title: Netmaker
     title: Netmaker
-    version: 0.19.0
+    version: 0.20.0
 paths:
 paths:
     /api/dns:
     /api/dns:
         get:
         get: