-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
92 lines (77 loc) · 2.31 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
package main
import (
"os"
"fmt"
"log"
"net"
"flag"
"net/http"
"os/signal"
"github.com/gorilla/websocket"
)
func gracefulExit(l net.Listener, c net.Conn, wc *websocket.Conn, msg string){
wc.Close()
c.Close()
l.Close()
log.Println(msg)
os.Exit(0)
}
func WSocket2UDSocket(l net.Listener, c net.Conn, wc *websocket.Conn) {
// First, force telnet to use BINARY transmission
c.Write([]byte{255, 253, 0})
for {
_, message, err := wc.ReadMessage()
if err != nil {
gracefulExit(l, c, wc, fmt.Sprintf("Websockets Read: %s", err))
}
_, err = c.Write(message)
if err != nil {
gracefulExit(l, c, wc, fmt.Sprintf("Unable to write unix socket: %s", err))
}
}
}
func UDSocket2WSocket(l net.Listener, c net.Conn, wc *websocket.Conn) {
message := make([]byte, 512)
for {
nr, err := c.Read(message[:])
if err != nil {
gracefulExit(l, c, wc, fmt.Sprintf("Unix socket reading error: %s", err))
}
data := message[0:nr]
if err := wc.WriteMessage(websocket.BinaryMessage, data); err != nil {
gracefulExit(l, c, wc, fmt.Sprintf("Websockets writing error: %s", err))
}
}
}
func main() {
ws_url := flag.String("u", "", "Assign the websockets endpoint. Starting with ws:// or wss://")
randN := flag.Int("r", 9487, "Assign a random number to distinguish unix domain sockets")
flag.Parse()
l, err := net.Listen("unix", fmt.Sprintf("tmp/telnetBYwebsocket.%d.sock", *randN))
if err != nil {
log.Fatal("listen error:", err)
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func(){
for sig := range ch {
l.Close()
log.Println("Aborted by user", sig)
os.Exit(0)
}
}()
var dialer *websocket.Dialer
c, _, err := dialer.Dial(*ws_url, http.Header{"Origin": {"https://www.ptt.cc"}})
if err != nil {
l.Close()
log.Fatal("websocket connect error:", err)
}
for {
fd, err := l.Accept()
if err != nil {
log.Fatal("accept error:", err)
}
go WSocket2UDSocket(l, fd, c)
go UDSocket2WSocket(l, fd, c)
}
}