From 47d7b16d935648c5e08c465defa31cf0f7df5610 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Wed, 31 Mar 2021 01:19:43 +0530 Subject: [PATCH 01/12] config ip and mask update --- service/ziti-tunnel/cli/constants.go | 4 + service/ziti-tunnel/cli/responseGenerator.go | 14 ++++ service/ziti-tunnel/cli/service.go | 50 +++++++++++- service/ziti-tunnel/main.go | 2 + service/ziti-tunnel/service/ipc.go | 18 ++++ service/ziti-tunnel/service/state.go | 86 +++++++++++++++++++- 6 files changed, 172 insertions(+), 2 deletions(-) diff --git a/service/ziti-tunnel/cli/constants.go b/service/ziti-tunnel/cli/constants.go index 3c9f4be5..5892ae96 100644 --- a/service/ziti-tunnel/cli/constants.go +++ b/service/ziti-tunnel/cli/constants.go @@ -42,6 +42,10 @@ var NOTIFY_IDENTITY_UI = dto.CommandMsg{ Function: "NotifyIdentityUI", } +var UPDATE_TUN_IPV4 = dto.CommandMsg{ + Function: "UpdateTunIpv4", +} + var monitorIpcPipe = `\\.\pipe\OpenZiti\ziti-monitor\ipc` var templateIdentity = `{{printf "%40s" "Name"}} | {{printf "%41s" "FingerPrint"}} | {{printf "%6s" "Active"}} | {{printf "%30s" "Config"}} | {{"Status"}} diff --git a/service/ziti-tunnel/cli/responseGenerator.go b/service/ziti-tunnel/cli/responseGenerator.go index 83ca8355..cc2b8c2c 100644 --- a/service/ziti-tunnel/cli/responseGenerator.go +++ b/service/ziti-tunnel/cli/responseGenerator.go @@ -160,6 +160,20 @@ func GetServicesFromRTS(args []string, status *dto.TunnelStatus, flags map[strin } +func GetStatusFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { + + if status == nil { + return dto.Response{Message: "Stopped / Unknown State", Code: service.SUCCESS, Error: "", Payload: ""} + } + + if status.Active { + return dto.Response{Message: "Running", Code: service.SUCCESS, Error: "", Payload: ""} + } else { + return dto.Response{Message: "Stopped", Code: service.SUCCESS, Error: "", Payload: ""} + } + +} + func generateResponse(dataType string, message string, filteredData interface{}, flags map[string]bool, templateStr string) dto.Response { var bytesData []byte diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index ebc1b290..359b47cd 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -2,8 +2,10 @@ package cli import ( "strings" - + "strconv" + "golang.org/x/sys/windows/svc" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/service" ) //GetIdentities is to fetch identities through cmdline @@ -53,3 +55,49 @@ func SetLogLevel(args []string, flags map[string]bool) { func GetFeedback(args []string, flags map[string]bool) { GetDataFromMonitorIpcPipe(&dto.FEEDBACK_REQUEST, args, flags) } + +func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { + CIDRstring := flags["CIDR"] + log.Infof("Updating the config file with IP CIDR %v", flags["CIDR"]) + var cidr = strings.Split(CIDRstring.(string), "/") + if len(cidr) != 2 { + log.Error("Incorrect cidr") + } + ipMask, err := strconv.Atoi(cidr[1]) + if err != nil { + log.Errorf("Incorrect ipv4 mask, %s", cidr[1]) + return + } + updateTunIpv4Payload := make(map[string]interface{}) + updateTunIpv4Payload["TunIPv4"] = cidr[0] + updateTunIpv4Payload["TunIPv4Mask"] = cidr[1] + UPDATE_TUN_IPV4.Payload = updateTunIpv4Payload + log.Debugf("updateTunIpv4 Payload %v", UPDATE_TUN_IPV4) + + status := GetDataFromIpcPipe(&UPDATE_TUN_IPV4, nil, GetResponseObjectFromRTS, args, nil) + + if !status { + log.Infof("Updating ip and mask in the config file. Manual restart is required") + err = service.UpdateRuntimeStateIpv4(true, cidr[0], ipMask) + if err != nil { + log.Errorf("Unable to set Tun ip and mask, %v", err) + return + } + log.Infof("ip and mask are set") + } + + if status { + log.Infof("Attempting to restart ziti ") + + err = service.ControlService(svc.Stop, svc.Stopped) + if (err != nil) { + log.Errorf("Unable to stop the service, %v", err) + return + } + err = service.StartService() + if (err != nil) { + log.Errorf("Unable to start the service, %v", err) + } + } + +} diff --git a/service/ziti-tunnel/main.go b/service/ziti-tunnel/main.go index c1c3f236..e765ea59 100644 --- a/service/ziti-tunnel/main.go +++ b/service/ziti-tunnel/main.go @@ -111,6 +111,8 @@ func main() { commandline.Execute() case "feedback": commandline.Execute() + case "config": + commandline.Execute() default: usage(fmt.Sprintf("invalid command %s", cmd)) } diff --git a/service/ziti-tunnel/service/ipc.go b/service/ziti-tunnel/service/ipc.go index fb8af897..16e63e12 100644 --- a/service/ziti-tunnel/service/ipc.go +++ b/service/ziti-tunnel/service/ipc.go @@ -42,6 +42,7 @@ import ( "os" "os/signal" "strings" + "strconv" "sync" "time" ) @@ -498,6 +499,8 @@ func serveIpc(conn net.Conn) { //save the state rts.SaveState() + case "UpdateTunIpv4": + updateTunIpv4(enc, cmd.Payload["TunIPv4"].(string), cmd.Payload["TunIPv4Mask"].(string)) case "NotifyLogLevelUIAndUpdateService": sendLogLevelAndNotify(enc, cmd.Payload["Level"].(string)) case "NotifyIdentityUI": @@ -622,6 +625,21 @@ func setLogLevel(out *json.Encoder, level string) { respond(out, dto.Response{Message: "log level set", Code: SUCCESS, Error: "", Payload: nil}) } +func updateTunIpv4(out *json.Encoder, ip string, ipmask string) { + ipMask, err := strconv.Atoi(ipmask) + if err != nil { + respondWithError(out, "Incorrect ipv4 mask", UNKNOWN_ERROR, err) + return + } + err = UpdateRuntimeStateIpv4(false, ip, ipMask) + if err != nil { + respondWithError(out, "Could not set Tun ip and mask", UNKNOWN_ERROR, err) + return + } + + respond(out, dto.Response{Message: "TunIPv4 and mask is set", Code: SUCCESS, Error: "", Payload: ""}) +} + func serveLogs(conn net.Conn) { log.Debug("accepted a logs connection, writing logs to pipe") w := bufio.NewWriter(conn) diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go index 1f286216..86dfd1f6 100644 --- a/service/ziti-tunnel/service/state.go +++ b/service/ziti-tunnel/service/state.go @@ -28,7 +28,8 @@ import ( "path" "strings" "time" - + "path/filepath" + "errors" "github.com/openziti/desktop-edge-win/service/cziti" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/config" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/constants" @@ -105,6 +106,58 @@ func backupConfig() (string, error) { return backup, err } + +func (t *RuntimeState) SaveStateWithPath(systemPath string) { + // overwrite file if it exists + _ = os.MkdirAll(systemPath, 0644) + + log.Debugf("backing up config") + backup, err := backupConfigWithPath(systemPath) + if err != nil { + log.Warnf("could not backup config file! %v", err) + } else { + log.Debugf("config file backed up to: %s", backup) + } + + cfg, err := os.OpenFile(filepath.Join(systemPath, string(os.PathSeparator), "config.json"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + defer cfg.Close() + if err != nil { + log.Panicf("An unexpected and unrecoverable error has occurred while %s: %v", "opening the config file", err) + } + + w := bufio.NewWriter(bufio.NewWriter(cfg)) + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + _ = enc.Encode(t.state) + _ = w.Flush() + + err = cfg.Close() + if err != nil { + log.Panicf("An unexpected and unrecoverable error has occurred while %s: %v", "closing the config file", err) + } + log.Debug("state saved") +} + +func backupConfigWithPath(systemPath string) (string, error) { + original, err := os.Open(filepath.Join(systemPath, string(os.PathSeparator), "config.json")) + if err != nil { + return "", err + } + defer original.Close() + backup := filepath.Join(systemPath, string(os.PathSeparator), "config.json.backup") + new, err := os.Create(backup) + if err != nil { + return "", err + } + defer new.Close() + + _, err = io.Copy(new, original) + if err != nil { + return "", err + } + return backup, err +} + func (t *RuntimeState) ToStatus(onlyInitialized bool) dto.TunnelStatus { var uptime int64 @@ -397,6 +450,37 @@ func (t *RuntimeState) UpdateIpv4(ipv4 string) { rts.SaveState() } +func UpdateRuntimeStateIpv4(offline bool, ip string, ipv4Mask int) error { + + log.Infof("ip and mask %s %d", ip, ipv4Mask) + + if offline { + systemDrivePath := os.Getenv("SystemDrive") + if systemDrivePath == "" { + return errors.New("SystemDrive env is not found") + } + configPath := "Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\NetFoundry" + systemPath := filepath.Join(systemDrivePath, string(os.PathSeparator), configPath) + err := readConfig(rts, filepath.Join(systemPath, string(os.PathSeparator), "config.json")) + if (err != nil) { + log.Errorf("Unable to read the config file, %v", err) + return err + } + + rts.state.TunIpv4 = ip + rts.state.TunIpv4Mask = ipv4Mask + + rts.SaveStateWithPath(systemPath) + + } else { + rts.state.TunIpv4 = ip + rts.state.TunIpv4Mask = ipv4Mask + rts.SaveState() + } + + return nil +} + // uses the registry to determine if IPv6 is enabled or disabled on this machine. If it is disabled an IPv6 DNS entry // will end up causing a fatal error on startup of the service. For this registry key and values see the MS documentation // at https://docs.microsoft.com/en-us/troubleshoot/windows-server/networking/configure-ipv6-in-windows From 55b0ca48f5e8f96c142be3a88df9b7aaa72b5cd1 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Mon, 5 Apr 2021 16:10:42 +0530 Subject: [PATCH 02/12] adding the config cli --- service/ziti-tunnel/cmd/config.go | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 service/ziti-tunnel/cmd/config.go diff --git a/service/ziti-tunnel/cmd/config.go b/service/ziti-tunnel/cmd/config.go new file mode 100644 index 00000000..cd347c20 --- /dev/null +++ b/service/ziti-tunnel/cmd/config.go @@ -0,0 +1,48 @@ +/* +Copyright © 2021 NAME HERE + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/cli" + + "github.com/spf13/cobra" +) + +var CIDR string + +// configCmd represents the config command +var configCmd = &cobra.Command{ + Use: "config", + Short: "A brief description of your command", + Long: `A longer description that spans multiple lines and likely contains examples +and usage of using your command. For example: + +Cobra is a CLI library for Go that empowers applications. +This application is a tool to generate the needed files +to quickly create a Cobra application.`, + Run: func(cmd *cobra.Command, args []string) { + flags := map[string]interface{}{} + flags["CIDR"] = CIDR + cli.UpdateConfigIPSubnet(args,flags) + }, +} + +func init() { + rootCmd.AddCommand(configCmd) + + configCmd.Flags().StringVar(&CIDR, "CIDR", "100.64.0.1/10", "Update the cidr value in the config file") + +} From ad2ff23b4fd093d223a7eb1f5d9a6ae3c51be0b3 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Wed, 14 Apr 2021 17:05:40 +0530 Subject: [PATCH 03/12] adding add dns flag to config update function --- service/ziti-tunnel/cli/service.go | 44 ++++++++++++++++-------- service/ziti-tunnel/cmd/config.go | 43 ++++++++++-------------- service/ziti-tunnel/cmd/update.go | 50 ++++++++++++++++++++++++++++ service/ziti-tunnel/service/ipc.go | 32 ++++++++++++++---- service/ziti-tunnel/service/state.go | 35 ++++++++++++++++--- 5 files changed, 154 insertions(+), 50 deletions(-) create mode 100644 service/ziti-tunnel/cmd/update.go diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index 4e4b04e4..a988b4e4 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -58,19 +58,37 @@ func GetFeedback(args []string, flags map[string]bool) { func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { CIDRstring := flags["CIDR"] - log.Infof("Updating the config file with IP CIDR %v", flags["CIDR"]) - var cidr = strings.Split(CIDRstring.(string), "/") - if len(cidr) != 2 { - log.Error("Incorrect cidr") - } - ipMask, err := strconv.Atoi(cidr[1]) - if err != nil { - log.Errorf("Incorrect ipv4 mask, %s", cidr[1]) - return - } + AddDns := flags["AddDns"] + log.Info("Updating the config file") + var cidr []string + var ipMask int + var err error + updateTunIpv4Payload := make(map[string]interface{}) - updateTunIpv4Payload["TunIPv4"] = cidr[0] - updateTunIpv4Payload["TunIPv4Mask"] = cidr[1] + if CIDRstring != "" { + cidr = strings.Split(CIDRstring.(string), "/") + if len(cidr) != 2 { + log.Error("Incorrect cidr") + } + ipMask, err = strconv.Atoi(cidr[1]) + if err != nil { + log.Errorf("Incorrect ipv4 mask, %s", cidr[1]) + return + } + updateTunIpv4Payload["TunIPv4"] = cidr[0] + updateTunIpv4Payload["TunIPv4Mask"] = cidr[1] + } + if AddDns != "" { + var addDnsBool bool + addDnsBool, err = strconv.ParseBool(AddDns.(string)) + + if err != nil { + log.Errorf("Incorrect addDns %v", err) + return + } + updateTunIpv4Payload["AddDns"] = addDnsBool + } + UPDATE_TUN_IPV4.Payload = updateTunIpv4Payload log.Debugf("updateTunIpv4 Payload %v", UPDATE_TUN_IPV4) @@ -78,7 +96,7 @@ func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { if !status { log.Infof("Updating ip and mask in the config file. Manual restart is required") - err = service.UpdateRuntimeStateIpv4(true, cidr[0], ipMask) + err = service.UpdateRuntimeStateIpv4(true, cidr[0], ipMask, AddDns.(string)) if err != nil { log.Errorf("Unable to set Tun ip and mask, %v", err) return diff --git a/service/ziti-tunnel/cmd/config.go b/service/ziti-tunnel/cmd/config.go index cd347c20..81c2ee08 100644 --- a/service/ziti-tunnel/cmd/config.go +++ b/service/ziti-tunnel/cmd/config.go @@ -1,28 +1,26 @@ -/* -Copyright © 2021 NAME HERE - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ package cmd -import ( - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/cli" +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +import ( "github.com/spf13/cobra" ) -var CIDR string - // configCmd represents the config command var configCmd = &cobra.Command{ Use: "config", @@ -34,15 +32,10 @@ Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { - flags := map[string]interface{}{} - flags["CIDR"] = CIDR - cli.UpdateConfigIPSubnet(args,flags) + checkHelp() }, } func init() { rootCmd.AddCommand(configCmd) - - configCmd.Flags().StringVar(&CIDR, "CIDR", "100.64.0.1/10", "Update the cidr value in the config file") - } diff --git a/service/ziti-tunnel/cmd/update.go b/service/ziti-tunnel/cmd/update.go new file mode 100644 index 00000000..25d2461c --- /dev/null +++ b/service/ziti-tunnel/cmd/update.go @@ -0,0 +1,50 @@ +package cmd + +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import ( + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/cli" + + "github.com/spf13/cobra" +) + +var CIDR string +var AddDns string + +// updateCmd represents the update command +var updateCmd = &cobra.Command{ + Use: "update", + Short: "Updates data into the ziti-tunnel", + Long: `update command should be used as a sub command to the main command + It helps to update the data into the ziti-tunnel. + eg: ziti-tunnel config update --CIDR 100.64.0.1/10 --AddDns=true`, + Run: func(cmd *cobra.Command, args []string) { + flags := map[string]interface{}{} + flags["CIDR"] = CIDR + flags["AddDns"] = AddDns + cli.UpdateConfigIPSubnet(args,flags) + }, +} + +func init() { + configCmd.AddCommand(updateCmd) + + updateCmd.Flags().StringVar(&CIDR, "CIDR", "", "Updates the cidr property in the config file") + updateCmd.Flags().StringVar(&AddDns, "AddDns", "", "Updates the Add Dns property in the config file") + +} diff --git a/service/ziti-tunnel/service/ipc.go b/service/ziti-tunnel/service/ipc.go index feffc2f4..f3c998de 100644 --- a/service/ziti-tunnel/service/ipc.go +++ b/service/ziti-tunnel/service/ipc.go @@ -500,7 +500,19 @@ func serveIpc(conn net.Conn) { //save the state rts.SaveState() case "UpdateTunIpv4": - updateTunIpv4(enc, cmd.Payload["TunIPv4"].(string), cmd.Payload["TunIPv4Mask"].(string)) + var tunIPv4 string + var tunIPv4Mask string + var addDns string + if cmd.Payload["TunIPv4"] != nil { + tunIPv4 = cmd.Payload["TunIPv4"].(string) + } + if cmd.Payload["TunIPv4Mask"] != nil { + tunIPv4Mask = cmd.Payload["TunIPv4Mask"].(string) + } + if cmd.Payload["AddDns"] != nil { + addDns = strconv.FormatBool(cmd.Payload["AddDns"].(bool)) + } + updateTunIpv4(enc, tunIPv4, tunIPv4Mask, addDns) case "NotifyLogLevelUIAndUpdateService": sendLogLevelAndNotify(enc, cmd.Payload["Level"].(string)) case "NotifyIdentityUI": @@ -625,13 +637,19 @@ func setLogLevel(out *json.Encoder, level string) { respond(out, dto.Response{Message: "log level set", Code: SUCCESS, Error: "", Payload: nil}) } -func updateTunIpv4(out *json.Encoder, ip string, ipmask string) { - ipMask, err := strconv.Atoi(ipmask) - if err != nil { - respondWithError(out, "Incorrect ipv4 mask", UNKNOWN_ERROR, err) - return +func updateTunIpv4(out *json.Encoder, ip string, ipmask string, addDns string) { + var ipMask int + var err error + if ipmask != "" { + ipMask, err = strconv.Atoi(ipmask) + + if err != nil { + respondWithError(out, "Incorrect ipv4 mask", UNKNOWN_ERROR, err) + return + } } - err = UpdateRuntimeStateIpv4(false, ip, ipMask) + + err = UpdateRuntimeStateIpv4(false, ip, ipMask, addDns) if err != nil { respondWithError(out, "Could not set Tun ip and mask", UNKNOWN_ERROR, err) return diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go index 7d68e1be..6557de96 100644 --- a/service/ziti-tunnel/service/state.go +++ b/service/ziti-tunnel/service/state.go @@ -31,6 +31,7 @@ import ( "time" "path/filepath" "errors" + "strconv" "github.com/openziti/desktop-edge-win/service/cziti" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/config" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/constants" @@ -454,10 +455,20 @@ func (t *RuntimeState) UpdateIpv4(ipv4 string) { rts.SaveState() } -func UpdateRuntimeStateIpv4(offline bool, ip string, ipv4Mask int) error { +func UpdateRuntimeStateIpv4(offline bool, ip string, ipv4Mask int, addDns string) error { log.Infof("ip and mask %s %d", ip, ipv4Mask) + var addDnsBool bool + var err error + if addDns != "" { + addDnsBool, err = strconv.ParseBool(addDns) + + if err != nil { + return errors.New(fmt.Sprintf("Incorrect addDns %v", err)) + } + } + if offline { systemDrivePath := os.Getenv("SystemDrive") if systemDrivePath == "" { @@ -471,14 +482,28 @@ func UpdateRuntimeStateIpv4(offline bool, ip string, ipv4Mask int) error { return err } - rts.state.TunIpv4 = ip - rts.state.TunIpv4Mask = ipv4Mask + // if ip is not empty, then we set both ip and mask + if ip != "" { + rts.state.TunIpv4 = ip + rts.state.TunIpv4Mask = ipv4Mask + } + if addDns != "" { + rts.state.AddDns = addDnsBool + } rts.SaveStateWithPath(systemPath) } else { - rts.state.TunIpv4 = ip - rts.state.TunIpv4Mask = ipv4Mask + + // if ip is not empty, then we set both ip and mask + if ip != "" { + rts.state.TunIpv4 = ip + rts.state.TunIpv4Mask = ipv4Mask + } + if addDns != "" { + rts.state.AddDns = addDnsBool + } + rts.SaveState() } From bd64b2e083fd8cb2c235d369b8afaf59ad91d8d2 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Wed, 14 Apr 2021 17:26:55 +0530 Subject: [PATCH 04/12] fixing fatal error --- service/ziti-tunnel/cli/ipcClient.go | 2 +- service/ziti-tunnel/cli/service.go | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/service/ziti-tunnel/cli/ipcClient.go b/service/ziti-tunnel/cli/ipcClient.go index 50a87b94..a042ef92 100644 --- a/service/ziti-tunnel/cli/ipcClient.go +++ b/service/ziti-tunnel/cli/ipcClient.go @@ -144,7 +144,7 @@ func GetDataFromIpcPipe(commandMsg *dto.CommandMsg, fn fetchStatusFromRTS, respo if err != nil { log.Errorf("Connection to ipc pipe is not established, %v", err) - log.Fatal("Ziti Desktop Edge app may not be running") + log.Errorf("Ziti Desktop Edge app may not be running") return false } readDone := make(chan bool) diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index a988b4e4..242ec967 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -96,7 +96,11 @@ func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { if !status { log.Infof("Updating ip and mask in the config file. Manual restart is required") - err = service.UpdateRuntimeStateIpv4(true, cidr[0], ipMask, AddDns.(string)) + var tunIpv4 string + if len(cidr) == 2 { + tunIpv4 = cidr[0] + } + err = service.UpdateRuntimeStateIpv4(true, tunIpv4, ipMask, AddDns.(string)) if err != nil { log.Errorf("Unable to set Tun ip and mask, %v", err) return From db181acaa17e32d5fe35fbc1b6987dded2b18560 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 15:37:35 +0530 Subject: [PATCH 05/12] accept mask as int value --- .../DataStructures/DataStructures.cs | 23 ++++++++++++++++++ .../ServiceClient/DataClient.cs | 24 +++++++++++++++++++ service/ziti-tunnel/cli/service.go | 2 +- service/ziti-tunnel/service/ipc.go | 19 ++++----------- 4 files changed, 53 insertions(+), 15 deletions(-) diff --git a/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs b/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs index c64191bc..5936e0c0 100644 --- a/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs +++ b/ZitiDesktopEdge.Client/DataStructures/DataStructures.cs @@ -459,4 +459,27 @@ namespace ZitiDesktopEdge.DataStructures { public class MfaRecoveryCodesResponse : SvcResponse { public string[] Payload { get; set; } } + + public class ConfigPayload + { + public string TunIPv4 { get; set; } + public int TunIPv4Mask { get; set; } + public bool AddDns { get; set; } + } + + public class ConfigUpdateFunction : ServiceFunction + { + public ConfigUpdateFunction(string tunIPv4, int tunIPv4Mask, bool addDns) + { + this.Function = "UpdateTunIpv4"; + this.Payload = new ConfigPayload() + { + TunIPv4 = tunIPv4, + TunIPv4Mask = tunIPv4Mask, + AddDns = addDns + }; + } + public ConfigPayload Payload { get; set; } + } + } diff --git a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs index af87b68d..cc1f0695 100644 --- a/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs +++ b/ZitiDesktopEdge.Client/ServiceClient/DataClient.cs @@ -390,6 +390,30 @@ namespace ZitiDesktopEdge.ServiceClient { return; } + async public Task UpdateConfigAsync(string tunIPv4, int tunIPv4Mask, bool addDns) { + SvcResponse resp = null; + try { + + ConfigUpdateFunction configPayload = new ConfigUpdateFunction(tunIPv4, tunIPv4Mask, addDns); + + await sendAsync(configPayload); + resp = await readAsync(ipcReader); + Logger.Debug("config update payload is sent to the ziti tunnel"); + } catch (Exception ex) { + //almost certainly a problem with the pipe - recreate the pipe... + //setupPipe(); + //throw; + Logger.Error(ex, "Unexpected error"); + CommunicationError(ex); + throw ex; + } + if (resp?.Code != 0) { + Logger.Warn("failed to update the config. {0} {1}", resp.Message, resp.Error); + throw new ServiceException("Failed to update the config", resp.Code, "Un expected error."); + } + return resp; + } + async public Task debugAsync() { try { await sendAsync(new ServiceFunction() { Function = "Debug" }); diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index 242ec967..52b4649c 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -76,7 +76,7 @@ func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { return } updateTunIpv4Payload["TunIPv4"] = cidr[0] - updateTunIpv4Payload["TunIPv4Mask"] = cidr[1] + updateTunIpv4Payload["TunIPv4Mask"] = ipMask } if AddDns != "" { var addDnsBool bool diff --git a/service/ziti-tunnel/service/ipc.go b/service/ziti-tunnel/service/ipc.go index f3c998de..9c20fcc4 100644 --- a/service/ziti-tunnel/service/ipc.go +++ b/service/ziti-tunnel/service/ipc.go @@ -501,13 +501,14 @@ func serveIpc(conn net.Conn) { rts.SaveState() case "UpdateTunIpv4": var tunIPv4 string - var tunIPv4Mask string + var tunIPv4Mask int var addDns string if cmd.Payload["TunIPv4"] != nil { tunIPv4 = cmd.Payload["TunIPv4"].(string) } if cmd.Payload["TunIPv4Mask"] != nil { - tunIPv4Mask = cmd.Payload["TunIPv4Mask"].(string) + var tunIpv4Mask = cmd.Payload["TunIPv4Mask"].(float64) + tunIPv4Mask = int(tunIpv4Mask) } if cmd.Payload["AddDns"] != nil { addDns = strconv.FormatBool(cmd.Payload["AddDns"].(bool)) @@ -637,19 +638,9 @@ func setLogLevel(out *json.Encoder, level string) { respond(out, dto.Response{Message: "log level set", Code: SUCCESS, Error: "", Payload: nil}) } -func updateTunIpv4(out *json.Encoder, ip string, ipmask string, addDns string) { - var ipMask int - var err error - if ipmask != "" { - ipMask, err = strconv.Atoi(ipmask) +func updateTunIpv4(out *json.Encoder, ip string, ipMask int, addDns string) { - if err != nil { - respondWithError(out, "Incorrect ipv4 mask", UNKNOWN_ERROR, err) - return - } - } - - err = UpdateRuntimeStateIpv4(false, ip, ipMask, addDns) + err := UpdateRuntimeStateIpv4(false, ip, ipMask, addDns) if err != nil { respondWithError(out, "Could not set Tun ip and mask", UNKNOWN_ERROR, err) return From 281876d001af281c606d8a6476ab02b4911efaf9 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 19:39:07 +0530 Subject: [PATCH 06/12] remove the offline update config option --- DesktopEdge/Views/Screens/MainMenu.xaml | 15 ++++ DesktopEdge/Views/Screens/MainMenu.xaml.cs | 17 ++++ service/ziti-tunnel/cli/ipcClient.go | 2 +- service/ziti-tunnel/cli/service.go | 45 ++++------ service/ziti-tunnel/main.go | 2 +- service/ziti-tunnel/service/ipc.go | 4 +- service/ziti-tunnel/service/state.go | 100 +++------------------ 7 files changed, 65 insertions(+), 120 deletions(-) diff --git a/DesktopEdge/Views/Screens/MainMenu.xaml b/DesktopEdge/Views/Screens/MainMenu.xaml index d3a8286a..0961caf4 100644 --- a/DesktopEdge/Views/Screens/MainMenu.xaml +++ b/DesktopEdge/Views/Screens/MainMenu.xaml @@ -93,6 +93,21 @@ + + + + + + + + + diff --git a/DesktopEdge/Views/Screens/MainMenu.xaml.cs b/DesktopEdge/Views/Screens/MainMenu.xaml.cs index aeb5726e..d85a9b7a 100644 --- a/DesktopEdge/Views/Screens/MainMenu.xaml.cs +++ b/DesktopEdge/Views/Screens/MainMenu.xaml.cs @@ -424,6 +424,23 @@ namespace ZitiDesktopEdge { CheckForUpdate.IsEnabled = true; } + async private void UpdateConfig_Click(object sender, RoutedEventArgs e) { + logger.Info("updating config..."); + DataClient client = (DataClient)Application.Current.Properties["ServiceClient"]; + try { + var newMaskVar = Int32.Parse(ConfigMaskNew.Text); + var addDnsNewVar = Convert.ToBoolean(AddDnsNew.Text); + + var r = await client.UpdateConfigAsync(ConfigIpNew.Text, newMaskVar, addDnsNewVar); + logger.Info("Got response from update config task : {0}", r); + } catch (DataStructures.ServiceException se) { + logger.Error(se, "service exception in update check: {0}", se.Message); + } + catch (Exception ex) { + logger.Error(ex, "unexpected error in update check: {0}", ex.Message); + } + } + async private void TriggerUpdate_Click(object sender, RoutedEventArgs e) { try { CheckForUpdate.IsEnabled = false; diff --git a/service/ziti-tunnel/cli/ipcClient.go b/service/ziti-tunnel/cli/ipcClient.go index a042ef92..50a87b94 100644 --- a/service/ziti-tunnel/cli/ipcClient.go +++ b/service/ziti-tunnel/cli/ipcClient.go @@ -144,7 +144,7 @@ func GetDataFromIpcPipe(commandMsg *dto.CommandMsg, fn fetchStatusFromRTS, respo if err != nil { log.Errorf("Connection to ipc pipe is not established, %v", err) - log.Errorf("Ziti Desktop Edge app may not be running") + log.Fatal("Ziti Desktop Edge app may not be running") return false } readDone := make(chan bool) diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index 52b4649c..be81a09a 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -1,11 +1,26 @@ package cli +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + import ( "strings" "strconv" - "golang.org/x/sys/windows/svc" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/service" ) //GetIdentities is to fetch identities through cmdline @@ -95,31 +110,7 @@ func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { status := GetDataFromIpcPipe(&UPDATE_TUN_IPV4, nil, GetResponseObjectFromRTS, args, nil) if !status { - log.Infof("Updating ip and mask in the config file. Manual restart is required") - var tunIpv4 string - if len(cidr) == 2 { - tunIpv4 = cidr[0] - } - err = service.UpdateRuntimeStateIpv4(true, tunIpv4, ipMask, AddDns.(string)) - if err != nil { - log.Errorf("Unable to set Tun ip and mask, %v", err) - return - } - log.Infof("ip and mask are set") - } - - if status { - log.Infof("Attempting to restart ziti ") - - err = service.ControlService(svc.Stop, svc.Stopped) - if (err != nil) { - log.Errorf("Unable to stop the service, %v", err) - return - } - err = service.StartService() - if (err != nil) { - log.Errorf("Unable to start the service, %v", err) - } + log.Infof("Config can be updated only if the tunnel is started") } } diff --git a/service/ziti-tunnel/main.go b/service/ziti-tunnel/main.go index e765ea59..1b5a51db 100644 --- a/service/ziti-tunnel/main.go +++ b/service/ziti-tunnel/main.go @@ -128,7 +128,7 @@ func usage(errmsg string) { "%s\n\n"+ "usage: %s \n"+ " where is one of\n"+ - " install, remove, debug, start, stop, pause, continue, list, identity, loglevel, feedback or version.\n", + " install, remove, debug, start, stop, pause, continue, list, identity, loglevel, feedback, config or version.\n", errmsg, os.Args[0]) os.Exit(2) } diff --git a/service/ziti-tunnel/service/ipc.go b/service/ziti-tunnel/service/ipc.go index 9c20fcc4..d2343c10 100644 --- a/service/ziti-tunnel/service/ipc.go +++ b/service/ziti-tunnel/service/ipc.go @@ -640,13 +640,13 @@ func setLogLevel(out *json.Encoder, level string) { func updateTunIpv4(out *json.Encoder, ip string, ipMask int, addDns string) { - err := UpdateRuntimeStateIpv4(false, ip, ipMask, addDns) + err := UpdateRuntimeStateIpv4(ip, ipMask, addDns) if err != nil { respondWithError(out, "Could not set Tun ip and mask", UNKNOWN_ERROR, err) return } - respond(out, dto.Response{Message: "TunIPv4 and mask is set", Code: SUCCESS, Error: "", Payload: ""}) + respond(out, dto.Response{Message: "TunIPv4 and mask is set, Manual Restart is required", Code: SUCCESS, Error: "", Payload: ""}) } func serveLogs(conn net.Conn) { diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go index 6557de96..ff2b9e15 100644 --- a/service/ziti-tunnel/service/state.go +++ b/service/ziti-tunnel/service/state.go @@ -29,7 +29,6 @@ import ( "path" "strings" "time" - "path/filepath" "errors" "strconv" "github.com/openziti/desktop-edge-win/service/cziti" @@ -109,57 +108,6 @@ func backupConfig() (string, error) { } -func (t *RuntimeState) SaveStateWithPath(systemPath string) { - // overwrite file if it exists - _ = os.MkdirAll(systemPath, 0644) - - log.Debugf("backing up config") - backup, err := backupConfigWithPath(systemPath) - if err != nil { - log.Warnf("could not backup config file! %v", err) - } else { - log.Debugf("config file backed up to: %s", backup) - } - - cfg, err := os.OpenFile(filepath.Join(systemPath, string(os.PathSeparator), "config.json"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) - defer cfg.Close() - if err != nil { - log.Panicf("An unexpected and unrecoverable error has occurred while %s: %v", "opening the config file", err) - } - - w := bufio.NewWriter(bufio.NewWriter(cfg)) - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - _ = enc.Encode(t.state) - _ = w.Flush() - - err = cfg.Close() - if err != nil { - log.Panicf("An unexpected and unrecoverable error has occurred while %s: %v", "closing the config file", err) - } - log.Debug("state saved") -} - -func backupConfigWithPath(systemPath string) (string, error) { - original, err := os.Open(filepath.Join(systemPath, string(os.PathSeparator), "config.json")) - if err != nil { - return "", err - } - defer original.Close() - backup := filepath.Join(systemPath, string(os.PathSeparator), "config.json.backup") - new, err := os.Create(backup) - if err != nil { - return "", err - } - defer new.Close() - - _, err = io.Copy(new, original) - if err != nil { - return "", err - } - return backup, err -} - func (t *RuntimeState) ToStatus(onlyInitialized bool) dto.TunnelStatus { var uptime int64 @@ -455,7 +403,7 @@ func (t *RuntimeState) UpdateIpv4(ipv4 string) { rts.SaveState() } -func UpdateRuntimeStateIpv4(offline bool, ip string, ipv4Mask int, addDns string) error { +func UpdateRuntimeStateIpv4(ip string, ipv4Mask int, addDns string) error { log.Infof("ip and mask %s %d", ip, ipv4Mask) @@ -469,43 +417,17 @@ func UpdateRuntimeStateIpv4(offline bool, ip string, ipv4Mask int, addDns string } } - if offline { - systemDrivePath := os.Getenv("SystemDrive") - if systemDrivePath == "" { - return errors.New("SystemDrive env is not found") - } - configPath := "Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\NetFoundry" - systemPath := filepath.Join(systemDrivePath, string(os.PathSeparator), configPath) - err := readConfig(rts, filepath.Join(systemPath, string(os.PathSeparator), "config.json")) - if (err != nil) { - log.Errorf("Unable to read the config file, %v", err) - return err - } - - // if ip is not empty, then we set both ip and mask - if ip != "" { - rts.state.TunIpv4 = ip - rts.state.TunIpv4Mask = ipv4Mask - } - if addDns != "" { - rts.state.AddDns = addDnsBool - } - - rts.SaveStateWithPath(systemPath) - - } else { - - // if ip is not empty, then we set both ip and mask - if ip != "" { - rts.state.TunIpv4 = ip - rts.state.TunIpv4Mask = ipv4Mask - } - if addDns != "" { - rts.state.AddDns = addDnsBool - } - - rts.SaveState() + // if ip is not empty, then we set both ip and mask + if ip != "" { + rts.state.TunIpv4 = ip + rts.state.TunIpv4Mask = ipv4Mask } + if addDns != "" { + rts.state.AddDns = addDnsBool + } + + rts.SaveState() + return nil } From aebd5226a37fd24037594ae048731679eccd6545 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 19:50:16 +0530 Subject: [PATCH 07/12] update the version --- release-notes.md | 12 +++++------- version | 2 +- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/release-notes.md b/release-notes.md index 67b66a3f..821b8fc0 100644 --- a/release-notes.md +++ b/release-notes.md @@ -1,16 +1,13 @@ -# Release 1.9.3 +# Release 1.9.4 ## What's New -* Page Service List -* Sort Service on Identity Details Page -* Consistent UX for MFA Screens +* none ## Other changes: -* Service to UI interaction is now with one bulk update of services instead of one event per service update -* Added a configuration option to control if DNS is applied to the TUN. Some users are having issues with NRPT-only working. For now we'll add a boolean that allows the user to control if DNS should be added to the TUN +* none ## Bugs fixed: -* none +* [#362](https://github.com/openziti/desktop-edge-win/issues/362) Update tun ip, mask and addDns flag ## Dependency Updates * none @@ -24,6 +21,7 @@ ## Other changes: * Service to UI interaction is now with one bulk update of services instead of one event per service update +* Added a configuration option to control if DNS is applied to the TUN. Some users are having issues with NRPT-only working. For now we'll add a boolean that allows the user to control if DNS should be added to the TUN ## Bugs fixed: * none diff --git a/version b/version index 77fee73a..d615fd0c 100644 --- a/version +++ b/version @@ -1 +1 @@ -1.9.3 +1.9.4 From 77ed580f759adbfe84635a3bb330139f69a9a659 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 20:01:24 +0530 Subject: [PATCH 08/12] formatting code --- service/ziti-tunnel/cli/constants.go | 118 ++--- service/ziti-tunnel/cli/responseGenerator.go | 485 +++++++++---------- service/ziti-tunnel/cli/service.go | 233 +++++---- 3 files changed, 417 insertions(+), 419 deletions(-) diff --git a/service/ziti-tunnel/cli/constants.go b/service/ziti-tunnel/cli/constants.go index e6e49187..150d45af 100644 --- a/service/ziti-tunnel/cli/constants.go +++ b/service/ziti-tunnel/cli/constants.go @@ -1,59 +1,59 @@ -package cli - -/* - * Copyright NetFoundry, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import ( - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/util/logging" -) - -var GET_STATUS = dto.CommandMsg{ - Function: "Status", -} - -var ONOFF_IDENTITY = dto.CommandMsg{ - Function: "IdentityOnOff", -} - -var SET_LOGLEVEL = dto.CommandMsg{ - Function: "SetLogLevel", -} - -var NOTIFY_LOGLEVEL_UI_MONITOR = dto.CommandMsg{ - Function: "NotifyLogLevelUIAndUpdateService", -} - -var NOTIFY_IDENTITY_UI = dto.CommandMsg{ - Function: "NotifyIdentityUI", -} - -var UPDATE_TUN_IPV4 = dto.CommandMsg{ - Function: "UpdateTunIpv4", -} - -var monitorIpcPipe = `\\.\pipe\OpenZiti\ziti-monitor\ipc` - -var templateIdentity = `{{printf "%40s" "Name"}} | {{printf "%41s" "FingerPrint"}} | {{printf "%6s" "Active"}} | {{printf "%30s" "Config"}} | {{"Status"}} -{{range .}}{{printf "%40s" .Name}} | {{printf "%41s" .FingerPrint}} | {{printf "%6t" .Active}} | {{printf "%30s" .Config}} | {{.Status}} -{{end}}` - -var templateService = `{{printf "%40s" "Name"}} | {{printf "%15s" "Id"}} | {{printf "%9s" "Protocols"}} | {{printf "%14s" "Ports"}} | {{printf "%60s" "Addresses"}} -{{range .}}{{printf "%40s" .Name}} | {{printf "%15s" .Id}} | {{printf "%9s" .Protocols}} | {{printf "%14s" .Ports}} | {{printf "%60s" .Addresses}} -{{end}}` - -var log = logging.Logger() +package cli + +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import ( + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/util/logging" +) + +var GET_STATUS = dto.CommandMsg{ + Function: "Status", +} + +var ONOFF_IDENTITY = dto.CommandMsg{ + Function: "IdentityOnOff", +} + +var SET_LOGLEVEL = dto.CommandMsg{ + Function: "SetLogLevel", +} + +var NOTIFY_LOGLEVEL_UI_MONITOR = dto.CommandMsg{ + Function: "NotifyLogLevelUIAndUpdateService", +} + +var NOTIFY_IDENTITY_UI = dto.CommandMsg{ + Function: "NotifyIdentityUI", +} + +var UPDATE_TUN_IPV4 = dto.CommandMsg{ + Function: "UpdateTunIpv4", +} + +var monitorIpcPipe = `\\.\pipe\OpenZiti\ziti-monitor\ipc` + +var templateIdentity = `{{printf "%40s" "Name"}} | {{printf "%41s" "FingerPrint"}} | {{printf "%6s" "Active"}} | {{printf "%30s" "Config"}} | {{"Status"}} +{{range .}}{{printf "%40s" .Name}} | {{printf "%41s" .FingerPrint}} | {{printf "%6t" .Active}} | {{printf "%30s" .Config}} | {{.Status}} +{{end}}` + +var templateService = `{{printf "%40s" "Name"}} | {{printf "%15s" "Id"}} | {{printf "%9s" "Protocols"}} | {{printf "%14s" "Ports"}} | {{printf "%60s" "Addresses"}} +{{range .}}{{printf "%40s" .Name}} | {{printf "%15s" .Id}} | {{printf "%9s" .Protocols}} | {{printf "%14s" .Ports}} | {{printf "%60s" .Addresses}} +{{end}}` + +var log = logging.Logger() diff --git a/service/ziti-tunnel/cli/responseGenerator.go b/service/ziti-tunnel/cli/responseGenerator.go index e736c7f4..2b19d6ad 100644 --- a/service/ziti-tunnel/cli/responseGenerator.go +++ b/service/ziti-tunnel/cli/responseGenerator.go @@ -1,243 +1,242 @@ -package cli - -/* - * Copyright NetFoundry, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - "text/template" - - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/service" -) - -func convertToIdentityCli(id *dto.Identity) dto.IdentityCli { - return dto.IdentityCli{ - Name: id.Name, - FingerPrint: id.FingerPrint, - Active: id.Active, - Config: id.Config.ZtAPI, - Status: id.Status, - } -} - -func convertToServiceCli(svc dto.Service) dto.ServiceCli { - cliPorts := "" - for _, val := range svc.Ports { - if len(cliPorts) != 0 { - cliPorts = fmt.Sprintf("%s, %d-%d", cliPorts, val.Low, val.High) - } else { - cliPorts = fmt.Sprintf("%d-%d", val.Low, val.High) - } - } - cliAddresses := "" - for _, val := range svc.Addresses { - if len(cliAddresses) != 0 { - cliAddresses = cliAddresses + ", " + val.HostName + "/" + val.IP - } else { - cliAddresses = val.HostName + "/" + val.IP - } - } - - return dto.ServiceCli{ - Name: svc.Name, - Id: svc.Id, - Protocols: strings.Join(svc.Protocols, ","), - Ports: cliPorts, - Addresses: cliAddresses, - } -} - -// GetIdentitiesFromRTS is to get identities from the RTS -func GetIdentitiesFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { - - var filteredIdentities []dto.IdentityCli - - if flags["services"] { - return filterServicesByIdentity(args, status, flags) - } - - for _, val := range args { - if val == "all" { - for _, id := range status.Identities { - filteredIdentities = append(filteredIdentities, convertToIdentityCli(id)) - } - break - } else { - for _, id := range status.Identities { - if strings.Compare(id.Name, val) == 0 { - filteredIdentities = append(filteredIdentities, convertToIdentityCli(id)) - } - } - } - } - - if len(filteredIdentities) == 0 { - errMsg := fmt.Sprintf("Could not find identities matching %s", args) - return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: nil} - } - message := fmt.Sprintf("Got %d identities - %s", len(filteredIdentities), args) - return generateResponse("identities", message, filteredIdentities, flags, templateIdentity) -} - -func filterServicesByIdentity(identity []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { - var filteredServices []dto.ServiceCli - - for _, id := range status.Identities { - for _, filterID := range identity { - if (filterID == "all" || id.Name == filterID) && len(id.Services) > 0 { - for _, svc := range id.Services { - filteredServices = append(filteredServices, convertToServiceCli(*svc)) - } - // if the filterId array has all or matching string, then fetch all the services and break from the filter loop - break - } - } - - } - - if len(filteredServices) == 0 { - errMsg := fmt.Sprintf("Could not find services for identity %s", identity) - return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: nil} - } - message := fmt.Sprintf("Got %d services for identity - %s", len(filteredServices), identity) - return generateResponse("services", message, filteredServices, flags, templateService) - -} - -func GetServicesFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { - - var filteredServices []dto.ServiceCli - - for _, val := range args { - if val == "all" { - for _, id := range status.Identities { - if len(id.Services) > 0 { - for _, svc := range id.Services { - filteredServices = append(filteredServices, convertToServiceCli(*svc)) - } - } - } - break - } else { - for _, id := range status.Identities { - if len(id.Services) > 0 { - for _, svc := range id.Services { - if strings.Compare(val, svc.Name) == 0 { - filteredServices = append(filteredServices, convertToServiceCli(*svc)) - } - } - } - } - } - } - - if len(filteredServices) == 0 { - errMsg := fmt.Sprintf("Could not find services matching %s", args) - return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: nil} - } - message := fmt.Sprintf("Got %d services - %s", len(filteredServices), args) - - return generateResponse("services", message, filteredServices, flags, templateService) - -} - -func generateResponse(dataType string, message string, filteredData interface{}, flags map[string]bool, templateStr string) dto.Response { - - var bytesData []byte - var err error - var responseBuffer bytes.Buffer - var responseStr string - - if flags["prettyJSON"] == true { - bytesData, err = json.MarshalIndent(filteredData, "", " ") - - if err != nil { - log.Error(err) - return dto.Response{Message: message, Code: service.ERROR, Error: "Could not fetch " + dataType + " from Runtime", Payload: nil} - } - responseStr = string(bytesData) - - } else { - it, err := template.New("filteredData").Parse(templateStr) - - if err != nil { - log.Error(err) - return dto.Response{Message: message, Code: service.ERROR, Error: "Could not parse " + dataType + " from Runtime", Payload: nil} - } - - err = it.Execute(&responseBuffer, filteredData) - - if err != nil { - log.Error(err) - return dto.Response{Message: message, Code: service.ERROR, Error: "Could not print " + dataType + " from Runtime", Payload: nil} - } - responseStr = responseBuffer.String() - } - - return dto.Response{Message: message, Code: service.SUCCESS, Error: "", Payload: responseStr} -} - -func GetLogLevelFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { - - if flags["query"] == true { - message := fmt.Sprintf("Loglevel is currently set to %s", status.LogLevel) - return dto.Response{Message: message, Code: service.SUCCESS, Error: "", Payload: ""} - } - errMsg := fmt.Sprintf("Unknown error: args %s flag %v", args, flags) - return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: ""} - -} - -// GetIdentityResponseObjectFromRTS is to get identity info from the RTS -func GetIdentityResponseObjectFromRTS(args []string, status dto.Response, flags map[string]bool) dto.Response { - log.Debugf("Message from ziti-tunnel : %v", status.Message) - if status.Error == "" && status.Payload != nil { - log.Debugf("Payload from RTS %v", status.Payload) - payloadData := status.Payload.(map[string]interface{}) - identityStatus := make(map[string]interface{}) - identityStatus["FingerPrint"] = payloadData["FingerPrint"] - identityStatus["Active"] = payloadData["Active"] - identityStatus["Name"] = payloadData["Name"] - return dto.Response{Message: status.Message, Code: service.SUCCESS, Error: "", Payload: identityStatus} - } else { - return status - } -} - -// GetResponseObjectFromRTS is to get response object info from the RTS -func GetResponseObjectFromRTS(args []string, status dto.Response, flags map[string]bool) dto.Response { - return status -} - -func GetStatusFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { - - if status == nil { - return dto.Response{Message: "Stopped / Unknown State", Code: service.SUCCESS, Error: "", Payload: ""} - } - - if status.Active { - return dto.Response{Message: "Running", Code: service.SUCCESS, Error: "", Payload: ""} - } else { - return dto.Response{Message: "Stopped", Code: service.SUCCESS, Error: "", Payload: ""} - } - -} - +package cli + +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" + "text/template" + + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/service" +) + +func convertToIdentityCli(id *dto.Identity) dto.IdentityCli { + return dto.IdentityCli{ + Name: id.Name, + FingerPrint: id.FingerPrint, + Active: id.Active, + Config: id.Config.ZtAPI, + Status: id.Status, + } +} + +func convertToServiceCli(svc dto.Service) dto.ServiceCli { + cliPorts := "" + for _, val := range svc.Ports { + if len(cliPorts) != 0 { + cliPorts = fmt.Sprintf("%s, %d-%d", cliPorts, val.Low, val.High) + } else { + cliPorts = fmt.Sprintf("%d-%d", val.Low, val.High) + } + } + cliAddresses := "" + for _, val := range svc.Addresses { + if len(cliAddresses) != 0 { + cliAddresses = cliAddresses + ", " + val.HostName + "/" + val.IP + } else { + cliAddresses = val.HostName + "/" + val.IP + } + } + + return dto.ServiceCli{ + Name: svc.Name, + Id: svc.Id, + Protocols: strings.Join(svc.Protocols, ","), + Ports: cliPorts, + Addresses: cliAddresses, + } +} + +// GetIdentitiesFromRTS is to get identities from the RTS +func GetIdentitiesFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { + + var filteredIdentities []dto.IdentityCli + + if flags["services"] { + return filterServicesByIdentity(args, status, flags) + } + + for _, val := range args { + if val == "all" { + for _, id := range status.Identities { + filteredIdentities = append(filteredIdentities, convertToIdentityCli(id)) + } + break + } else { + for _, id := range status.Identities { + if strings.Compare(id.Name, val) == 0 { + filteredIdentities = append(filteredIdentities, convertToIdentityCli(id)) + } + } + } + } + + if len(filteredIdentities) == 0 { + errMsg := fmt.Sprintf("Could not find identities matching %s", args) + return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: nil} + } + message := fmt.Sprintf("Got %d identities - %s", len(filteredIdentities), args) + return generateResponse("identities", message, filteredIdentities, flags, templateIdentity) +} + +func filterServicesByIdentity(identity []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { + var filteredServices []dto.ServiceCli + + for _, id := range status.Identities { + for _, filterID := range identity { + if (filterID == "all" || id.Name == filterID) && len(id.Services) > 0 { + for _, svc := range id.Services { + filteredServices = append(filteredServices, convertToServiceCli(*svc)) + } + // if the filterId array has all or matching string, then fetch all the services and break from the filter loop + break + } + } + + } + + if len(filteredServices) == 0 { + errMsg := fmt.Sprintf("Could not find services for identity %s", identity) + return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: nil} + } + message := fmt.Sprintf("Got %d services for identity - %s", len(filteredServices), identity) + return generateResponse("services", message, filteredServices, flags, templateService) + +} + +func GetServicesFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { + + var filteredServices []dto.ServiceCli + + for _, val := range args { + if val == "all" { + for _, id := range status.Identities { + if len(id.Services) > 0 { + for _, svc := range id.Services { + filteredServices = append(filteredServices, convertToServiceCli(*svc)) + } + } + } + break + } else { + for _, id := range status.Identities { + if len(id.Services) > 0 { + for _, svc := range id.Services { + if strings.Compare(val, svc.Name) == 0 { + filteredServices = append(filteredServices, convertToServiceCli(*svc)) + } + } + } + } + } + } + + if len(filteredServices) == 0 { + errMsg := fmt.Sprintf("Could not find services matching %s", args) + return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: nil} + } + message := fmt.Sprintf("Got %d services - %s", len(filteredServices), args) + + return generateResponse("services", message, filteredServices, flags, templateService) + +} + +func generateResponse(dataType string, message string, filteredData interface{}, flags map[string]bool, templateStr string) dto.Response { + + var bytesData []byte + var err error + var responseBuffer bytes.Buffer + var responseStr string + + if flags["prettyJSON"] == true { + bytesData, err = json.MarshalIndent(filteredData, "", " ") + + if err != nil { + log.Error(err) + return dto.Response{Message: message, Code: service.ERROR, Error: "Could not fetch " + dataType + " from Runtime", Payload: nil} + } + responseStr = string(bytesData) + + } else { + it, err := template.New("filteredData").Parse(templateStr) + + if err != nil { + log.Error(err) + return dto.Response{Message: message, Code: service.ERROR, Error: "Could not parse " + dataType + " from Runtime", Payload: nil} + } + + err = it.Execute(&responseBuffer, filteredData) + + if err != nil { + log.Error(err) + return dto.Response{Message: message, Code: service.ERROR, Error: "Could not print " + dataType + " from Runtime", Payload: nil} + } + responseStr = responseBuffer.String() + } + + return dto.Response{Message: message, Code: service.SUCCESS, Error: "", Payload: responseStr} +} + +func GetLogLevelFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { + + if flags["query"] == true { + message := fmt.Sprintf("Loglevel is currently set to %s", status.LogLevel) + return dto.Response{Message: message, Code: service.SUCCESS, Error: "", Payload: ""} + } + errMsg := fmt.Sprintf("Unknown error: args %s flag %v", args, flags) + return dto.Response{Message: "", Code: service.ERROR, Error: errMsg, Payload: ""} + +} + +// GetIdentityResponseObjectFromRTS is to get identity info from the RTS +func GetIdentityResponseObjectFromRTS(args []string, status dto.Response, flags map[string]bool) dto.Response { + log.Debugf("Message from ziti-tunnel : %v", status.Message) + if status.Error == "" && status.Payload != nil { + log.Debugf("Payload from RTS %v", status.Payload) + payloadData := status.Payload.(map[string]interface{}) + identityStatus := make(map[string]interface{}) + identityStatus["FingerPrint"] = payloadData["FingerPrint"] + identityStatus["Active"] = payloadData["Active"] + identityStatus["Name"] = payloadData["Name"] + return dto.Response{Message: status.Message, Code: service.SUCCESS, Error: "", Payload: identityStatus} + } else { + return status + } +} + +// GetResponseObjectFromRTS is to get response object info from the RTS +func GetResponseObjectFromRTS(args []string, status dto.Response, flags map[string]bool) dto.Response { + return status +} + +func GetStatusFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { + + if status == nil { + return dto.Response{Message: "Stopped / Unknown State", Code: service.SUCCESS, Error: "", Payload: ""} + } + + if status.Active { + return dto.Response{Message: "Running", Code: service.SUCCESS, Error: "", Payload: ""} + } else { + return dto.Response{Message: "Stopped", Code: service.SUCCESS, Error: "", Payload: ""} + } + +} diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index be81a09a..3b9a9e03 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -1,117 +1,116 @@ -package cli - -/* - * Copyright NetFoundry, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import ( - "strings" - "strconv" - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" -) - -//GetIdentities is to fetch identities through cmdline -func GetIdentities(args []string, flags map[string]bool) { - GetDataFromIpcPipe(&GET_STATUS, GetIdentitiesFromRTS, nil, args, flags) -} - -//GetServices is to fetch services through cmdline -func GetServices(args []string, flags map[string]bool) { - GetDataFromIpcPipe(&GET_STATUS, GetServicesFromRTS, nil, args, flags) -} - -//OnOffIdentity is to enable or disable the identity through cmdline -func OnOffIdentity(args []string, flags map[string]bool) { - identityPayload := make(map[string]interface{}) - identityPayload["OnOff"] = strings.EqualFold(args[1], "on") - identityPayload["Fingerprint"] = args[0] - ONOFF_IDENTITY.Payload = identityPayload - log.Debugf("OnOffIdentity Payload %v", ONOFF_IDENTITY) - status := GetDataFromIpcPipe(&ONOFF_IDENTITY, nil, GetIdentityResponseObjectFromRTS, args, flags) - if status { - NOTIFY_IDENTITY_UI.Payload = identityPayload - log.Infof("Notifying the Identity Status to UI %v", identityPayload) - GetDataFromIpcPipe(&NOTIFY_IDENTITY_UI, nil, GetResponseObjectFromRTS, args, flags) - } -} - -//SetLogLevel is to change the loglevel through cmdline -func SetLogLevel(args []string, flags map[string]bool) { - if flags["query"] == true { - GetDataFromIpcPipe(&GET_STATUS, GetLogLevelFromRTS, nil, args, flags) - } else { - loglevelPayload := make(map[string]interface{}) - loglevelPayload["Level"] = args[0] - SET_LOGLEVEL.Payload = loglevelPayload - log.Debugf("LogLevel Payload %v", SET_LOGLEVEL) - status := GetDataFromIpcPipe(&SET_LOGLEVEL, nil, GetResponseObjectFromRTS, args, flags) - if status { - NOTIFY_LOGLEVEL_UI_MONITOR.Payload = loglevelPayload - log.Infof("Notifying the LogLevel to UI and Ziti monitor service %v", loglevelPayload) - GetDataFromIpcPipe(&NOTIFY_LOGLEVEL_UI_MONITOR, nil, GetResponseObjectFromRTS, args, flags) - } - } -} - -//GetFeedback is to create logs zip through cmdline -func GetFeedback(args []string, flags map[string]bool) { - GetDataFromMonitorIpcPipe(&dto.FEEDBACK_REQUEST, args, flags) -} - -func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { - CIDRstring := flags["CIDR"] - AddDns := flags["AddDns"] - log.Info("Updating the config file") - var cidr []string - var ipMask int - var err error - - updateTunIpv4Payload := make(map[string]interface{}) - if CIDRstring != "" { - cidr = strings.Split(CIDRstring.(string), "/") - if len(cidr) != 2 { - log.Error("Incorrect cidr") - } - ipMask, err = strconv.Atoi(cidr[1]) - if err != nil { - log.Errorf("Incorrect ipv4 mask, %s", cidr[1]) - return - } - updateTunIpv4Payload["TunIPv4"] = cidr[0] - updateTunIpv4Payload["TunIPv4Mask"] = ipMask - } - if AddDns != "" { - var addDnsBool bool - addDnsBool, err = strconv.ParseBool(AddDns.(string)) - - if err != nil { - log.Errorf("Incorrect addDns %v", err) - return - } - updateTunIpv4Payload["AddDns"] = addDnsBool - } - - UPDATE_TUN_IPV4.Payload = updateTunIpv4Payload - log.Debugf("updateTunIpv4 Payload %v", UPDATE_TUN_IPV4) - - status := GetDataFromIpcPipe(&UPDATE_TUN_IPV4, nil, GetResponseObjectFromRTS, args, nil) - - if !status { - log.Infof("Config can be updated only if the tunnel is started") - } - -} - +package cli + +/* + * Copyright NetFoundry, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import ( + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" + "strconv" + "strings" +) + +//GetIdentities is to fetch identities through cmdline +func GetIdentities(args []string, flags map[string]bool) { + GetDataFromIpcPipe(&GET_STATUS, GetIdentitiesFromRTS, nil, args, flags) +} + +//GetServices is to fetch services through cmdline +func GetServices(args []string, flags map[string]bool) { + GetDataFromIpcPipe(&GET_STATUS, GetServicesFromRTS, nil, args, flags) +} + +//OnOffIdentity is to enable or disable the identity through cmdline +func OnOffIdentity(args []string, flags map[string]bool) { + identityPayload := make(map[string]interface{}) + identityPayload["OnOff"] = strings.EqualFold(args[1], "on") + identityPayload["Fingerprint"] = args[0] + ONOFF_IDENTITY.Payload = identityPayload + log.Debugf("OnOffIdentity Payload %v", ONOFF_IDENTITY) + status := GetDataFromIpcPipe(&ONOFF_IDENTITY, nil, GetIdentityResponseObjectFromRTS, args, flags) + if status { + NOTIFY_IDENTITY_UI.Payload = identityPayload + log.Infof("Notifying the Identity Status to UI %v", identityPayload) + GetDataFromIpcPipe(&NOTIFY_IDENTITY_UI, nil, GetResponseObjectFromRTS, args, flags) + } +} + +//SetLogLevel is to change the loglevel through cmdline +func SetLogLevel(args []string, flags map[string]bool) { + if flags["query"] == true { + GetDataFromIpcPipe(&GET_STATUS, GetLogLevelFromRTS, nil, args, flags) + } else { + loglevelPayload := make(map[string]interface{}) + loglevelPayload["Level"] = args[0] + SET_LOGLEVEL.Payload = loglevelPayload + log.Debugf("LogLevel Payload %v", SET_LOGLEVEL) + status := GetDataFromIpcPipe(&SET_LOGLEVEL, nil, GetResponseObjectFromRTS, args, flags) + if status { + NOTIFY_LOGLEVEL_UI_MONITOR.Payload = loglevelPayload + log.Infof("Notifying the LogLevel to UI and Ziti monitor service %v", loglevelPayload) + GetDataFromIpcPipe(&NOTIFY_LOGLEVEL_UI_MONITOR, nil, GetResponseObjectFromRTS, args, flags) + } + } +} + +//GetFeedback is to create logs zip through cmdline +func GetFeedback(args []string, flags map[string]bool) { + GetDataFromMonitorIpcPipe(&dto.FEEDBACK_REQUEST, args, flags) +} + +func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { + CIDRstring := flags["CIDR"] + AddDns := flags["AddDns"] + log.Info("Updating the config file") + var cidr []string + var ipMask int + var err error + + updateTunIpv4Payload := make(map[string]interface{}) + if CIDRstring != "" { + cidr = strings.Split(CIDRstring.(string), "/") + if len(cidr) != 2 { + log.Error("Incorrect cidr") + } + ipMask, err = strconv.Atoi(cidr[1]) + if err != nil { + log.Errorf("Incorrect ipv4 mask, %s", cidr[1]) + return + } + updateTunIpv4Payload["TunIPv4"] = cidr[0] + updateTunIpv4Payload["TunIPv4Mask"] = ipMask + } + if AddDns != "" { + var addDnsBool bool + addDnsBool, err = strconv.ParseBool(AddDns.(string)) + + if err != nil { + log.Errorf("Incorrect addDns %v", err) + return + } + updateTunIpv4Payload["AddDns"] = addDnsBool + } + + UPDATE_TUN_IPV4.Payload = updateTunIpv4Payload + log.Debugf("updateTunIpv4 Payload %v", UPDATE_TUN_IPV4) + + status := GetDataFromIpcPipe(&UPDATE_TUN_IPV4, nil, GetResponseObjectFromRTS, args, nil) + + if !status { + log.Infof("Config can be updated only if the tunnel is started") + } + +} From 4f0021fc8f73340030979ecaaacaeee4a64ed705 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 20:08:29 +0530 Subject: [PATCH 09/12] removing unused function --- service/ziti-tunnel/cli/responseGenerator.go | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/service/ziti-tunnel/cli/responseGenerator.go b/service/ziti-tunnel/cli/responseGenerator.go index 2b19d6ad..d469dad7 100644 --- a/service/ziti-tunnel/cli/responseGenerator.go +++ b/service/ziti-tunnel/cli/responseGenerator.go @@ -226,17 +226,3 @@ func GetIdentityResponseObjectFromRTS(args []string, status dto.Response, flags func GetResponseObjectFromRTS(args []string, status dto.Response, flags map[string]bool) dto.Response { return status } - -func GetStatusFromRTS(args []string, status *dto.TunnelStatus, flags map[string]bool) dto.Response { - - if status == nil { - return dto.Response{Message: "Stopped / Unknown State", Code: service.SUCCESS, Error: "", Payload: ""} - } - - if status.Active { - return dto.Response{Message: "Running", Code: service.SUCCESS, Error: "", Payload: ""} - } else { - return dto.Response{Message: "Stopped", Code: service.SUCCESS, Error: "", Payload: ""} - } - -} From 2f7bb542c863e59da30a2811c98a86e64a8af10a Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 20:16:40 +0530 Subject: [PATCH 10/12] removing unused code --- service/ziti-tunnel/service/state.go | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go index ff2b9e15..b34c5513 100644 --- a/service/ziti-tunnel/service/state.go +++ b/service/ziti-tunnel/service/state.go @@ -407,14 +407,14 @@ func UpdateRuntimeStateIpv4(ip string, ipv4Mask int, addDns string) error { log.Infof("ip and mask %s %d", ip, ipv4Mask) - var addDnsBool bool - var err error if addDns != "" { - addDnsBool, err = strconv.ParseBool(addDns) + addDnsBool, err := strconv.ParseBool(addDns) if err != nil { return errors.New(fmt.Sprintf("Incorrect addDns %v", err)) } + + rts.state.AddDns = addDnsBool } // if ip is not empty, then we set both ip and mask @@ -422,9 +422,6 @@ func UpdateRuntimeStateIpv4(ip string, ipv4Mask int, addDns string) error { rts.state.TunIpv4 = ip rts.state.TunIpv4Mask = ipv4Mask } - if addDns != "" { - rts.state.AddDns = addDnsBool - } rts.SaveState() From 4507c2f6e5859e7966248994f45496ba5767d189 Mon Sep 17 00:00:00 2001 From: Mary Lincy Dcouto Date: Thu, 15 Apr 2021 21:30:13 +0530 Subject: [PATCH 11/12] fixing the code review comments --- service/ziti-tunnel/cli/service.go | 20 +++++++------------- service/ziti-tunnel/service/state.go | 6 +++++- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index 3b9a9e03..dd6ebcfb 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -21,6 +21,7 @@ import ( "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" "strconv" "strings" + "net" ) //GetIdentities is to fetch identities through cmdline @@ -75,27 +76,20 @@ func UpdateConfigIPSubnet(args []string, flags map[string]interface{}) { CIDRstring := flags["CIDR"] AddDns := flags["AddDns"] log.Info("Updating the config file") - var cidr []string - var ipMask int - var err error updateTunIpv4Payload := make(map[string]interface{}) if CIDRstring != "" { - cidr = strings.Split(CIDRstring.(string), "/") - if len(cidr) != 2 { - log.Error("Incorrect cidr") - } - ipMask, err = strconv.Atoi(cidr[1]) + ip, ipnet, err := net.ParseCIDR(CIDRstring.(string)) if err != nil { - log.Errorf("Incorrect ipv4 mask, %s", cidr[1]) - return + log.Error("Incorrect cidr %s", CIDRstring.(string)) } - updateTunIpv4Payload["TunIPv4"] = cidr[0] + ipMask, _ := ipnet.Mask.Size() + + updateTunIpv4Payload["TunIPv4"] = ip updateTunIpv4Payload["TunIPv4Mask"] = ipMask } if AddDns != "" { - var addDnsBool bool - addDnsBool, err = strconv.ParseBool(AddDns.(string)) + addDnsBool, err := strconv.ParseBool(AddDns.(string)) if err != nil { log.Errorf("Incorrect addDns %v", err) diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go index b34c5513..aa625adb 100644 --- a/service/ziti-tunnel/service/state.go +++ b/service/ziti-tunnel/service/state.go @@ -405,7 +405,11 @@ func (t *RuntimeState) UpdateIpv4(ipv4 string) { func UpdateRuntimeStateIpv4(ip string, ipv4Mask int, addDns string) error { - log.Infof("ip and mask %s %d", ip, ipv4Mask) + log.Infof("updating configuration ip: %s, mask: %d, dns: %t", ip, ipv4Mask, addDns) + + if ipv4Mask < constants.Ipv4MaxMask || ipv4Mask > constants.Ipv4MinMask { + return errors.New(fmt.Sprintf("ipv4Mask should be between %d and %d", constants.Ipv4MaxMask, constants.Ipv4MinMask)) + } if addDns != "" { addDnsBool, err := strconv.ParseBool(addDns) From af86b732296f1b8832104fa7c6f59865af0ae5d1 Mon Sep 17 00:00:00 2001 From: ziti-ci Date: Thu, 15 Apr 2021 16:13:32 +0000 Subject: [PATCH 12/12] [ci skip] committing updated version related files --- DesktopEdge/Properties/AssemblyInfo.cs | 6 +++--- Installer/ZitiDesktopEdge.aip | 4 ++-- ZitiUpdateService/Properties/AssemblyInfo.cs | 6 +++--- service/ziti-tunnel/version.go | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/DesktopEdge/Properties/AssemblyInfo.cs b/DesktopEdge/Properties/AssemblyInfo.cs index ec3cefc3..127f5b62 100644 --- a/DesktopEdge/Properties/AssemblyInfo.cs +++ b/DesktopEdge/Properties/AssemblyInfo.cs @@ -50,6 +50,6 @@ using System.Windows; // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: -// [assembly: AssemblyVersion("1.9.3.0")] -[assembly: AssemblyVersion("1.9.3.0")] -[assembly: AssemblyFileVersion("1.9.3.0")] +// [assembly: AssemblyVersion("1.9.4.0")] +[assembly: AssemblyVersion("1.9.4.0")] +[assembly: AssemblyFileVersion("1.9.4.0")] diff --git a/Installer/ZitiDesktopEdge.aip b/Installer/ZitiDesktopEdge.aip index fff0961b..9da73f34 100644 --- a/Installer/ZitiDesktopEdge.aip +++ b/Installer/ZitiDesktopEdge.aip @@ -23,10 +23,10 @@ - + - + diff --git a/ZitiUpdateService/Properties/AssemblyInfo.cs b/ZitiUpdateService/Properties/AssemblyInfo.cs index 6c15d9ab..7b16007f 100644 --- a/ZitiUpdateService/Properties/AssemblyInfo.cs +++ b/ZitiUpdateService/Properties/AssemblyInfo.cs @@ -30,6 +30,6 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: -// [assembly: AssemblyVersion("1.9.3.0")] -[assembly: AssemblyVersion("1.9.3.0")] -[assembly: AssemblyFileVersion("1.9.3.0")] +// [assembly: AssemblyVersion("1.9.4.0")] +[assembly: AssemblyVersion("1.9.4.0")] +[assembly: AssemblyFileVersion("1.9.4.0")] diff --git a/service/ziti-tunnel/version.go b/service/ziti-tunnel/version.go index 6f114ee5..f7619a3b 100644 --- a/service/ziti-tunnel/version.go +++ b/service/ziti-tunnel/version.go @@ -20,9 +20,9 @@ package main const ( - Version = "1.9.3" - Revision = "a02a50cf6437" - Branch = "main" + Version = "1.9.4" + Revision = "138ceebaefbf" + Branch = "release-next" BuildUser = "" - BuildDate = "2021-04-12 17:35:14" + BuildDate = "2021-04-15 16:07:55" )