aboutsummaryrefslogtreecommitdiff
path: root/xP/xP.go
blob: b9ab73c9a51d23210df523b4ecfb555415236d10 (plain)
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
// Copyright (c) 2022, Přemysl Eric Janouch <p@janouch.name>
// SPDX-License-Identifier: 0BSD

package main

import (
	"context"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	"golang.org/x/net/websocket"
)

var (
	addressBind    string
	addressConnect string
)

func clientToRelay(
	ctx context.Context, ws *websocket.Conn, conn net.Conn) bool {
	var j string
	if err := websocket.Message.Receive(ws, &j); err != nil {
		log.Println("Command receive failed: " + err.Error())
		return false
	}

	log.Printf("?> %s\n", j)

	var m RelayCommandMessage
	if err := json.Unmarshal([]byte(j), &m); err != nil {
		log.Println("Command unmarshalling failed: " + err.Error())
		return false
	}

	b, ok := m.AppendTo(make([]byte, 4))
	if !ok {
		log.Println("Command serialization failed")
		return false
	}
	binary.BigEndian.PutUint32(b[:4], uint32(len(b)-4))
	if _, err := conn.Write(b); err != nil {
		log.Println("Command send failed: " + err.Error())
		return false
	}

	log.Printf("-> %v\n", b)
	return true
}

func relayToClient(
	ctx context.Context, ws *websocket.Conn, conn net.Conn) bool {
	var length uint32
	if err := binary.Read(conn, binary.BigEndian, &length); err != nil {
		log.Println("Event receive failed: " + err.Error())
		return false
	}
	b := make([]byte, length)
	if _, err := io.ReadFull(conn, b); err != nil {
		log.Println("Event receive failed: " + err.Error())
		return false
	}

	log.Printf("<? %v\n", b)

	var m RelayEventMessage
	if after, ok := m.ConsumeFrom(b); !ok {
		log.Println("Event deserialization failed")
		return false
	} else if len(after) != 0 {
		log.Println("Event deserialization failed: trailing data")
		return false
	}

	j, err := json.Marshal(&m)
	if err != nil {
		log.Println("Event marshalling failed: " + err.Error())
		return false
	}
	if err := websocket.Message.Send(ws, string(j)); err != nil {
		log.Println("Event send failed: " + err.Error())
		return false
	}

	log.Printf("<- %s\n", j)
	return true
}

func errorToClient(ws *websocket.Conn, err error) bool {
	j, err := json.Marshal(&RelayEventMessage{
		EventSeq: 0,
		Data: RelayEventData{
			Interface: RelayEventDataError{
				Event:      RelayEventError,
				CommandSeq: 0,
				Error:      err.Error(),
			},
		},
	})
	if err != nil {
		log.Println("Event marshalling failed: " + err.Error())
		return false
	}
	if err := websocket.Message.Send(ws, string(j)); err != nil {
		log.Println("Event send failed: " + err.Error())
		return false
	}
	return true
}

func handleWebSocket(ws *websocket.Conn) {
	conn, err := net.Dial("tcp", addressConnect)
	if err != nil {
		errorToClient(ws, err)
		return
	}

	// We don't need to intervene, so it's just two separate pipes so far.
	ctx, cancel := context.WithCancel(ws.Request().Context())
	go func() {
		for clientToRelay(ctx, ws, conn) {
		}
		cancel()
	}()
	go func() {
		for relayToClient(ctx, ws, conn) {
		}
		cancel()
	}()
	<-ctx.Done()
}

var staticHandler = http.FileServer(http.Dir("."))

var page = template.Must(template.New("/").Parse(`<!DOCTYPE html>
<html>
<head>
	<title>xP</title>
	<meta charset="utf-8" />
	<link rel="stylesheet" href="xP.css" />
</head>
<body>
	<script src="mithril.js">
	</script>
	<script>
	let proxy = '{{ . }}'
	</script>
	<script src="xP.js">
	</script>
</body>
</html>`))

func handleDefault(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		staticHandler.ServeHTTP(w, r)
		return
	}

	wsURI := fmt.Sprintf("ws://%s/ws", r.Host)
	if err := page.Execute(w, wsURI); err != nil {
		log.Println("Template execution failed: " + err.Error())
	}
}

func main() {
	if len(os.Args) != 3 {
		log.Fatalf("usage: %s BIND CONNECT\n", os.Args[0])
	}

	addressBind, addressConnect = os.Args[1], os.Args[2]

	http.Handle("/ws", websocket.Handler(handleWebSocket))
	http.Handle("/", http.HandlerFunc(handleDefault))

	s := &http.Server{
		Addr:           addressBind,
		ReadTimeout:    60 * time.Second,
		WriteTimeout:   60 * time.Second,
		MaxHeaderBytes: 32 << 10,
	}
	log.Fatal(s.ListenAndServe())
}