-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
220 lines (177 loc) · 5.66 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
211
212
213
214
215
216
217
218
219
220
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"time"
"math/rand"
chclient "github.com/jpillora/chisel/client"
"github.com/jpillora/chisel/share/cos"
"github.com/jpillora/chisel/share/settings"
)
var (
version = "dev" // Set by goreleaser
)
func main() {
client(os.Args[1:])
}
func generatePidFile() {
pid := []byte(strconv.Itoa(os.Getpid()))
if err := ioutil.WriteFile("outsystemscc.pid", pid, 0644); err != nil {
log.Fatal(err)
}
}
type headerFlags struct {
http.Header
}
func (flag *headerFlags) String() string {
out := ""
for k, v := range flag.Header {
out += fmt.Sprintf("%s: %s\n", k, v)
}
return out
}
func (flag *headerFlags) Set(arg string) error {
index := strings.Index(arg, ":")
if index < 0 {
return fmt.Errorf(`Invalid header (%s). Should be in the format "HeaderName: HeaderContent"`, arg)
}
if flag.Header == nil {
flag.Header = http.Header{}
}
key := arg[0:index]
value := arg[index+1:]
flag.Header.Set(key, strings.TrimSpace(value))
return nil
}
var clientHelp = `
Usage: outsystemscc [options] <server> <remote> [remote] [remote] ...
<server> is the URL to the server. Use the Address displayed on ODC Portal.
<remote>s are remote connections tunneled through the server, each of
which come in the form:
R:<local-port>:<remote-host>:<remote-port>
which does reverse port forwarding, sharing <remote-host>:<remote-port>
from the client to the server's <local-port>.
example remotes
R:8081:192.168.0.3:8393
R:8082:192.168.0.4:587
See https://github.com/OutSystems/cloud-connector for examples in context.
Options:
--keepalive, An optional keepalive interval. Since the underlying
transport is HTTP, in many instances we'll be traversing through
proxies, often these proxies will close idle connections. You must
specify a time with a unit, for example '5s' or '2m'. Defaults
to '25s' (set to 0s to disable).
--max-retry-count, Maximum number of times to retry before exiting.
Defaults to unlimited.
--max-retry-interval, Maximum wait time before retrying after a
disconnection. Defaults to 5 minutes.
--proxy, An optional HTTP CONNECT or SOCKS5 proxy which will be
used to reach the server. Authentication can be specified
inside the URL.
For example, http://admin:[email protected]:8081
or: socks://admin:[email protected]:1080
--header, Set a custom header in the form "HeaderName: HeaderContent".
Use the Token displayed on ODC Portal in using token as HeaderName.
--hostname, Optionally set the 'Host' header (defaults to the host
found in the server url).
--pid Generate pid file in current working directory
-v, Enable verbose logging
--help, This help text
Signals:
The outsystemscc process is listening for:
a SIGUSR2 to print process stats, and
a SIGHUP to short-circuit the client reconnect timer
Version:
` + version + ` (` + runtime.Version() + `)
`
func client(args []string) {
flags := flag.NewFlagSet("client", flag.ContinueOnError)
config := chclient.Config{Headers: http.Header{}}
flags.DurationVar(&config.KeepAlive, "keepalive", 25*time.Second, "")
flags.IntVar(&config.MaxRetryCount, "max-retry-count", -1, "")
flags.DurationVar(&config.MaxRetryInterval, "max-retry-interval", 0, "")
flags.StringVar(&config.Proxy, "proxy", "", "")
flags.Var(&headerFlags{config.Headers}, "header", "")
hostname := flags.String("hostname", "", "")
pid := flags.Bool("pid", false, "")
verbose := flags.Bool("v", false, "")
flags.Usage = func() {
fmt.Print(clientHelp)
os.Exit(0)
}
flags.Parse(args)
//pull out options, put back remaining args
args = flags.Args()
if len(args) < 2 {
log.Fatalf("A server and least one remote is required")
}
localPorts, err := validateRemotes(args[1:])
if err != nil {
log.Fatal(err)
}
queryParams := generateQueryParameters(localPorts)
config.Server = fmt.Sprintf("%s%s", args[0], queryParams)
config.Remotes = args[1:]
//default auth
if config.Auth == "" {
config.Auth = os.Getenv("AUTH")
}
//move hostname onto headers
if *hostname != "" {
config.Headers.Set("Host", *hostname)
}
//ready
c, err := chclient.NewClient(&config)
if err != nil {
log.Fatal(err)
}
c.Debug = *verbose
if *pid {
generatePidFile()
}
go cos.GoStats()
ctx := cos.InterruptContext()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
if err := c.Wait(); err != nil {
log.Fatal(err)
}
}
func generateQueryParameters(localPorts string) string {
return fmt.Sprintf("?id=%v&ports=%v", rand.Intn(999999999-100000000)+100000000, localPorts)
}
// validate the provided Remotes configuration is valid
func validateRemotes(remotes []string) (string, error) {
uniqueRemotes := []string{}
localPorts := []string{}
for _, newRemote := range remotes {
remote, err := settings.DecodeRemote(newRemote)
if err != nil {
return "", fmt.Errorf("failed to decode remote '%s': %s", newRemote, err)
}
// iterate all remotes already in the unique list, if duplicate is found return error
for _, unique := range uniqueRemotes {
validatedRemote, err := settings.DecodeRemote(unique)
if err != nil {
return "", fmt.Errorf("failed to decode remote '%s': %s", unique, err)
}
if isDuplicatedRemote(validatedRemote, remote) {
return "", fmt.Errorf("invalid Remote configuration: local port '%s' is duplicated", remote.LocalPort)
}
}
uniqueRemotes = append(uniqueRemotes, newRemote)
localPorts = append(localPorts, remote.LocalPort)
}
return strings.Join(localPorts, ","), nil
}
func isDuplicatedRemote(first, second *settings.Remote) bool {
return first.LocalPort == second.LocalPort
}