From c1d3b3d0a977723789573d505f73f2d5cd9343ea Mon Sep 17 00:00:00 2001 From: dovholuknf <46322585+dovholuknf@users.noreply.github.com> Date: Tue, 6 Apr 2021 16:31:20 -0400 Subject: [PATCH] one big commit - nothing but go fmt ./... --- service/cziti/ctun.go | 2 +- service/cziti/mfa.go | 16 +- service/cziti/sdk.go | 2 +- service/ziti-tunnel/cli/constants.go | 110 ++-- service/ziti-tunnel/cli/ipcClient.go | 516 +++++++++--------- service/ziti-tunnel/cli/responseGenerator.go | 458 ++++++++-------- service/ziti-tunnel/cli/service.go | 110 ++-- service/ziti-tunnel/constants/consts.go | 8 +- service/ziti-tunnel/dto/clidtos.go | 94 ++-- service/ziti-tunnel/dto/events.go | 12 +- service/ziti-tunnel/service/debug.go | 10 +- service/ziti-tunnel/service/install.go | 8 +- .../service/orphaned-identities.go | 202 +++---- service/ziti-tunnel/service/permissions.go | 2 +- service/ziti-tunnel/service/pkg-vars.go | 4 +- service/ziti-tunnel/service/service.go | 2 +- service/ziti-tunnel/service/state.go | 6 +- service/ziti-tunnel/service/topic.go | 12 +- service/ziti-tunnel/service/types.go | 2 +- service/ziti-tunnel/util/detect-ip-changes.go | 10 +- service/ziti-tunnel/util/iputil/iputil.go | 2 +- service/ziti-tunnel/util/logging/loghelper.go | 15 +- 22 files changed, 801 insertions(+), 802 deletions(-) diff --git a/service/cziti/ctun.go b/service/cziti/ctun.go index 4a700e906..09c082cd0 100644 --- a/service/cziti/ctun.go +++ b/service/cziti/ctun.go @@ -321,4 +321,4 @@ Set-NetIPInterface -InterfaceIndex $i.ifIndex -InterfaceMetric %d`, interfaceNam if err != nil { log.Errorf("ERROR setting interface metric: %v", err) } -} \ No newline at end of file +} diff --git a/service/cziti/mfa.go b/service/cziti/mfa.go index bf8ddcc0a..ee8ab0363 100644 --- a/service/cziti/mfa.go +++ b/service/cziti/mfa.go @@ -113,9 +113,9 @@ func ziti_mfa_cb_verify_go(_ C.ziti_context, status C.int, cFingerprint *C.char) fp := C.GoString(cFingerprint) log.Debugf("ziti_mfa_cb_verify_go called for %s. status: %d for ", fp, int(status)) var m = dto.MfaEvent{ - ActionEvent: dto.MFAEnrollmentVerificationEvent, - Fingerprint: fp, - Successful: false, + ActionEvent: dto.MFAEnrollmentVerificationEvent, + Fingerprint: fp, + Successful: false, RecoveryCodes: nil, } @@ -135,6 +135,7 @@ func ziti_mfa_cb_verify_go(_ C.ziti_context, status C.int, cFingerprint *C.char) } var rtnCodes = make(chan mfaCodes) + func ReturnMfaCodes(id *ZIdentity, code string) ([]string, error) { ccode := C.CString(code) defer C.free(unsafe.Pointer(ccode)) @@ -179,6 +180,7 @@ func ziti_mfa_recovery_codes_cb_return(_ C.ziti_context, status C.int, recoveryC } var genCodes = make(chan mfaCodes) + func GenerateMfaCodes(id *ZIdentity, code string) ([]string, error) { ccode := C.CString(code) defer C.free(unsafe.Pointer(ccode)) @@ -292,9 +294,9 @@ func ziti_mfa_cb_remove_go(_ C.ziti_context, status C.int, cFingerprint *C.char) log.Debugf("ziti_mfa_cb_remove_go called for %s. status: %d for ", fp, int(status)) var m = dto.MfaEvent{ - ActionEvent: dto.MFAEnrollmentRemovedEvent, - Fingerprint: fp, - Successful: false, + ActionEvent: dto.MFAEnrollmentRemovedEvent, + Fingerprint: fp, + Successful: false, RecoveryCodes: nil, } @@ -311,4 +313,4 @@ func ziti_mfa_cb_remove_go(_ C.ziti_context, status C.int, cFingerprint *C.char) log.Debugf("sending ziti_mfa_verify response back to UI for %s. verified: %t. error: %s", fp, m.Successful, m.Error) goapi.BroadcastEvent(m) -} \ No newline at end of file +} diff --git a/service/cziti/sdk.go b/service/cziti/sdk.go index 975fac586..503820a84 100644 --- a/service/cziti/sdk.go +++ b/service/cziti/sdk.go @@ -453,7 +453,7 @@ func eventCB(ztx C.ziti_context, event *C.ziti_event_t) { var m = dto.IdentityEvent{ ActionEvent: dto.IdentityUpdateComplete, - Id: dto.Identity{ + Id: dto.Identity{ FingerPrint: zid.Fingerprint, }, } diff --git a/service/ziti-tunnel/cli/constants.go b/service/ziti-tunnel/cli/constants.go index 3c9f4be51..8191fe454 100644 --- a/service/ziti-tunnel/cli/constants.go +++ b/service/ziti-tunnel/cli/constants.go @@ -1,55 +1,55 @@ -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 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 "%40s" "Addresses"}} | {{"OwnsIntercept"}} -{{range .}}{{printf "%40s" .Name}} | {{printf "%15s" .Id}} | {{printf "%9s" .Protocols}} | {{printf "%14s" .Ports}} | {{printf "%40s" .Addresses}} | {{.OwnsIntercept}} -{{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 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 "%40s" "Addresses"}} | {{"OwnsIntercept"}} +{{range .}}{{printf "%40s" .Name}} | {{printf "%15s" .Id}} | {{printf "%9s" .Protocols}} | {{printf "%14s" .Ports}} | {{printf "%40s" .Addresses}} | {{.OwnsIntercept}} +{{end}}` + +var log = logging.Logger() diff --git a/service/ziti-tunnel/cli/ipcClient.go b/service/ziti-tunnel/cli/ipcClient.go index 3a395e66b..ef6210834 100644 --- a/service/ziti-tunnel/cli/ipcClient.go +++ b/service/ziti-tunnel/cli/ipcClient.go @@ -1,258 +1,258 @@ -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 ( - "bufio" - "encoding/json" - "io" - "net" - "strings" - "time" - - "github.com/Microsoft/go-winio" - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/service" -) - -type fetchStatusFromRTS func([]string, *dto.TunnelStatus, map[string]bool) dto.Response -type fetchResponseFromRTS func([]string, dto.Response, map[string]bool) dto.Response - -func sendMessagetoPipe(ipcPipeConn net.Conn, commandMsg *dto.CommandMsg, args []string) error { - writer := bufio.NewWriter(ipcPipeConn) - enc := json.NewEncoder(writer) - - err := enc.Encode(commandMsg) - if err != nil { - log.Error("could not encode or writer list identities message, %v", err) - return err - } - - log.Debug("Message sent to ipc pipe") - - writer.Flush() - - return nil -} - -func readMessageFromPipe(ipcPipeConn net.Conn, readDone chan bool, fn fetchStatusFromRTS, responseFn fetchResponseFromRTS, args []string, flags map[string]bool) { - - reader := bufio.NewReader(ipcPipeConn) - msg, err := reader.ReadString('\n') - - if err != nil { - log.Error(err) - readDone <- false - return - } - - if len(args) == 0 { - args = append(args, "all") - } - - dec := json.NewDecoder(strings.NewReader(msg)) - - if fn != nil { - var tunnelStatus dto.ZitiTunnelStatus - if err := dec.Decode(&tunnelStatus); err == io.EOF { - readDone <- false - return - } else if err != nil { - log.Fatal(err) - readDone <- false - return - } - - if tunnelStatus.Status != nil { - responseMsg := fn(args, tunnelStatus.Status, flags) - if responseMsg.Code == service.SUCCESS { - log.Info("\n" + responseMsg.Payload.(string) + "\n" + responseMsg.Message) - readDone <- true - return - } else { - if responseMsg.Error != "" { - log.Info(responseMsg.Error) - } else { - log.Info(responseMsg.Message) - } - } - } else { - log.Errorf("Ziti tunnel retuned nil status") - } - } - - if responseFn != nil { - var response dto.Response - if err := dec.Decode(&response); err == io.EOF { - readDone <- false - return - } else if err != nil { - log.Fatal(err) - readDone <- false - return - } - - if response.Message != "" { - responseMsg := responseFn(args, response, flags) - if responseMsg.Code == service.SUCCESS { - if responseMsg.Payload != nil { - log.Infof("Payload : %v", responseMsg.Payload) - } - log.Infof("Message : %s", responseMsg.Message) - readDone <- true - return - } else { - if responseMsg.Error != "" { - log.Info(responseMsg.Error) - } else { - log.Info(responseMsg.Message) - } - } - } else { - log.Errorf("Ziti tunnel retuned nil response") - } - } - - readDone <- false - return -} - -func GetDataFromIpcPipe(commandMsg *dto.CommandMsg, fn fetchStatusFromRTS, responseFn fetchResponseFromRTS, args []string, flags map[string]bool) bool { - log.Infof("Command %s with args %s", commandMsg.Function, args) - - log.Debug("Connecting to pipe") - timeout := 2000 * time.Millisecond - ipcPipeConn, err := winio.DialPipe(service.IpcPipeName(), &timeout) - defer closeConn(ipcPipeConn) - - if err != nil { - log.Errorf("Connection to ipc pipe is not established, %v", err) - log.Errorf("Ziti Desktop Edge app may not be running") - return false - } - readDone := make(chan bool) - defer close(readDone) // ensure that goroutine exits - - go readMessageFromPipe(ipcPipeConn, readDone, fn, responseFn, args, flags) - - err = sendMessagetoPipe(ipcPipeConn, commandMsg, args) - if err != nil { - log.Errorf("Message is not sent to ipc pipe, %v", err) - return false - } - - log.Debugf("Connection to ipc pipe is established - %s and remote address %s", ipcPipeConn.LocalAddr().String(), ipcPipeConn.RemoteAddr().String()) - - status := <-readDone - log.Debug("read finished normally") - return status -} - -// monitor ipc messages - -func GetDataFromMonitorIpcPipe(actionMessage *dto.ActionEvent, args []string, flags map[string]bool) bool { - log.Infof("Command %s with args %s", actionMessage.StatusEvent.Op, args) - - log.Debug("Connecting to pipe") - timeout := 2000 * time.Millisecond - ipcPipeConn, err := winio.DialPipe(monitorIpcPipe, &timeout) - defer closeConn(ipcPipeConn) - - if err != nil { - log.Errorf("Connection to monitor ipc pipe is not established, %v", err) - log.Errorf("Ziti Update service may not be running") - return false - } - readDone := make(chan bool) - defer close(readDone) // ensure that goroutine exits - - go readMessageFromMonitorPipe(ipcPipeConn, readDone, args, flags) - - err = sendMessageToMonitorPipe(ipcPipeConn, actionMessage, args) - if err != nil { - log.Errorf("Message is not sent to monitor ipc pipe, %v", err) - return false - } - - log.Debugf("Connection to monitor ipc pipe is established - %s and remote address %s", ipcPipeConn.LocalAddr().String(), ipcPipeConn.RemoteAddr().String()) - - status := <-readDone - log.Debug("read finished normally") - return status -} - -func sendMessageToMonitorPipe(ipcPipeConn net.Conn, actionMessage *dto.ActionEvent, args []string) error { - writer := bufio.NewWriter(ipcPipeConn) - enc := json.NewEncoder(writer) - - err := enc.Encode(actionMessage) - if err != nil { - log.Error("could not encode or write response message, %v", err) - return err - } - - log.Debug("Message sent to monitor ipc pipe") - - writer.Flush() - - return nil -} - -func readMessageFromMonitorPipe(ipcPipeConn net.Conn, readDone chan bool, args []string, flags map[string]bool) { - - reader := bufio.NewReader(ipcPipeConn) - msg, err := reader.ReadString('\n') - - if err != nil { - log.Error(err) - readDone <- false - return - } - - dec := json.NewDecoder(strings.NewReader(msg)) - - var monitorServiceResponse dto.MonitorServiceResponse - if err := dec.Decode(&monitorServiceResponse); err == io.EOF { - readDone <- false - return - } else if err != nil { - log.Fatal(err) - readDone <- false - return - } - - if monitorServiceResponse.Code == service.SUCCESS { - log.Infof("Feedback file %s is created", monitorServiceResponse.Message) - readDone <- true - return - } else { - log.Info(monitorServiceResponse.Error) - } - - readDone <- false - return -} - -func closeConn(conn net.Conn) { - if conn != nil { - err := conn.Close() - if err != nil { - log.Warnf("abnormal error while closing connection. %v", err) - } - } -} +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 ( + "bufio" + "encoding/json" + "io" + "net" + "strings" + "time" + + "github.com/Microsoft/go-winio" + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/service" +) + +type fetchStatusFromRTS func([]string, *dto.TunnelStatus, map[string]bool) dto.Response +type fetchResponseFromRTS func([]string, dto.Response, map[string]bool) dto.Response + +func sendMessagetoPipe(ipcPipeConn net.Conn, commandMsg *dto.CommandMsg, args []string) error { + writer := bufio.NewWriter(ipcPipeConn) + enc := json.NewEncoder(writer) + + err := enc.Encode(commandMsg) + if err != nil { + log.Error("could not encode or writer list identities message, %v", err) + return err + } + + log.Debug("Message sent to ipc pipe") + + writer.Flush() + + return nil +} + +func readMessageFromPipe(ipcPipeConn net.Conn, readDone chan bool, fn fetchStatusFromRTS, responseFn fetchResponseFromRTS, args []string, flags map[string]bool) { + + reader := bufio.NewReader(ipcPipeConn) + msg, err := reader.ReadString('\n') + + if err != nil { + log.Error(err) + readDone <- false + return + } + + if len(args) == 0 { + args = append(args, "all") + } + + dec := json.NewDecoder(strings.NewReader(msg)) + + if fn != nil { + var tunnelStatus dto.ZitiTunnelStatus + if err := dec.Decode(&tunnelStatus); err == io.EOF { + readDone <- false + return + } else if err != nil { + log.Fatal(err) + readDone <- false + return + } + + if tunnelStatus.Status != nil { + responseMsg := fn(args, tunnelStatus.Status, flags) + if responseMsg.Code == service.SUCCESS { + log.Info("\n" + responseMsg.Payload.(string) + "\n" + responseMsg.Message) + readDone <- true + return + } else { + if responseMsg.Error != "" { + log.Info(responseMsg.Error) + } else { + log.Info(responseMsg.Message) + } + } + } else { + log.Errorf("Ziti tunnel retuned nil status") + } + } + + if responseFn != nil { + var response dto.Response + if err := dec.Decode(&response); err == io.EOF { + readDone <- false + return + } else if err != nil { + log.Fatal(err) + readDone <- false + return + } + + if response.Message != "" { + responseMsg := responseFn(args, response, flags) + if responseMsg.Code == service.SUCCESS { + if responseMsg.Payload != nil { + log.Infof("Payload : %v", responseMsg.Payload) + } + log.Infof("Message : %s", responseMsg.Message) + readDone <- true + return + } else { + if responseMsg.Error != "" { + log.Info(responseMsg.Error) + } else { + log.Info(responseMsg.Message) + } + } + } else { + log.Errorf("Ziti tunnel retuned nil response") + } + } + + readDone <- false + return +} + +func GetDataFromIpcPipe(commandMsg *dto.CommandMsg, fn fetchStatusFromRTS, responseFn fetchResponseFromRTS, args []string, flags map[string]bool) bool { + log.Infof("Command %s with args %s", commandMsg.Function, args) + + log.Debug("Connecting to pipe") + timeout := 2000 * time.Millisecond + ipcPipeConn, err := winio.DialPipe(service.IpcPipeName(), &timeout) + defer closeConn(ipcPipeConn) + + if err != nil { + log.Errorf("Connection to ipc pipe is not established, %v", err) + log.Errorf("Ziti Desktop Edge app may not be running") + return false + } + readDone := make(chan bool) + defer close(readDone) // ensure that goroutine exits + + go readMessageFromPipe(ipcPipeConn, readDone, fn, responseFn, args, flags) + + err = sendMessagetoPipe(ipcPipeConn, commandMsg, args) + if err != nil { + log.Errorf("Message is not sent to ipc pipe, %v", err) + return false + } + + log.Debugf("Connection to ipc pipe is established - %s and remote address %s", ipcPipeConn.LocalAddr().String(), ipcPipeConn.RemoteAddr().String()) + + status := <-readDone + log.Debug("read finished normally") + return status +} + +// monitor ipc messages + +func GetDataFromMonitorIpcPipe(actionMessage *dto.ActionEvent, args []string, flags map[string]bool) bool { + log.Infof("Command %s with args %s", actionMessage.StatusEvent.Op, args) + + log.Debug("Connecting to pipe") + timeout := 2000 * time.Millisecond + ipcPipeConn, err := winio.DialPipe(monitorIpcPipe, &timeout) + defer closeConn(ipcPipeConn) + + if err != nil { + log.Errorf("Connection to monitor ipc pipe is not established, %v", err) + log.Errorf("Ziti Update service may not be running") + return false + } + readDone := make(chan bool) + defer close(readDone) // ensure that goroutine exits + + go readMessageFromMonitorPipe(ipcPipeConn, readDone, args, flags) + + err = sendMessageToMonitorPipe(ipcPipeConn, actionMessage, args) + if err != nil { + log.Errorf("Message is not sent to monitor ipc pipe, %v", err) + return false + } + + log.Debugf("Connection to monitor ipc pipe is established - %s and remote address %s", ipcPipeConn.LocalAddr().String(), ipcPipeConn.RemoteAddr().String()) + + status := <-readDone + log.Debug("read finished normally") + return status +} + +func sendMessageToMonitorPipe(ipcPipeConn net.Conn, actionMessage *dto.ActionEvent, args []string) error { + writer := bufio.NewWriter(ipcPipeConn) + enc := json.NewEncoder(writer) + + err := enc.Encode(actionMessage) + if err != nil { + log.Error("could not encode or write response message, %v", err) + return err + } + + log.Debug("Message sent to monitor ipc pipe") + + writer.Flush() + + return nil +} + +func readMessageFromMonitorPipe(ipcPipeConn net.Conn, readDone chan bool, args []string, flags map[string]bool) { + + reader := bufio.NewReader(ipcPipeConn) + msg, err := reader.ReadString('\n') + + if err != nil { + log.Error(err) + readDone <- false + return + } + + dec := json.NewDecoder(strings.NewReader(msg)) + + var monitorServiceResponse dto.MonitorServiceResponse + if err := dec.Decode(&monitorServiceResponse); err == io.EOF { + readDone <- false + return + } else if err != nil { + log.Fatal(err) + readDone <- false + return + } + + if monitorServiceResponse.Code == service.SUCCESS { + log.Infof("Feedback file %s is created", monitorServiceResponse.Message) + readDone <- true + return + } else { + log.Info(monitorServiceResponse.Error) + } + + readDone <- false + return +} + +func closeConn(conn net.Conn) { + if conn != nil { + err := conn.Close() + if err != nil { + log.Warnf("abnormal error while closing connection. %v", err) + } + } +} diff --git a/service/ziti-tunnel/cli/responseGenerator.go b/service/ziti-tunnel/cli/responseGenerator.go index 83ca8355c..fd06eedad 100644 --- a/service/ziti-tunnel/cli/responseGenerator.go +++ b/service/ziti-tunnel/cli/responseGenerator.go @@ -1,229 +1,229 @@ -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, - OwnsIntercept: svc.OwnsIntercept, - } -} - -// 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 -} +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, + OwnsIntercept: svc.OwnsIntercept, + } +} + +// 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 +} diff --git a/service/ziti-tunnel/cli/service.go b/service/ziti-tunnel/cli/service.go index ebc1b290b..ae695c888 100644 --- a/service/ziti-tunnel/cli/service.go +++ b/service/ziti-tunnel/cli/service.go @@ -1,55 +1,55 @@ -package cli - -import ( - "strings" - - "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) -} +package cli + +import ( + "strings" + + "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) +} diff --git a/service/ziti-tunnel/constants/consts.go b/service/ziti-tunnel/constants/consts.go index 029611028..cc1c95eae 100644 --- a/service/ziti-tunnel/constants/consts.go +++ b/service/ziti-tunnel/constants/consts.go @@ -17,9 +17,9 @@ package constants -const( +const ( Ipv4ip = "100.64.0.1" - Ipv4MaxMask = 8 - Ipv4MinMask = 16 + Ipv4MaxMask = 8 + Ipv4MinMask = 16 Ipv4DefaultMask = 10 -) \ No newline at end of file +) diff --git a/service/ziti-tunnel/dto/clidtos.go b/service/ziti-tunnel/dto/clidtos.go index 030cdce87..8f3166f5f 100644 --- a/service/ziti-tunnel/dto/clidtos.go +++ b/service/ziti-tunnel/dto/clidtos.go @@ -1,47 +1,47 @@ -package dto - -/* - * 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. - * - */ - -type IdentityCli struct { - Name string - FingerPrint string - Active bool - Config string - ControllerVersion string - Status string -} - -type ServiceCli struct { - Name string - Id string - Protocols string - Ports string - Addresses string - OwnsIntercept bool -} - -type IdentityOnOffPayload struct { - OnOff string - Fingerprint string -} - -type MonitorServiceResponse struct { - Code int - Message string - Error string -} +package dto + +/* + * 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. + * + */ + +type IdentityCli struct { + Name string + FingerPrint string + Active bool + Config string + ControllerVersion string + Status string +} + +type ServiceCli struct { + Name string + Id string + Protocols string + Ports string + Addresses string + OwnsIntercept bool +} + +type IdentityOnOffPayload struct { + OnOff string + Fingerprint string +} + +type MonitorServiceResponse struct { + Code int + Message string + Error string +} diff --git a/service/ziti-tunnel/dto/events.go b/service/ziti-tunnel/dto/events.go index 1971a1b0a..c216ced3b 100644 --- a/service/ziti-tunnel/dto/events.go +++ b/service/ziti-tunnel/dto/events.go @@ -21,8 +21,8 @@ const ( REMOVED = "removed" ERROR = "error" UPDATED = "updated" - CHANGED = "changed" - NORMAL = "Normal" + CHANGED = "changed" + NORMAL = "Normal" SERVICE_OP = "service" IDENTITY_OP = "identity" @@ -30,11 +30,11 @@ const ( FEEDBACK_OP = "CaptureLogs" MFA_OP = "mfa" - MFAEnrollmentChallengAtion = "enrollment_challenge" - MFAEnrollmentVerificationAction = "enrollment_verification" - MFAEnrollmentRemovedAction = "enrollment_remove" + MFAEnrollmentChallengAtion = "enrollment_challenge" + MFAEnrollmentVerificationAction = "enrollment_verification" + MFAEnrollmentRemovedAction = "enrollment_remove" - MFA_AUTH_CHALLENGE_ACTION = "auth_challenge" + MFA_AUTH_CHALLENGE_ACTION = "auth_challenge" ) var SERVICE_ADDED = ActionEvent{ diff --git a/service/ziti-tunnel/service/debug.go b/service/ziti-tunnel/service/debug.go index 6da5bdd4e..47f87435c 100644 --- a/service/ziti-tunnel/service/debug.go +++ b/service/ziti-tunnel/service/debug.go @@ -18,8 +18,8 @@ package service import ( - idcfg "github.com/openziti/sdk-golang/ziti/config" "github.com/openziti/desktop-edge-win/service/ziti-tunnel/dto" + idcfg "github.com/openziti/sdk-golang/ziti/config" ) func dbg() { @@ -28,15 +28,15 @@ func dbg() { events.broadcast <- dto.TunnelStatusEvent{ StatusEvent: dto.StatusEvent{Op: "status"}, Status: r, - ApiVersion: API_VERSION, + ApiVersion: API_VERSION, } svcs := make([]*dto.Service, 2) svcs[0] = &dto.Service{ - Name: "FakeService1", + Name: "FakeService1", } svcs[1] = &dto.Service{ - Name: "Second Fake Service", + Name: "Second Fake Service", } events.broadcast <- dto.IdentityEvent{ @@ -57,7 +57,7 @@ func dbg() { events.broadcast <- dto.ServiceEvent{ ActionEvent: dto.SERVICE_ADDED, Service: &dto.Service{ - Name: "New Service", + Name: "New Service", }, Fingerprint: "new_id_fingerprint", } diff --git a/service/ziti-tunnel/service/install.go b/service/ziti-tunnel/service/install.go index 65910e420..7ec0c3dbd 100644 --- a/service/ziti-tunnel/service/install.go +++ b/service/ziti-tunnel/service/install.go @@ -52,9 +52,9 @@ func InstallService() error { log.Infof("service installed using path: %s", fullPath) s, err = m.CreateService(SvcStartName, fullPath, mgr.Config{ - StartType: mgr.StartAutomatic, - DisplayName: SvcName, - Description: SvcNameLong, + StartType: mgr.StartAutomatic, + DisplayName: SvcName, + Description: SvcNameLong, }) if err != nil { return err @@ -89,4 +89,4 @@ func RemoveService() error { return fmt.Errorf("RemoveEventLogSource() failed: %s", err) } return nil -} \ No newline at end of file +} diff --git a/service/ziti-tunnel/service/orphaned-identities.go b/service/ziti-tunnel/service/orphaned-identities.go index af6f5c10e..470d1863f 100644 --- a/service/ziti-tunnel/service/orphaned-identities.go +++ b/service/ziti-tunnel/service/orphaned-identities.go @@ -1,101 +1,101 @@ -package service - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/openziti/desktop-edge-win/service/ziti-tunnel/config" -) - -// After System update, the identity files are not getting copied to the config path -// So we are adding a function to scan for identities in the backtup location -func scanForIdentitiesPostWindowsUpdate() error { - srcBackUpPaths := [2]string{"Windows.~BT\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\NetFoundry", - "Windows.old\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\NetFoundry"} - systemDrivePath := os.Getenv("SystemDrive") - if systemDrivePath == "" { - return nil - } - for _, srcPath := range srcBackUpPaths { - sourcePath := filepath.Join(systemDrivePath, string(os.PathSeparator), srcPath) - _, err := os.Stat(sourcePath) - if err != nil { - log.Debugf("Folder %s does not exist", sourcePath) - continue - } - err = searchAndCopyFilesFromBackup(sourcePath) - if err != nil { - log.Debugf("Copy files from %s failed, %v", sourcePath, err) - } - } - return nil -} - -func searchAndCopyFilesFromBackup(srcPath string) error { - err := filepath.Walk(srcPath, copyFilesFromBackUp) - if err != nil { - return err - } - return nil -} - -func copyFilesFromBackUp(path string, f os.FileInfo, err error) error { - if !f.IsDir() { - log.Infof("Found: %s", path) - destinationFile := filepath.Join(config.Path(), string(os.PathSeparator), f.Name()) - //check if the file is present in the destination folder - _, err := os.Stat(destinationFile) - if err == nil && !strings.Contains(f.Name(), ConfigFileName) { - log.Debugf("File %s is already present in the config path and it is not %s, So not transfering", f.Name(), ConfigFileName) - deleteFile(path) - return nil - } - _, err = copy(path, destinationFile) - if err != nil { - log.Errorf("Error occurred while copying the Windows backup folder %s --> %s %v", f.Name(), destinationFile, err) - return nil - } else { - log.Infof("Found backup file at %s. Restored this file to %s", path, destinationFile) - deleteFile(path) - } - } - return nil -} -func deleteFile(path string) { - log.Infof("Removing file %s", path) - err := os.Remove(path) - if err != nil { - log.Errorf("Error occured while removing the file %s, %v", path, err) - } else { - log.Infof("Removed file %s", path) - } -} - -func copy(src, dst string) (int64, error) { - sourceFileStat, err := os.Stat(src) - if err != nil { - return 0, err - } - - if !sourceFileStat.Mode().IsRegular() { - return 0, errors.New(fmt.Sprintf("%s is not a regular file", src)) - } - - source, err := os.Open(src) - if err != nil { - return 0, err - } - defer source.Close() - - destination, err := os.Create(dst) - if err != nil { - return 0, err - } - defer destination.Close() - nBytes, err := io.Copy(destination, source) - return nBytes, err -} +package service + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/openziti/desktop-edge-win/service/ziti-tunnel/config" +) + +// After System update, the identity files are not getting copied to the config path +// So we are adding a function to scan for identities in the backtup location +func scanForIdentitiesPostWindowsUpdate() error { + srcBackUpPaths := [2]string{"Windows.~BT\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\NetFoundry", + "Windows.old\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\NetFoundry"} + systemDrivePath := os.Getenv("SystemDrive") + if systemDrivePath == "" { + return nil + } + for _, srcPath := range srcBackUpPaths { + sourcePath := filepath.Join(systemDrivePath, string(os.PathSeparator), srcPath) + _, err := os.Stat(sourcePath) + if err != nil { + log.Debugf("Folder %s does not exist", sourcePath) + continue + } + err = searchAndCopyFilesFromBackup(sourcePath) + if err != nil { + log.Debugf("Copy files from %s failed, %v", sourcePath, err) + } + } + return nil +} + +func searchAndCopyFilesFromBackup(srcPath string) error { + err := filepath.Walk(srcPath, copyFilesFromBackUp) + if err != nil { + return err + } + return nil +} + +func copyFilesFromBackUp(path string, f os.FileInfo, err error) error { + if !f.IsDir() { + log.Infof("Found: %s", path) + destinationFile := filepath.Join(config.Path(), string(os.PathSeparator), f.Name()) + //check if the file is present in the destination folder + _, err := os.Stat(destinationFile) + if err == nil && !strings.Contains(f.Name(), ConfigFileName) { + log.Debugf("File %s is already present in the config path and it is not %s, So not transfering", f.Name(), ConfigFileName) + deleteFile(path) + return nil + } + _, err = copy(path, destinationFile) + if err != nil { + log.Errorf("Error occurred while copying the Windows backup folder %s --> %s %v", f.Name(), destinationFile, err) + return nil + } else { + log.Infof("Found backup file at %s. Restored this file to %s", path, destinationFile) + deleteFile(path) + } + } + return nil +} +func deleteFile(path string) { + log.Infof("Removing file %s", path) + err := os.Remove(path) + if err != nil { + log.Errorf("Error occured while removing the file %s, %v", path, err) + } else { + log.Infof("Removed file %s", path) + } +} + +func copy(src, dst string) (int64, error) { + sourceFileStat, err := os.Stat(src) + if err != nil { + return 0, err + } + + if !sourceFileStat.Mode().IsRegular() { + return 0, errors.New(fmt.Sprintf("%s is not a regular file", src)) + } + + source, err := os.Open(src) + if err != nil { + return 0, err + } + defer source.Close() + + destination, err := os.Create(dst) + if err != nil { + return 0, err + } + defer destination.Close() + nBytes, err := io.Copy(destination, source) + return nBytes, err +} diff --git a/service/ziti-tunnel/service/permissions.go b/service/ziti-tunnel/service/permissions.go index 8525a1d66..39fe88463 100644 --- a/service/ziti-tunnel/service/permissions.go +++ b/service/ziti-tunnel/service/permissions.go @@ -53,4 +53,4 @@ func EnsurePermissions(group string) string { } return sid -} \ No newline at end of file +} diff --git a/service/ziti-tunnel/service/pkg-vars.go b/service/ziti-tunnel/service/pkg-vars.go index 264a08c3d..e081df8b9 100644 --- a/service/ziti-tunnel/service/pkg-vars.go +++ b/service/ziti-tunnel/service/pkg-vars.go @@ -59,8 +59,8 @@ const ( IDENTITY_NOT_FOUND = 1000 MFA_FAILED_TO_GENERATE_CODES = 200 - MFA_FAILED_TO_RETURN_CODES = 201 - MFA_FINGERPRINT_NOT_FOUND = 202 + MFA_FAILED_TO_RETURN_CODES = 201 + MFA_FINGERPRINT_NOT_FOUND = 202 DEFAULT_REFRESH_INTERVAL = 10 diff --git a/service/ziti-tunnel/service/service.go b/service/ziti-tunnel/service/service.go index fbf72ca43..3ddd42d0f 100644 --- a/service/ziti-tunnel/service/service.go +++ b/service/ziti-tunnel/service/service.go @@ -87,7 +87,7 @@ loop: changes <- svc.Status{State: svc.StopPending} log.Infof("waiting for shutdown to complete") - <- control + <-control log.Infof("normal shutdown complete") return } diff --git a/service/ziti-tunnel/service/state.go b/service/ziti-tunnel/service/state.go index 0c5dfd6e5..26933a70b 100644 --- a/service/ziti-tunnel/service/state.go +++ b/service/ziti-tunnel/service/state.go @@ -152,9 +152,9 @@ func (t *RuntimeState) ToMetrics() dto.TunnelStatus { Name: id.Name, FingerPrint: id.FingerPrint, Metrics: id.Metrics, - Active: id.Active, - MfaEnabled: id.MfaEnabled, - MfaNeeded: id.MfaNeeded, + Active: id.Active, + MfaEnabled: id.MfaEnabled, + MfaNeeded: id.MfaNeeded, } i++ } diff --git a/service/ziti-tunnel/service/topic.go b/service/ziti-tunnel/service/topic.go index de09edab7..c6d95897d 100644 --- a/service/ziti-tunnel/service/topic.go +++ b/service/ziti-tunnel/service/topic.go @@ -19,8 +19,8 @@ package service type topic struct { broadcast chan interface{} - channels map[int]chan interface{} - done chan bool + channels map[int]chan interface{} + done chan bool } func newTopic(cap int16) topic { @@ -31,19 +31,19 @@ func newTopic(cap int16) topic { } } -func(t *topic) register(id int, c chan interface{}) { +func (t *topic) register(id int, c chan interface{}) { t.channels[id] = c } -func(t *topic) unregister(id int) { +func (t *topic) unregister(id int) { delete(t.channels, id) } -func(t *topic) shutdown() { +func (t *topic) shutdown() { t.done <- true } -func(t *topic) run() { +func (t *topic) run() { go func() { for { select { diff --git a/service/ziti-tunnel/service/types.go b/service/ziti-tunnel/service/types.go index 973652738..67ec14950 100644 --- a/service/ziti-tunnel/service/types.go +++ b/service/ziti-tunnel/service/types.go @@ -8,4 +8,4 @@ import ( type Id struct { dto.Identity CId *cziti.ZIdentity -} \ No newline at end of file +} diff --git a/service/ziti-tunnel/util/detect-ip-changes.go b/service/ziti-tunnel/util/detect-ip-changes.go index 9044090e0..077d21e50 100644 --- a/service/ziti-tunnel/util/detect-ip-changes.go +++ b/service/ziti-tunnel/util/detect-ip-changes.go @@ -29,10 +29,10 @@ var ( modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll") - procWSACreateEvent = modws2_32.NewProc("WSACreateEvent") - procNotifyAddrChange = modiphlpapi.NewProc("NotifyAddrChange") + procWSACreateEvent = modws2_32.NewProc("WSACreateEvent") + procNotifyAddrChange = modiphlpapi.NewProc("NotifyAddrChange") procNotifyRouteChange = modiphlpapi.NewProc("NotifyRouteChange") - log = logging.Logger() + log = logging.Logger() ) func OnIPChange(callback func()) { @@ -43,7 +43,7 @@ func OnIPChange(callback func()) { log.Debugf("Symbol [NotifyAddrChange] loaded at %#v", procNotifyAddrChange.Addr()) var ( - err error + err error overlap *windows.Overlapped = &windows.Overlapped{} ) @@ -84,4 +84,4 @@ func WSACreateEvent() (windows.Handle, error) { } else { return windows.Handle(handlePtr), nil } -} \ No newline at end of file +} diff --git a/service/ziti-tunnel/util/iputil/iputil.go b/service/ziti-tunnel/util/iputil/iputil.go index 838664de6..b9ad861c9 100644 --- a/service/ziti-tunnel/util/iputil/iputil.go +++ b/service/ziti-tunnel/util/iputil/iputil.go @@ -35,7 +35,7 @@ func Ipv4Inc(ip net.IP, maskBits int) net.IP { newIpAsInt := ipAsInt + 1 - return Uint32ToIpv4(baseIp + newIpAsInt & uint32(ipMask)) + return Uint32ToIpv4(baseIp + newIpAsInt&uint32(ipMask)) } func Ipv4ToUint32(ip net.IP) uint32 { if len(ip) == 16 { diff --git a/service/ziti-tunnel/util/logging/loghelper.go b/service/ziti-tunnel/util/logging/loghelper.go index d2981f258..8005ead84 100644 --- a/service/ziti-tunnel/util/logging/loghelper.go +++ b/service/ziti-tunnel/util/logging/loghelper.go @@ -48,16 +48,13 @@ func init() { setConsoleModeProc := kernel32DLL.NewProc("SetConsoleMode") setConsoleModeProc.Call(uintptr(handle), 0x0001|0x0002|0x0004) - - with := &dateFormatterNoFilename{ - } + with := &dateFormatterNoFilename{} /*with := &dateFormatterWithFilename{ }*/ with.dateFormatter.timeFormat = UTCFormat() withFilenameLogger.SetFormatter(with) - without := &dateFormatterNoFilename{ - } + without := &dateFormatterNoFilename{} without.dateFormatter.timeFormat = UTCFormat() noFilenamelogger.SetFormatter(without) } @@ -70,7 +67,7 @@ func NoFilenameLogger() *logrus.Logger { return noFilenamelogger } -func SetLoggingLevel(goLevel logrus.Level){ +func SetLoggingLevel(goLevel logrus.Level) { withFilenameLogger.SetLevel(goLevel) noFilenamelogger.SetLevel(goLevel) } @@ -84,8 +81,8 @@ func initLogger(logger *logrus.Logger, level logrus.Level) { logger.SetReportCaller(true) - rl, _ := rotatelogs.New(config.LogFile() + ".%Y%m%d%H%M.log", - rotatelogs.WithRotationTime(24 * time.Hour), + rl, _ := rotatelogs.New(config.LogFile()+".%Y%m%d%H%M.log", + rotatelogs.WithRotationTime(24*time.Hour), rotatelogs.WithRotationCount(7), rotatelogs.WithLinkName(config.LogFile())) @@ -205,4 +202,4 @@ var errorColor = ansi.Red + "ERROR" + ansi.DefaultFG var warnColor = ansi.Yellow + " WARN" + ansi.DefaultFG var infoColor = ansi.White + " INFO" + ansi.DefaultFG var debugColor = ansi.Blue + "DEBUG" + ansi.DefaultFG -var traceColor = ansi.LightBlack + "TRACE" + ansi.DefaultFG \ No newline at end of file +var traceColor = ansi.LightBlack + "TRACE" + ansi.DefaultFG