mirror of
https://github.com/gravitl/netmaker.git
synced 2025-10-17 22:31:23 +08:00
Merge pull request #340 from gravitl/feature_v0.8.3_cleanup
code linting
This commit is contained in:
@@ -49,13 +49,13 @@ type ServerConfig struct {
|
|||||||
AgentBackend string `yaml:"agentbackend"`
|
AgentBackend string `yaml:"agentbackend"`
|
||||||
ClientMode string `yaml:"clientmode"`
|
ClientMode string `yaml:"clientmode"`
|
||||||
DNSMode string `yaml:"dnsmode"`
|
DNSMode string `yaml:"dnsmode"`
|
||||||
SplitDNS string `yaml:"splitdns"`
|
SplitDNS string `yaml:"splitdns"`
|
||||||
DisableRemoteIPCheck string `yaml:"disableremoteipcheck"`
|
DisableRemoteIPCheck string `yaml:"disableremoteipcheck"`
|
||||||
DisableDefaultNet string `yaml:"disabledefaultnet"`
|
DisableDefaultNet string `yaml:"disabledefaultnet"`
|
||||||
GRPCSSL string `yaml:"grpcssl"`
|
GRPCSSL string `yaml:"grpcssl"`
|
||||||
Version string `yaml:"version"`
|
Version string `yaml:"version"`
|
||||||
SQLConn string `yaml:"sqlconn"`
|
SQLConn string `yaml:"sqlconn"`
|
||||||
Platform string `yaml:"platform"`
|
Platform string `yaml:"platform"`
|
||||||
Database string `yaml:database`
|
Database string `yaml:database`
|
||||||
CheckinInterval string `yaml:checkininterval`
|
CheckinInterval string `yaml:checkininterval`
|
||||||
DefaultNodeLimit int32 `yaml:"defaultnodelimit"`
|
DefaultNodeLimit int32 `yaml:"defaultnodelimit"`
|
||||||
|
@@ -124,7 +124,7 @@ func (s *NodeServiceServer) Login(ctx context.Context, req *nodepb.Object) (*nod
|
|||||||
err = errors.New("Missing Password.")
|
err = errors.New("Missing Password.")
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
|
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API until approved).
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@@ -7,11 +7,13 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/gorilla/handlers"
|
"github.com/gorilla/handlers"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/gravitl/netmaker/servercfg"
|
"github.com/gravitl/netmaker/servercfg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// HandleRESTRequests - handles the rest requests
|
||||||
func HandleRESTRequests(wg *sync.WaitGroup) {
|
func HandleRESTRequests(wg *sync.WaitGroup) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
|
||||||
@@ -30,7 +32,7 @@ func HandleRESTRequests(wg *sync.WaitGroup) {
|
|||||||
fileHandlers(r)
|
fileHandlers(r)
|
||||||
serverHandlers(r)
|
serverHandlers(r)
|
||||||
extClientHandlers(r)
|
extClientHandlers(r)
|
||||||
|
|
||||||
port := servercfg.GetAPIPort()
|
port := servercfg.GetAPIPort()
|
||||||
|
|
||||||
srv := &http.Server{Addr: ":" + port, Handler: handlers.CORS(originsOk, headersOk, methodsOk)(r)}
|
srv := &http.Server{Addr: ":" + port, Handler: handlers.CORS(originsOk, headersOk, methodsOk)(r)}
|
||||||
@@ -41,7 +43,7 @@ func HandleRESTRequests(wg *sync.WaitGroup) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
log.Println("REST Server succesfully started on port " + port + " (REST)")
|
log.Println("REST Server successfully started on port " + port + " (REST)")
|
||||||
c := make(chan os.Signal)
|
c := make(chan os.Signal)
|
||||||
|
|
||||||
// Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
|
// Relay os.Interrupt to our channel (os.Interrupt = CTRL+C)
|
||||||
|
@@ -56,6 +56,7 @@ func getAllDNS(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(dns)
|
json.NewEncoder(w).Encode(dns)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetAllDNS - gets all dns entries
|
||||||
func GetAllDNS() ([]models.DNSEntry, error) {
|
func GetAllDNS() ([]models.DNSEntry, error) {
|
||||||
var dns []models.DNSEntry
|
var dns []models.DNSEntry
|
||||||
networks, err := models.GetNetworks()
|
networks, err := models.GetNetworks()
|
||||||
@@ -72,6 +73,7 @@ func GetAllDNS() ([]models.DNSEntry, error) {
|
|||||||
return dns, nil
|
return dns, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNodeDNS - gets node dns
|
||||||
func GetNodeDNS(network string) ([]models.DNSEntry, error) {
|
func GetNodeDNS(network string) ([]models.DNSEntry, error) {
|
||||||
|
|
||||||
var dns []models.DNSEntry
|
var dns []models.DNSEntry
|
||||||
@@ -114,6 +116,7 @@ func getCustomDNS(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(dns)
|
json.NewEncoder(w).Encode(dns)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetDNSEntryNum - gets which entry the dns was
|
||||||
func GetDNSEntryNum(domain string, network string) (int, error) {
|
func GetDNSEntryNum(domain string, network string) (int, error) {
|
||||||
|
|
||||||
num := 0
|
num := 0
|
||||||
@@ -133,7 +136,7 @@ func GetDNSEntryNum(domain string, network string) (int, error) {
|
|||||||
return num, nil
|
return num, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Gets all nodes associated with network, including pending nodes
|
// Gets all nodes associated with network, including pending nodes
|
||||||
func getDNS(w http.ResponseWriter, r *http.Request) {
|
func getDNS(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -202,7 +205,7 @@ func updateDNS(w http.ResponseWriter, r *http.Request) {
|
|||||||
returnErrorResponse(w, r, formatError(err, "badrequest"))
|
returnErrorResponse(w, r, formatError(err, "badrequest"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
//fill in any missing fields
|
// fill in any missing fields
|
||||||
if dnschange.Name == "" {
|
if dnschange.Name == "" {
|
||||||
dnschange.Name = entry.Name
|
dnschange.Name = entry.Name
|
||||||
}
|
}
|
||||||
@@ -257,6 +260,7 @@ func deleteDNS(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(entrytext + " deleted.")
|
json.NewEncoder(w).Encode(entrytext + " deleted.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateDNS - creates a DNS entry
|
||||||
func CreateDNS(entry models.DNSEntry) (models.DNSEntry, error) {
|
func CreateDNS(entry models.DNSEntry) (models.DNSEntry, error) {
|
||||||
|
|
||||||
data, err := json.Marshal(&entry)
|
data, err := json.Marshal(&entry)
|
||||||
@@ -272,6 +276,7 @@ func CreateDNS(entry models.DNSEntry) (models.DNSEntry, error) {
|
|||||||
return entry, err
|
return entry, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetDNSEntry - gets a DNS entry
|
||||||
func GetDNSEntry(domain string, network string) (models.DNSEntry, error) {
|
func GetDNSEntry(domain string, network string) (models.DNSEntry, error) {
|
||||||
var entry models.DNSEntry
|
var entry models.DNSEntry
|
||||||
key, err := functions.GetRecordKey(domain, network)
|
key, err := functions.GetRecordKey(domain, network)
|
||||||
@@ -286,6 +291,7 @@ func GetDNSEntry(domain string, network string) (models.DNSEntry, error) {
|
|||||||
return entry, err
|
return entry, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateDNS - updates DNS entry
|
||||||
func UpdateDNS(dnschange models.DNSEntry, entry models.DNSEntry) (models.DNSEntry, error) {
|
func UpdateDNS(dnschange models.DNSEntry, entry models.DNSEntry) (models.DNSEntry, error) {
|
||||||
|
|
||||||
key, err := functions.GetRecordKey(entry.Name, entry.Network)
|
key, err := functions.GetRecordKey(entry.Name, entry.Network)
|
||||||
@@ -308,9 +314,9 @@ func UpdateDNS(dnschange models.DNSEntry, entry models.DNSEntry) (models.DNSEntr
|
|||||||
data, err := json.Marshal(&entry)
|
data, err := json.Marshal(&entry)
|
||||||
err = database.Insert(newkey, string(data), database.DNS_TABLE_NAME)
|
err = database.Insert(newkey, string(data), database.DNS_TABLE_NAME)
|
||||||
return entry, err
|
return entry, err
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteDNS - deletes a DNS entry
|
||||||
func DeleteDNS(domain string, network string) error {
|
func DeleteDNS(domain string, network string) error {
|
||||||
key, err := functions.GetRecordKey(domain, network)
|
key, err := functions.GetRecordKey(domain, network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -334,6 +340,7 @@ func pushDNS(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode("DNS Pushed to CoreDNS")
|
json.NewEncoder(w).Encode("DNS Pushed to CoreDNS")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidateDNSCreate - checks if an entry is valid
|
||||||
func ValidateDNSCreate(entry models.DNSEntry) error {
|
func ValidateDNSCreate(entry models.DNSEntry) error {
|
||||||
|
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
@@ -357,6 +364,7 @@ func ValidateDNSCreate(entry models.DNSEntry) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidateDNSUpdate - validates a DNS update
|
||||||
func ValidateDNSUpdate(change models.DNSEntry, entry models.DNSEntry) error {
|
func ValidateDNSUpdate(change models.DNSEntry, entry models.DNSEntry) error {
|
||||||
|
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
|
@@ -56,6 +56,7 @@ func getNetworkExtClients(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(extclients)
|
json.NewEncoder(w).Encode(extclients)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNetworkExtClients - gets the ext clients of given network
|
||||||
func GetNetworkExtClients(network string) ([]models.ExtClient, error) {
|
func GetNetworkExtClients(network string) ([]models.ExtClient, error) {
|
||||||
var extclients []models.ExtClient
|
var extclients []models.ExtClient
|
||||||
|
|
||||||
@@ -130,6 +131,7 @@ func getExtClient(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(client)
|
json.NewEncoder(w).Encode(client)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetExtClient - gets a single ext client on a network
|
||||||
func GetExtClient(clientid string, network string) (models.ExtClient, error) {
|
func GetExtClient(clientid string, network string) (models.ExtClient, error) {
|
||||||
var extclient models.ExtClient
|
var extclient models.ExtClient
|
||||||
key, err := functions.GetRecordKey(clientid, network)
|
key, err := functions.GetRecordKey(clientid, network)
|
||||||
@@ -238,6 +240,7 @@ Endpoint = %s
|
|||||||
json.NewEncoder(w).Encode(client)
|
json.NewEncoder(w).Encode(client)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateExtClient - creates an extclient
|
||||||
func CreateExtClient(extclient models.ExtClient) error {
|
func CreateExtClient(extclient models.ExtClient) error {
|
||||||
if extclient.PrivateKey == "" {
|
if extclient.PrivateKey == "" {
|
||||||
privateKey, err := wgtypes.GeneratePrivateKey()
|
privateKey, err := wgtypes.GeneratePrivateKey()
|
||||||
@@ -351,6 +354,7 @@ func updateExtClient(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(newclient)
|
json.NewEncoder(w).Encode(newclient)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateExtClient - only supports name changes right now
|
||||||
func UpdateExtClient(newclientid string, network string, client models.ExtClient) (models.ExtClient, error) {
|
func UpdateExtClient(newclientid string, network string, client models.ExtClient) (models.ExtClient, error) {
|
||||||
|
|
||||||
err := DeleteExtClient(network, client.ClientID)
|
err := DeleteExtClient(network, client.ClientID)
|
||||||
@@ -362,6 +366,7 @@ func UpdateExtClient(newclientid string, network string, client models.ExtClient
|
|||||||
return client, err
|
return client, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteExtClient - deletes an existing ext client
|
||||||
func DeleteExtClient(network string, clientid string) error {
|
func DeleteExtClient(network string, clientid string) error {
|
||||||
key, err := functions.GetRecordKey(clientid, network)
|
key, err := functions.GetRecordKey(clientid, network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -371,9 +376,7 @@ func DeleteExtClient(network string, clientid string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network
|
||||||
* Deletes ext clients based on gateway (mac) of ingress node and network
|
|
||||||
*/
|
|
||||||
func DeleteGatewayExtClients(gatewayID string, networkName string) error {
|
func DeleteGatewayExtClients(gatewayID string, networkName string) error {
|
||||||
currentExtClients, err := GetNetworkExtClients(networkName)
|
currentExtClients, err := GetNetworkExtClients(networkName)
|
||||||
if err != nil && !database.IsEmptyRecord(err) {
|
if err != nil && !database.IsEmptyRecord(err) {
|
||||||
@@ -411,6 +414,7 @@ func deleteExtClient(w http.ResponseWriter, r *http.Request) {
|
|||||||
returnSuccessResponse(w, r, params["clientid"]+" deleted.")
|
returnSuccessResponse(w, r, params["clientid"]+" deleted.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StringWithCharset - returns a random string in a charset
|
||||||
func StringWithCharset(length int, charset string) string {
|
func StringWithCharset(length int, charset string) string {
|
||||||
b := make([]byte, length)
|
b := make([]byte, length)
|
||||||
for i := range b {
|
for i := range b {
|
||||||
|
@@ -1,11 +1,10 @@
|
|||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"github.com/gorilla/mux"
|
||||||
"github.com/gorilla/mux"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
func fileHandlers(r *mux.Router) {
|
func fileHandlers(r *mux.Router) {
|
||||||
r.PathPrefix("/meshclient/files").Handler(http.StripPrefix("/meshclient/files", http.FileServer(http.Dir("./meshclient/files"))))
|
r.PathPrefix("/meshclient/files").Handler(http.StripPrefix("/meshclient/files", http.FileServer(http.Dir("./meshclient/files"))))
|
||||||
}
|
}
|
||||||
|
@@ -228,14 +228,14 @@ func TestValidateNetworkUpdate(t *testing.T) {
|
|||||||
|
|
||||||
//DeleteNetworks
|
//DeleteNetworks
|
||||||
cases := []NetworkValidationTestCase{
|
cases := []NetworkValidationTestCase{
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "InvalidAddress",
|
testname: "InvalidAddress",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
AddressRange: "10.0.0.256",
|
AddressRange: "10.0.0.256",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'AddressRange' failed on the 'cidr' tag",
|
errMessage: "Field validation for 'AddressRange' failed on the 'cidr' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "InvalidAddress6",
|
testname: "InvalidAddress6",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
AddressRange6: "2607::ag",
|
AddressRange6: "2607::ag",
|
||||||
@@ -243,77 +243,77 @@ func TestValidateNetworkUpdate(t *testing.T) {
|
|||||||
errMessage: "Field validation for 'AddressRange6' failed on the 'cidr' tag",
|
errMessage: "Field validation for 'AddressRange6' failed on the 'cidr' tag",
|
||||||
},
|
},
|
||||||
|
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "BadDisplayName",
|
testname: "BadDisplayName",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DisplayName: "skynet*",
|
DisplayName: "skynet*",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DisplayName' failed on the 'alphanum' tag",
|
errMessage: "Field validation for 'DisplayName' failed on the 'alphanum' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "DisplayNameTooLong",
|
testname: "DisplayNameTooLong",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DisplayName: "Thisisareallylongdisplaynamethatistoolong",
|
DisplayName: "Thisisareallylongdisplaynamethatistoolong",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DisplayName' failed on the 'max' tag",
|
errMessage: "Field validation for 'DisplayName' failed on the 'max' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "DisplayNameTooShort",
|
testname: "DisplayNameTooShort",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DisplayName: "1",
|
DisplayName: "1",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DisplayName' failed on the 'min' tag",
|
errMessage: "Field validation for 'DisplayName' failed on the 'min' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "InvalidNetID",
|
testname: "InvalidNetID",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
NetID: "contains spaces",
|
NetID: "contains spaces",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'NetID' failed on the 'alphanum' tag",
|
errMessage: "Field validation for 'NetID' failed on the 'alphanum' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "NetIDTooLong",
|
testname: "NetIDTooLong",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
NetID: "LongNetIDName",
|
NetID: "LongNetIDName",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'NetID' failed on the 'max' tag",
|
errMessage: "Field validation for 'NetID' failed on the 'max' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "ListenPortTooLow",
|
testname: "ListenPortTooLow",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DefaultListenPort: 1023,
|
DefaultListenPort: 1023,
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DefaultListenPort' failed on the 'min' tag",
|
errMessage: "Field validation for 'DefaultListenPort' failed on the 'min' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "ListenPortTooHigh",
|
testname: "ListenPortTooHigh",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DefaultListenPort: 65536,
|
DefaultListenPort: 65536,
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DefaultListenPort' failed on the 'max' tag",
|
errMessage: "Field validation for 'DefaultListenPort' failed on the 'max' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "KeepAliveTooBig",
|
testname: "KeepAliveTooBig",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DefaultKeepalive: 1010,
|
DefaultKeepalive: 1010,
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DefaultKeepalive' failed on the 'max' tag",
|
errMessage: "Field validation for 'DefaultKeepalive' failed on the 'max' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "InvalidLocalRange",
|
testname: "InvalidLocalRange",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
LocalRange: "192.168.0.1",
|
LocalRange: "192.168.0.1",
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'LocalRange' failed on the 'cidr' tag",
|
errMessage: "Field validation for 'LocalRange' failed on the 'cidr' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "CheckInIntervalTooBig",
|
testname: "CheckInIntervalTooBig",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DefaultCheckInInterval: 100001,
|
DefaultCheckInInterval: 100001,
|
||||||
},
|
},
|
||||||
errMessage: "Field validation for 'DefaultCheckInInterval' failed on the 'max' tag",
|
errMessage: "Field validation for 'DefaultCheckInInterval' failed on the 'max' tag",
|
||||||
},
|
},
|
||||||
NetworkValidationTestCase{
|
{
|
||||||
testname: "CheckInIntervalTooSmall",
|
testname: "CheckInIntervalTooSmall",
|
||||||
network: models.Network{
|
network: models.Network{
|
||||||
DefaultCheckInInterval: 1,
|
DefaultCheckInInterval: 1,
|
||||||
|
@@ -12,10 +12,12 @@ import (
|
|||||||
"github.com/gravitl/netmaker/models"
|
"github.com/gravitl/netmaker/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// NodeServiceServer - represents the service server for gRPC
|
||||||
type NodeServiceServer struct {
|
type NodeServiceServer struct {
|
||||||
nodepb.UnimplementedNodeServiceServer
|
nodepb.UnimplementedNodeServiceServer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NodeServiceServer.ReadNode - reads node and responds with gRPC
|
||||||
func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
||||||
// convert string id (from proto) to mongoDB ObjectId
|
// convert string id (from proto) to mongoDB ObjectId
|
||||||
macAndNetwork := strings.Split(req.Data, "###")
|
macAndNetwork := strings.Split(req.Data, "###")
|
||||||
@@ -41,6 +43,7 @@ func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.Object) (*
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NodeServiceServer.CreateNode - creates a node and responds over gRPC
|
||||||
func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
||||||
// Get the protobuf node type from the protobuf request type
|
// Get the protobuf node type from the protobuf request type
|
||||||
// Essentially doing req.Node to access the struct with a nil check
|
// Essentially doing req.Node to access the struct with a nil check
|
||||||
@@ -86,6 +89,7 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.Object)
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NodeServiceServer.UpdateNode updates a node and responds over gRPC
|
||||||
func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
||||||
// Get the node data from the request
|
// Get the node data from the request
|
||||||
var newnode models.Node
|
var newnode models.Node
|
||||||
@@ -113,6 +117,7 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.Object)
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NodeServiceServer.DeleteNode - deletes a node and responds over gRPC
|
||||||
func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
||||||
nodeID := req.GetData()
|
nodeID := req.GetData()
|
||||||
|
|
||||||
@@ -127,6 +132,7 @@ func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.Object)
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NodeServiceServer.GetPeers - fetches peers over gRPC
|
||||||
func (s *NodeServiceServer) GetPeers(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
func (s *NodeServiceServer) GetPeers(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
||||||
macAndNetwork := strings.Split(req.Data, "###")
|
macAndNetwork := strings.Split(req.Data, "###")
|
||||||
if len(macAndNetwork) == 2 {
|
if len(macAndNetwork) == 2 {
|
||||||
@@ -135,7 +141,7 @@ func (s *NodeServiceServer) GetPeers(ctx context.Context, req *nodepb.Object) (*
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if node.IsServer == "yes" && logic.IsLeader(&node){
|
if node.IsServer == "yes" && logic.IsLeader(&node) {
|
||||||
logic.SetNetworkServerPeers(&node)
|
logic.SetNetworkServerPeers(&node)
|
||||||
}
|
}
|
||||||
excludeIsRelayed := node.IsRelay != "yes"
|
excludeIsRelayed := node.IsRelay != "yes"
|
||||||
@@ -161,10 +167,7 @@ func (s *NodeServiceServer) GetPeers(ctx context.Context, req *nodepb.Object) (*
|
|||||||
}, errors.New("could not fetch peers, invalid node id")
|
}, errors.New("could not fetch peers, invalid node id")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// NodeServiceServer.GetExtPeers - returns ext peers for a gateway node
|
||||||
* Return Ext Peers (clients).NodeCheckIn
|
|
||||||
* When a gateway node checks in, it pulls these peers to add to peers list in addition to normal network peers.
|
|
||||||
*/
|
|
||||||
func (s *NodeServiceServer) GetExtPeers(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
func (s *NodeServiceServer) GetExtPeers(ctx context.Context, req *nodepb.Object) (*nodepb.Object, error) {
|
||||||
// Initiate a NodeItem type to write decoded data to
|
// Initiate a NodeItem type to write decoded data to
|
||||||
//data := &models.PeersResponse{}
|
//data := &models.PeersResponse{}
|
||||||
|
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/gravitl/netmaker/database"
|
"github.com/gravitl/netmaker/database"
|
||||||
"github.com/gravitl/netmaker/dnslogic"
|
"github.com/gravitl/netmaker/dnslogic"
|
||||||
@@ -71,7 +72,7 @@ func authenticate(response http.ResponseWriter, request *http.Request) {
|
|||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
|
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API until approved).
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errorResponse.Code = http.StatusBadRequest
|
errorResponse.Code = http.StatusBadRequest
|
||||||
@@ -189,7 +190,7 @@ func authorize(networkCheck bool, authNetwork string, next http.Handler) http.Ha
|
|||||||
//This checks if
|
//This checks if
|
||||||
//A: the token is the master password
|
//A: the token is the master password
|
||||||
//B: the token corresponds to a mac address, and if so, which one
|
//B: the token corresponds to a mac address, and if so, which one
|
||||||
//TODO: There's probably a better way of dealing with the "master token"/master password. Plz Halp.
|
//TODO: There's probably a better way of dealing with the "master token"/master password. Plz Help.
|
||||||
var isAuthorized = false
|
var isAuthorized = false
|
||||||
var macaddress = ""
|
var macaddress = ""
|
||||||
username, networks, isadmin, errN := functions.VerifyUserToken(authToken)
|
username, networks, isadmin, errN := functions.VerifyUserToken(authToken)
|
||||||
|
@@ -33,6 +33,7 @@ func createRelay(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(node)
|
json.NewEncoder(w).Encode(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateRelay - creates a relay
|
||||||
func CreateRelay(relay models.RelayRequest) (models.Node, error) {
|
func CreateRelay(relay models.RelayRequest) (models.Node, error) {
|
||||||
node, err := functions.GetNodeByMacAddress(relay.NetID, relay.NodeID)
|
node, err := functions.GetNodeByMacAddress(relay.NetID, relay.NodeID)
|
||||||
if node.OS == "windows" || node.OS == "macos" { // add in darwin later
|
if node.OS == "windows" || node.OS == "macos" { // add in darwin later
|
||||||
@@ -87,6 +88,7 @@ func deleteRelay(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(node)
|
json.NewEncoder(w).Encode(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetRelayedNodes- set relayed nodes
|
||||||
func SetRelayedNodes(yesOrno string, networkName string, addrs []string) error {
|
func SetRelayedNodes(yesOrno string, networkName string, addrs []string) error {
|
||||||
|
|
||||||
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -118,6 +120,7 @@ func SetRelayedNodes(yesOrno string, networkName string, addrs []string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidateRelay - checks if relay is valid
|
||||||
func ValidateRelay(relay models.RelayRequest) error {
|
func ValidateRelay(relay models.RelayRequest) error {
|
||||||
var err error
|
var err error
|
||||||
//isIp := functions.IsIpCIDR(gateway.RangeString)
|
//isIp := functions.IsIpCIDR(gateway.RangeString)
|
||||||
@@ -128,6 +131,7 @@ func ValidateRelay(relay models.RelayRequest) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateRelay - updates a relay
|
||||||
func UpdateRelay(network string, oldAddrs []string, newAddrs []string) {
|
func UpdateRelay(network string, oldAddrs []string, newAddrs []string) {
|
||||||
time.Sleep(time.Second / 4)
|
time.Sleep(time.Second / 4)
|
||||||
err := SetRelayedNodes("no", network, oldAddrs)
|
err := SetRelayedNodes("no", network, oldAddrs)
|
||||||
@@ -140,6 +144,7 @@ func UpdateRelay(network string, oldAddrs []string, newAddrs []string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteRelay - deletes a relay
|
||||||
func DeleteRelay(network, macaddress string) (models.Node, error) {
|
func DeleteRelay(network, macaddress string) (models.Node, error) {
|
||||||
|
|
||||||
node, err := functions.GetNodeByMacAddress(network, macaddress)
|
node, err := functions.GetNodeByMacAddress(network, macaddress)
|
||||||
|
@@ -49,7 +49,7 @@ func securityCheckServer(adminonly bool, next http.Handler) http.HandlerFunc {
|
|||||||
if !adminonly && (err != nil || user == "") {
|
if !adminonly && (err != nil || user == "") {
|
||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if adminonly && !isadmin && !authenticateMasterServer(authToken) {
|
if adminonly && !isadmin && !authenticateMasterServer(authToken) {
|
||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
|
@@ -28,11 +28,11 @@ func userHandlers(r *mux.Router) {
|
|||||||
r.HandleFunc("/api/users", authorizeUserAdm(http.HandlerFunc(getUsers))).Methods("GET")
|
r.HandleFunc("/api/users", authorizeUserAdm(http.HandlerFunc(getUsers))).Methods("GET")
|
||||||
}
|
}
|
||||||
|
|
||||||
//Node authenticates using its password and retrieves a JWT for authorization.
|
// Node authenticates using its password and retrieves a JWT for authorization.
|
||||||
func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
||||||
|
|
||||||
//Auth request consists of Mac Address and Password (from node that is authorizing
|
// Auth request consists of Mac Address and Password (from node that is authorizing
|
||||||
//in case of Master, auth is ignored and mac is set to "mastermac"
|
// in case of Master, auth is ignored and mac is set to "mastermac"
|
||||||
var authRequest models.UserAuthParams
|
var authRequest models.UserAuthParams
|
||||||
var errorResponse = models.ErrorResponse{
|
var errorResponse = models.ErrorResponse{
|
||||||
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
|
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
|
||||||
@@ -53,7 +53,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if jwt == "" {
|
if jwt == "" {
|
||||||
//very unlikely that err is !nil and no jwt returned, but handle it anyways.
|
// very unlikely that err is !nil and no jwt returned, but handle it anyways.
|
||||||
returnErrorResponse(response, request, formatError(errors.New("No token returned"), "internal"))
|
returnErrorResponse(response, request, formatError(errors.New("No token returned"), "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -67,7 +67,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
|||||||
UserName: username,
|
UserName: username,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
//Send back the JWT
|
// Send back the JWT
|
||||||
successJSONResponse, jsonError := json.Marshal(successResponse)
|
successJSONResponse, jsonError := json.Marshal(successResponse)
|
||||||
|
|
||||||
if jsonError != nil {
|
if jsonError != nil {
|
||||||
@@ -79,6 +79,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
|||||||
response.Write(successJSONResponse)
|
response.Write(successJSONResponse)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// VerifyAuthRequest - verifies an auth request
|
||||||
func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
|
func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
|
||||||
var result models.User
|
var result models.User
|
||||||
if authRequest.UserName == "" {
|
if authRequest.UserName == "" {
|
||||||
@@ -86,7 +87,7 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
|
|||||||
} else if authRequest.Password == "" {
|
} else if authRequest.Password == "" {
|
||||||
return "", errors.New("password can't be empty")
|
return "", errors.New("password can't be empty")
|
||||||
}
|
}
|
||||||
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
|
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API until approved).
|
||||||
record, err := database.FetchRecord(database.USERS_TABLE_NAME, authRequest.UserName)
|
record, err := database.FetchRecord(database.USERS_TABLE_NAME, authRequest.UserName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.New("incorrect credentials")
|
return "", errors.New("incorrect credentials")
|
||||||
@@ -95,9 +96,9 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
|
|||||||
return "", errors.New("incorrect credentials")
|
return "", errors.New("incorrect credentials")
|
||||||
}
|
}
|
||||||
|
|
||||||
//compare password from request to stored password in database
|
// compare password from request to stored password in database
|
||||||
//might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
|
// might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
|
||||||
//TODO: Consider a way of hashing the password client side before sending, or using certificates
|
// TODO: Consider a way of hashing the password client side before sending, or using certificates
|
||||||
if err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password)); err != nil {
|
if err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password)); err != nil {
|
||||||
return "", errors.New("incorrect credentials")
|
return "", errors.New("incorrect credentials")
|
||||||
}
|
}
|
||||||
@@ -107,19 +108,19 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
|
|||||||
return tokenString, nil
|
return tokenString, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//The middleware for most requests to the API
|
// The middleware for most requests to the API
|
||||||
//They all pass through here first
|
// They all pass through here first
|
||||||
//This will validate the JWT (or check for master token)
|
// This will validate the JWT (or check for master token)
|
||||||
//This will also check against the authNetwork and make sure the node should be accessing that endpoint,
|
// This will also check against the authNetwork and make sure the node should be accessing that endpoint,
|
||||||
//even if it's technically ok
|
// even if it's technically ok
|
||||||
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
// This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
||||||
//TODO: Consider better RBAC implementations
|
// TODO: Consider better RBAC implementations
|
||||||
func authorizeUser(next http.Handler) http.HandlerFunc {
|
func authorizeUser(next http.Handler) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
//get the auth token
|
// get the auth token
|
||||||
bearerToken := r.Header.Get("Authorization")
|
bearerToken := r.Header.Get("Authorization")
|
||||||
username := params["username"]
|
username := params["username"]
|
||||||
err := ValidateUserToken(bearerToken, username, false)
|
err := ValidateUserToken(bearerToken, username, false)
|
||||||
@@ -150,6 +151,7 @@ func authorizeUserAdm(next http.Handler) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidateUserToken - self explained
|
||||||
func ValidateUserToken(token string, user string, adminonly bool) error {
|
func ValidateUserToken(token string, user string, adminonly bool) error {
|
||||||
var tokenSplit = strings.Split(token, " ")
|
var tokenSplit = strings.Split(token, " ")
|
||||||
//I put this in in case the user doesn't put in a token at all (in which case it's empty)
|
//I put this in in case the user doesn't put in a token at all (in which case it's empty)
|
||||||
@@ -179,6 +181,7 @@ func ValidateUserToken(token string, user string, adminonly bool) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HasAdmin - checks if server has an admin
|
||||||
func HasAdmin() (bool, error) {
|
func HasAdmin() (bool, error) {
|
||||||
|
|
||||||
collection, err := database.FetchRecords(database.USERS_TABLE_NAME)
|
collection, err := database.FetchRecords(database.USERS_TABLE_NAME)
|
||||||
@@ -218,6 +221,7 @@ func hasAdmin(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetUser - gets a user
|
||||||
func GetUser(username string) (models.ReturnUser, error) {
|
func GetUser(username string) (models.ReturnUser, error) {
|
||||||
|
|
||||||
var user models.ReturnUser
|
var user models.ReturnUser
|
||||||
@@ -231,6 +235,7 @@ func GetUser(username string) (models.ReturnUser, error) {
|
|||||||
return user, err
|
return user, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetUserInternal - gets an internal user
|
||||||
func GetUserInternal(username string) (models.User, error) {
|
func GetUserInternal(username string) (models.User, error) {
|
||||||
|
|
||||||
var user models.User
|
var user models.User
|
||||||
@@ -244,6 +249,7 @@ func GetUserInternal(username string) (models.User, error) {
|
|||||||
return user, err
|
return user, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetUsers - gets users
|
||||||
func GetUsers() ([]models.ReturnUser, error) {
|
func GetUsers() ([]models.ReturnUser, error) {
|
||||||
|
|
||||||
var users []models.ReturnUser
|
var users []models.ReturnUser
|
||||||
@@ -267,7 +273,7 @@ func GetUsers() ([]models.ReturnUser, error) {
|
|||||||
return users, err
|
return users, err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Get an individual node. Nothin fancy here folks.
|
// Get an individual node. Nothin fancy here folks.
|
||||||
func getUser(w http.ResponseWriter, r *http.Request) {
|
func getUser(w http.ResponseWriter, r *http.Request) {
|
||||||
// set header.
|
// set header.
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -284,7 +290,7 @@ func getUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(user)
|
json.NewEncoder(w).Encode(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Get an individual node. Nothin fancy here folks.
|
// Get an individual node. Nothin fancy here folks.
|
||||||
func getUsers(w http.ResponseWriter, r *http.Request) {
|
func getUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
// set header.
|
// set header.
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -300,8 +306,9 @@ func getUsers(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(users)
|
json.NewEncoder(w).Encode(users)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateUser - creates a user
|
||||||
func CreateUser(user models.User) (models.User, error) {
|
func CreateUser(user models.User) (models.User, error) {
|
||||||
//check if user exists
|
// check if user exists
|
||||||
if _, err := GetUser(user.UserName); err == nil {
|
if _, err := GetUser(user.UserName); err == nil {
|
||||||
return models.User{}, errors.New("user exists")
|
return models.User{}, errors.New("user exists")
|
||||||
}
|
}
|
||||||
@@ -310,18 +317,18 @@ func CreateUser(user models.User) (models.User, error) {
|
|||||||
return models.User{}, err
|
return models.User{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
//encrypt that password so we never see it again
|
// encrypt that password so we never see it again
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5)
|
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return user, err
|
return user, err
|
||||||
}
|
}
|
||||||
//set password to encrypted password
|
// set password to encrypted password
|
||||||
user.Password = string(hash)
|
user.Password = string(hash)
|
||||||
|
|
||||||
tokenString, _ := functions.CreateUserJWT(user.UserName, user.Networks, user.IsAdmin)
|
tokenString, _ := functions.CreateUserJWT(user.UserName, user.Networks, user.IsAdmin)
|
||||||
|
|
||||||
if tokenString == "" {
|
if tokenString == "" {
|
||||||
//returnErrorResponse(w, r, errorResponse)
|
// returnErrorResponse(w, r, errorResponse)
|
||||||
return user, err
|
return user, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,7 +346,7 @@ func createAdmin(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var admin models.User
|
var admin models.User
|
||||||
//get node from body of request
|
// get node from body of request
|
||||||
_ = json.NewDecoder(r.Body).Decode(&admin)
|
_ = json.NewDecoder(r.Body).Decode(&admin)
|
||||||
admin.IsAdmin = true
|
admin.IsAdmin = true
|
||||||
admin, err := CreateUser(admin)
|
admin, err := CreateUser(admin)
|
||||||
@@ -356,7 +363,7 @@ func createUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var user models.User
|
var user models.User
|
||||||
//get node from body of request
|
// get node from body of request
|
||||||
_ = json.NewDecoder(r.Body).Decode(&user)
|
_ = json.NewDecoder(r.Body).Decode(&user)
|
||||||
|
|
||||||
user, err := CreateUser(user)
|
user, err := CreateUser(user)
|
||||||
@@ -369,6 +376,7 @@ func createUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(user)
|
json.NewEncoder(w).Encode(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateUser - updates a given user
|
||||||
func UpdateUser(userchange models.User, user models.User) (models.User, error) {
|
func UpdateUser(userchange models.User, user models.User) (models.User, error) {
|
||||||
//check if user exists
|
//check if user exists
|
||||||
if _, err := GetUser(user.UserName); err != nil {
|
if _, err := GetUser(user.UserName); err != nil {
|
||||||
@@ -389,13 +397,13 @@ func UpdateUser(userchange models.User, user models.User) (models.User, error) {
|
|||||||
user.Networks = userchange.Networks
|
user.Networks = userchange.Networks
|
||||||
}
|
}
|
||||||
if userchange.Password != "" {
|
if userchange.Password != "" {
|
||||||
//encrypt that password so we never see it again
|
// encrypt that password so we never see it again
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(userchange.Password), 5)
|
hash, err := bcrypt.GenerateFromPassword([]byte(userchange.Password), 5)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return userchange, err
|
return userchange, err
|
||||||
}
|
}
|
||||||
//set password to encrypted password
|
// set password to encrypted password
|
||||||
userchange.Password = string(hash)
|
userchange.Password = string(hash)
|
||||||
|
|
||||||
user.Password = userchange.Password
|
user.Password = userchange.Password
|
||||||
@@ -418,7 +426,7 @@ func updateUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
var user models.User
|
var user models.User
|
||||||
//start here
|
// start here
|
||||||
username := params["username"]
|
username := params["username"]
|
||||||
user, err := GetUserInternal(username)
|
user, err := GetUserInternal(username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -446,7 +454,7 @@ func updateUserAdm(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
var user models.User
|
var user models.User
|
||||||
//start here
|
// start here
|
||||||
username := params["username"]
|
username := params["username"]
|
||||||
user, err := GetUserInternal(username)
|
user, err := GetUserInternal(username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -469,6 +477,7 @@ func updateUserAdm(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(user)
|
json.NewEncoder(w).Encode(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteUser - deletes a given user
|
||||||
func DeleteUser(user string) (bool, error) {
|
func DeleteUser(user string) (bool, error) {
|
||||||
|
|
||||||
if userRecord, err := database.FetchRecord(database.USERS_TABLE_NAME, user); err != nil || len(userRecord) == 0 {
|
if userRecord, err := database.FetchRecord(database.USERS_TABLE_NAME, user); err != nil || len(userRecord) == 0 {
|
||||||
@@ -504,6 +513,7 @@ func deleteUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(params["username"] + " deleted.")
|
json.NewEncoder(w).Encode(params["username"] + " deleted.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidateUser - validates a user model
|
||||||
func ValidateUser(operation string, user models.User) error {
|
func ValidateUser(operation string, user models.User) error {
|
||||||
|
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
|
@@ -2,10 +2,10 @@ package database
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"time"
|
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
|
||||||
"github.com/gravitl/netmaker/servercfg"
|
"github.com/gravitl/netmaker/servercfg"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const NETWORKS_TABLE_NAME = "networks"
|
const NETWORKS_TABLE_NAME = "networks"
|
||||||
@@ -46,7 +46,7 @@ func getCurrentDB() map[string]interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func InitializeDatabase() error {
|
func InitializeDatabase() error {
|
||||||
log.Println("connecting to",servercfg.GetDB())
|
log.Println("connecting to", servercfg.GetDB())
|
||||||
tperiod := time.Now().Add(10 * time.Second)
|
tperiod := time.Now().Add(10 * time.Second)
|
||||||
for {
|
for {
|
||||||
if err := getCurrentDB()[INIT_DB].(func() error)(); err != nil {
|
if err := getCurrentDB()[INIT_DB].(func() error)(); err != nil {
|
||||||
|
@@ -7,8 +7,10 @@ import (
|
|||||||
"github.com/rqlite/gorqlite"
|
"github.com/rqlite/gorqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// RQliteDatabase - the rqlite db connection
|
||||||
var RQliteDatabase gorqlite.Connection
|
var RQliteDatabase gorqlite.Connection
|
||||||
|
|
||||||
|
// RQLITE_FUNCTIONS - all the functions to run with rqlite
|
||||||
var RQLITE_FUNCTIONS = map[string]interface{}{
|
var RQLITE_FUNCTIONS = map[string]interface{}{
|
||||||
INIT_DB: initRqliteDatabase,
|
INIT_DB: initRqliteDatabase,
|
||||||
CREATE_TABLE: rqliteCreateTable,
|
CREATE_TABLE: rqliteCreateTable,
|
||||||
@@ -46,9 +48,8 @@ func rqliteInsert(key string, value string, tableName string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
} else {
|
|
||||||
return errors.New("invalid insert " + key + " : " + value)
|
|
||||||
}
|
}
|
||||||
|
return errors.New("invalid insert " + key + " : " + value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func rqliteInsertPeer(key string, value string) error {
|
func rqliteInsertPeer(key string, value string) error {
|
||||||
@@ -58,9 +59,8 @@ func rqliteInsertPeer(key string, value string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
} else {
|
|
||||||
return errors.New("invalid peer insert " + key + " : " + value)
|
|
||||||
}
|
}
|
||||||
|
return errors.New("invalid peer insert " + key + " : " + value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func rqliteDeleteRecord(tableName string, key string) error {
|
func rqliteDeleteRecord(tableName string, key string) error {
|
||||||
|
@@ -6,14 +6,16 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
_ "github.com/mattn/go-sqlite3" // need to blank import this package
|
||||||
)
|
)
|
||||||
|
|
||||||
// == sqlite ==
|
// == sqlite ==
|
||||||
const dbFilename = "netmaker.db"
|
const dbFilename = "netmaker.db"
|
||||||
|
|
||||||
|
// SqliteDB is the db object fro sqlite database connections
|
||||||
var SqliteDB *sql.DB
|
var SqliteDB *sql.DB
|
||||||
|
|
||||||
|
// SQLITE_FUNCTIONS - contains a map of the functions for sqlite
|
||||||
var SQLITE_FUNCTIONS = map[string]interface{}{
|
var SQLITE_FUNCTIONS = map[string]interface{}{
|
||||||
INIT_DB: initSqliteDB,
|
INIT_DB: initSqliteDB,
|
||||||
CREATE_TABLE: sqliteCreateTable,
|
CREATE_TABLE: sqliteCreateTable,
|
||||||
@@ -67,9 +69,8 @@ func sqliteInsert(key string, value string, tableName string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
} else {
|
|
||||||
return errors.New("invalid insert " + key + " : " + value)
|
|
||||||
}
|
}
|
||||||
|
return errors.New("invalid insert " + key + " : " + value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func sqliteInsertPeer(key string, value string) error {
|
func sqliteInsertPeer(key string, value string) error {
|
||||||
@@ -79,9 +80,8 @@ func sqliteInsertPeer(key string, value string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
} else {
|
|
||||||
return errors.New("invalid peer insert " + key + " : " + value)
|
|
||||||
}
|
}
|
||||||
|
return errors.New("invalid peer insert " + key + " : " + value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func sqliteDeleteRecord(tableName string, key string) error {
|
func sqliteDeleteRecord(tableName string, key string) error {
|
||||||
|
@@ -5,6 +5,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetPeers - sets peers for a network
|
||||||
func SetPeers(newPeers map[string]string, networkName string) bool {
|
func SetPeers(newPeers map[string]string, networkName string) bool {
|
||||||
areEqual := PeersAreEqual(newPeers, networkName)
|
areEqual := PeersAreEqual(newPeers, networkName)
|
||||||
if !areEqual {
|
if !areEqual {
|
||||||
@@ -17,6 +18,8 @@ func SetPeers(newPeers map[string]string, networkName string) bool {
|
|||||||
}
|
}
|
||||||
return !areEqual
|
return !areEqual
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPeers - gets peers for a given network
|
||||||
func GetPeers(networkName string) (map[string]string, error) {
|
func GetPeers(networkName string) (map[string]string, error) {
|
||||||
record, err := FetchRecord(PEERS_TABLE_NAME, networkName)
|
record, err := FetchRecord(PEERS_TABLE_NAME, networkName)
|
||||||
if err != nil && !IsEmptyRecord(err) {
|
if err != nil && !IsEmptyRecord(err) {
|
||||||
@@ -30,6 +33,7 @@ func GetPeers(networkName string) (map[string]string, error) {
|
|||||||
return currentDataMap, err
|
return currentDataMap, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PeersAreEqual - checks if peers are the same
|
||||||
func PeersAreEqual(toCompare map[string]string, networkName string) bool {
|
func PeersAreEqual(toCompare map[string]string, networkName string) bool {
|
||||||
currentDataMap, err := GetPeers(networkName)
|
currentDataMap, err := GetPeers(networkName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -46,6 +50,7 @@ func PeersAreEqual(toCompare map[string]string, networkName string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsEmptyRecord - checks for if it's an empty record error or not
|
||||||
func IsEmptyRecord(err error) bool {
|
func IsEmptyRecord(err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
|
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/txn2/txeh"
|
"github.com/txn2/txeh"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetDNS - sets the dns on file
|
||||||
func SetDNS() error {
|
func SetDNS() error {
|
||||||
hostfile := txeh.Hosts{}
|
hostfile := txeh.Hosts{}
|
||||||
var corefilestring string
|
var corefilestring string
|
||||||
@@ -42,6 +43,7 @@ func SetDNS() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetDNS - gets the DNS of a current network
|
||||||
func GetDNS(network string) ([]models.DNSEntry, error) {
|
func GetDNS(network string) ([]models.DNSEntry, error) {
|
||||||
|
|
||||||
var dns []models.DNSEntry
|
var dns []models.DNSEntry
|
||||||
@@ -58,6 +60,7 @@ func GetDNS(network string) ([]models.DNSEntry, error) {
|
|||||||
return dns, nil
|
return dns, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNodeDNS - gets the DNS of a network node
|
||||||
func GetNodeDNS(network string) ([]models.DNSEntry, error) {
|
func GetNodeDNS(network string) ([]models.DNSEntry, error) {
|
||||||
|
|
||||||
var dns []models.DNSEntry
|
var dns []models.DNSEntry
|
||||||
@@ -81,6 +84,7 @@ func GetNodeDNS(network string) ([]models.DNSEntry, error) {
|
|||||||
return dns, nil
|
return dns, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetCustomDNS - gets the custom DNS of a network
|
||||||
func GetCustomDNS(network string) ([]models.DNSEntry, error) {
|
func GetCustomDNS(network string) ([]models.DNSEntry, error) {
|
||||||
|
|
||||||
var dns []models.DNSEntry
|
var dns []models.DNSEntry
|
||||||
|
@@ -20,6 +20,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/servercfg"
|
"github.com/gravitl/netmaker/servercfg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// PrintUserLog - prints a log with a given username
|
||||||
func PrintUserLog(username string, message string, loglevel int) {
|
func PrintUserLog(username string, message string, loglevel int) {
|
||||||
log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
|
log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
|
||||||
if int32(loglevel) <= servercfg.GetVerbose() && servercfg.GetVerbose() != 0 {
|
if int32(loglevel) <= servercfg.GetVerbose() && servercfg.GetVerbose() != 0 {
|
||||||
@@ -27,24 +28,28 @@ func PrintUserLog(username string, message string, loglevel int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseNetwork - parses a network into a model
|
||||||
func ParseNetwork(value string) (models.Network, error) {
|
func ParseNetwork(value string) (models.Network, error) {
|
||||||
var network models.Network
|
var network models.Network
|
||||||
err := json.Unmarshal([]byte(value), &network)
|
err := json.Unmarshal([]byte(value), &network)
|
||||||
return network, err
|
return network, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseNode - parses a node into a model
|
||||||
func ParseNode(value string) (models.Node, error) {
|
func ParseNode(value string) (models.Node, error) {
|
||||||
var node models.Node
|
var node models.Node
|
||||||
err := json.Unmarshal([]byte(value), &node)
|
err := json.Unmarshal([]byte(value), &node)
|
||||||
return node, err
|
return node, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseExtClient - parses an extclient into a model
|
||||||
func ParseExtClient(value string) (models.ExtClient, error) {
|
func ParseExtClient(value string) (models.ExtClient, error) {
|
||||||
var extClient models.ExtClient
|
var extClient models.ExtClient
|
||||||
err := json.Unmarshal([]byte(value), &extClient)
|
err := json.Unmarshal([]byte(value), &extClient)
|
||||||
return extClient, err
|
return extClient, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseIntClient - parses int client
|
||||||
func ParseIntClient(value string) (models.IntClient, error) {
|
func ParseIntClient(value string) (models.IntClient, error) {
|
||||||
var intClient models.IntClient
|
var intClient models.IntClient
|
||||||
err := json.Unmarshal([]byte(value), &intClient)
|
err := json.Unmarshal([]byte(value), &intClient)
|
||||||
@@ -54,6 +59,7 @@ func ParseIntClient(value string) (models.IntClient, error) {
|
|||||||
//Takes in an arbitrary field and value for field and checks to see if any other
|
//Takes in an arbitrary field and value for field and checks to see if any other
|
||||||
//node has that value for the same field within the network
|
//node has that value for the same field within the network
|
||||||
|
|
||||||
|
// GetUser - gets a user
|
||||||
func GetUser(username string) (models.User, error) {
|
func GetUser(username string) (models.User, error) {
|
||||||
|
|
||||||
var user models.User
|
var user models.User
|
||||||
@@ -67,6 +73,7 @@ func GetUser(username string) (models.User, error) {
|
|||||||
return user, err
|
return user, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SliceContains - sees if a slice contains something
|
||||||
func SliceContains(slice []string, item string) bool {
|
func SliceContains(slice []string, item string) bool {
|
||||||
set := make(map[string]struct{}, len(slice))
|
set := make(map[string]struct{}, len(slice))
|
||||||
for _, s := range slice {
|
for _, s := range slice {
|
||||||
@@ -77,6 +84,7 @@ func SliceContains(slice []string, item string) bool {
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateServerToken - creates a server token
|
||||||
func CreateServerToken(netID string) (string, error) {
|
func CreateServerToken(netID string) (string, error) {
|
||||||
var network models.Network
|
var network models.Network
|
||||||
var accesskey models.AccessKey
|
var accesskey models.AccessKey
|
||||||
@@ -130,6 +138,7 @@ func CreateServerToken(netID string) (string, error) {
|
|||||||
return accesskey.AccessString, nil
|
return accesskey.AccessString, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPeersList - gets peers for given network
|
||||||
func GetPeersList(networkName string) ([]models.PeersResponse, error) {
|
func GetPeersList(networkName string) ([]models.PeersResponse, error) {
|
||||||
|
|
||||||
var peers []models.PeersResponse
|
var peers []models.PeersResponse
|
||||||
@@ -151,6 +160,7 @@ func GetPeersList(networkName string) ([]models.PeersResponse, error) {
|
|||||||
return peers, err
|
return peers, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetIntPeersList - get int peers list
|
||||||
func GetIntPeersList() ([]models.PeersResponse, error) {
|
func GetIntPeersList() ([]models.PeersResponse, error) {
|
||||||
|
|
||||||
var peers []models.PeersResponse
|
var peers []models.PeersResponse
|
||||||
@@ -176,6 +186,7 @@ func GetIntPeersList() ([]models.PeersResponse, error) {
|
|||||||
return peers, err
|
return peers, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetServerIntClient - get server int client
|
||||||
func GetServerIntClient() (*models.IntClient, error) {
|
func GetServerIntClient() (*models.IntClient, error) {
|
||||||
|
|
||||||
intClients, err := database.FetchRecords(database.INT_CLIENTS_TABLE_NAME)
|
intClients, err := database.FetchRecords(database.INT_CLIENTS_TABLE_NAME)
|
||||||
@@ -192,6 +203,7 @@ func GetServerIntClient() (*models.IntClient, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NetworkExists - check if network exists
|
||||||
func NetworkExists(name string) (bool, error) {
|
func NetworkExists(name string) (bool, error) {
|
||||||
|
|
||||||
var network string
|
var network string
|
||||||
@@ -201,6 +213,8 @@ func NetworkExists(name string) (bool, error) {
|
|||||||
}
|
}
|
||||||
return len(network) > 0, nil
|
return len(network) > 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetRecordKey - get record key
|
||||||
func GetRecordKey(id string, network string) (string, error) {
|
func GetRecordKey(id string, network string) (string, error) {
|
||||||
if id == "" || network == "" {
|
if id == "" || network == "" {
|
||||||
return "", errors.New("unable to get record key")
|
return "", errors.New("unable to get record key")
|
||||||
@@ -208,6 +222,7 @@ func GetRecordKey(id string, network string) (string, error) {
|
|||||||
return id + "###" + network, nil
|
return id + "###" + network, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateNetworkNodeAddresses - updates network node addresses
|
||||||
func UpdateNetworkNodeAddresses(networkName string) error {
|
func UpdateNetworkNodeAddresses(networkName string) error {
|
||||||
|
|
||||||
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -244,6 +259,7 @@ func UpdateNetworkNodeAddresses(networkName string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NetworkNodesUpdateAction - updates action of network nodes
|
||||||
func NetworkNodesUpdateAction(networkName string, action string) error {
|
func NetworkNodesUpdateAction(networkName string, action string) error {
|
||||||
|
|
||||||
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -277,6 +293,7 @@ func NetworkNodesUpdateAction(networkName string, action string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NetworkNodesUpdatePullChanges - tells nodes on network to pull
|
||||||
func NetworkNodesUpdatePullChanges(networkName string) error {
|
func NetworkNodesUpdatePullChanges(networkName string) error {
|
||||||
|
|
||||||
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collections, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -308,6 +325,7 @@ func NetworkNodesUpdatePullChanges(networkName string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateNetworkLocalAddresses - updates network localaddresses
|
||||||
func UpdateNetworkLocalAddresses(networkName string) error {
|
func UpdateNetworkLocalAddresses(networkName string) error {
|
||||||
|
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -346,6 +364,7 @@ func UpdateNetworkLocalAddresses(networkName string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsNetworkDisplayNameUnique - checks if network display name unique
|
||||||
func IsNetworkDisplayNameUnique(name string) (bool, error) {
|
func IsNetworkDisplayNameUnique(name string) (bool, error) {
|
||||||
|
|
||||||
isunique := true
|
isunique := true
|
||||||
@@ -365,6 +384,7 @@ func IsNetworkDisplayNameUnique(name string) (bool, error) {
|
|||||||
return isunique, nil
|
return isunique, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsMacAddressUnique - checks if mac is unique
|
||||||
func IsMacAddressUnique(macaddress string, networkName string) (bool, error) {
|
func IsMacAddressUnique(macaddress string, networkName string) (bool, error) {
|
||||||
|
|
||||||
_, err := database.FetchRecord(database.NODES_TABLE_NAME, macaddress+"###"+networkName)
|
_, err := database.FetchRecord(database.NODES_TABLE_NAME, macaddress+"###"+networkName)
|
||||||
@@ -375,6 +395,7 @@ func IsMacAddressUnique(macaddress string, networkName string) (bool, error) {
|
|||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNetworkNonServerNodeCount - get number of network non server nodes
|
||||||
func GetNetworkNonServerNodeCount(networkName string) (int, error) {
|
func GetNetworkNonServerNodeCount(networkName string) (int, error) {
|
||||||
|
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -400,6 +421,8 @@ func GetNetworkNonServerNodeCount(networkName string) (int, error) {
|
|||||||
//Does so by checking against all keys and seeing if any have the same value
|
//Does so by checking against all keys and seeing if any have the same value
|
||||||
//may want to hash values before comparing...consider this
|
//may want to hash values before comparing...consider this
|
||||||
//TODO: No error handling!!!!
|
//TODO: No error handling!!!!
|
||||||
|
|
||||||
|
// IsKeyValid - check if key is valid
|
||||||
func IsKeyValid(networkname string, keyvalue string) bool {
|
func IsKeyValid(networkname string, keyvalue string) bool {
|
||||||
|
|
||||||
network, _ := GetParentNetwork(networkname)
|
network, _ := GetParentNetwork(networkname)
|
||||||
@@ -422,6 +445,7 @@ func IsKeyValid(networkname string, keyvalue string) bool {
|
|||||||
return isvalid
|
return isvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsKeyValidGlobal - checks if a key is valid globally
|
||||||
func IsKeyValidGlobal(keyvalue string) bool {
|
func IsKeyValidGlobal(keyvalue string) bool {
|
||||||
|
|
||||||
networks, _ := models.GetNetworks()
|
networks, _ := models.GetNetworks()
|
||||||
@@ -453,6 +477,8 @@ func IsKeyValidGlobal(keyvalue string) bool {
|
|||||||
//This just gets a network object from a network name
|
//This just gets a network object from a network name
|
||||||
//Should probably just be GetNetwork. kind of a dumb name.
|
//Should probably just be GetNetwork. kind of a dumb name.
|
||||||
//Used in contexts where it's not the Parent network.
|
//Used in contexts where it's not the Parent network.
|
||||||
|
|
||||||
|
// GetParentNetwork - get parent network
|
||||||
func GetParentNetwork(networkname string) (models.Network, error) {
|
func GetParentNetwork(networkname string) (models.Network, error) {
|
||||||
|
|
||||||
var network models.Network
|
var network models.Network
|
||||||
@@ -466,6 +492,7 @@ func GetParentNetwork(networkname string) (models.Network, error) {
|
|||||||
return network, nil
|
return network, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsIpNet - checks if valid ip
|
||||||
func IsIpNet(host string) bool {
|
func IsIpNet(host string) bool {
|
||||||
return net.ParseIP(host) != nil
|
return net.ParseIP(host) != nil
|
||||||
}
|
}
|
||||||
@@ -473,6 +500,8 @@ func IsIpNet(host string) bool {
|
|||||||
//Similar to above but checks if Cidr range is valid
|
//Similar to above but checks if Cidr range is valid
|
||||||
//At least this guy's got some print statements
|
//At least this guy's got some print statements
|
||||||
//still not good error handling
|
//still not good error handling
|
||||||
|
|
||||||
|
// IsIpCIDR - IsIpCIDR
|
||||||
func IsIpCIDR(host string) bool {
|
func IsIpCIDR(host string) bool {
|
||||||
|
|
||||||
ip, ipnet, err := net.ParseCIDR(host)
|
ip, ipnet, err := net.ParseCIDR(host)
|
||||||
@@ -488,6 +517,8 @@ func IsIpCIDR(host string) bool {
|
|||||||
|
|
||||||
//This checks to make sure a network name is valid.
|
//This checks to make sure a network name is valid.
|
||||||
//Switch to REGEX?
|
//Switch to REGEX?
|
||||||
|
|
||||||
|
// NameInNetworkCharSet - see if name is in charset for networks
|
||||||
func NameInNetworkCharSet(name string) bool {
|
func NameInNetworkCharSet(name string) bool {
|
||||||
|
|
||||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_."
|
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_."
|
||||||
@@ -500,6 +531,7 @@ func NameInNetworkCharSet(name string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NameInDNSCharSet - name in dns char set
|
||||||
func NameInDNSCharSet(name string) bool {
|
func NameInDNSCharSet(name string) bool {
|
||||||
|
|
||||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-."
|
charset := "abcdefghijklmnopqrstuvwxyz1234567890-."
|
||||||
@@ -512,6 +544,7 @@ func NameInDNSCharSet(name string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NameInNodeCharSet - name in node char set
|
||||||
func NameInNodeCharSet(name string) bool {
|
func NameInNodeCharSet(name string) bool {
|
||||||
|
|
||||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
|
charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
|
||||||
@@ -528,6 +561,8 @@ func NameInNodeCharSet(name string) bool {
|
|||||||
//The mac address acts as the Unique ID for nodes.
|
//The mac address acts as the Unique ID for nodes.
|
||||||
//Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
|
//Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
|
||||||
//It doesn't really provide a tangible benefit over a random ID
|
//It doesn't really provide a tangible benefit over a random ID
|
||||||
|
|
||||||
|
// GetNodeByMacAddress - gets a node by mac address
|
||||||
func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
|
func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
|
||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
@@ -551,6 +586,7 @@ func GetNodeByMacAddress(network string, macaddress string) (models.Node, error)
|
|||||||
return node, nil
|
return node, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetDeletedNodeByMacAddress - get a deleted node
|
||||||
func GetDeletedNodeByMacAddress(network string, macaddress string) (models.Node, error) {
|
func GetDeletedNodeByMacAddress(network string, macaddress string) (models.Node, error) {
|
||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
@@ -574,10 +610,12 @@ func GetDeletedNodeByMacAddress(network string, macaddress string) (models.Node,
|
|||||||
return node, nil
|
return node, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveDeletedNode - remove deleted node
|
||||||
func RemoveDeletedNode(nodeid string) bool {
|
func RemoveDeletedNode(nodeid string) bool {
|
||||||
return database.DeleteRecord(database.DELETED_NODES_TABLE_NAME, nodeid) == nil
|
return database.DeleteRecord(database.DELETED_NODES_TABLE_NAME, nodeid) == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteAllIntClients - delete all int clients
|
||||||
func DeleteAllIntClients() error {
|
func DeleteAllIntClients() error {
|
||||||
err := database.DeleteAllRecords(database.INT_CLIENTS_TABLE_NAME)
|
err := database.DeleteAllRecords(database.INT_CLIENTS_TABLE_NAME)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -586,6 +624,7 @@ func DeleteAllIntClients() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetAllIntClients - get all int clients
|
||||||
func GetAllIntClients() ([]models.IntClient, error) {
|
func GetAllIntClients() ([]models.IntClient, error) {
|
||||||
var clients []models.IntClient
|
var clients []models.IntClient
|
||||||
collection, err := database.FetchRecords(database.INT_CLIENTS_TABLE_NAME)
|
collection, err := database.FetchRecords(database.INT_CLIENTS_TABLE_NAME)
|
||||||
@@ -607,6 +646,7 @@ func GetAllIntClients() ([]models.IntClient, error) {
|
|||||||
return clients, nil
|
return clients, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetAllExtClients - get all ext clients
|
||||||
func GetAllExtClients() ([]models.ExtClient, error) {
|
func GetAllExtClients() ([]models.ExtClient, error) {
|
||||||
var extclients []models.ExtClient
|
var extclients []models.ExtClient
|
||||||
collection, err := database.FetchRecords(database.EXT_CLIENT_TABLE_NAME)
|
collection, err := database.FetchRecords(database.EXT_CLIENT_TABLE_NAME)
|
||||||
@@ -633,6 +673,8 @@ func GetAllExtClients() ([]models.ExtClient, error) {
|
|||||||
//and checks against all nodes to see if it's taken, until it finds one.
|
//and checks against all nodes to see if it's taken, until it finds one.
|
||||||
//TODO: We do not handle a case where we run out of addresses.
|
//TODO: We do not handle a case where we run out of addresses.
|
||||||
//We will need to handle that eventually
|
//We will need to handle that eventually
|
||||||
|
|
||||||
|
// UniqueAddress - see if address is unique
|
||||||
func UniqueAddress(networkName string) (string, error) {
|
func UniqueAddress(networkName string) (string, error) {
|
||||||
|
|
||||||
var network models.Network
|
var network models.Network
|
||||||
@@ -669,6 +711,7 @@ func UniqueAddress(networkName string) (string, error) {
|
|||||||
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UniqueAddress6 - see if ipv6 address is unique
|
||||||
func UniqueAddress6(networkName string) (string, error) {
|
func UniqueAddress6(networkName string) (string, error) {
|
||||||
|
|
||||||
var network models.Network
|
var network models.Network
|
||||||
@@ -701,7 +744,7 @@ func UniqueAddress6(networkName string) (string, error) {
|
|||||||
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
||||||
}
|
}
|
||||||
|
|
||||||
//generate an access key value
|
// GenKey - generates access key
|
||||||
func GenKey() string {
|
func GenKey() string {
|
||||||
|
|
||||||
var seededRand *rand.Rand = rand.New(
|
var seededRand *rand.Rand = rand.New(
|
||||||
@@ -721,6 +764,8 @@ func GenKey() string {
|
|||||||
//we should probably just have 1 random string generator
|
//we should probably just have 1 random string generator
|
||||||
//that can be used across all functions
|
//that can be used across all functions
|
||||||
//have a "base string" a "length" and a "charset"
|
//have a "base string" a "length" and a "charset"
|
||||||
|
|
||||||
|
// GenKeyName - generates a key name
|
||||||
func GenKeyName() string {
|
func GenKeyName() string {
|
||||||
|
|
||||||
var seededRand *rand.Rand = rand.New(
|
var seededRand *rand.Rand = rand.New(
|
||||||
@@ -736,6 +781,7 @@ func GenKeyName() string {
|
|||||||
return "key" + string(b)
|
return "key" + string(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsIPUnique - checks if an IP is unique
|
||||||
func IsIPUnique(network string, ip string, tableName string, isIpv6 bool) bool {
|
func IsIPUnique(network string, ip string, tableName string, isIpv6 bool) bool {
|
||||||
|
|
||||||
isunique := true
|
isunique := true
|
||||||
@@ -766,6 +812,7 @@ func IsIPUnique(network string, ip string, tableName string, isIpv6 bool) bool {
|
|||||||
|
|
||||||
//called once key has been used by createNode
|
//called once key has been used by createNode
|
||||||
//reduces value by one and deletes if necessary
|
//reduces value by one and deletes if necessary
|
||||||
|
// DecrimentKey - decriments key uses
|
||||||
func DecrimentKey(networkName string, keyvalue string) {
|
func DecrimentKey(networkName string, keyvalue string) {
|
||||||
|
|
||||||
var network models.Network
|
var network models.Network
|
||||||
@@ -796,7 +843,7 @@ func DecrimentKey(networkName string, keyvalue string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//takes the logic from controllers.deleteKey
|
// DeleteKey - deletes a key
|
||||||
func DeleteKey(network models.Network, i int) {
|
func DeleteKey(network models.Network, i int) {
|
||||||
|
|
||||||
network.AccessKeys = append(network.AccessKeys[:i],
|
network.AccessKeys = append(network.AccessKeys[:i],
|
||||||
@@ -809,7 +856,7 @@ func DeleteKey(network models.Network, i int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//increments an IP over the previous
|
// Inc - increments an IP
|
||||||
func Inc(ip net.IP) {
|
func Inc(ip net.IP) {
|
||||||
for j := len(ip) - 1; j >= 0; j-- {
|
for j := len(ip) - 1; j >= 0; j-- {
|
||||||
ip[j]++
|
ip[j]++
|
||||||
|
@@ -3,6 +3,7 @@ package functions
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v4"
|
"github.com/golang-jwt/jwt/v4"
|
||||||
"github.com/gravitl/netmaker/models"
|
"github.com/gravitl/netmaker/models"
|
||||||
"github.com/gravitl/netmaker/servercfg"
|
"github.com/gravitl/netmaker/servercfg"
|
||||||
@@ -29,6 +30,7 @@ func CreateJWT(macaddress string, network string) (response string, err error) {
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateUserJWT - creates a user jwt token
|
||||||
func CreateUserJWT(username string, networks []string, isadmin bool) (response string, err error) {
|
func CreateUserJWT(username string, networks []string, isadmin bool) (response string, err error) {
|
||||||
expirationTime := time.Now().Add(60 * 12 * time.Minute)
|
expirationTime := time.Now().Add(60 * 12 * time.Minute)
|
||||||
claims := &models.UserClaims{
|
claims := &models.UserClaims{
|
||||||
@@ -70,7 +72,7 @@ func VerifyUserToken(tokenString string) (username string, networks []string, is
|
|||||||
return "", nil, false, err
|
return "", nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GRPC [nodes] Only
|
// VerifyToken - gRPC [nodes] Only
|
||||||
func VerifyToken(tokenString string) (macaddress string, network string, err error) {
|
func VerifyToken(tokenString string) (macaddress string, network string, err error) {
|
||||||
claims := &models.Claims{}
|
claims := &models.Claims{}
|
||||||
|
|
||||||
|
@@ -14,31 +14,31 @@ func FileExists(f string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func SetDNSDir() error {
|
func SetDNSDir() error {
|
||||||
dir, err := os.Getwd()
|
dir, err := os.Getwd()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = os.Stat(dir + "/config/dnsconfig")
|
_, err = os.Stat(dir + "/config/dnsconfig")
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
os.Mkdir(dir+"/config/dnsconfig", 0744)
|
os.Mkdir(dir+"/config/dnsconfig", 0744)
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
PrintUserLog("","couldnt find or create /config/dnsconfig",0)
|
PrintUserLog("", "couldnt find or create /config/dnsconfig", 0)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = os.Stat(dir + "/config/dnsconfig/Corefile")
|
_, err = os.Stat(dir + "/config/dnsconfig/Corefile")
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
err = SetCorefile(".")
|
err = SetCorefile(".")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
PrintUserLog("",err.Error(),0)
|
PrintUserLog("", err.Error(), 0)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_, err = os.Stat(dir + "/config/dnsconfig/netmaker.hosts")
|
}
|
||||||
if os.IsNotExist(err) {
|
_, err = os.Stat(dir + "/config/dnsconfig/netmaker.hosts")
|
||||||
_, err = os.Create(dir + "/config/dnsconfig/netmaker.hosts")
|
if os.IsNotExist(err) {
|
||||||
if err != nil {
|
_, err = os.Create(dir + "/config/dnsconfig/netmaker.hosts")
|
||||||
PrintUserLog("",err.Error(),0)
|
if err != nil {
|
||||||
}
|
PrintUserLog("", err.Error(), 0)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,7 +51,7 @@ func SetCorefile(domains string) error {
|
|||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
os.Mkdir(dir+"/config/dnsconfig", 744)
|
os.Mkdir(dir+"/config/dnsconfig", 744)
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
PrintUserLog("","couldnt find or create /config/dnsconfig",0)
|
PrintUserLog("", "couldnt find or create /config/dnsconfig", 0)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -8,6 +8,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/models"
|
"github.com/gravitl/netmaker/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetExtPeersList - gets the ext peers lists
|
||||||
func GetExtPeersList(macaddress string, networkName string) ([]models.ExtPeersResponse, error) {
|
func GetExtPeersList(macaddress string, networkName string) ([]models.ExtPeersResponse, error) {
|
||||||
|
|
||||||
var peers []models.ExtPeersResponse
|
var peers []models.ExtPeersResponse
|
||||||
|
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/models"
|
"github.com/gravitl/netmaker/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetNetworkNodes - gets the nodes of a network
|
||||||
func GetNetworkNodes(network string) ([]models.Node, error) {
|
func GetNetworkNodes(network string) ([]models.Node, error) {
|
||||||
var nodes []models.Node
|
var nodes []models.Node
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -33,6 +34,7 @@ func GetNetworkNodes(network string) ([]models.Node, error) {
|
|||||||
return nodes, nil
|
return nodes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetSortedNetworkServerNodes - gets nodes of a network, except sorted by update time
|
||||||
func GetSortedNetworkServerNodes(network string) ([]models.Node, error) {
|
func GetSortedNetworkServerNodes(network string) ([]models.Node, error) {
|
||||||
var nodes []models.Node
|
var nodes []models.Node
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -57,6 +59,7 @@ func GetSortedNetworkServerNodes(network string) ([]models.Node, error) {
|
|||||||
return nodes, nil
|
return nodes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPeers - gets the peers of a given node
|
||||||
func GetPeers(node models.Node) ([]models.Node, error) {
|
func GetPeers(node models.Node) ([]models.Node, error) {
|
||||||
if node.IsServer == "yes" && IsLeader(&node) {
|
if node.IsServer == "yes" && IsLeader(&node) {
|
||||||
SetNetworkServerPeers(&node)
|
SetNetworkServerPeers(&node)
|
||||||
@@ -73,6 +76,7 @@ func GetPeers(node models.Node) ([]models.Node, error) {
|
|||||||
return peers, nil
|
return peers, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsLeader - determines if a given server node is a leader
|
||||||
func IsLeader(node *models.Node) bool {
|
func IsLeader(node *models.Node) bool {
|
||||||
nodes, err := GetSortedNetworkServerNodes(node.Network)
|
nodes, err := GetSortedNetworkServerNodes(node.Network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@@ -2,11 +2,12 @@
|
|||||||
package logic
|
package logic
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"encoding/base64"
|
|
||||||
"github.com/gravitl/netmaker/database"
|
"github.com/gravitl/netmaker/database"
|
||||||
"github.com/gravitl/netmaker/dnslogic"
|
"github.com/gravitl/netmaker/dnslogic"
|
||||||
"github.com/gravitl/netmaker/functions"
|
"github.com/gravitl/netmaker/functions"
|
||||||
@@ -16,17 +17,20 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
//This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
|
// IsBase64 - checks if a string is in base64 format
|
||||||
|
// This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
|
||||||
func IsBase64(s string) bool {
|
func IsBase64(s string) bool {
|
||||||
_, err := base64.StdEncoding.DecodeString(s)
|
_, err := base64.StdEncoding.DecodeString(s)
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckEndpoint - checks if an endpoint is valid
|
||||||
func CheckEndpoint(endpoint string) bool {
|
func CheckEndpoint(endpoint string) bool {
|
||||||
endpointarr := strings.Split(endpoint, ":")
|
endpointarr := strings.Split(endpoint, ":")
|
||||||
return len(endpointarr) == 2
|
return len(endpointarr) == 2
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetNetworkServerPeers - sets the network server peers of a given node
|
||||||
func SetNetworkServerPeers(node *models.Node) {
|
func SetNetworkServerPeers(node *models.Node) {
|
||||||
if currentPeersList, err := GetSystemPeers(node); err == nil {
|
if currentPeersList, err := GetSystemPeers(node); err == nil {
|
||||||
if database.SetPeers(currentPeersList, node.Network) {
|
if database.SetPeers(currentPeersList, node.Network) {
|
||||||
@@ -38,7 +42,7 @@ func SetNetworkServerPeers(node *models.Node) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteNode - deletes a node from database or moves into delete nodes table
|
||||||
func DeleteNode(key string, exterminate bool) error {
|
func DeleteNode(key string, exterminate bool) error {
|
||||||
var err error
|
var err error
|
||||||
if !exterminate {
|
if !exterminate {
|
||||||
@@ -70,7 +74,7 @@ func DeleteNode(key string, exterminate bool) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateNode - creates a node in database
|
||||||
func CreateNode(node models.Node, networkName string) (models.Node, error) {
|
func CreateNode(node models.Node, networkName string) (models.Node, error) {
|
||||||
|
|
||||||
//encrypt that password so we never see it
|
//encrypt that password so we never see it
|
||||||
@@ -130,6 +134,7 @@ func CreateNode(node models.Node, networkName string) (models.Node, error) {
|
|||||||
return node, err
|
return node, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetNetworkNodesLastModified - sets the network nodes last modified
|
||||||
func SetNetworkNodesLastModified(networkName string) error {
|
func SetNetworkNodesLastModified(networkName string) error {
|
||||||
|
|
||||||
timestamp := time.Now().Unix()
|
timestamp := time.Now().Unix()
|
||||||
@@ -150,6 +155,7 @@ func SetNetworkNodesLastModified(networkName string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNode - fetches a node from database
|
||||||
func GetNode(macaddress string, network string) (models.Node, error) {
|
func GetNode(macaddress string, network string) (models.Node, error) {
|
||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
@@ -173,6 +179,7 @@ func GetNode(macaddress string, network string) (models.Node, error) {
|
|||||||
return node, err
|
return node, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNodePeers - fetches peers for a given node
|
||||||
func GetNodePeers(networkName string, excludeRelayed bool) ([]models.Node, error) {
|
func GetNodePeers(networkName string, excludeRelayed bool) ([]models.Node, error) {
|
||||||
var peers []models.Node
|
var peers []models.Node
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
@@ -229,6 +236,7 @@ func GetNodePeers(networkName string, excludeRelayed bool) ([]models.Node, error
|
|||||||
return peers, err
|
return peers, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPeersList - gets the peers of a given network
|
||||||
func GetPeersList(networkName string, excludeRelayed bool, relayedNodeAddr string) ([]models.Node, error) {
|
func GetPeersList(networkName string, excludeRelayed bool, relayedNodeAddr string) ([]models.Node, error) {
|
||||||
var peers []models.Node
|
var peers []models.Node
|
||||||
var relayNode models.Node
|
var relayNode models.Node
|
||||||
|
@@ -5,6 +5,7 @@ import (
|
|||||||
"golang.zx2c4.com/wireguard/wgctrl"
|
"golang.zx2c4.com/wireguard/wgctrl"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetSystemPeers - gets the server peers
|
||||||
func GetSystemPeers(node *models.Node) (map[string]string, error) {
|
func GetSystemPeers(node *models.Node) (map[string]string, error) {
|
||||||
peers := make(map[string]string)
|
peers := make(map[string]string)
|
||||||
|
|
||||||
|
2
main.go
2
main.go
@@ -156,7 +156,7 @@ func runGRPC(wg *sync.WaitGroup) {
|
|||||||
log.Fatalf("Failed to serve: %v", err)
|
log.Fatalf("Failed to serve: %v", err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
log.Println("Agent Server succesfully started on port " + grpcport + " (gRPC)")
|
log.Println("Agent Server successfully started on port " + grpcport + " (gRPC)")
|
||||||
|
|
||||||
// Right way to stop the server using a SHUTDOWN HOOK
|
// Right way to stop the server using a SHUTDOWN HOOK
|
||||||
// Create a channel to receive OS signals
|
// Create a channel to receive OS signals
|
||||||
|
@@ -7,27 +7,27 @@ type AccessToken struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ClientConfig struct {
|
type ClientConfig struct {
|
||||||
Network string `json:"network"`
|
Network string `json:"network"`
|
||||||
Key string `json:"key"`
|
Key string `json:"key"`
|
||||||
LocalRange string `json:"localrange"`
|
LocalRange string `json:"localrange"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
CoreDNSAddr string `json:"corednsaddr"`
|
CoreDNSAddr string `json:"corednsaddr"`
|
||||||
APIConnString string `json:"apiconn"`
|
APIConnString string `json:"apiconn"`
|
||||||
APIHost string `json:"apihost"`
|
APIHost string `json:"apihost"`
|
||||||
APIPort string `json:"apiport"`
|
APIPort string `json:"apiport"`
|
||||||
GRPCConnString string `json:"grpcconn"`
|
GRPCConnString string `json:"grpcconn"`
|
||||||
GRPCHost string `json:"grpchost"`
|
GRPCHost string `json:"grpchost"`
|
||||||
GRPCPort string `json:"grpcport"`
|
GRPCPort string `json:"grpcport"`
|
||||||
GRPCSSL string `json:"grpcssl"`
|
GRPCSSL string `json:"grpcssl"`
|
||||||
CheckinInterval string `json:"checkininterval"`
|
CheckinInterval string `json:"checkininterval"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type WG struct {
|
type WG struct {
|
||||||
GRPCWireGuard string `json:"grpcwg"`
|
GRPCWireGuard string `json:"grpcwg"`
|
||||||
GRPCWGAddress string `json:"grpcwgaddr"`
|
GRPCWGAddress string `json:"grpcwgaddr"`
|
||||||
GRPCWGPort string `json:"grpcwgport"`
|
GRPCWGPort string `json:"grpcwgport"`
|
||||||
GRPCWGPubKey string `json:"grpcwgpubkey"`
|
GRPCWGPubKey string `json:"grpcwgpubkey"`
|
||||||
GRPCWGEndpoint string `json:"grpcwgendpoint"`
|
GRPCWGEndpoint string `json:"grpcwgendpoint"`
|
||||||
}
|
}
|
||||||
|
@@ -6,6 +6,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/database"
|
"github.com/gravitl/netmaker/database"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 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"`
|
Description string `json:"description" bson:"description"`
|
||||||
@@ -18,10 +19,7 @@ type ExtClient struct {
|
|||||||
LastModified int64 `json:"lastmodified" bson:"lastmodified"`
|
LastModified int64 `json:"lastmodified" bson:"lastmodified"`
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client
|
||||||
* Get the egress gateway ips of a given ExtClient struct
|
|
||||||
* returns as []string
|
|
||||||
*/
|
|
||||||
func (client *ExtClient) GetEgressRangesOnNetwork() ([]string, error) {
|
func (client *ExtClient) GetEgressRangesOnNetwork() ([]string, error) {
|
||||||
|
|
||||||
var result []string
|
var result []string
|
||||||
|
@@ -1,18 +1,18 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
type IntClient struct {
|
type IntClient struct {
|
||||||
ClientID string `json:"clientid" bson:"clientid"`
|
ClientID string `json:"clientid" bson:"clientid"`
|
||||||
PrivateKey string `json:"privatekey" bson:"privatekey"`
|
PrivateKey string `json:"privatekey" bson:"privatekey"`
|
||||||
PublicKey string `json:"publickey" bson:"publickey"`
|
PublicKey string `json:"publickey" bson:"publickey"`
|
||||||
AccessKey string `json:"accesskey" bson:"accesskey"`
|
AccessKey string `json:"accesskey" bson:"accesskey"`
|
||||||
Address string `json:"address" bson:"address"`
|
Address string `json:"address" bson:"address"`
|
||||||
Address6 string `json:"address6" bson:"address6"`
|
Address6 string `json:"address6" bson:"address6"`
|
||||||
Network string `json:"network" bson:"network"`
|
Network string `json:"network" bson:"network"`
|
||||||
ServerPublicEndpoint string `json:"serverpublicendpoint" bson:"serverpublicendpoint"`
|
ServerPublicEndpoint string `json:"serverpublicendpoint" bson:"serverpublicendpoint"`
|
||||||
ServerAPIPort string `json:"serverapiport" bson:"serverapiport"`
|
ServerAPIPort string `json:"serverapiport" bson:"serverapiport"`
|
||||||
ServerPrivateAddress string `json:"serverprivateaddress" bson:"serverprivateaddress"`
|
ServerPrivateAddress string `json:"serverprivateaddress" bson:"serverprivateaddress"`
|
||||||
ServerWGPort string `json:"serverwgport" bson:"serverwgport"`
|
ServerWGPort string `json:"serverwgport" bson:"serverwgport"`
|
||||||
ServerGRPCPort string `json:"servergrpcport" bson:"servergrpcport"`
|
ServerGRPCPort string `json:"servergrpcport" bson:"servergrpcport"`
|
||||||
ServerKey string `json:"serverkey" bson:"serverkey"`
|
ServerKey string `json:"serverkey" bson:"serverkey"`
|
||||||
IsServer string `json:"isserver" bson:"isserver"`
|
IsServer string `json:"isserver" bson:"isserver"`
|
||||||
}
|
}
|
||||||
|
@@ -12,43 +12,45 @@ import (
|
|||||||
"github.com/gravitl/netmaker/servercfg"
|
"github.com/gravitl/netmaker/servercfg"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Network Struct
|
// Network Struct - contains info for a given unique network
|
||||||
//At some point, need to replace all instances of Name with something else like Identifier
|
//At some point, need to replace all instances of Name with something else like Identifier
|
||||||
type Network struct {
|
type Network struct {
|
||||||
AddressRange string `json:"addressrange" bson:"addressrange" validate:"required,cidr"`
|
AddressRange string `json:"addressrange" bson:"addressrange" validate:"required,cidr"`
|
||||||
AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"regexp=^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$"`
|
AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"regexp=^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$"`
|
||||||
DisplayName string `json:"displayname,omitempty" bson:"displayname,omitempty" validate:"omitempty,min=1,max=20,displayname_valid"`
|
DisplayName string `json:"displayname,omitempty" bson:"displayname,omitempty" validate:"omitempty,min=1,max=20,displayname_valid"`
|
||||||
NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=12,netid_valid"`
|
NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=12,netid_valid"`
|
||||||
NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"`
|
NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"`
|
||||||
NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"`
|
NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"`
|
||||||
DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=15"`
|
DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=15"`
|
||||||
DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,min=1024,max=65535"`
|
DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,min=1024,max=65535"`
|
||||||
NodeLimit int32 `json:"nodelimit" bson:"nodelimit"`
|
NodeLimit int32 `json:"nodelimit" bson:"nodelimit"`
|
||||||
DefaultPostUp string `json:"defaultpostup" bson:"defaultpostup"`
|
DefaultPostUp string `json:"defaultpostup" bson:"defaultpostup"`
|
||||||
DefaultPostDown string `json:"defaultpostdown" bson:"defaultpostdown"`
|
DefaultPostDown string `json:"defaultpostdown" bson:"defaultpostdown"`
|
||||||
KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp"`
|
KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp"`
|
||||||
DefaultKeepalive int32 `json:"defaultkeepalive" bson:"defaultkeepalive" validate:"omitempty,max=1000"`
|
DefaultKeepalive int32 `json:"defaultkeepalive" bson:"defaultkeepalive" validate:"omitempty,max=1000"`
|
||||||
DefaultSaveConfig string `json:"defaultsaveconfig" bson:"defaultsaveconfig" validate:"checkyesorno"`
|
DefaultSaveConfig string `json:"defaultsaveconfig" bson:"defaultsaveconfig" validate:"checkyesorno"`
|
||||||
AccessKeys []AccessKey `json:"accesskeys" bson:"accesskeys"`
|
AccessKeys []AccessKey `json:"accesskeys" bson:"accesskeys"`
|
||||||
AllowManualSignUp string `json:"allowmanualsignup" bson:"allowmanualsignup" validate:"checkyesorno"`
|
AllowManualSignUp string `json:"allowmanualsignup" bson:"allowmanualsignup" validate:"checkyesorno"`
|
||||||
IsLocal string `json:"islocal" bson:"islocal" validate:"checkyesorno"`
|
IsLocal string `json:"islocal" bson:"islocal" validate:"checkyesorno"`
|
||||||
IsDualStack string `json:"isdualstack" bson:"isdualstack" validate:"checkyesorno"`
|
IsDualStack string `json:"isdualstack" bson:"isdualstack" validate:"checkyesorno"`
|
||||||
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"`
|
||||||
IsGRPCHub string `json:"isgrpchub" bson:"isgrpchub" validate:"checkyesorno"`
|
IsGRPCHub string `json:"isgrpchub" bson:"isgrpchub" validate:"checkyesorno"`
|
||||||
LocalRange string `json:"localrange" bson:"localrange" validate:"omitempty,cidr"`
|
LocalRange string `json:"localrange" bson:"localrange" validate:"omitempty,cidr"`
|
||||||
|
|
||||||
// checkin interval is depreciated at the network level. Set on server with CHECKIN_INTERVAL
|
// checkin interval is depreciated at the network level. Set on server with CHECKIN_INTERVAL
|
||||||
DefaultCheckInInterval int32 `json:"checkininterval,omitempty" bson:"checkininterval,omitempty" validate:"omitempty,numeric,min=2,max=100000"`
|
DefaultCheckInInterval int32 `json:"checkininterval,omitempty" bson:"checkininterval,omitempty" validate:"omitempty,numeric,min=2,max=100000"`
|
||||||
DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"`
|
DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"`
|
||||||
DefaultExtClientDNS string `json:"defaultextclientdns" bson:"defaultextclientdns"`
|
DefaultExtClientDNS string `json:"defaultextclientdns" bson:"defaultextclientdns"`
|
||||||
DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"`
|
DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SaveData - sensitive fields of a network that should be kept the same
|
||||||
type SaveData struct { // put sensitive fields here
|
type SaveData struct { // put sensitive fields here
|
||||||
NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=12,netid_valid"`
|
NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=12,netid_valid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.NetIDInNetworkCharSet - checks if a netid of a network uses valid characters
|
||||||
func (network *Network) NetIDInNetworkCharSet() bool {
|
func (network *Network) NetIDInNetworkCharSet() bool {
|
||||||
|
|
||||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_."
|
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_."
|
||||||
@@ -61,6 +63,7 @@ func (network *Network) NetIDInNetworkCharSet() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.DisplayNameInNetworkCharSet - checks if displayname uses valid characters
|
||||||
func (network *Network) DisplayNameInNetworkCharSet() bool {
|
func (network *Network) DisplayNameInNetworkCharSet() bool {
|
||||||
|
|
||||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_./;% ^#()!@$*"
|
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_./;% ^#()!@$*"
|
||||||
@@ -73,7 +76,7 @@ func (network *Network) DisplayNameInNetworkCharSet() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Anyway, returns all the networks
|
// GetNetworks - returns all networks from database
|
||||||
func GetNetworks() ([]Network, error) {
|
func GetNetworks() ([]Network, error) {
|
||||||
var networks []Network
|
var networks []Network
|
||||||
|
|
||||||
@@ -95,6 +98,7 @@ func GetNetworks() ([]Network, error) {
|
|||||||
return networks, err
|
return networks, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.IsNetworkDisplayNameUnique - checks if displayname is unique from other networks
|
||||||
func (network *Network) IsNetworkDisplayNameUnique() (bool, error) {
|
func (network *Network) IsNetworkDisplayNameUnique() (bool, error) {
|
||||||
|
|
||||||
isunique := true
|
isunique := true
|
||||||
@@ -115,7 +119,7 @@ func (network *Network) IsNetworkDisplayNameUnique() (bool, error) {
|
|||||||
return isunique, nil
|
return isunique, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Checks to see if any other networks have the same name (id)
|
// Network.IsNetworkNameUnique - checks to see if any other networks have the same name (id)
|
||||||
func (network *Network) IsNetworkNameUnique() (bool, error) {
|
func (network *Network) IsNetworkNameUnique() (bool, error) {
|
||||||
|
|
||||||
isunique := true
|
isunique := true
|
||||||
@@ -136,6 +140,7 @@ func (network *Network) IsNetworkNameUnique() (bool, error) {
|
|||||||
return isunique, nil
|
return isunique, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.Validate - validates fields of an network struct
|
||||||
func (network *Network) Validate(isUpdate bool) error {
|
func (network *Network) Validate(isUpdate bool) error {
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
_ = v.RegisterValidation("netid_valid", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("netid_valid", func(fl validator.FieldLevel) bool {
|
||||||
@@ -168,16 +173,17 @@ func (network *Network) Validate(isUpdate bool) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO:
|
// Network.SetNodesLastModified - sets nodes last modified on network, depricated
|
||||||
//Not sure if we need the below two functions. Got rid of one of the calls. May want to revisit
|
|
||||||
func (network *Network) SetNodesLastModified() {
|
func (network *Network) SetNodesLastModified() {
|
||||||
network.NodesLastModified = time.Now().Unix()
|
network.NodesLastModified = time.Now().Unix()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.SetNetworkLastModified - sets network last modified time
|
||||||
func (network *Network) SetNetworkLastModified() {
|
func (network *Network) SetNetworkLastModified() {
|
||||||
network.NetworkLastModified = time.Now().Unix()
|
network.NetworkLastModified = time.Now().Unix()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.SetDefaults - sets default values for a network struct
|
||||||
func (network *Network) SetDefaults() {
|
func (network *Network) SetDefaults() {
|
||||||
if network.DefaultUDPHolePunch == "" {
|
if network.DefaultUDPHolePunch == "" {
|
||||||
if servercfg.IsClientMode() != "off" {
|
if servercfg.IsClientMode() != "off" {
|
||||||
@@ -237,6 +243,7 @@ func (network *Network) SetDefaults() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.Update - updates a network with another network's fields
|
||||||
func (currentNetwork *Network) Update(newNetwork *Network) (bool, bool, error) {
|
func (currentNetwork *Network) Update(newNetwork *Network) (bool, bool, error) {
|
||||||
if err := newNetwork.Validate(true); err != nil {
|
if err := newNetwork.Validate(true); err != nil {
|
||||||
return false, false, err
|
return false, false, err
|
||||||
@@ -244,18 +251,19 @@ func (currentNetwork *Network) Update(newNetwork *Network) (bool, bool, error) {
|
|||||||
if newNetwork.NetID == currentNetwork.NetID {
|
if newNetwork.NetID == currentNetwork.NetID {
|
||||||
hasrangeupdate := newNetwork.AddressRange != currentNetwork.AddressRange
|
hasrangeupdate := newNetwork.AddressRange != currentNetwork.AddressRange
|
||||||
localrangeupdate := newNetwork.LocalRange != currentNetwork.LocalRange
|
localrangeupdate := newNetwork.LocalRange != currentNetwork.LocalRange
|
||||||
if data, err := json.Marshal(newNetwork); err != nil {
|
data, err := json.Marshal(newNetwork)
|
||||||
|
if err != nil {
|
||||||
return false, false, err
|
return false, false, err
|
||||||
} else {
|
|
||||||
newNetwork.SetNetworkLastModified()
|
|
||||||
err = database.Insert(newNetwork.NetID, string(data), database.NETWORKS_TABLE_NAME)
|
|
||||||
return hasrangeupdate, localrangeupdate, err
|
|
||||||
}
|
}
|
||||||
|
newNetwork.SetNetworkLastModified()
|
||||||
|
err = database.Insert(newNetwork.NetID, string(data), database.NETWORKS_TABLE_NAME)
|
||||||
|
return hasrangeupdate, localrangeupdate, err
|
||||||
}
|
}
|
||||||
// copy values
|
// copy values
|
||||||
return false, false, errors.New("failed to update network " + newNetwork.NetID + ", cannot change netid.")
|
return false, false, errors.New("failed to update network " + newNetwork.NetID + ", cannot change netid.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Network.SetNetworkNodesLastModified - sets network nodes last modified time
|
||||||
func (network *Network) SetNetworkNodesLastModified() error {
|
func (network *Network) SetNetworkNodesLastModified() error {
|
||||||
|
|
||||||
timestamp := time.Now().Unix()
|
timestamp := time.Now().Unix()
|
||||||
@@ -272,6 +280,7 @@ func (network *Network) SetNetworkNodesLastModified() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNetwork - gets a network from database
|
||||||
func GetNetwork(networkname string) (Network, error) {
|
func GetNetwork(networkname string) (Network, error) {
|
||||||
|
|
||||||
var network Network
|
var network Network
|
||||||
|
@@ -1,16 +1,16 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"github.com/go-playground/validator/v10"
|
||||||
|
"github.com/gravitl/netmaker/database"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"bytes"
|
|
||||||
"github.com/go-playground/validator/v10"
|
|
||||||
"github.com/gravitl/netmaker/database"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
@@ -2,11 +2,13 @@ package models
|
|||||||
|
|
||||||
import jwt "github.com/golang-jwt/jwt/v4"
|
import jwt "github.com/golang-jwt/jwt/v4"
|
||||||
|
|
||||||
|
// AuthParams - struct for auth params
|
||||||
type AuthParams struct {
|
type AuthParams struct {
|
||||||
MacAddress string `json:"macaddress"`
|
MacAddress string `json:"macaddress"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// User struct - struct for Users
|
||||||
type User struct {
|
type User struct {
|
||||||
UserName string `json:"username" bson:"username" validate:"min=3,max=40,regexp=^(([a-zA-Z,\-,\.]*)|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})){3,40}$"`
|
UserName string `json:"username" bson:"username" validate:"min=3,max=40,regexp=^(([a-zA-Z,\-,\.]*)|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})){3,40}$"`
|
||||||
Password string `json:"password" bson:"password" validate:"required,min=5"`
|
Password string `json:"password" bson:"password" validate:"required,min=5"`
|
||||||
@@ -14,17 +16,20 @@ type User struct {
|
|||||||
IsAdmin bool `json:"isadmin" bson:"isadmin"`
|
IsAdmin bool `json:"isadmin" bson:"isadmin"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReturnUser - return user struct
|
||||||
type ReturnUser struct {
|
type ReturnUser struct {
|
||||||
UserName string `json:"username" bson:"username" validate:"min=3,max=40,regexp=^(([a-zA-Z,\-,\.]*)|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})){3,40}$"`
|
UserName string `json:"username" bson:"username" validate:"min=3,max=40,regexp=^(([a-zA-Z,\-,\.]*)|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})){3,40}$"`
|
||||||
Networks []string `json:"networks" bson:"networks"`
|
Networks []string `json:"networks" bson:"networks"`
|
||||||
IsAdmin bool `json:"isadmin" bson:"isadmin"`
|
IsAdmin bool `json:"isadmin" bson:"isadmin"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UserAuthParams - user auth params struct
|
||||||
type UserAuthParams struct {
|
type UserAuthParams struct {
|
||||||
UserName string `json:"username"`
|
UserName string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UserClaims - user claims struct
|
||||||
type UserClaims struct {
|
type UserClaims struct {
|
||||||
IsAdmin bool
|
IsAdmin bool
|
||||||
UserName string
|
UserName string
|
||||||
@@ -32,6 +37,7 @@ type UserClaims struct {
|
|||||||
jwt.StandardClaims
|
jwt.StandardClaims
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SuccessfulUserLoginResponse - successlogin struct
|
||||||
type SuccessfulUserLoginResponse struct {
|
type SuccessfulUserLoginResponse struct {
|
||||||
UserName string
|
UserName string
|
||||||
AuthToken string
|
AuthToken string
|
||||||
@@ -51,11 +57,13 @@ type SuccessfulLoginResponse struct {
|
|||||||
AuthToken string
|
AuthToken string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ErrorResponse is struct for error
|
||||||
type ErrorResponse struct {
|
type ErrorResponse struct {
|
||||||
Code int
|
Code int
|
||||||
Message string
|
Message string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NodeAuth - struct for node auth
|
||||||
type NodeAuth struct {
|
type NodeAuth struct {
|
||||||
Network string
|
Network string
|
||||||
Password string
|
Password string
|
||||||
@@ -69,6 +77,7 @@ type SuccessResponse struct {
|
|||||||
Response interface{}
|
Response interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AccessKey - access key struct
|
||||||
type AccessKey struct {
|
type AccessKey struct {
|
||||||
Name string `json:"name" bson:"name" validate:"omitempty,max=20"`
|
Name string `json:"name" bson:"name" validate:"omitempty,max=20"`
|
||||||
Value string `json:"value" bson:"value" validate:"omitempty,alphanum,max=16"`
|
Value string `json:"value" bson:"value" validate:"omitempty,alphanum,max=16"`
|
||||||
@@ -76,17 +85,20 @@ type AccessKey struct {
|
|||||||
Uses int `json:"uses" bson:"uses"`
|
Uses int `json:"uses" bson:"uses"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DisplayKey - what is displayed for key
|
||||||
type DisplayKey struct {
|
type DisplayKey struct {
|
||||||
Name string `json:"name" bson:"name"`
|
Name string `json:"name" bson:"name"`
|
||||||
Uses int `json:"uses" bson:"uses"`
|
Uses int `json:"uses" bson:"uses"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GlobalConfig - global config
|
||||||
type GlobalConfig struct {
|
type GlobalConfig struct {
|
||||||
Name string `json:"name" bson:"name"`
|
Name string `json:"name" bson:"name"`
|
||||||
PortGRPC string `json:"portgrpc" bson:"portgrpc"`
|
PortGRPC string `json:"portgrpc" bson:"portgrpc"`
|
||||||
ServerGRPC string `json:"servergrpc" bson:"servergrpc"`
|
ServerGRPC string `json:"servergrpc" bson:"servergrpc"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckInResponse - checkin response
|
||||||
type CheckInResponse struct {
|
type CheckInResponse struct {
|
||||||
Success bool `json:"success" bson:"success"`
|
Success bool `json:"success" bson:"success"`
|
||||||
NeedPeerUpdate bool `json:"needpeerupdate" bson:"needpeerupdate"`
|
NeedPeerUpdate bool `json:"needpeerupdate" bson:"needpeerupdate"`
|
||||||
@@ -97,6 +109,7 @@ type CheckInResponse struct {
|
|||||||
IsPending bool `json:"ispending" bson:"ispending"`
|
IsPending bool `json:"ispending" bson:"ispending"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PeersResponse - peers response
|
||||||
type PeersResponse struct {
|
type PeersResponse struct {
|
||||||
PublicKey string `json:"publickey" bson:"publickey"`
|
PublicKey string `json:"publickey" bson:"publickey"`
|
||||||
Endpoint string `json:"endpoint" bson:"endpoint"`
|
Endpoint string `json:"endpoint" bson:"endpoint"`
|
||||||
@@ -109,6 +122,7 @@ type PeersResponse struct {
|
|||||||
KeepAlive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
KeepAlive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ExtPeersResponse - ext peers response
|
||||||
type ExtPeersResponse struct {
|
type ExtPeersResponse struct {
|
||||||
PublicKey string `json:"publickey" bson:"publickey"`
|
PublicKey string `json:"publickey" bson:"publickey"`
|
||||||
Endpoint string `json:"endpoint" bson:"endpoint"`
|
Endpoint string `json:"endpoint" bson:"endpoint"`
|
||||||
@@ -119,6 +133,7 @@ type ExtPeersResponse struct {
|
|||||||
KeepAlive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
KeepAlive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EgressGatewayRequest - egress gateway request
|
||||||
type EgressGatewayRequest struct {
|
type EgressGatewayRequest struct {
|
||||||
NodeID string `json:"nodeid" bson:"nodeid"`
|
NodeID string `json:"nodeid" bson:"nodeid"`
|
||||||
NetID string `json:"netid" bson:"netid"`
|
NetID string `json:"netid" bson:"netid"`
|
||||||
@@ -129,6 +144,7 @@ type EgressGatewayRequest struct {
|
|||||||
PostDown string `json:"postdown" bson:"postdown"`
|
PostDown string `json:"postdown" bson:"postdown"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RelayRequest - relay request struct
|
||||||
type RelayRequest struct {
|
type RelayRequest struct {
|
||||||
NodeID string `json:"nodeid" bson:"nodeid"`
|
NodeID string `json:"nodeid" bson:"nodeid"`
|
||||||
NetID string `json:"netid" bson:"netid"`
|
NetID string `json:"netid" bson:"netid"`
|
||||||
|
@@ -6,10 +6,12 @@ import (
|
|||||||
"github.com/go-playground/validator/v10"
|
"github.com/go-playground/validator/v10"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// CheckYesOrNo - checks if a field on a struct is yes or no
|
||||||
func CheckYesOrNo(fl validator.FieldLevel) bool {
|
func CheckYesOrNo(fl validator.FieldLevel) bool {
|
||||||
return fl.Field().String() == "yes" || fl.Field().String() == "no"
|
return fl.Field().String() == "yes" || fl.Field().String() == "no"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckRegex - check if a struct's field passes regex test
|
||||||
func CheckRegex(fl validator.FieldLevel) bool {
|
func CheckRegex(fl validator.FieldLevel) bool {
|
||||||
re := regexp.MustCompile(fl.Param())
|
re := regexp.MustCompile(fl.Param())
|
||||||
return re.MatchString(fl.Field().String())
|
return re.MatchString(fl.Field().String())
|
||||||
|
@@ -18,7 +18,7 @@ import (
|
|||||||
"google.golang.org/grpc/status"
|
"google.golang.org/grpc/status"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateJWT func will used to create the JWT while signing in and signing out
|
// SetJWT func will used to create the JWT while signing in and signing out
|
||||||
func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, error) {
|
func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, error) {
|
||||||
home := ncutils.GetNetclientPathSpecific()
|
home := ncutils.GetNetclientPathSpecific()
|
||||||
tokentext, err := ioutil.ReadFile(home + "nettoken-" + network)
|
tokentext, err := ioutil.ReadFile(home + "nettoken-" + network)
|
||||||
@@ -41,6 +41,7 @@ func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, e
|
|||||||
return ctx, nil
|
return ctx, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AutoLogin - auto logins whenever client needs to request from server
|
||||||
func AutoLogin(client nodepb.NodeServiceClient, network string) error {
|
func AutoLogin(client nodepb.NodeServiceClient, network string) error {
|
||||||
home := ncutils.GetNetclientPathSpecific()
|
home := ncutils.GetNetclientPathSpecific()
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
@@ -77,17 +78,20 @@ func AutoLogin(client nodepb.NodeServiceClient, network string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StoreSecret - stores auth secret locally
|
||||||
func StoreSecret(key string, network string) error {
|
func StoreSecret(key string, network string) error {
|
||||||
d1 := []byte(key)
|
d1 := []byte(key)
|
||||||
err := ioutil.WriteFile(ncutils.GetNetclientPathSpecific()+"secret-"+network, d1, 0644)
|
err := ioutil.WriteFile(ncutils.GetNetclientPathSpecific()+"secret-"+network, d1, 0644)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RetrieveSecret - fetches secret locally
|
||||||
func RetrieveSecret(network string) (string, error) {
|
func RetrieveSecret(network string) (string, error) {
|
||||||
dat, err := ioutil.ReadFile(ncutils.GetNetclientPathSpecific() + "secret-" + network)
|
dat, err := ioutil.ReadFile(ncutils.GetNetclientPathSpecific() + "secret-" + network)
|
||||||
return string(dat), err
|
return string(dat), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Configuraion - struct for mac and pass
|
||||||
type Configuration struct {
|
type Configuration struct {
|
||||||
MacAddress string
|
MacAddress string
|
||||||
Password string
|
Password string
|
||||||
|
@@ -15,11 +15,13 @@ import (
|
|||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GlobalConfig - struct for handling IntClients currently
|
||||||
type GlobalConfig struct {
|
type GlobalConfig struct {
|
||||||
GRPCWireGuard string `yaml:"grpcwg"`
|
GRPCWireGuard string `yaml:"grpcwg"`
|
||||||
Client models.IntClient
|
Client models.IntClient
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ClientConfig - struct for dealing with client configuration
|
||||||
type ClientConfig struct {
|
type ClientConfig struct {
|
||||||
Server ServerConfig `yaml:"server"`
|
Server ServerConfig `yaml:"server"`
|
||||||
Node models.Node `yaml:"node"`
|
Node models.Node `yaml:"node"`
|
||||||
@@ -28,23 +30,25 @@ type ClientConfig struct {
|
|||||||
OperatingSystem string `yaml:"operatingsystem"`
|
OperatingSystem string `yaml:"operatingsystem"`
|
||||||
DebugJoin bool `yaml:"debugjoin"`
|
DebugJoin bool `yaml:"debugjoin"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ServerConfig - struct for dealing with the server information for a netclient
|
||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
CoreDNSAddr string `yaml:"corednsaddr"`
|
CoreDNSAddr string `yaml:"corednsaddr"`
|
||||||
GRPCAddress string `yaml:"grpcaddress"`
|
GRPCAddress string `yaml:"grpcaddress"`
|
||||||
APIAddress string `yaml:"apiaddress"`
|
APIAddress string `yaml:"apiaddress"`
|
||||||
AccessKey string `yaml:"accesskey"`
|
AccessKey string `yaml:"accesskey"`
|
||||||
GRPCSSL string `yaml:"grpcssl"`
|
GRPCSSL string `yaml:"grpcssl"`
|
||||||
GRPCWireGuard string `yaml:"grpcwg"`
|
GRPCWireGuard string `yaml:"grpcwg"`
|
||||||
CheckinInterval string `yaml:"checkininterval"`
|
CheckinInterval string `yaml:"checkininterval"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//reading in the env file
|
// Write - writes the config of a client to disk
|
||||||
func Write(config *ClientConfig, network string) error {
|
func Write(config *ClientConfig, network string) error {
|
||||||
if network == "" {
|
if network == "" {
|
||||||
err := errors.New("no network provided - exiting")
|
err := errors.New("no network provided - exiting")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err := os.Stat(ncutils.GetNetclientPath()+"/config")
|
_, err := os.Stat(ncutils.GetNetclientPath() + "/config")
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0744)
|
os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0744)
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
@@ -66,6 +70,7 @@ func Write(config *ClientConfig, network string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteServer - writes the config of a server to disk for client
|
||||||
func WriteServer(server string, accesskey string, network string) error {
|
func WriteServer(server string, accesskey string, network string) error {
|
||||||
if network == "" {
|
if network == "" {
|
||||||
err := errors.New("no network provided - exiting")
|
err := errors.New("no network provided - exiting")
|
||||||
@@ -73,7 +78,7 @@ func WriteServer(server string, accesskey string, network string) error {
|
|||||||
}
|
}
|
||||||
nofile := false
|
nofile := false
|
||||||
//home, err := homedir.Dir()
|
//home, err := homedir.Dir()
|
||||||
_, err := os.Stat(ncutils.GetNetclientPath()+"/config")
|
_, err := os.Stat(ncutils.GetNetclientPath() + "/config")
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0744)
|
os.MkdirAll(ncutils.GetNetclientPath()+"/config", 0744)
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
@@ -149,6 +154,7 @@ func WriteServer(server string, accesskey string, network string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ClientConfig.ReadConfig - used to read config from client disk into memory
|
||||||
func (config *ClientConfig) ReadConfig() {
|
func (config *ClientConfig) ReadConfig() {
|
||||||
|
|
||||||
nofile := false
|
nofile := false
|
||||||
@@ -181,6 +187,7 @@ func (config *ClientConfig) ReadConfig() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ModConfig - overwrites the node inside client config on disk
|
||||||
func ModConfig(node *models.Node) error {
|
func ModConfig(node *models.Node) error {
|
||||||
network := node.Network
|
network := node.Network
|
||||||
if network == "" {
|
if network == "" {
|
||||||
@@ -201,6 +208,7 @@ func ModConfig(node *models.Node) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetCLIConfig - gets the cli flags as a config
|
||||||
func GetCLIConfig(c *cli.Context) (ClientConfig, string, error) {
|
func GetCLIConfig(c *cli.Context) (ClientConfig, string, error) {
|
||||||
var cfg ClientConfig
|
var cfg ClientConfig
|
||||||
if c.String("token") != "" {
|
if c.String("token") != "" {
|
||||||
@@ -312,6 +320,7 @@ func GetCLIConfig(c *cli.Context) (ClientConfig, string, error) {
|
|||||||
return cfg, privateKey, nil
|
return cfg, privateKey, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReadConfig - reads a config of a client from disk for specified network
|
||||||
func ReadConfig(network string) (*ClientConfig, error) {
|
func ReadConfig(network string) (*ClientConfig, error) {
|
||||||
if network == "" {
|
if network == "" {
|
||||||
err := errors.New("no network provided - exiting")
|
err := errors.New("no network provided - exiting")
|
||||||
@@ -340,6 +349,7 @@ func ReadConfig(network string) (*ClientConfig, error) {
|
|||||||
return &cfg, err
|
return &cfg, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FileExists - checks if a file exists on disk
|
||||||
func FileExists(f string) bool {
|
func FileExists(f string) bool {
|
||||||
info, err := os.Stat(f)
|
info, err := os.Stat(f)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
@@ -348,6 +358,7 @@ func FileExists(f string) bool {
|
|||||||
return !info.IsDir()
|
return !info.IsDir()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNode - parses a network specified client config for node data
|
||||||
func GetNode(network string) models.Node {
|
func GetNode(network string) models.Node {
|
||||||
|
|
||||||
modcfg, err := ReadConfig(network)
|
modcfg, err := ReadConfig(network)
|
||||||
|
@@ -1,12 +1,12 @@
|
|||||||
package daemon
|
package daemon
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"fmt"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const MAC_SERVICE_NAME = "com.gravitl.netclient"
|
const MAC_SERVICE_NAME = "com.gravitl.netclient"
|
||||||
@@ -93,7 +93,7 @@ func MacDaemonString(interval string) string {
|
|||||||
</dict>
|
</dict>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
`,interval)
|
`, interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
type MacTemplateData struct {
|
type MacTemplateData struct {
|
||||||
|
@@ -11,8 +11,9 @@ import (
|
|||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetupSystemDDaemon - sets system daemon for supported machines
|
||||||
func SetupSystemDDaemon(interval string) error {
|
func SetupSystemDDaemon(interval string) error {
|
||||||
|
|
||||||
if ncutils.IsWindows() {
|
if ncutils.IsWindows() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -96,6 +97,7 @@ WantedBy=timers.target
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveSystemDServices - removes the systemd services on a machine
|
||||||
func RemoveSystemDServices(network string) error {
|
func RemoveSystemDServices(network string) error {
|
||||||
//sysExec, err := exec.LookPath("systemctl")
|
//sysExec, err := exec.LookPath("systemctl")
|
||||||
if !ncutils.IsWindows() {
|
if !ncutils.IsWindows() {
|
||||||
@@ -130,7 +132,6 @@ func RemoveSystemDServices(network string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func isOnlyService(network string) (bool, error) {
|
func isOnlyService(network string) (bool, error) {
|
||||||
isonly := false
|
isonly := false
|
||||||
files, err := filepath.Glob("/etc/netclient/config/netconfig-*")
|
files, err := filepath.Glob("/etc/netclient/config/netconfig-*")
|
||||||
|
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetupWindowsDaemon - sets up the Windows daemon service
|
||||||
func SetupWindowsDaemon() error {
|
func SetupWindowsDaemon() error {
|
||||||
|
|
||||||
if !ncutils.FileExists(ncutils.GetNetclientPathSpecific() + "winsw.xml") {
|
if !ncutils.FileExists(ncutils.GetNetclientPathSpecific() + "winsw.xml") {
|
||||||
@@ -42,6 +43,7 @@ func SetupWindowsDaemon() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CleanupWindows - cleans up windows files
|
||||||
func CleanupWindows() {
|
func CleanupWindows() {
|
||||||
if !ncutils.FileExists(ncutils.GetNetclientPathSpecific() + "winsw.xml") {
|
if !ncutils.FileExists(ncutils.GetNetclientPathSpecific() + "winsw.xml") {
|
||||||
writeServiceConfig()
|
writeServiceConfig()
|
||||||
@@ -73,12 +75,15 @@ func writeServiceConfig() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// == Daemon ==
|
// == Daemon ==
|
||||||
|
|
||||||
|
// StopWindowsDaemon - stops the Windows daemon
|
||||||
func StopWindowsDaemon() {
|
func StopWindowsDaemon() {
|
||||||
ncutils.Log("no networks detected, stopping Windows, Netclient daemon")
|
ncutils.Log("no networks detected, stopping Windows, Netclient daemon")
|
||||||
// stop daemon, will not overwrite
|
// stop daemon, will not overwrite
|
||||||
ncutils.RunCmd(strings.Replace(ncutils.GetNetclientPathSpecific(), `\\`, `\`, -1)+`winsw.exe stop`, true)
|
ncutils.RunCmd(strings.Replace(ncutils.GetNetclientPathSpecific(), `\\`, `\`, -1)+`winsw.exe stop`, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveWindowsDaemon - removes the Windows daemon
|
||||||
func RemoveWindowsDaemon() {
|
func RemoveWindowsDaemon() {
|
||||||
// uninstall daemon, will not restart or start another
|
// uninstall daemon, will not restart or start another
|
||||||
ncutils.RunCmd(strings.Replace(ncutils.GetNetclientPathSpecific(), `\\`, `\`, -1)+`winsw.exe uninstall`, true)
|
ncutils.RunCmd(strings.Replace(ncutils.GetNetclientPathSpecific(), `\\`, `\`, -1)+`winsw.exe uninstall`, true)
|
||||||
|
@@ -111,6 +111,7 @@ func checkNodeActions(node *models.Node, networkName string, servercfg config.Se
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckConfig - checks if current config of client needs update, see flow below
|
||||||
/**
|
/**
|
||||||
* Pull changes if any (interface refresh)
|
* Pull changes if any (interface refresh)
|
||||||
* - Save it
|
* - Save it
|
||||||
@@ -148,10 +149,7 @@ func CheckConfig(cliconf config.ClientConfig) error {
|
|||||||
return Push(network)
|
return Push(network)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Pull - pulls the latest config from the server, if manual it will overwrite
|
||||||
* Pull the latest node from server
|
|
||||||
* Perform action if necessary
|
|
||||||
*/
|
|
||||||
func Pull(network string, manual bool) (*models.Node, error) {
|
func Pull(network string, manual bool) (*models.Node, error) {
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
node := cfg.Node
|
node := cfg.Node
|
||||||
@@ -259,6 +257,7 @@ func Pull(network string, manual bool) (*models.Node, error) {
|
|||||||
return &resNode, err
|
return &resNode, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Push - pushes current client configuration to server
|
||||||
func Push(network string) error {
|
func Push(network string) error {
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@@ -28,6 +28,7 @@ var (
|
|||||||
wcclient nodepb.NodeServiceClient
|
wcclient nodepb.NodeServiceClient
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ListPorts - lists ports of WireGuard devices
|
||||||
func ListPorts() error {
|
func ListPorts() error {
|
||||||
wgclient, err := wgctrl.New()
|
wgclient, err := wgctrl.New()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -127,6 +128,7 @@ func needInterfaceUpdate(ctx context.Context, mac string, network string, iface
|
|||||||
return iface != oldiface, oldiface, err
|
return iface != oldiface, oldiface, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNode - gets node locally
|
||||||
func GetNode(network string) models.Node {
|
func GetNode(network string) models.Node {
|
||||||
|
|
||||||
modcfg, err := config.ReadConfig(network)
|
modcfg, err := config.ReadConfig(network)
|
||||||
@@ -137,6 +139,7 @@ func GetNode(network string) models.Node {
|
|||||||
return modcfg.Node
|
return modcfg.Node
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Uninstall - uninstalls networks from client
|
||||||
func Uninstall() error {
|
func Uninstall() error {
|
||||||
networks, err := ncutils.GetSystemNetworks()
|
networks, err := ncutils.GetSystemNetworks()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -162,6 +165,7 @@ func Uninstall() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LeaveNetwork - client exits a network
|
||||||
func LeaveNetwork(network string) error {
|
func LeaveNetwork(network string) error {
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -211,6 +215,7 @@ func LeaveNetwork(network string) error {
|
|||||||
return RemoveLocalInstance(cfg, network)
|
return RemoveLocalInstance(cfg, network)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveLocalInstance - remove all netclient files locally for a network
|
||||||
func RemoveLocalInstance(cfg *config.ClientConfig, networkName string) error {
|
func RemoveLocalInstance(cfg *config.ClientConfig, networkName string) error {
|
||||||
err := WipeLocal(networkName)
|
err := WipeLocal(networkName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -230,6 +235,7 @@ func RemoveLocalInstance(cfg *config.ClientConfig, networkName string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteInterface - delete an interface of a network
|
||||||
func DeleteInterface(ifacename string, postdown string) error {
|
func DeleteInterface(ifacename string, postdown string) error {
|
||||||
var err error
|
var err error
|
||||||
if !ncutils.IsKernel() {
|
if !ncutils.IsKernel() {
|
||||||
@@ -249,6 +255,7 @@ func DeleteInterface(ifacename string, postdown string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// List - lists all networks on local machine
|
||||||
func List() error {
|
func List() error {
|
||||||
|
|
||||||
networks, err := ncutils.GetSystemNetworks()
|
networks, err := ncutils.GetSystemNetworks()
|
||||||
@@ -274,6 +281,7 @@ func List() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WipeLocal - wipes local instance
|
||||||
func WipeLocal(network string) error {
|
func WipeLocal(network string) error {
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@@ -21,6 +21,7 @@ import (
|
|||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// JoinNetwork - helps a client join a network
|
||||||
func JoinNetwork(cfg config.ClientConfig, privateKey string) error {
|
func JoinNetwork(cfg config.ClientConfig, privateKey string) error {
|
||||||
|
|
||||||
hasnet := local.HasNetwork(cfg.Network)
|
hasnet := local.HasNetwork(cfg.Network)
|
||||||
|
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetDNS - sets the DNS of a local machine
|
||||||
func SetDNS(nameserver string) error {
|
func SetDNS(nameserver string) error {
|
||||||
bytes, err := ioutil.ReadFile("/etc/resolv.conf")
|
bytes, err := ioutil.ReadFile("/etc/resolv.conf")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -33,6 +34,7 @@ func SetDNS(nameserver string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateDNS - updates local DNS of client
|
||||||
func UpdateDNS(ifacename string, network string, nameserver string) error {
|
func UpdateDNS(ifacename string, network string, nameserver string) error {
|
||||||
if ncutils.IsWindows() {
|
if ncutils.IsWindows() {
|
||||||
return nil
|
return nil
|
||||||
|
@@ -5,13 +5,15 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"os/exec"
|
|
||||||
"os"
|
|
||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetIPForwarding - Sets IP forwarding if it's mac or linux
|
||||||
func SetIPForwarding() error {
|
func SetIPForwarding() error {
|
||||||
os := runtime.GOOS
|
os := runtime.GOOS
|
||||||
var err error
|
var err error
|
||||||
@@ -26,6 +28,7 @@ func SetIPForwarding() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetIPForwardingLinux - sets the ipforwarding for linux
|
||||||
func SetIPForwardingLinux() error {
|
func SetIPForwardingLinux() error {
|
||||||
out, err := ncutils.RunCmd("sysctl net.ipv4.ip_forward", true)
|
out, err := ncutils.RunCmd("sysctl net.ipv4.ip_forward", true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -44,6 +47,7 @@ func SetIPForwardingLinux() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetIPForwardingMac - sets ip forwarding for mac
|
||||||
func SetIPForwardingMac() error {
|
func SetIPForwardingMac() error {
|
||||||
_, err := ncutils.RunCmd("sysctl -w net.inet.ip.forwarding=1", true)
|
_, err := ncutils.RunCmd("sysctl -w net.inet.ip.forwarding=1", true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -52,6 +56,7 @@ func SetIPForwardingMac() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsWGInstalled - checks if WireGuard is installed
|
||||||
func IsWGInstalled() bool {
|
func IsWGInstalled() bool {
|
||||||
out, err := ncutils.RunCmd("wg help", true)
|
out, err := ncutils.RunCmd("wg help", true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -61,6 +66,7 @@ func IsWGInstalled() bool {
|
|||||||
return strings.Contains(out, "Available subcommand")
|
return strings.Contains(out, "Available subcommand")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetMacIface - gets mac interface
|
||||||
func GetMacIface(ipstring string) (string, error) {
|
func GetMacIface(ipstring string) (string, error) {
|
||||||
var wgiface string
|
var wgiface string
|
||||||
_, checknet, err := net.ParseCIDR(ipstring + "/24")
|
_, checknet, err := net.ParseCIDR(ipstring + "/24")
|
||||||
@@ -90,6 +96,7 @@ func GetMacIface(ipstring string) (string, error) {
|
|||||||
return wgiface, err
|
return wgiface, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HasNetwork - checks if a network exists locally
|
||||||
func HasNetwork(network string) bool {
|
func HasNetwork(network string) bool {
|
||||||
return ncutils.FileExists(ncutils.GetNetclientPathSpecific() + "netconfig-" + network)
|
return ncutils.FileExists(ncutils.GetNetclientPathSpecific() + "netconfig-" + network)
|
||||||
}
|
}
|
||||||
|
@@ -23,31 +23,49 @@ import (
|
|||||||
"google.golang.org/grpc/credentials"
|
"google.golang.org/grpc/credentials"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// NO_DB_RECORD - error message result
|
||||||
const NO_DB_RECORD = "no result found"
|
const NO_DB_RECORD = "no result found"
|
||||||
|
|
||||||
|
// NO_DB_RECORDS - error record result
|
||||||
const NO_DB_RECORDS = "could not find any records"
|
const NO_DB_RECORDS = "could not find any records"
|
||||||
|
|
||||||
|
// LINUX_APP_DATA_PATH - linux path
|
||||||
const LINUX_APP_DATA_PATH = "/etc/netclient"
|
const LINUX_APP_DATA_PATH = "/etc/netclient"
|
||||||
|
|
||||||
|
// WINDOWS_APP_DATA_PATH - windows path
|
||||||
const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
|
const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
|
||||||
|
|
||||||
|
// WINDOWS_SVC_NAME - service name
|
||||||
const WINDOWS_SVC_NAME = "netclient"
|
const WINDOWS_SVC_NAME = "netclient"
|
||||||
|
|
||||||
|
// NETCLIENT_DEFAULT_PORT - default port
|
||||||
const NETCLIENT_DEFAULT_PORT = 51821
|
const NETCLIENT_DEFAULT_PORT = 51821
|
||||||
|
|
||||||
|
// DEFAULT_GC_PERCENT - garbage collection percent
|
||||||
const DEFAULT_GC_PERCENT = 10
|
const DEFAULT_GC_PERCENT = 10
|
||||||
|
|
||||||
|
// Log - logs a message
|
||||||
func Log(message string) {
|
func Log(message string) {
|
||||||
log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
|
log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
|
||||||
log.Println("[netclient]", message)
|
log.Println("[netclient]", message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsWindows - checks if is windows
|
||||||
func IsWindows() bool {
|
func IsWindows() bool {
|
||||||
return runtime.GOOS == "windows"
|
return runtime.GOOS == "windows"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsMac - checks if is a mac
|
||||||
func IsMac() bool {
|
func IsMac() bool {
|
||||||
return runtime.GOOS == "darwin"
|
return runtime.GOOS == "darwin"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsLinux - checks if is linux
|
||||||
func IsLinux() bool {
|
func IsLinux() bool {
|
||||||
return runtime.GOOS == "linux"
|
return runtime.GOOS == "linux"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetWireGuard - checks if wg is installed
|
||||||
func GetWireGuard() string {
|
func GetWireGuard() string {
|
||||||
userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
|
userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
|
||||||
if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
|
if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
|
||||||
@@ -56,6 +74,7 @@ func GetWireGuard() string {
|
|||||||
return "wg"
|
return "wg"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsKernel - checks if running kernel WireGuard
|
||||||
func IsKernel() bool {
|
func IsKernel() bool {
|
||||||
//TODO
|
//TODO
|
||||||
//Replace && true with some config file value
|
//Replace && true with some config file value
|
||||||
@@ -63,7 +82,7 @@ func IsKernel() bool {
|
|||||||
return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
|
return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// == database returned nothing error ==
|
// IsEmptyRecord - repeat from database
|
||||||
func IsEmptyRecord(err error) bool {
|
func IsEmptyRecord(err error) bool {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return false
|
return false
|
||||||
@@ -72,6 +91,7 @@ func IsEmptyRecord(err error) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//generate an access key value
|
//generate an access key value
|
||||||
|
// GenPass - generates a pass
|
||||||
func GenPass() string {
|
func GenPass() string {
|
||||||
|
|
||||||
var seededRand *rand.Rand = rand.New(
|
var seededRand *rand.Rand = rand.New(
|
||||||
@@ -87,6 +107,7 @@ func GenPass() string {
|
|||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetPublicIP - gets public ip
|
||||||
func GetPublicIP() (string, error) {
|
func GetPublicIP() (string, error) {
|
||||||
|
|
||||||
iplist := []string{"http://ip.client.gravitl.com", "https://ifconfig.me", "http://api.ipify.org", "http://ipinfo.io/ip"}
|
iplist := []string{"http://ip.client.gravitl.com", "https://ifconfig.me", "http://api.ipify.org", "http://ipinfo.io/ip"}
|
||||||
@@ -113,6 +134,7 @@ func GetPublicIP() (string, error) {
|
|||||||
return endpoint, err
|
return endpoint, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetMacAddr - get's mac address
|
||||||
func GetMacAddr() ([]string, error) {
|
func GetMacAddr() ([]string, error) {
|
||||||
ifas, err := net.Interfaces()
|
ifas, err := net.Interfaces()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -154,6 +176,7 @@ PersistentKeepAlive = %s
|
|||||||
return peersString, nil
|
return peersString, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateUserSpaceConf - creates a user space WireGuard conf
|
||||||
func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
|
func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
|
||||||
peersString, err := parsePeers(perskeepalive, peers)
|
peersString, err := parsePeers(perskeepalive, peers)
|
||||||
listenPortString := ""
|
listenPortString := ""
|
||||||
@@ -183,6 +206,7 @@ MTU = %s
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetLocalIP - gets local ip of machine
|
||||||
func GetLocalIP(localrange string) (string, error) {
|
func GetLocalIP(localrange string) (string, error) {
|
||||||
_, localRange, err := net.ParseCIDR(localrange)
|
_, localRange, err := net.ParseCIDR(localrange)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -229,6 +253,7 @@ func GetLocalIP(localrange string) (string, error) {
|
|||||||
return local, nil
|
return local, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetFreePort - gets free port of machine
|
||||||
func GetFreePort(rangestart int32) (int32, error) {
|
func GetFreePort(rangestart int32) (int32, error) {
|
||||||
if rangestart == 0 {
|
if rangestart == 0 {
|
||||||
rangestart = NETCLIENT_DEFAULT_PORT
|
rangestart = NETCLIENT_DEFAULT_PORT
|
||||||
@@ -259,6 +284,7 @@ func GetFreePort(rangestart int32) (int32, error) {
|
|||||||
|
|
||||||
// == OS PATH FUNCTIONS ==
|
// == OS PATH FUNCTIONS ==
|
||||||
|
|
||||||
|
// GetHomeDirWindows - gets home directory in windows
|
||||||
func GetHomeDirWindows() string {
|
func GetHomeDirWindows() string {
|
||||||
if IsWindows() {
|
if IsWindows() {
|
||||||
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
|
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
|
||||||
@@ -270,6 +296,7 @@ func GetHomeDirWindows() string {
|
|||||||
return os.Getenv("HOME")
|
return os.Getenv("HOME")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNetclientPath - gets netclient path locally
|
||||||
func GetNetclientPath() string {
|
func GetNetclientPath() string {
|
||||||
if IsWindows() {
|
if IsWindows() {
|
||||||
return WINDOWS_APP_DATA_PATH
|
return WINDOWS_APP_DATA_PATH
|
||||||
@@ -280,6 +307,7 @@ func GetNetclientPath() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNetclientPathSpecific - gets specific netclient config path
|
||||||
func GetNetclientPathSpecific() string {
|
func GetNetclientPathSpecific() string {
|
||||||
if IsWindows() {
|
if IsWindows() {
|
||||||
return WINDOWS_APP_DATA_PATH + "\\"
|
return WINDOWS_APP_DATA_PATH + "\\"
|
||||||
@@ -290,6 +318,7 @@ func GetNetclientPathSpecific() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GRPCRequestOpts - gets grps request opts
|
||||||
func GRPCRequestOpts(isSecure string) grpc.DialOption {
|
func GRPCRequestOpts(isSecure string) grpc.DialOption {
|
||||||
var requestOpts grpc.DialOption
|
var requestOpts grpc.DialOption
|
||||||
requestOpts = grpc.WithInsecure()
|
requestOpts = grpc.WithInsecure()
|
||||||
@@ -300,6 +329,7 @@ func GRPCRequestOpts(isSecure string) grpc.DialOption {
|
|||||||
return requestOpts
|
return requestOpts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Copy - copies a src file to dest
|
||||||
func Copy(src, dst string) (int64, error) {
|
func Copy(src, dst string) (int64, error) {
|
||||||
sourceFileStat, err := os.Stat(src)
|
sourceFileStat, err := os.Stat(src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -329,6 +359,7 @@ func Copy(src, dst string) (int64, error) {
|
|||||||
return nBytes, err
|
return nBytes, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RunCmd - runs a local command
|
||||||
func RunCmd(command string, printerr bool) (string, error) {
|
func RunCmd(command string, printerr bool) (string, error) {
|
||||||
args := strings.Fields(command)
|
args := strings.Fields(command)
|
||||||
cmd := exec.Command(args[0], args[1:]...)
|
cmd := exec.Command(args[0], args[1:]...)
|
||||||
@@ -341,6 +372,7 @@ func RunCmd(command string, printerr bool) (string, error) {
|
|||||||
return string(out), err
|
return string(out), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RunsCmds - runs cmds
|
||||||
func RunCmds(commands []string, printerr bool) error {
|
func RunCmds(commands []string, printerr bool) error {
|
||||||
var err error
|
var err error
|
||||||
for _, command := range commands {
|
for _, command := range commands {
|
||||||
@@ -354,6 +386,7 @@ func RunCmds(commands []string, printerr bool) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FileExists - checks if file exists locally
|
||||||
func FileExists(f string) bool {
|
func FileExists(f string) bool {
|
||||||
info, err := os.Stat(f)
|
info, err := os.Stat(f)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
@@ -362,6 +395,7 @@ func FileExists(f string) bool {
|
|||||||
return !info.IsDir()
|
return !info.IsDir()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PrintLog - prints log
|
||||||
func PrintLog(message string, loglevel int) {
|
func PrintLog(message string, loglevel int) {
|
||||||
log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
|
log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
|
||||||
if loglevel < 2 {
|
if loglevel < 2 {
|
||||||
@@ -369,6 +403,7 @@ func PrintLog(message string, loglevel int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetSystemNetworks - get networks locally
|
||||||
func GetSystemNetworks() ([]string, error) {
|
func GetSystemNetworks() ([]string, error) {
|
||||||
var networks []string
|
var networks []string
|
||||||
files, err := ioutil.ReadDir(GetNetclientPathSpecific())
|
files, err := ioutil.ReadDir(GetNetclientPathSpecific())
|
||||||
@@ -394,5 +429,5 @@ func stringAfter(original string, substring string) string {
|
|||||||
if adjustedPosition >= len(original) {
|
if adjustedPosition >= len(original) {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return original[adjustedPosition:len(original)]
|
return original[adjustedPosition:]
|
||||||
}
|
}
|
||||||
|
@@ -8,7 +8,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Initialize windows directory & files and such
|
// InitWindows - Initialize windows directory & files and such
|
||||||
func InitWindows() {
|
func InitWindows() {
|
||||||
|
|
||||||
_, directoryErr := os.Stat(ncutils.GetNetclientPath()) // Check if data directory exists or not
|
_, directoryErr := os.Stat(ncutils.GetNetclientPath()) // Check if data directory exists or not
|
||||||
|
@@ -19,6 +19,7 @@ import (
|
|||||||
"google.golang.org/grpc/metadata"
|
"google.golang.org/grpc/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// RELAY_KEEPALIVE_MARKER - sets the relay keepalive marker
|
||||||
const RELAY_KEEPALIVE_MARKER = "20007ms"
|
const RELAY_KEEPALIVE_MARKER = "20007ms"
|
||||||
|
|
||||||
func getGrpcClient(cfg *config.ClientConfig) (nodepb.NodeServiceClient, error) {
|
func getGrpcClient(cfg *config.ClientConfig) (nodepb.NodeServiceClient, error) {
|
||||||
@@ -35,6 +36,7 @@ func getGrpcClient(cfg *config.ClientConfig) (nodepb.NodeServiceClient, error) {
|
|||||||
return wcclient, nil
|
return wcclient, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckIn - checkin for node on a network
|
||||||
func CheckIn(network string) (*models.Node, error) {
|
func CheckIn(network string) (*models.Node, error) {
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -120,6 +122,7 @@ func RemoveNetwork(network string) error {
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// GetPeers - gets the peers for a node
|
||||||
func GetPeers(macaddress string, network string, server string, dualstack bool, isIngressGateway bool, isServer bool) ([]wgtypes.PeerConfig, bool, []string, error) {
|
func GetPeers(macaddress string, network string, server string, dualstack bool, isIngressGateway bool, isServer bool) ([]wgtypes.PeerConfig, bool, []string, error) {
|
||||||
hasGateway := false
|
hasGateway := false
|
||||||
var gateways []string
|
var gateways []string
|
||||||
@@ -251,7 +254,7 @@ func GetPeers(macaddress string, network string, server string, dualstack bool,
|
|||||||
}
|
}
|
||||||
allowedips = append(allowedips, addr6)
|
allowedips = append(allowedips, addr6)
|
||||||
}
|
}
|
||||||
if nodecfg.IsServer == "yes" && !(node.IsServer == "yes"){
|
if nodecfg.IsServer == "yes" && !(node.IsServer == "yes") {
|
||||||
peer = wgtypes.PeerConfig{
|
peer = wgtypes.PeerConfig{
|
||||||
PublicKey: pubkey,
|
PublicKey: pubkey,
|
||||||
PersistentKeepaliveInterval: &keepaliveserver,
|
PersistentKeepaliveInterval: &keepaliveserver,
|
||||||
@@ -292,6 +295,8 @@ func GetPeers(macaddress string, network string, server string, dualstack bool,
|
|||||||
}
|
}
|
||||||
return peers, hasGateway, gateways, err
|
return peers, hasGateway, gateways, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetExtPeers - gets the extpeers for a client
|
||||||
func GetExtPeers(macaddress string, network string, server string, dualstack bool) ([]wgtypes.PeerConfig, error) {
|
func GetExtPeers(macaddress string, network string, server string, dualstack bool) ([]wgtypes.PeerConfig, error) {
|
||||||
var peers []wgtypes.PeerConfig
|
var peers []wgtypes.PeerConfig
|
||||||
|
|
||||||
|
@@ -18,9 +18,9 @@ import (
|
|||||||
"github.com/gravitl/netmaker/netclient/server"
|
"github.com/gravitl/netmaker/netclient/server"
|
||||||
"golang.zx2c4.com/wireguard/wgctrl"
|
"golang.zx2c4.com/wireguard/wgctrl"
|
||||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
//homedir "github.com/mitchellh/go-homedir"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetPeers - sets peers on a given WireGuard interface
|
||||||
func SetPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
|
func SetPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
|
||||||
|
|
||||||
client, err := wgctrl.New()
|
client, err := wgctrl.New()
|
||||||
@@ -95,6 +95,7 @@ func SetPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initializes a WireGuard interface
|
||||||
func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string) error {
|
func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string) error {
|
||||||
|
|
||||||
key, err := wgtypes.ParseKey(privkey)
|
key, err := wgtypes.ParseKey(privkey)
|
||||||
@@ -258,6 +259,7 @@ func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
|
||||||
func SetWGConfig(network string, peerupdate bool) error {
|
func SetWGConfig(network string, peerupdate bool) error {
|
||||||
|
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
@@ -291,6 +293,7 @@ func SetWGConfig(network string, peerupdate bool) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveConf - removes a configuration for a given WireGuard interface
|
||||||
func RemoveConf(iface string, printlog bool) error {
|
func RemoveConf(iface string, printlog bool) error {
|
||||||
os := runtime.GOOS
|
os := runtime.GOOS
|
||||||
var err error
|
var err error
|
||||||
@@ -304,6 +307,7 @@ func RemoveConf(iface string, printlog bool) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ApplyConf - applys a conf on disk to WireGuard interface
|
||||||
func ApplyConf(confPath string) error {
|
func ApplyConf(confPath string) error {
|
||||||
os := runtime.GOOS
|
os := runtime.GOOS
|
||||||
var err error
|
var err error
|
||||||
|
@@ -7,9 +7,9 @@ import (
|
|||||||
"github.com/gravitl/netmaker/netclient/config"
|
"github.com/gravitl/netmaker/netclient/config"
|
||||||
"github.com/gravitl/netmaker/netclient/ncutils"
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
||||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
//homedir "github.com/mitchellh/go-homedir"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// SetWGKeyConfig - sets the wg conf with a new private key
|
||||||
func SetWGKeyConfig(network string, serveraddr string) error {
|
func SetWGKeyConfig(network string, serveraddr string) error {
|
||||||
|
|
||||||
cfg, err := config.ReadConfig(network)
|
cfg, err := config.ReadConfig(network)
|
||||||
@@ -48,6 +48,7 @@ func SetWGKeyConfig(network string, serveraddr string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ApplyWGQuickConf - applies wg-quick commands if os supports
|
||||||
func ApplyWGQuickConf(confPath string) error {
|
func ApplyWGQuickConf(confPath string) error {
|
||||||
if _, err := ncutils.RunCmd("wg-quick up "+confPath, true); err != nil {
|
if _, err := ncutils.RunCmd("wg-quick up "+confPath, true); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -55,6 +56,7 @@ func ApplyWGQuickConf(confPath string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveWGQuickConf - calls wg-quick down
|
||||||
func RemoveWGQuickConf(confPath string, printlog bool) error {
|
func RemoveWGQuickConf(confPath string, printlog bool) error {
|
||||||
if _, err := ncutils.RunCmd("wg-quick down "+confPath, printlog); err != nil {
|
if _, err := ncutils.RunCmd("wg-quick down "+confPath, printlog); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -62,12 +64,14 @@ func RemoveWGQuickConf(confPath string, printlog bool) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StorePrivKey - stores wg priv key on disk locally
|
||||||
func StorePrivKey(key string, network string) error {
|
func StorePrivKey(key string, network string) error {
|
||||||
d1 := []byte(key)
|
d1 := []byte(key)
|
||||||
err := ioutil.WriteFile(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0644)
|
err := ioutil.WriteFile(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0644)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RetrievePrivKey - reads wg priv key from local disk
|
||||||
func RetrievePrivKey(network string) (string, error) {
|
func RetrievePrivKey(network string) (string, error) {
|
||||||
dat, err := ioutil.ReadFile(ncutils.GetNetclientPathSpecific() + "wgkey-" + network)
|
dat, err := ioutil.ReadFile(ncutils.GetNetclientPathSpecific() + "wgkey-" + network)
|
||||||
return string(dat), err
|
return string(dat), err
|
||||||
|
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/models"
|
"github.com/gravitl/netmaker/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetNodeRelay - gets the relay node of a given network
|
||||||
func GetNodeRelay(network string, relayedNodeAddr string) (models.Node, error) {
|
func GetNodeRelay(network string, relayedNodeAddr string) (models.Node, error) {
|
||||||
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
|
||||||
var relay models.Node
|
var relay models.Node
|
||||||
|
@@ -15,6 +15,7 @@ import (
|
|||||||
"github.com/gravitl/netmaker/servercfg"
|
"github.com/gravitl/netmaker/servercfg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetServerWGConf - gets the server WG configuration
|
||||||
func GetServerWGConf() (models.IntClient, error) {
|
func GetServerWGConf() (models.IntClient, error) {
|
||||||
var server models.IntClient
|
var server models.IntClient
|
||||||
collection, err := database.FetchRecords(database.INT_CLIENTS_TABLE_NAME)
|
collection, err := database.FetchRecords(database.INT_CLIENTS_TABLE_NAME)
|
||||||
@@ -30,6 +31,7 @@ func GetServerWGConf() (models.IntClient, error) {
|
|||||||
return models.IntClient{}, errors.New("could not find comms server")
|
return models.IntClient{}, errors.New("could not find comms server")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InstallNetclient netclient installation for server - depricated
|
||||||
func InstallNetclient() error {
|
func InstallNetclient() error {
|
||||||
|
|
||||||
netclientPath := ncutils.GetNetclientPath()
|
netclientPath := ncutils.GetNetclientPath()
|
||||||
@@ -53,6 +55,7 @@ func InstallNetclient() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FileExists - checks if local file exists
|
||||||
func FileExists(f string) bool {
|
func FileExists(f string) bool {
|
||||||
info, err := os.Stat(f)
|
info, err := os.Stat(f)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
@@ -90,11 +93,13 @@ func copy(src, dst string) (int64, error) {
|
|||||||
return nBytes, err
|
return nBytes, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveNetwork - removes a network locally on server
|
||||||
func RemoveNetwork(network string) (bool, error) {
|
func RemoveNetwork(network string) (bool, error) {
|
||||||
err := nccommand.Leave(config.ClientConfig{Network: network})
|
err := nccommand.Leave(config.ClientConfig{Network: network})
|
||||||
return true, err
|
return true, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InitServerNetclient - intializes the server netclient
|
||||||
func InitServerNetclient() error {
|
func InitServerNetclient() error {
|
||||||
netclientDir := ncutils.GetNetclientPath()
|
netclientDir := ncutils.GetNetclientPath()
|
||||||
_, err := os.Stat(netclientDir + "/config")
|
_, err := os.Stat(netclientDir + "/config")
|
||||||
@@ -107,6 +112,7 @@ func InitServerNetclient() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HandleContainedClient - function for checkins on server
|
||||||
func HandleContainedClient() error {
|
func HandleContainedClient() error {
|
||||||
servernets, err := models.GetNetworks()
|
servernets, err := models.GetNetworks()
|
||||||
if err != nil && !database.IsEmptyRecord(err) {
|
if err != nil && !database.IsEmptyRecord(err) {
|
||||||
@@ -132,6 +138,7 @@ func HandleContainedClient() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SyncNetworks - syncs the networks for servers
|
||||||
func SyncNetworks(servernets []models.Network) error {
|
func SyncNetworks(servernets []models.Network) error {
|
||||||
|
|
||||||
localnets, err := ncutils.GetSystemNetworks()
|
localnets, err := ncutils.GetSystemNetworks()
|
||||||
@@ -179,6 +186,7 @@ func SyncNetworks(servernets []models.Network) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AddNetwork - add a network to server in client mode
|
||||||
func AddNetwork(network string) (bool, error) {
|
func AddNetwork(network string) (bool, error) {
|
||||||
err := nccommand.Join(config.ClientConfig{
|
err := nccommand.Join(config.ClientConfig{
|
||||||
Network: network,
|
Network: network,
|
||||||
|
Reference in New Issue
Block a user