-
Notifications
You must be signed in to change notification settings - Fork 46
/
handlers.go
379 lines (322 loc) · 9.42 KB
/
handlers.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
Copyright 2020,2021 Avi Zimmerman
This file is part of kvdi.
kvdi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
kvdi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with kvdi. If not, see <https://www.gnu.org/licenses/>.
*/
package server
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/kennygrant/sanitize"
v1 "github.com/kvdi/kvdi/apis/meta/v1"
"github.com/kvdi/kvdi/pkg/audio"
"github.com/kvdi/kvdi/pkg/audio/pa"
"github.com/kvdi/kvdi/pkg/proxyproto"
"github.com/kvdi/kvdi/pkg/types"
"github.com/kvdi/kvdi/pkg/util/common"
"github.com/kvdi/kvdi/pkg/util/errors"
)
func (p *Server) setupPulseAudio(manager *pa.DeviceManager) error {
if err := manager.WaitForReady(time.Second * 2); err != nil {
return err
}
if _, err := manager.AddSink(p.opts.PlaybackDeviceName, p.opts.PlaybackDeviceDescription); err != nil {
return err
}
if _, err := manager.AddSource(&pa.SourceOpts{
Name: p.opts.RecordingDeviceName,
Description: p.opts.RecordingDeviceDescription,
FifoPath: p.opts.RecordingDevicePath,
SampleFormat: p.opts.RecordingDeviceFormat,
SampleRate: p.opts.RecordingDeviceSampleRate,
Channels: p.opts.RecordingDeviceChannels,
}); err != nil {
return err
}
if err := manager.SetDefaultSource(p.opts.RecordingDeviceName); err != nil {
return err
}
return nil
}
func (p *Server) handleDisplay(conn *proxyproto.Conn) {
addr := fmt.Sprintf("%s://%s", p.opts.DisplayProto, p.opts.DisplayAddress)
p.log.Info(fmt.Sprintf("Received display proxy request, connecting to %s", addr))
defer conn.Close()
displayConn, err := net.Dial(p.opts.DisplayProto, p.opts.DisplayAddress)
if err != nil {
p.log.Error(err, "Failed to connect to display server")
conn.WriteError(err)
return
}
p.log.Info("Connection to display server established")
p.log.Info("Starting display proxy")
if err := conn.WriteStatus(proxyproto.RequestOK); err != nil {
p.log.Error(err, "Failed to write response header")
return
}
stChan := p.logConnectionMetrics("display", conn)
defer func() { stChan <- struct{}{} }()
ctx, cancel := context.WithCancel(context.Background())
go func() {
defer cancel()
if _, err := io.Copy(displayConn, conn); err != nil {
p.log.Error(err, "Error while copying stream from client connection to display socket")
}
}()
// Copy server connection to the client
go func() {
defer cancel()
if _, err := io.Copy(conn, displayConn); err != nil {
p.log.Error(err, "Error while copying stream from display socket to client connection")
}
}()
p.log.Info(fmt.Sprintf("Connecting to pulse server: %s", p.opts.PulseServer))
paDevices, err := pa.NewDeviceManager(&pa.DeviceManagerOpts{
PulseServer: p.opts.PulseServer,
})
if err != nil {
p.log.Error(err, "Failed to setup pulseaudio, playback will not function")
}
if paDevices != nil {
defer func() {
if derr := paDevices.Destroy(); derr != nil {
p.log.Error(derr, "Failed to cleanup device manager")
}
}()
p.log.Info("Setting up audio devices")
if err := p.setupPulseAudio(paDevices); err != nil {
if derr := paDevices.Destroy(); derr != nil {
p.log.Error(derr, "Failed to cleanup device manager")
}
p.log.Error(err, "Failed to setup pulseaudio, playback will not function")
}
}
// block until the context is finished
for range ctx.Done() {
}
}
func (p *Server) handleAudio(conn *proxyproto.Conn) {
p.log.Info("Received audio proxy request, setting up pulseaudio/g-streamer")
defer conn.Close()
p.log.Info("Starting audio buffer")
// Create a new audio buffer
audioBuffer := audio.NewBuffer(&audio.BufferOpts{
Logger: p.log,
PulseServer: p.opts.PulseServer,
PulseMonitorSampleRate: p.opts.PlaybackSampleRate,
PulseMonitorName: p.opts.PlaybackDeviceName,
PulseMicName: p.opts.RecordingDeviceName,
PulseMicPath: p.opts.RecordingDevicePath,
})
// Start the audio buffer
if err := audioBuffer.Start(); err != nil {
conn.WriteError(err)
return
}
p.log.Info("Starting audio proxy")
if err := conn.WriteStatus(proxyproto.RequestOK); err != nil {
p.log.Error(err, "Failed to write response header")
return
}
stChan := p.logConnectionMetrics("audio", conn)
defer func() { stChan <- struct{}{} }()
// Copy audio playback data to the connection
go func() {
defer audioBuffer.Close()
if _, err := io.Copy(conn, audioBuffer); err != nil {
if !errors.IsBrokenPipeError(err) {
p.log.Error(err, "Error while copying from audio stream to websocket connection")
}
}
}()
// Copy any received recording data to the buffer
go func() {
defer audioBuffer.Close()
if _, err := io.Copy(audioBuffer, conn); err != nil {
if !errors.IsBrokenPipeError(err) {
p.log.Error(err, "Error while copying from websocket connection to audio buffer")
}
}
}()
// Block on the audio pipeline
audioBuffer.RunLoop()
p.log.Info("Audio stream proxy ended")
}
func (p *Server) handleStat(conn *proxyproto.Conn) {
defer conn.Close()
req := &proxyproto.FStatRequest{}
if err := conn.ReadStructure(req); err != nil {
p.log.Error(err, "Could not read stat request from client")
conn.WriteError(err)
return
}
p.log.Info(req.String())
path, err := getLocalPathFromRequest(req.Path)
if err != nil {
p.log.Error(err, "Could not retrieve path from request")
conn.WriteError(err)
return
}
finfo, err := os.Stat(path)
if err != nil {
conn.WriteError(err)
return
}
resp := &types.StatDesktopFileResponse{
Stat: &types.FileStat{
Name: finfo.Name(),
IsDirectory: finfo.IsDir(),
},
}
if finfo.IsDir() {
resp.Stat.Contents = make([]*types.FileStat, 0)
files, err := ioutil.ReadDir(path)
if err != nil {
conn.WriteError(err)
return
}
for _, file := range files {
resp.Stat.Contents = append(resp.Stat.Contents, &types.FileStat{
Name: file.Name(),
IsDirectory: file.IsDir(),
Size: file.Size(),
})
}
} else {
resp.Stat.Size = finfo.Size()
}
out, err := json.MarshalIndent(resp, "", " ")
if err != nil {
p.log.Error(err, "Failed to marshal response")
conn.WriteError(err)
return
}
if err := conn.WriteStatus(proxyproto.RequestOK); err != nil {
p.log.Error(err, "Failed to write response status header")
return
}
if _, err := conn.Write(out); err != nil {
p.log.Error(err, "Failed to copy response to client")
}
}
func (p *Server) handleGet(conn *proxyproto.Conn) {
defer conn.Close()
req := &proxyproto.FGetRequest{}
if err := conn.ReadStructure(req); err != nil {
p.log.Error(err, "Could not read get request from client")
conn.WriteError(err)
return
}
p.log.Info(req.String())
path, err := getLocalPathFromRequest(req.Path)
if err != nil {
p.log.Error(err, "Could not retrieve path from request")
conn.WriteError(err)
return
}
finfo, err := os.Stat(path)
if err != nil {
conn.WriteError(err)
return
}
if finfo.IsDir() {
serveDir(conn, path)
return
}
serveFile(conn, finfo, path)
}
func (p *Server) handlePut(conn *proxyproto.Conn) {
defer conn.Close()
req := &proxyproto.FPutRequest{}
if err := conn.ReadStructure(req); err != nil {
p.log.Error(err, "Could not read put request from client")
conn.WriteError(err)
return
}
p.log.Info(req.String())
uploadDir := filepath.Join(v1.DesktopHomeMntPath, "Uploads")
if err := os.MkdirAll(uploadDir, 0755); err != nil {
conn.WriteError(err)
return
}
if err := os.Chown(uploadDir, p.opts.FSUserID, p.opts.FSUserID); err != nil {
conn.WriteError(err)
return
}
fName := sanitize.BaseName(req.Name)
dstFile := filepath.Join(uploadDir, fName)
f, err := os.Create(dstFile)
if err != nil {
conn.WriteError(err)
return
}
defer f.Close()
if _, err := io.CopyN(f, req.Body, req.Size); err != nil {
conn.WriteError(err)
return
}
if err := os.Chown(dstFile, p.opts.FSUserID, p.opts.FSUserID); err != nil {
conn.WriteError(err)
return
}
if err := conn.WriteStatus(proxyproto.RequestOK); err != nil {
p.log.Error(err, "Error writing OK to connection")
}
}
func serveDir(conn *proxyproto.Conn, path string) {
tarball, err := common.TarDirectoryToTempFile(path)
if err != nil {
conn.WriteError(err)
return
}
finfo, err := os.Stat(tarball)
if err != nil {
conn.WriteError(err)
return
}
serveFile(conn, finfo, tarball)
}
func serveFile(conn *proxyproto.Conn, finfo os.FileInfo, path string) {
f, err := os.Open(path)
if err != nil {
conn.WriteError(err)
return
}
defer f.Close()
// Get the file header
hdr := make([]byte, 512)
if _, err := f.Read(hdr); err != nil {
conn.WriteError(errors.New("Failed to read header from file"))
return
}
// Seek back to the start of the file (since we read the header already)
if _, err := f.Seek(0, 0); err != nil {
conn.WriteError(errors.New("Failed to seek to beginning of file"))
return
}
// Get content type of file
contentType := http.DetectContentType(hdr)
conn.WriteResponse(&proxyproto.FGetResponse{
Name: filepath.Base(finfo.Name()),
Type: contentType,
Size: finfo.Size(),
Body: f,
})
}