-
Notifications
You must be signed in to change notification settings - Fork 4
/
mikoi.go
226 lines (187 loc) · 4.76 KB
/
mikoi.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
package main
import (
"fmt"
"io"
"net"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"github.com/jessevdk/go-flags"
)
const unknownReturnCode = 3
const portPlaceHolder = "{}"
var opts struct {
Host string `short:"H" long:"hostname" description:"host name" required:"true"`
Port string `short:"p" long:"port" description:"port number" required:"true"`
Timeout time.Duration `short:"t" long:"timeout" description:"connection times out" default:"10s"`
Verbose bool `short:"V" long:"verbose" description:"verbose"`
ProxyProto bool `short:"P" long:"proxyproto" description:"use ProxyProto"`
ProxyProtoVersion int `long:"proxyproto-version" description:"specify ProxyProtocol version" default:"1"`
ProxyProtoSrc string `long:"proxyproto-src" description:"Source address for ProxyProto"`
}
// When there is no argument for command line, mikoi is in proxy server mode.
var serverMode bool
func main() {
args, err := flags.Parse(&opts)
if err != nil {
os.Exit(unknownReturnCode)
}
if opts.Verbose {
fmt.Fprintln(os.Stderr, "cmd args:", args)
}
if len(args) > 1 && !hasPortPlaceHolder(args) {
fmt.Fprintln(os.Stderr, "command that mikoi will fork must have at least one port place holder")
os.Exit(unknownReturnCode)
}
if len(args) == 0 {
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi is now running as proxy server mode")
}
serverMode = true
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Fprintln(os.Stderr, "unable to listen to localhost")
os.Exit(unknownReturnCode)
}
laddr, ok := ln.Addr().(*net.TCPAddr)
if !ok {
fmt.Fprintln(os.Stderr, "unable to get a ephemeral port")
os.Exit(unknownReturnCode)
}
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi is now listening to", laddr.Port)
}
serverErrCh := make(chan error)
// launching proxy server
go server(ln, serverErrCh)
cmdErrCh := make(chan error)
if !serverMode {
cmdArgs := replacePortPlaceHolder(laddr.Port, args)
if opts.Verbose {
fmt.Fprintln(os.Stderr, "cmd:", cmdArgs)
}
go cmdExecuter(cmdArgs, cmdErrCh)
if opts.Verbose {
fmt.Fprintln(os.Stderr, "waiting for command to be finished")
}
}
for {
select {
case err := <-serverErrCh:
fmt.Fprintln(os.Stderr, err)
if serverMode {
return
}
case err := <-cmdErrCh:
if opts.Verbose {
fmt.Fprintf(os.Stderr, "command was finished: %#v\n", err)
}
if err == nil {
return
}
if eerr, ok := err.(*exec.ExitError); ok {
if ws, wsok := eerr.Sys().(syscall.WaitStatus); wsok {
es := ws.ExitStatus()
os.Exit(es)
}
}
os.Exit(unknownReturnCode)
}
}
}
func serve(conn net.Conn, errCh chan<- error) {
defer conn.Close()
conn.SetDeadline(time.Now().Add(opts.Timeout))
// opening a connection to server
pconn, err := net.DialTimeout("tcp", opts.Host+":"+opts.Port, opts.Timeout)
if err != nil {
errCh <- err
return
}
defer pconn.Close()
pconn.SetDeadline(time.Now().Add(opts.Timeout))
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi connects a connection to server")
}
// Upgrade pconn to use ProxyProtocol
if opts.ProxyProto {
var src net.Addr
if opts.ProxyProtoSrc != "" {
tcpAddr, err := net.ResolveTCPAddr("tcp", opts.ProxyProtoSrc)
if err != nil {
errCh <- err
return
}
src = tcpAddr
} else {
src = pconn.LocalAddr()
}
pconn = &ProxyConn{
Conn: &mikoiConn{Conn: pconn, Src: src},
version: opts.ProxyProtoVersion,
}
}
// proxying a connection from plugin to server
doneCh := make(chan struct{})
go func() {
io.Copy(pconn, conn)
doneCh <- struct{}{}
}()
go func() {
io.Copy(conn, pconn)
doneCh <- struct{}{}
}()
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi is now proxying traffic")
}
<-doneCh
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi is closing connections")
}
}
func server(ln net.Listener, errCh chan<- error) {
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi is launching server")
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
errCh <- err
continue
}
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi accepts a connection from plugin")
}
go serve(conn, errCh)
}
}
func cmdExecuter(cmdArgs []string, errCh chan<- error) {
if opts.Verbose {
fmt.Fprintln(os.Stderr, "mikoi is executing command")
}
cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
errCh <- cmd.Run()
}
func hasPortPlaceHolder(args []string) bool {
for _, a := range args {
if strings.Contains(a, portPlaceHolder) {
return true
}
}
return false
}
func replacePortPlaceHolder(port int, args []string) []string {
p := strconv.Itoa(port)
ret := make([]string, 0, len(args))
for _, a := range args {
ret = append(ret, strings.Replace(a, portPlaceHolder, p, -1))
}
return ret
}