-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
ws.go
205 lines (185 loc) · 4.91 KB
/
ws.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
// Copyright 2020-2021 Changkun Ou. All rights reserved.
// Use of this source code is governed by a GPL-3.0
// license that can be found in the LICENSE file.
package daemon
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"sync"
"time"
"changkun.de/x/midgard/internal/clipboard"
"changkun.de/x/midgard/internal/config"
"changkun.de/x/midgard/internal/types"
"changkun.de/x/midgard/internal/utils"
"github.com/gorilla/websocket"
)
func (m *Daemon) wsConnect() error {
m.Lock()
defer m.Unlock()
// connect to midgard server via websocket
creds := config.Get().Server.Auth.User + ":" + config.Get().Server.Auth.Pass
token := base64.StdEncoding.EncodeToString(utils.StringToBytes(creds))
h := http.Header{"Authorization": {"Basic " + token}}
api := types.EndpointSubscribe
if strings.Contains(config.Get().Domain, "localhost") || strings.Contains(config.Get().Domain, "0.0.0.0") {
api = "ws://" + api
} else {
api = "wss://" + api
}
log.Println("connecting to:", api)
conn, _, err := websocket.DefaultDialer.Dial(api, h)
if err != nil {
return fmt.Errorf("failed to connect midgard server: %w", err)
}
m.ws = conn
// handshake with midgard server
err = m.ws.WriteMessage(websocket.BinaryMessage, (&types.WebsocketMessage{
Action: types.ActionHandshakeRegister,
UserID: m.ID,
Data: nil,
}).Encode())
if err != nil {
return fmt.Errorf("failed to send handshake message: %w", err)
}
_, msg, err := m.ws.ReadMessage()
if err != nil {
return fmt.Errorf("failed to read message for handshake: %w", err)
}
wsm := &types.WebsocketMessage{}
err = wsm.Decode(msg)
if err != nil {
return fmt.Errorf("failed to handshake with midgard server: %w", err)
}
switch wsm.Action {
case types.ActionHandshakeReady:
if wsm.UserID != m.ID {
m.ID = wsm.UserID // update local id if user id is updated
log.Println("conflict hostname, updated daemon id: ", m.ID)
}
default:
conn.Close() // close the connection if handshake is not ready
return fmt.Errorf("failed to handshake with midgard server: %w", err)
}
return nil
}
func (m *Daemon) wsClose() {
m.ws.Close()
}
// wsReconnect tries to reconnect to the midgard server and returns
// until it connects to the server.
func (m *Daemon) wsReconnect(ctx context.Context) {
tk := time.NewTicker(10 * time.Second)
defer tk.Stop()
for {
select {
case <-ctx.Done():
return
case <-tk.C:
err := m.wsConnect()
if err == nil {
log.Println("connected to midgard server.")
m.forceUpdate <- struct{}{}
return
}
log.Printf("%v\n", err)
log.Println("retry in 10 seconds..")
}
}
}
func (m *Daemon) handleIO(ctx context.Context) {
if m.ws == nil {
m.wsReconnect(ctx)
}
log.Println("daemon id:", m.ID)
wg := sync.WaitGroup{}
wg.Add(2)
go func() { // read from server
defer wg.Done()
m.readFromServer(ctx)
}()
go func() { // write to server
defer wg.Done()
for {
select {
case <-ctx.Done():
if m.ws == nil {
log.Println("connection was not ready")
return
}
_ = m.ws.WriteMessage(websocket.BinaryMessage, (&types.WebsocketMessage{
Action: types.ActionTerminate,
UserID: m.ID,
}).Encode())
return
case msg := <-m.writeCh:
if m.ws == nil {
log.Println("connection is not ready yet")
continue
}
err := m.ws.WriteMessage(websocket.BinaryMessage, msg.Encode())
if err != nil {
log.Printf("failed to write message to server: %v", err)
return
}
}
}
}()
wg.Wait()
}
func (m *Daemon) readFromServer(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
_, msg, err := m.ws.ReadMessage()
if err != nil {
log.Printf("failed to read message from the clipboard channel: %v", err)
m.Lock()
m.ws = nil
m.Unlock()
m.wsReconnect(ctx) // block until connection is ready again
continue
}
wsm := &types.WebsocketMessage{}
err = wsm.Decode(msg)
if err != nil {
log.Printf("failed to read message: %v", err)
continue
}
// duplicate messages to all readers, readers should not edit the message
m.readChs.Range(func(k, v interface{}) bool {
readerCh := v.(chan *types.WebsocketMessage)
readerCh <- wsm
return true
})
switch wsm.Action {
case types.ActionClipboardChanged:
var d types.ClipboardData
err = json.Unmarshal(wsm.Data, &d)
if err != nil {
log.Printf("failed to parse clipboard data: %v", err)
continue
}
var raw []byte
if d.Type == types.MIMEImagePNG {
// We assume the server send us a base64 encoded image data,
// Let's decode it into bytes.
raw, err = base64.StdEncoding.DecodeString(d.Data)
if err != nil {
raw = []byte{}
}
} else {
raw = utils.StringToBytes(d.Data)
}
log.Printf("universal clipboard has changed from %s, type: %s, sync with local...", wsm.UserID, d.Type)
clipboard.Local.Write(d.Type, raw) // change local clipboard
}
}
}
}