forked from davrodpin/mole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mole.go
519 lines (421 loc) · 12.5 KB
/
mole.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package mole
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/davrodpin/mole/alias"
"github.com/davrodpin/mole/fsutils"
"github.com/davrodpin/mole/rpc"
"github.com/davrodpin/mole/tunnel"
"github.com/awnumar/memguard"
"github.com/gofrs/uuid"
"github.com/mitchellh/mapstructure"
daemon "github.com/sevlyar/go-daemon"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
)
const (
// IdFlagName is the name of the flag that carries the unique idenfier for a
// mole instance.
IdFlagName = "id"
)
// cli keeps a reference to the latest Client object created.
// This is mostly needed to introspect client states during runtime (e.g. a
// remote procedure call that needs to check certain runtime information)
var cli *Client
type Configuration struct {
Id string `json:"id" mapstructure:"id" toml:"id"`
TunnelType string `json:"tunnel-type" mapstructure:"tunnel-type" toml:"tunnel-type"`
Verbose bool `json:"verbose" mapstructure:"verbose" toml:"verbose"`
Insecure bool `json:"insecure" mapstructure:"insecure" toml:"insecure"`
Detach bool `json:"detach" mapstructure:"detach" toml:"detach"`
Source AddressInputList `json:"source" mapstructure:"source" toml:"source"`
Destination AddressInputList `json:"destination" mapstructure:"destination" toml:"destination"`
Server AddressInput `json:"server" mapstructure:"server" toml:"server"`
Key string `json:"key" mapstructure:"key" toml:"key"`
KeepAliveInterval time.Duration `json:"keep-alive-interval" mapstructure:"keep-alive-interva" toml:"keep-alive-interval"`
ConnectionRetries int `json:"connection-retries" mapstructure:"connection-retries" toml:"connection-retries"`
WaitAndRetry time.Duration `json:"wait-and-retry" mapstructure:"wait-and-retry" toml:"wait-and-retry"`
SshAgent string `json:"ssh-agent" mapstructure:"ssh-agent" toml:"ssh-agent"`
Timeout time.Duration `json:"timeout" mapstructure:"timeout" toml:"timeout"`
SshConfig string `json:"ssh-config" mapstructure:"ssh-config" toml:"ssh-config"`
Rpc bool `json:"rpc" mapstructure:"rpc" toml:"rpc"`
RpcAddress string `json:"rpc-address" mapstructure:"rpc-address" toml:"rpc-address"`
}
// ParseAlias translates a Configuration object to an Alias object.
func (c Configuration) ParseAlias(name string) *alias.Alias {
return &alias.Alias{
Name: name,
TunnelType: c.TunnelType,
Verbose: c.Verbose,
Insecure: c.Insecure,
Detach: c.Detach,
Source: c.Source.List(),
Destination: c.Destination.List(),
Server: c.Server.String(),
Key: c.Key,
KeepAliveInterval: c.KeepAliveInterval.String(),
ConnectionRetries: c.ConnectionRetries,
WaitAndRetry: c.WaitAndRetry.String(),
SshAgent: c.SshAgent,
Timeout: c.Timeout.String(),
SshConfig: c.SshConfig,
Rpc: c.Rpc,
RpcAddress: c.RpcAddress,
}
}
// Client manages the overall state of the application based on its configuration.
type Client struct {
Conf *Configuration
Tunnel *tunnel.Tunnel
sigs chan os.Signal
}
// New initializes a new mole's client.
func New(conf *Configuration) *Client {
cli = &Client{
Conf: conf,
sigs: make(chan os.Signal, 1),
}
return cli
}
// Start kicks off mole's client, establishing the tunnel and its channels
// based on the client configuration attributes.
func (c *Client) Start() error {
// memguard is used to securely keep sensitive information in memory.
// This call makes sure all data will be destroy when the program exits.
defer memguard.Purge()
if c.Conf.Id == "" {
u, err := uuid.NewV4()
if err != nil {
return fmt.Errorf("could not auto generate app instance id: %v", err)
}
c.Conf.Id = u.String()[:8]
}
r, err := c.Running()
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error while checking for another instance using the same id")
return err
}
if r {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).Error("can't start. Another instance is already using the same id")
return fmt.Errorf("can't start. Another instance is already using the same id %s", c.Conf.Id)
}
log.Infof("instance identifier is %s", c.Conf.Id)
if c.Conf.Detach {
var err error
ic, err := NewDetachedInstance(c.Conf.Id)
if err != nil {
log.WithError(err).Errorf("error while creating directory to store mole instance related files")
return err
}
err = startDaemonProcess(ic)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error starting ssh tunnel")
return err
}
} else {
go c.handleSignals()
}
if c.Conf.Verbose {
log.SetLevel(log.DebugLevel)
}
d, err := fsutils.CreateInstanceDir(c.Conf.Id)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating directory for mole instance")
return err
}
if c.Conf.Rpc {
addr, err := rpc.Start(c.Conf.RpcAddress)
if err != nil {
return err
}
rd := filepath.Join(d.Dir, "rpc")
err = ioutil.WriteFile(rd, []byte(addr.String()), 0644)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating file with rpc address")
return err
}
c.Conf.RpcAddress = addr.String()
log.Infof("rpc server address saved on %s", rd)
}
t, err := createTunnel(c.Conf)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating tunnel")
return err
}
c.Tunnel = t
if err = c.Tunnel.Start(); err != nil {
log.WithFields(log.Fields{
"tunnel": c.Tunnel.String(),
}).WithError(err).Error("error while starting tunnel")
return err
}
return nil
}
// Stop shuts down a detached mole's application instance.
func (c *Client) Stop() error {
pfp, err := fsutils.GetPidFileLocation(c.Conf.Id)
if err != nil {
return fmt.Errorf("error getting information about aliases directory: %v", err)
}
if _, err := os.Stat(pfp); os.IsNotExist(err) {
return fmt.Errorf("no instance of mole with id %s is running", c.Conf.Id)
}
cntxt := &daemon.Context{
PidFileName: pfp,
}
d, err := cntxt.Search()
if err != nil {
return err
}
if c.Conf.Detach {
err = os.RemoveAll(pfp)
if err != nil {
return err
}
} else {
d, err := fsutils.InstanceDir(c.Conf.Id)
if err != nil {
return err
}
err = os.RemoveAll(d.Dir)
if err != nil {
return err
}
}
err = d.Kill()
if err != nil {
return err
}
return nil
}
func (c *Client) handleSignals() {
signal.Notify(c.sigs, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
sig := <-c.sigs
log.Debugf("process signal %s received", sig)
err := c.Stop()
if err != nil {
log.WithError(err).Error("instance not properly stopped")
}
}
// Merge overwrites Configuration from the given Alias.
//
// Certain attributes like Verbose, Insecure and Detach will be overwritten
// only if they are found on the givenFlags which should contain the name of
// all flags given by the user through UI (e.g. CLI).
func (c *Configuration) Merge(al *alias.Alias, givenFlags []string) error {
var fl flags = givenFlags
if !fl.lookup("verbose") {
c.Verbose = al.Verbose
}
if !fl.lookup("insecure") {
c.Insecure = al.Insecure
}
if !fl.lookup("detach") {
c.Detach = al.Detach
}
c.Id = al.Name
c.TunnelType = al.TunnelType
srcl := AddressInputList{}
for _, src := range al.Source {
err := srcl.Set(src)
if err != nil {
return err
}
}
c.Source = srcl
dstl := AddressInputList{}
for _, dst := range al.Destination {
err := dstl.Set(dst)
if err != nil {
return err
}
}
c.Destination = dstl
srv := AddressInput{}
err := srv.Set(al.Server)
if err != nil {
return err
}
c.Server = srv
c.Key = al.Key
kai, err := time.ParseDuration(al.KeepAliveInterval)
if err != nil {
return err
}
c.KeepAliveInterval = kai
c.ConnectionRetries = al.ConnectionRetries
war, err := time.ParseDuration(al.WaitAndRetry)
if err != nil {
return err
}
c.WaitAndRetry = war
c.SshAgent = al.SshAgent
tim, err := time.ParseDuration(al.Timeout)
if err != nil {
return err
}
c.Timeout = tim
c.SshConfig = al.SshConfig
c.Rpc = al.Rpc
c.RpcAddress = al.RpcAddress
return nil
}
// ShowInstances returns the runtime information about all instances of mole
// running on the system with rpc enabled.
func ShowInstances() (*InstancesRuntime, error) {
ctx := context.Background()
data, err := rpc.ShowAll(ctx)
if err != nil {
return nil, err
}
var instances []Runtime
err = mapstructure.Decode(data, &instances)
if err != nil {
return nil, err
}
runtime := InstancesRuntime(instances)
if len(runtime) == 0 {
return nil, fmt.Errorf("no instances were found.")
}
return &runtime, nil
}
// ShowInstance returns the runtime information about an application instance
// from the given id or alias.
func ShowInstance(id string) (*Runtime, error) {
ctx := context.Background()
info, err := rpc.Show(ctx, id)
if err != nil {
return nil, err
}
var r Runtime
err = mapstructure.Decode(info, &r)
if err != nil {
return nil, err
}
return &r, nil
}
func startDaemonProcess(instanceConf *DetachedInstance) error {
args := appendIdArg(instanceConf.Id, os.Args)
cntxt := &daemon.Context{
PidFileName: instanceConf.PidFile,
PidFilePerm: 0644,
LogFileName: instanceConf.LogFile,
LogFilePerm: 0640,
Umask: 027,
Args: args,
}
d, err := cntxt.Reborn()
if err != nil {
return err
}
if d != nil {
err = os.Rename(instanceConf.PidFile, instanceConf.PidFile)
if err != nil {
return err
}
err = os.Rename(instanceConf.LogFile, instanceConf.LogFile)
if err != nil {
return err
}
log.Infof("execute \"mole stop %s\" if you like to stop it at any time", instanceConf.Id)
os.Exit(0)
}
defer func() {
err := cntxt.Release()
if err != nil {
log.WithFields(log.Fields{
"id": instanceConf.Id,
}).WithError(err).Error("error detaching the mole instance")
}
}()
return nil
}
type flags []string
func (fs flags) lookup(flag string) bool {
for _, f := range fs {
if flag == f {
return true
}
}
return false
}
func createTunnel(conf *Configuration) (*tunnel.Tunnel, error) {
s, err := tunnel.NewServer(conf.Server.User, conf.Server.Address(), conf.Key, conf.SshAgent, conf.SshConfig)
if err != nil {
log.Errorf("error processing server options: %v\n", err)
return nil, err
}
s.Insecure = conf.Insecure
s.Timeout = conf.Timeout
err = s.Key.HandlePassphrase(func() ([]byte, error) {
fmt.Printf("The key provided is secured by a password. Please provide it below:\n")
fmt.Printf("Password: ")
p, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Printf("\n")
return p, err
})
if err != nil {
log.WithError(err).Error("error setting up password handling function")
return nil, err
}
log.Debugf("server: %s", s)
source := make([]string, len(conf.Source))
for i, r := range conf.Source {
source[i] = r.String()
}
destination := make([]string, len(conf.Destination))
for i, r := range conf.Destination {
if r.Port == "" {
log.WithError(err).Errorf("missing port in destination address: %s", r.String())
return nil, err
}
destination[i] = r.String()
}
t, err := tunnel.New(conf.TunnelType, s, source, destination, conf.SshConfig)
if err != nil {
log.Error(err)
return nil, err
}
//TODO need to find a way to require the attributes below to be always set
// since they are not optional (functionality will break if they are not
// set and CLI parsing is the one setting the default values).
// That could be done by make them required in the constructor's signature or
// by creating a configuration struct for a tunnel object.
t.ConnectionRetries = conf.ConnectionRetries
t.WaitAndRetry = conf.WaitAndRetry
t.KeepAliveInterval = conf.KeepAliveInterval
return t, nil
}
// appendIdArg adds the id argument to the list of arguments passed by the user.
// This is helpful for scenarios where the process will be detached from the
// parent process and the new child process needs context about the instance.
func appendIdArg(id string, args []string) (newArgs []string) {
for _, arg := range args {
if arg == "--id" {
return args
}
}
newArgs = make([]string, len(args)+2)
copy(newArgs, args)
newArgs[len(args)-2] = fmt.Sprintf("--%s", IdFlagName)
newArgs[len(args)-1] = id
return
}