This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
323 lines (311 loc) · 6.89 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
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
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path"
"syscall"
"time"
"github.com/google/uuid"
"github.com/nobonobo/ssh-p2p/signaling"
"github.com/pions/webrtc"
"github.com/pions/webrtc/pkg/datachannel"
"github.com/pions/webrtc/pkg/ice"
)
const usage = `Usage: ssh-p2p SUBCMD [options]
sub-commands:
newkey
new generate key of connection
server -key="..." [-dial="127.0.0.1:22"]
ssh server side peer mode
client -key="..." [-listen="127.0.0.1:2222"]
ssh client side peer mode
`
var (
defaultRTCConfiguration = webrtc.RTCConfiguration{
IceServers: []webrtc.RTCIceServer{
{
URLs: []string{
"stun:stun.l.google.com:19302",
},
},
},
}
)
func push(dst, src, sdp string) error {
buf := bytes.NewBuffer(nil)
if err := json.NewEncoder(buf).Encode(signaling.ConnectInfo{
Source: src,
SDP: sdp,
}); err != nil {
return err
}
resp, err := http.Post(signaling.URI+path.Join("/", "push", dst), "application/json", buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http failed")
}
return nil
}
func pull(ctx context.Context, id string) <-chan signaling.ConnectInfo {
ch := make(chan signaling.ConnectInfo)
var retry time.Duration
go func() {
faild := func() {
if retry < 10 {
retry++
}
time.Sleep(retry * time.Second)
}
defer close(ch)
for {
req, err := http.NewRequest("GET", signaling.URI+path.Join("/", "pull", id), nil)
if err != nil {
if ctx.Err() == context.Canceled {
return
}
log.Println("get failed:", err)
faild()
continue
}
req = req.WithContext(ctx)
res, err := http.DefaultClient.Do(req)
if err != nil {
if ctx.Err() == context.Canceled {
return
}
log.Println("get failed:", err)
faild()
continue
}
defer res.Body.Close()
retry = time.Duration(0)
var info signaling.ConnectInfo
if err := json.NewDecoder(res.Body).Decode(&info); err != nil {
if err == io.EOF {
continue
}
if ctx.Err() == context.Canceled {
return
}
log.Println("get failed:", err)
faild()
continue
}
if len(info.Source) > 0 && len(info.SDP) > 0 {
ch <- info
}
}
}()
return ch
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
cmd := ""
if len(os.Args) > 1 {
cmd = os.Args[1]
}
var flags *flag.FlagSet
flags = flag.NewFlagSet("", flag.ExitOnError)
flags.Usage = func() {
fmt.Fprintf(os.Stderr, usage)
flags.PrintDefaults()
os.Exit(1)
}
switch cmd {
default:
flags.Usage()
case "newkey":
key := uuid.New().String()
fmt.Println(key)
os.Exit(0)
case "server":
var addr, key string
flags.StringVar(&addr, "dial", "127.0.0.1:22", "dial addr = host:port")
flags.StringVar(&key, "key", "sample", "connection key")
if err := flags.Parse(os.Args[2:]); err != nil {
log.Fatalln(err)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT)
ctx, cancel := context.WithCancel(context.Background())
go serve(ctx, key, addr)
<-sig
cancel()
case "client":
var addr, key string
flags.StringVar(&addr, "listen", "127.0.0.1:2222", "listen addr = host:port")
flags.StringVar(&key, "key", "sample", "connection key")
if err := flags.Parse(os.Args[2:]); err != nil {
log.Fatalln(err)
}
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalln(err)
}
log.Println("listen:", addr)
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT)
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
sock, err := l.Accept()
if err != nil {
log.Println(err)
continue
}
go connect(ctx, key, sock)
}
}()
<-sig
cancel()
}
}
type sendWrap struct {
*webrtc.RTCDataChannel
}
func (s *sendWrap) Write(b []byte) (int, error) {
err := s.RTCDataChannel.Send(datachannel.PayloadBinary{Data: b})
return len(b), err
}
func serve(ctx context.Context, key, addr string) {
log.Println("server started")
for v := range pull(ctx, key) {
log.Printf("info: %#v", v)
pc, err := webrtc.New(defaultRTCConfiguration)
if err != nil {
log.Println("rtc error:", err)
continue
}
ssh, err := net.Dial("tcp", addr)
if err != nil {
log.Println("ssh dial filed:", err)
pc.Close()
continue
}
pc.OnICEConnectionStateChange(func(state ice.ConnectionState) {
log.Print("pc ice state change:", state)
if state == ice.ConnectionStateDisconnected {
pc.Close()
ssh.Close()
}
})
pc.OnDataChannel(func(dc *webrtc.RTCDataChannel) {
//dc.Lock()
dc.OnOpen(func() {
log.Print("dial:", addr)
io.Copy(&sendWrap{dc}, ssh)
log.Println("disconnected")
})
dc.Onmessage(func(payload datachannel.Payload) {
switch p := payload.(type) {
case *datachannel.PayloadBinary:
_, err := ssh.Write(p.Data)
if err != nil {
log.Println("ssh write failed:", err)
pc.Close()
return
}
}
})
//dc.Unlock()
})
if err := pc.SetRemoteDescription(webrtc.RTCSessionDescription{
Type: webrtc.RTCSdpTypeOffer,
Sdp: string(v.SDP),
}); err != nil {
log.Println("rtc error:", err)
pc.Close()
ssh.Close()
continue
}
answer, err := pc.CreateAnswer(nil)
if err != nil {
log.Println("rtc error:", err)
pc.Close()
ssh.Close()
continue
}
if err := push(v.Source, key, answer.Sdp); err != nil {
log.Println("rtc error:", err)
pc.Close()
ssh.Close()
continue
}
}
}
func connect(ctx context.Context, key string, sock net.Conn) {
id := uuid.New().String()
log.Println("client id:", id)
pc, err := webrtc.New(defaultRTCConfiguration)
if err != nil {
log.Println("rtc error:", err)
return
}
pc.OnICEConnectionStateChange(func(state ice.ConnectionState) {
log.Print("pc ice state change:", state)
})
dc, err := pc.CreateDataChannel("data", nil)
if err != nil {
log.Println("create dc failed:", err)
pc.Close()
return
}
//dc.Lock()
dc.OnOpen(func() {
io.Copy(&sendWrap{dc}, sock)
pc.Close()
log.Println("disconnected")
})
dc.OnMessage(func(payload datachannel.Payload) {
switch p := payload.(type) {
case *datachannel.PayloadBinary:
_, err := sock.Write(p.Data)
if err != nil {
log.Println("sock write failed:", err)
pc.Close()
return
}
}
})
//dc.Unlock()
log.Print("DataChannel:", dc)
go func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for v := range pull(ctx, id) {
log.Printf("info: %#v", v)
if err := pc.SetRemoteDescription(webrtc.RTCSessionDescription{
Type: webrtc.RTCSdpTypeAnswer,
Sdp: string(v.SDP),
}); err != nil {
log.Println("rtc error:", err)
pc.Close()
return
}
return
}
}()
offer, err := pc.CreateOffer(nil)
if err != nil {
log.Println("create offer error:", err)
pc.Close()
return
}
if err := push(key, id, offer.Sdp); err != nil {
log.Println("push error:", err)
pc.Close()
return
}
}