-
Notifications
You must be signed in to change notification settings - Fork 108
/
xc.go
125 lines (116 loc) · 2.59 KB
/
xc.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
// +build go1.15
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net"
"os"
"strings"
"time"
"regexp"
"./client"
"./server"
"github.com/hashicorp/yamux"
"github.com/libp2p/go-reuseport"
"path/filepath"
)
func usage() {
fmt.Printf("Usage: \n")
fmt.Printf("- Client: xc <ip> <port>\n")
fmt.Printf("- Server: xc -l -p <port>\n")
}
func main() {
listenPtr := flag.Bool("l", false, "use as server")
portPtr := flag.Int("p", 1337, "port to listen on, default 1337")
flag.Parse()
rand.Seed(time.Now().UnixNano())
if *listenPtr {
banner := `
__ _____
\ \/ / __|
> < (__
/_/\_\___| by @xct_de
build: §version§
`
fmt.Println(banner)
// server mode
listener, err := reuseport.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", *portPtr))
if err != nil {
log.Fatalln("Unable to bind to port")
}
log.Printf("Listening on :%d\n", *portPtr)
for {
log.Println("Waiting for connections...")
conn, err := listener.Accept()
if err != nil {
log.Println("Unable to accept connection")
continue
}
log.Printf("Connection from %s\n", conn.RemoteAddr().String())
session, err := yamux.Server(conn, nil)
if err != nil {
log.Println(err)
continue
}
stream, err := session.Accept()
if err != nil {
log.Println(err)
continue
}
log.Printf("Stream established")
server.Run(session, stream)
conn.Close()
}
} else {
// client mode
var (
ip string
port string
)
init := false
if flag.NArg() < 2 {
// (thanks @jkr)
name := filepath.Base(os.Args[0])
parts := strings.Split(name, "_")
if len(parts) == 3 {
ip = parts[1]
// split by first nonnumeric
var re = regexp.MustCompile(`([0-9]*).*`)
port = re.ReplaceAllString(parts[2], `$1`)
fmt.Printf("Detected client arguments from executable name: %s:%s\n", ip, port)
init = true
} else {
usage()
os.Exit(1)
}
}
if !init {
ip = flag.Arg(0)
port = flag.Arg(1)
}
// keep connecting (in case the server is exiting ungracefully we can just restart it and get a connection back)
for {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", ip, port))
if err != nil {
log.Println("Couldn't connect. Trying again...")
time.Sleep(3000 * time.Millisecond)
continue
}
log.Printf("Connected to %s\n", conn.RemoteAddr().String())
session, err := yamux.Client(conn, nil)
if err != nil {
log.Fatalln(err)
continue
}
stream, err := session.Open()
if err != nil {
log.Fatalln(err)
continue
}
client.Run(session, stream)
time.Sleep(5000 * time.Millisecond)
}
}
}