-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathhttp.go
More file actions
484 lines (414 loc) · 13.8 KB
/
http.go
File metadata and controls
484 lines (414 loc) · 13.8 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
_ "net/http/pprof"
"runtime"
godebug "runtime/debug"
"strings"
"github.com/owulveryck/goMarkableStream/internal/delta"
internalDebug "github.com/owulveryck/goMarkableStream/internal/debug"
"github.com/owulveryck/goMarkableStream/internal/eventhttphandler"
"github.com/owulveryck/goMarkableStream/internal/jwtutil"
"github.com/owulveryck/goMarkableStream/internal/pubsub"
"github.com/owulveryck/goMarkableStream/internal/remarkable"
"github.com/owulveryck/goMarkableStream/internal/stream"
"github.com/owulveryck/goMarkableStream/internal/tlsutil"
"github.com/owulveryck/goMarkableStream/internal/trace"
)
type stripFS struct {
fs http.FileSystem
}
func (s stripFS) Open(name string) (http.File, error) {
return s.fs.Open("client" + name)
}
func setMuxer(eventPublisher *pubsub.PubSub, tm *TailscaleManager, restartCh chan<- bool, jwtMgr *jwtutil.Manager) *http.ServeMux {
mux := http.NewServeMux()
// Custom handler to serve index.html for root path
mux.HandleFunc("/", newIndexHandler(stripFS{http.FS(assetsFS)}, jwtMgr != nil))
// Login endpoint for JWT authentication
mux.HandleFunc("/login", handleLogin(jwtMgr))
streamHandler := stream.NewStreamHandler(file, pointerAddr, eventPublisher, c.DeltaThreshold)
mux.Handle("/stream", stream.ThrottlingMiddleware(streamHandler))
// Register idle callback to release memory when streaming ends
stream.SetOnIdleCallback(func() {
internalDebug.Log("Idle: releasing memory pools")
stream.ResetFrameBufferPool()
delta.ResetEncoderPool()
streamHandler.ReleaseMemory()
// Force garbage collection and return memory to OS
runtime.GC()
godebug.FreeOSMemory()
internalDebug.Log("Idle: memory returned to OS")
})
wsHandler := eventhttphandler.NewEventHandler(eventPublisher)
mux.Handle("/events", wsHandler)
gestureHandler := eventhttphandler.NewGestureHandler(eventPublisher)
mux.Handle("/gestures", gestureHandler)
screenshotHandler := stream.NewScreenshotHandler(file, pointerAddr)
mux.Handle("/screenshot", screenshotHandler)
// Version endpoint
mux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
bi, ok := godebug.ReadBuildInfo()
if !ok {
http.Error(w, "Unable to read build info", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "%s", bi.Main.Version)
})
// Funnel status and toggle endpoint
mux.HandleFunc("/funnel", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if tm == nil {
if err := json.NewEncoder(w).Encode(map[string]interface{}{
"available": false,
"enabled": false,
"url": "",
}); err != nil {
log.Printf("failed to encode JSON response: %v", err)
}
return
}
if r.Method == "POST" {
var req struct {
Enable bool `json:"enable"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Printf("Funnel toggle: failed to decode request: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Printf("Funnel toggle: requested enable=%v", req.Enable)
// Cancel active streams before toggling listener
stream.CancelActiveStreams()
_, err := tm.ToggleFunnel(req.Enable)
if err != nil {
log.Printf("Funnel toggle: failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Funnel toggle: success, enabled=%v", req.Enable)
// Manage temporary credentials based on Funnel state
if req.Enable {
// Generate temporary credentials when enabling Funnel
if funnelCreds != nil {
username, password := funnelCreds.Generate()
log.Printf("Funnel: temporary credentials generated (user: %s)", username)
_ = password // password is returned in response
}
} else {
// Clear temporary credentials when disabling Funnel
if funnelCreds != nil {
funnelCreds.Clear()
log.Println("Funnel: temporary credentials cleared")
}
}
// Signal main to restart Tailscale server goroutine
if restartCh != nil {
select {
case restartCh <- req.Enable:
log.Println("Funnel toggle: restart signal sent")
default:
log.Println("Funnel toggle: restart channel full, skipping signal")
}
}
}
enabled, url, err := tm.GetFunnelInfo()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response := map[string]interface{}{
"available": true,
"enabled": enabled,
"url": url,
}
// Include temporary credentials if Funnel is enabled and credentials are active
if enabled && funnelCreds != nil {
username, password, active := funnelCreds.GetCredentials()
if active {
response["tempCredentials"] = map[string]string{
"username": username,
"password": password,
}
}
}
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("failed to encode JSON response: %v", err)
}
})
// Trace endpoints (only when tracing build tag is enabled)
if hasTraceSupport && c.TraceEnabled {
mux.HandleFunc("/trace/status", handleTraceStatus)
mux.HandleFunc("/trace/start", handleTraceStart)
mux.HandleFunc("/trace/stop", handleTraceStop)
mux.HandleFunc("/trace/files", handleTraceFiles)
mux.HandleFunc("/trace/download/", handleTraceDownload)
// pprof endpoints with authentication
// pprof handlers are registered at /debug/pprof/ by the import
// We need to wrap them with our auth middleware
mux.Handle("/debug/pprof/", http.StripPrefix("/debug/pprof", http.DefaultServeMux))
}
if c.DevMode {
rawHandler := stream.NewRawHandler(file, pointerAddr)
mux.Handle("/raw", rawHandler)
}
return mux
}
func parseIndexTemplate(templatePath string) (*template.Template, error) {
indexData, err := assetsFS.ReadFile(templatePath)
if err != nil {
return nil, err
}
tmpl, err := template.New("index.html").Parse(string(indexData))
if err != nil {
return nil, err
}
return tmpl, nil
}
// handleLogin handles the /login endpoint for JWT authentication.
func handleLogin(jwtMgr *jwtutil.Manager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Check if JWT is enabled
if jwtMgr == nil {
http.Error(w, "JWT authentication not enabled", http.StatusServiceUnavailable)
return
}
// Parse request body
var req struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid request body"})
return
}
// Validate credentials
if !checkCredentials(req.Username, req.Password) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid credentials"})
return
}
// Create JWT token
token, err := jwtMgr.CreateToken(req.Username)
if err != nil {
log.Printf("Failed to create JWT token: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to create token"})
return
}
// Return token
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"token": token,
"expiresIn": int64(jwtMgr.GetTokenLifetime().Seconds()),
})
}
}
func newIndexHandler(fs http.FileSystem, jwtEnabled bool) http.HandlerFunc {
tmpl, err := parseIndexTemplate("client/index.html")
if err != nil {
log.Fatalf("Error parsing index template: %v", err)
panic(err)
}
staticFileServer := http.FileServer(fs)
data := struct {
ScreenWidth int
ScreenHeight int
MaxXValue int
MaxYValue int
DeviceModel string
UseBGRA bool
TextureFlipped bool
JWTEnabled bool
}{
ScreenWidth: remarkable.Config.Width,
ScreenHeight: remarkable.Config.Height,
MaxXValue: remarkable.MaxXValue,
MaxYValue: remarkable.MaxYValue,
DeviceModel: remarkable.Model.String(),
UseBGRA: remarkable.Config.UseBGRA,
TextureFlipped: remarkable.Config.TextureFlipped,
JWTEnabled: jwtEnabled,
}
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
w.Header().Set("Content-Type", "text/html")
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, "Error rendering template", http.StatusInternalServerError)
log.Printf("Error rendering template: %v", err)
}
return
}
staticFileServer.ServeHTTP(w, r)
}
}
func runTLS(l net.Listener, server *http.Server, tlsMgr *tlsutil.Manager) error {
tlsConfig, _, err := tlsMgr.GetTLSConfig()
if err != nil {
return fmt.Errorf("failed to get TLS config: %w", err)
}
tlsListener := tls.NewListener(l, tlsConfig)
// Start the server
return server.Serve(tlsListener)
}
// createTLSManager creates a TLS manager from the configuration.
func createTLSManager(cfg *configuration) *tlsutil.Manager {
// Load embedded certificates as fallback
embeddedCert, certErr := tlsAssets.ReadFile("assets/cert.pem")
embeddedKey, keyErr := tlsAssets.ReadFile("assets/key.pem")
var cert, key []byte
if certErr == nil && keyErr == nil {
cert = embeddedCert
key = embeddedKey
}
return tlsutil.NewManager(tlsutil.ManagerConfig{
CertFile: cfg.TLSCertFile,
KeyFile: cfg.TLSKeyFile,
CertDir: cfg.TLSCertDir,
AutoGenerate: cfg.TLSAutoGenerate,
Hostnames: cfg.TLSHostnames,
ValidDays: cfg.TLSValidDays,
ExpiryThresholdDays: 30,
EmbeddedCert: cert,
EmbeddedKey: key,
})
}
// Trace HTTP handlers
func handleTraceStatus(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
status := trace.GetStatus()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(status); err != nil {
log.Printf("Failed to encode trace status: %v", err)
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
func handleTraceStart(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Mode string `json:"mode"` // "runtime", "spans", or "both"
}
// Default to configured mode if not specified
req.Mode = c.TraceMode
// Try to decode request body
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF {
log.Printf("Trace start: failed to decode request: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := trace.Start(req.Mode); err != nil {
log.Printf("Failed to start trace: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "started",
"mode": req.Mode,
})
}
func handleTraceStop(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
files, err := trace.Stop()
if err != nil {
log.Printf("Failed to stop trace: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "stopped",
"files": files,
})
}
func handleTraceFiles(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if r.Method == http.MethodDelete {
// Delete a specific file
var req struct {
Filename string `json:"filename"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := trace.DeleteFile(req.Filename); err != nil {
log.Printf("Failed to delete trace file %s: %v", req.Filename, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "deleted",
"file": req.Filename,
})
return
}
// GET - list files
files, err := trace.ListFiles()
if err != nil {
log.Printf("Failed to list trace files: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(files); err != nil {
log.Printf("Failed to encode trace files: %v", err)
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
func handleTraceDownload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Extract filename from path
filename := strings.TrimPrefix(r.URL.Path, "/trace/download/")
if filename == "" {
http.Error(w, "Filename required", http.StatusBadRequest)
return
}
// Get file path (validates filename)
filePath, err := trace.GetFilePath(filename)
if err != nil {
log.Printf("Failed to get trace file %s: %v", filename, err)
http.Error(w, "File not found", http.StatusNotFound)
return
}
// Set content type based on file extension
if strings.HasSuffix(filename, ".trace") {
w.Header().Set("Content-Type", "application/octet-stream")
} else if strings.HasSuffix(filename, ".jsonl") {
w.Header().Set("Content-Type", "application/x-ndjson")
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
http.ServeFile(w, r, filePath)
}