-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
279 lines (232 loc) · 6.44 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
267
268
269
270
271
272
273
274
275
276
277
278
279
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"log"
"net"
"os"
"regexp"
"strings"
"sync"
"text/template"
)
const sipResponse = "SIP/2.0 200 OK\r\n" +
"{{ .Via }};received=0.0.0.0\r\n" +
"From: <sip:[email protected];transport=TCP>;tag=U7c3d519\r\n" +
"To: <sip:[email protected];transport=TCP>;tag=37GkEhwl6\r\n" +
"Call-ID: aaaaaaaaaaaaaaaaa0404aaaaaaaaaaaabbbbbbZjQ4M2M.\r\n" +
"CSeq: 1 REGISTER\r\n" +
"{{ .Contact }};expires=3600\r\n" +
"Content-Length: 0\r\n" +
"\r\n"
const sipRequest = "REGISTER sip:example.org;transport=TCP SIP/2.0\r\n" +
"Via: SIP/2.0/TCP {{ .LocalIP }}:{{ .RemotePort }};branch=I9hG4bK-d8754z-c2ac7de1b3ce90f7-1---d8754z-;rport;transport=TCP\r\n" +
"Max-Forwards: 70\r\n" +
"Contact: <sip:wuzzi@{{ .LocalIP }}:{{ .LocalPort }};rinstance=v40f3f83b335139c;transport=TCP>\r\n" +
"To: <sip:[email protected];transport=TCP>\r\n" +
"From: <sip:[email protected];transport=TCP>;tag=U7c3d519\r\n" +
"Call-ID: aaaaaaaaaaaaaaaaa0404aaaaaaaaaaaabbbbbbZjQ4M2M.\r\n" +
"CSeq: 1 REGISTER\r\n" +
"Expires: 60\r\n" +
"Allow: REGISTER, INVITE, ACK, CANCEL, BYE, NOTIFY, REFER, MESSAGE, OPTIONS, INFO, SUBSCRIBE\r\n" +
"Supported: replaces, norefersub, extended-refer, timer, X-cisco-serviceuri\r\n" +
"Allow-Events: presence, kpml\r\n" +
"Content-Length: 0\r\n" +
"\r\n"
var extractContact = regexp.MustCompile(`Contact:[^\r]+`)
var extractVia = regexp.MustCompile(`Via:[^\r]+`)
var extractCallback = regexp.MustCompile(`@(?P<callback>[^;]+)`)
func startSIPServer(sipPort string) error {
t := template.Must(template.New("sip_response").Parse(sipResponse))
l, err := net.Listen("tcp", ":"+sipPort)
if err != nil {
return err
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Println("unable to accept connection:", err)
continue
}
log.Println("accepted connection from:", conn.RemoteAddr())
go handleConnection(conn, t)
}
}
func handleConnection(conn net.Conn, t *template.Template) {
defer conn.Close()
data := make([]byte, 0, 1024)
read := 0
for {
ch := make([]byte, 1)
n, err := conn.Read(ch)
if err != nil {
log.Println("unable to read:", err)
return
}
data = append(data, ch...)
read += n
if read > 3 {
if bytes.Compare(data[read-4:read], []byte("\r\n\r\n")) == 0 {
break
}
}
}
contact := extractContact.Find(data)
if len(contact) < 1 {
log.Println("bad contact")
return
}
via := extractVia.Find(data)
if len(via) < 1 {
log.Println("bad via")
return
}
vars := struct {
Via string
Contact string
}{
Via: string(via),
Contact: string(contact),
}
var buff bytes.Buffer
// NOTE: we need to buffer this response. Writing directly to the
// connection caused the packets to get fragmented which stopped
// the ALG from working correctly
err := t.Execute(&buff, vars)
if err != nil {
log.Println("unable to execute response template:", err)
return
}
_, err = conn.Write(buff.Bytes())
if err != nil {
log.Println("error sending response:", err)
return
}
matches := extractCallback.FindSubmatch(contact)
if len(matches) < 2 {
log.Println("invalid host/port in contact")
return
}
connectBackHost := string(matches[1])
log.Println("connecting back to:", connectBackHost)
c2, err := net.Dial("tcp", connectBackHost)
if err != nil {
log.Println("unable to connect to host behind NAT:", err)
return
}
defer c2.Close()
_, err = c2.Write([]byte("hello from the internet!\n"))
if err != nil {
log.Println("unable to write to host behind NAT:", err)
}
}
func setupListener(port string, wg *sync.WaitGroup) {
defer wg.Done()
// NOTE: listening on :<port> ends up breaking when testing this in WSL
// doing port forwarding I assume due to WSL attempting to bind to
// Window's interface and failing and the forwarding getting confused.
// Disabling the forwarding doesn't actually fix it.
ln, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
if err != nil {
log.Fatal("unable to open socket for listening:", err)
}
defer ln.Close()
fmt.Println("listening on port:", port)
conn, err := ln.Accept()
if err != nil {
log.Fatal("unable to accept incoming connect:", err)
}
defer conn.Close()
fmt.Println("accepted connection from:", conn.RemoteAddr())
reader := bufio.NewReader(conn)
line, err := reader.ReadString('\n')
if err != nil {
log.Println("unable to read from connection:", err)
}
fmt.Printf("received message from remote server: `%s`\n", strings.TrimRight(line, "\n"))
}
func sendRequest(host, localIP, localPort, remotePort string) error {
t := template.Must(template.New("sip_request").Parse(sipRequest))
vars := struct {
LocalIP string
LocalPort string
RemotePort string
}{
LocalIP: localIP,
LocalPort: localPort,
RemotePort: remotePort,
}
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", host, remotePort))
if err != nil {
return err
}
// see note above about buffering response and fragmentation
var buff bytes.Buffer
err = t.Execute(&buff, vars)
if err != nil {
return err
}
_, err = conn.Write(buff.Bytes())
if err != nil {
return err
}
return nil
}
func main() {
var (
remotePort string
localPort string
localIP string
host string
listen bool
)
flag.StringVar(&localPort, "lp", "", "the port to listen on locally (server and client)")
flag.StringVar(&remotePort, "rp", "", "the port to connect to (client)")
flag.StringVar(&localIP, "ip", "", "the local NAT ip to connect back to")
flag.StringVar(&host, "host", "", "the host to connect to")
flag.BoolVar(&listen, "l", false, "listen for incoming connections; this makes it a server")
flag.Parse()
if listen {
if localPort == "" {
fmt.Fprintf(os.Stderr, "you must specify a local port\n")
flag.Usage()
os.Exit(1)
}
err := startSIPServer(localPort)
if err != nil {
log.Fatal("unable to start SIP sever", err)
}
} else {
if localPort == "" {
fmt.Fprintf(os.Stderr, "you must specify a local port\n")
flag.Usage()
os.Exit(1)
}
if remotePort == "" {
fmt.Fprintf(os.Stderr, "you must specify a remote port\n")
flag.Usage()
os.Exit(1)
}
if localIP == "" {
fmt.Fprintf(os.Stderr, "you must specify a local ip address\n")
flag.Usage()
os.Exit(1)
}
if host == "" {
fmt.Fprintf(os.Stderr, "you must specify a host\n")
flag.Usage()
os.Exit(1)
}
wg := sync.WaitGroup{}
wg.Add(1)
go setupListener(localPort, &wg)
err := sendRequest(host, localIP, localPort, remotePort)
if err != nil {
log.Fatal(err)
}
wg.Wait()
}
}