forked from ivpn/desktop-app-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
210 lines (182 loc) · 5.37 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//
// IVPN command line interface (CLI)
// https://github.com/ivpn/desktop-app-cli
//
// Created by Stelnykovych Alexandr.
// Copyright (c) 2020 Privatus Limited.
//
// This file is part of the IVPN command line interface.
//
// The IVPN command line interface is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// The IVPN command line interface is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License
// along with the IVPN command line interface. If not, see <https://www.gnu.org/licenses/>.
//
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"text/tabwriter"
"github.com/ivpn/desktop-app-cli/commands"
"github.com/ivpn/desktop-app-cli/flags"
"github.com/ivpn/desktop-app-cli/protocol"
"github.com/ivpn/desktop-app-daemon/service/platform"
"github.com/ivpn/desktop-app-daemon/version"
)
// ICommand interface for command line command
type ICommand interface {
Init()
Parse(arguments []string) error
Run() error
Name() string
Description() string
Usage(short bool)
UsageFormetted(w *tabwriter.Writer, short bool)
}
var (
_commands []ICommand
)
func addCommand(cmd ICommand) {
cmd.Init()
_commands = append(_commands, cmd)
}
func printHeader() {
fmt.Println("Command-line interface for IVPN client (www.ivpn.net)")
fmt.Println("version:" + version.GetFullVersion() + "\n")
}
func printUsageAll(short bool) {
printHeader()
fmt.Printf("Usage: %s COMMAND [OPTIONS...] [COMMAND_PARAMETER] [-h|-help]\n\n", filepath.Base(os.Args[0]))
fmt.Println("COMMANDS:")
writer := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
for _, c := range _commands {
c.UsageFormetted(writer, short)
if short == false {
fmt.Fprintln(writer, "\t")
}
}
writer.Flush()
if short {
commands.PrintTips([]commands.TipType{commands.TipHelpCommand, commands.TipHelpFull})
}
}
func main() {
// initialize all possible commands
stateCmd := commands.CmdState{}
addCommand(&stateCmd)
addCommand(&commands.CmdConnect{})
addCommand(&commands.CmdDisconnect{})
addCommand(&commands.CmdServers{})
addCommand(&commands.CmdFirewall{})
addCommand(&commands.CmdWireGuard{})
addCommand(&commands.CmdDns{})
addCommand(&commands.CmdAntitracker{})
addCommand(&commands.CmdLogs{})
addCommand(&commands.CmdLogin{})
addCommand(&commands.CmdLogout{})
addCommand(&commands.CmdAccount{})
if len(os.Args) >= 2 {
if os.Args[1] == "?" || os.Args[1] == "-?" || os.Args[1] == "-h" || os.Args[1] == "--h" || os.Args[1] == "-help" || os.Args[1] == "--help" {
if len(os.Args) >= 3 && strings.ToLower(os.Args[2]) == "-full" {
printUsageAll(false) // detailed commans descriptions
} else {
printUsageAll(true) // short commands descriptions
}
os.Exit(0)
}
}
// initialize command handler
port, secret, err := readDaemonPort()
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: Unable to connect to service: %s\n", err)
printServStartInstructions()
os.Exit(1)
}
proto := protocol.CreateClient(port, secret)
if err := proto.Connect(); err != nil {
fmt.Fprintf(os.Stderr, "ERROR: Failed to connect to service : %s\n", err)
printServStartInstructions()
os.Exit(1)
}
commands.Initialize(proto)
if len(os.Args) < 2 {
if err := stateCmd.Run(); err != nil {
fmt.Fprintf(os.Stderr, "\n%v\n", err)
os.Exit(1)
}
return
}
// process command
isProcessed := false
for _, c := range _commands {
if c.Name() == os.Args[1] {
isProcessed = true
runCommand(c, os.Args[2:])
break
}
}
// unknown command
if isProcessed == false {
fmt.Fprintf(os.Stderr, "Error. Unexpected command %s\n", os.Args[1])
printUsageAll(true)
os.Exit(1)
}
}
func runCommand(c ICommand, args []string) {
if err := c.Parse(args); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
if _, ok := err.(flags.BadParameter); ok == true {
c.Usage(false)
}
os.Exit(1)
}
if err := c.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
if _, ok := err.(flags.BadParameter); ok == true {
c.Usage(false)
}
os.Exit(1)
}
}
// read port+secret to be able to connect to a daemon
func readDaemonPort() (port int, secret uint64, err error) {
file := platform.ServicePortFile()
if len(file) == 0 {
return 0, 0, fmt.Errorf("connection-info file not defined")
}
if _, err := os.Stat(file); err != nil {
if os.IsNotExist(err) {
return 0, 0, fmt.Errorf("please, ensure IVPN daemon is running (connection-info not exists)")
}
return 0, 0, fmt.Errorf("connection-info check error: %s", err)
}
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
vars := strings.Split(string(data), ":")
if len(vars) != 2 {
return 0, 0, fmt.Errorf("failed to parse connection-info")
}
port, err = strconv.Atoi(strings.TrimSpace(vars[0]))
if err != nil {
return 0, 0, fmt.Errorf("failed to parse connection-info: %w", err)
}
secret, err = strconv.ParseUint(strings.TrimSpace(vars[1]), 16, 64)
if err != nil {
return 0, 0, fmt.Errorf("failed to parse connection-info: %w", err)
}
return port, secret, nil
}