-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
266 lines (247 loc) · 6.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
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
package main
import (
"flag"
"fmt"
"io"
"log"
"log/syslog"
"net"
"os"
"os/exec"
"os/signal"
"sync"
"syscall"
"time"
"sshportfw/safeCounter"
"github.com/juju/fslock"
"github.com/kirsle/configdir"
)
const (
Appname = "sshportfw"
ForwardingsPath = "forwardings.json"
)
// global variables are bad but given how simple the program is, lets accept 2 of them
var routineCount = safeCounter.New()
var activeForwardings = safeCounter.New()
type forwarding struct {
Service string
ListenAddr string
RemoteAddr string
}
type serverInfo struct {
Host string
Forward []forwarding
}
// Stops the timer and drains the chan safely
// TODO delete
func stopTimer(t *time.Timer) {
t.Stop()
select {
case <-t.C:
default:
}
}
func flagParse() {
var version bool
var syslogOutput bool
var output string
var lines bool
var printtime bool
flag.BoolVar(&version, "version", false, "prints current sshportfw version")
flag.BoolVar(&version, "v", false, "")
flag.BoolVar(&syslogOutput, "syslog", false, "redirects output to syslog")
flag.BoolVar(&syslogOutput, "s", false, "")
flag.StringVar(&output, "output", "", "Redirect output to file, only messages from ssh client are displayed to console. Use -o /dev/null for quiet operation")
flag.StringVar(&output, "o", "", "")
flag.BoolVar(&lines, "lines", false, "Print source code line numbers for debugging")
flag.BoolVar(&lines, "l", false, "")
flag.BoolVar(&printtime, "time", false, "Print date and time for every line of output (ignored on syslog output)")
flag.BoolVar(&printtime, "t", false, "")
flag.Parse()
currflags := 0
if version {
fmt.Println("sshportfw Version 0.6.3")
os.Exit(0)
}
if output != "" && syslogOutput {
log.Print("-s and -o flags cannot be enabled at the same time")
os.Exit(1)
}
if output != "" {
outfile, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}
log.SetOutput(outfile)
}
if lines {
currflags = currflags | log.Lshortfile
}
if printtime && !syslogOutput {
// logger will print date and time
currflags = currflags | log.Ldate | log.Ltime
}
if syslogOutput {
log.SetFlags(0)
// Configure logger to write to the syslog
logwriter, err := syslog.New(syslog.LOG_NOTICE, Appname)
if err == nil {
log.SetOutput(logwriter)
} else {
log.Fatal("Cannot set syslog output")
}
}
log.SetFlags(currflags)
}
// called as a Goroutine, takes a net.Conn, spawns a ssh connection and bidirectionally transfers data
func sshInstance(localConn net.Conn, fw forwarding, host string) {
cmd := exec.Command("ssh", "-W", fw.RemoteAddr, host)
stdin, err := cmd.StdinPipe()
if err != nil {
log.Print(err)
return
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Print(err)
return
}
id := routineCount.Inc()
// Now we actually execute the ssh command
err = cmd.Start()
if err != nil {
log.Print(err)
return
}
log.Printf("#%d Start forwarding : %s %s", id, host, fw.Service)
// we use it to limit the exit message to just the first terminating goroutine
once := sync.Once{}
// We use it to wait for the goroutines
wg := sync.WaitGroup{}
// we will have 3 goroutines
wg.Add(3)
//active :=
go func() {
_, err := io.Copy(stdin, localConn)
localConn.Close() // we force the other io.Copy to terminate (reader)
if err != nil {
once.Do(func() {
log.Printf("#%d local --> remote : %q", id, err)
})
}
/* pr := cmd.Process
if pr != nil {
log.Printf("#%d Sending term signal to ssh client", id)
pr.Signal(syscall.SIGTERM)
} */
wg.Done()
}()
go func() {
_, err := io.Copy(localConn, stdout)
localConn.Close() // we force the other io.Copy(goroutine) to exit (reader)
if err != nil {
once.Do(func() {
log.Printf("#%d remote --> local : %q", id, err)
})
}
/* pr := cmd.Process
if pr != nil {
log.Printf("#%d Sending term signal to ssh client", id)
pr.Signal(syscall.SIGTERM)
} */
wg.Done()
}()
go func() {
err = cmd.Wait()
if err != nil {
once.Do(func() {
log.Printf("#%d : %q", id, err)
})
}
localConn.Close()
wg.Done()
}()
log.Printf("#%d Copy routine started (total active %d)", id, activeForwardings.Inc())
// wait until all 3 goroutines are terminted
wg.Wait()
//once.Do(func() {
log.Printf("#%d ssh forwarder ends (active remaining %d)", id, activeForwardings.Dec())
//})
//log.Printf("Active SSH forwardings remaining : %d")
}
// listens to a local port and whan a local connection occurs
// connects to remote ssh if necessary
// establishes a socket for communication and starts a DataCopy goroutine for the copying of
// the data send and received
func localPortListen(fw forwarding, host string) {
tag := fmt.Sprintf("%s-%s", host, fw.Service)
defer log.Printf("%s goroutine ends", tag)
var localListener net.Listener
for {
var err error
localListener, err = net.Listen("tcp", fw.ListenAddr)
if err == nil {
break
}
log.Printf("%s listen failed at %s err=%q", tag, fw.ListenAddr, err)
time.Sleep(time.Minute)
}
log.Printf("%s listening at %s", tag, fw.ListenAddr)
for {
localConn, err := localListener.Accept()
if err != nil {
log.Printf("%s listen.Accept failed: %v", tag, err)
time.Sleep(time.Minute)
continue
}
go sshInstance(localConn, fw, host)
}
}
func main() {
log.SetOutput(os.Stdout)
flagParse()
// The location of the config dir on linux is ~/.config/sshportfw
configPath := configdir.LocalConfig(Appname)
if err := configdir.MakePath(configPath); err != nil {
log.Print(err)
return
}
if err := os.Chdir(configPath); err != nil {
log.Print(err)
return
}
// Do not allow 2 insrances of the program to run at the same time
{
lock := fslock.New("lock")
if err := lock.TryLock(); err != nil {
log.Printf("%q : %s", err, "Check if the program is already running in another console or in the background.")
//log.Print("Already running")
os.Exit(1)
}
}
// we check for the necessary env vars and programs zenity and notify-send
if err := checkEnvironment(); err != nil {
log.Print(err)
os.Exit(1)
}
// the SSH servers as defined in the config file
allServers, err := getServers(configPath)
if err != nil {
log.Print(err)
os.Exit(1)
}
for _, info := range allServers {
for _, fw := range info.Forward {
go localPortListen(fw, info.Host)
}
}
// must have capacity of 1 accordig to docs
sigChannel := make(chan os.Signal, 1)
signal.Notify(sigChannel, os.Interrupt, syscall.SIGTERM)
signal.Notify(sigChannel, os.Interrupt, syscall.SIGABRT)
signal.Notify(sigChannel, os.Interrupt, syscall.SIGHUP)
signal.Notify(sigChannel, os.Interrupt, syscall.SIGINT)
// waiting for terminating signal from the os
sig := <-sigChannel
log.Printf("Signal %q, program ends", sig)
}