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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strconv"
"strings"
varlinklib "codeberg.org/Profpatsch/Profpatsch/users/Profpatsch/varlink-lib"
"github.com/varlink/go/varlink/idl"
)
// Proxy handles HTTP to varlink translation
type Proxy struct {
services map[string]string // interface name -> socket address
debug bool
}
// fetchIDL fetches and parses the IDL for a given interface from its socket
func (p *Proxy) fetchIDL(socketAddr, interfaceName string) (*idl.IDL, error) {
conn, err := varlinklib.DialVarlinkSocket(socketAddr)
if err != nil {
return nil, fmt.Errorf("failed to connect to %s: %w", socketAddr, err)
}
defer conn.Close()
// Manually build and send GetInterfaceDescription call
call := map[string]any{
"method": "org.varlink.service.GetInterfaceDescription",
"parameters": map[string]any{"interface": interfaceName},
}
callJSON, err := json.Marshal(call)
if err != nil {
return nil, fmt.Errorf("failed to marshal call: %w", err)
}
// Send with null terminator
if _, err := conn.Write(append(callJSON, 0)); err != nil {
return nil, fmt.Errorf("failed to write call: %w", err)
}
// Read response
scanner := bufio.NewScanner(conn)
scanner.Split(scanNullTerminated)
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
return nil, fmt.Errorf("no response from service")
}
var response map[string]any
if err := json.Unmarshal(scanner.Bytes(), &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
// Check for errors
if errMsg, hasErr := response["error"]; hasErr {
return nil, fmt.Errorf("varlink error: %v", errMsg)
}
// Extract interface description
params, ok := response["parameters"].(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid response: missing parameters")
}
description, ok := params["description"].(string)
if !ok {
return nil, fmt.Errorf("invalid response: missing description")
}
// Parse IDL
parsedIDL, err := idl.New(description)
if err != nil {
return nil, fmt.Errorf("failed to parse IDL: %w", err)
}
if p.debug {
log.Printf("Fetched IDL for %s: %d methods\n", interfaceName, len(parsedIDL.Methods))
}
return parsedIDL, nil
}
// handleHTTP routes incoming HTTP requests to varlink services
func (p *Proxy) handleHTTP(w http.ResponseWriter, r *http.Request) {
// Handle resource requests
if r.URL.Path == "/r" && r.Method == http.MethodGet {
p.handleResourceRequest(w, r)
return
}
// Handle results page
if r.URL.Path == "/results" && r.Method == http.MethodGet {
p.handleResults(w, r)
return
}
// Handle GET requests for HTML UI
if r.Method == http.MethodGet {
p.handleGET(w, r)
return
}
// Handle POST requests
if r.Method == http.MethodPost {
p.handlePOST(w, r)
return
}
http.Error(w, "Only GET and POST methods are allowed", http.StatusMethodNotAllowed)
}
// handleGET handles GET requests for HTML UI
func (p *Proxy) handleGET(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
// Index page - list all interfaces
if path == "" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
renderIndexHTML(w, p.services)
return
}
// Interface page - show forms for methods
interfaceName := path
socketAddr, exists := p.services[interfaceName]
if !exists {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
renderErrorHTML(w, "Interface Not Found", fmt.Sprintf("Unknown interface: %s", interfaceName))
return
}
// Fetch fresh IDL
parsedIDL, err := p.fetchIDL(socketAddr, interfaceName)
if err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusServiceUnavailable)
renderErrorHTML(w, "Failed to Fetch Interface",
fmt.Sprintf("Could not fetch IDL for %s: %v. The service may be down or unreachable.", interfaceName, err))
return
}
if p.debug {
log.Printf("Rendering interface page for %s at %s\n", interfaceName, socketAddr)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
renderInterfaceHTML(w, interfaceName, parsedIDL)
}
// handlePOST handles POST requests (both form submissions and varlink protocol)
func (p *Proxy) handlePOST(w http.ResponseWriter, r *http.Request) {
// Extract interface name from path
interfaceName := strings.TrimPrefix(r.URL.Path, "/")
if interfaceName == "" {
p.writeError(w, http.StatusBadRequest, "Path must specify interface name (e.g., /de.profpatsch.ClaudeLastPosition)")
return
}
// Find socket address for this interface
socketAddr, exists := p.services[interfaceName]
if !exists {
p.writeError(w, http.StatusNotFound, fmt.Sprintf("Unknown interface: %s", interfaceName))
return
}
// Check content type to determine handling
contentType := r.Header.Get("Content-Type")
// Form submission
if strings.Contains(contentType, "application/x-www-form-urlencoded") {
p.handleFormSubmission(w, r, interfaceName, socketAddr)
return
}
// Varlink protocol (existing handler)
if err := p.proxyToVarlink(w, r, socketAddr); err != nil {
log.Printf("Proxy error for %s: %v\n", interfaceName, err)
// Don't write error here - connection might already be in use
}
}
// proxyToVarlink handles bidirectional streaming between HTTP and varlink
func (p *Proxy) proxyToVarlink(w http.ResponseWriter, r *http.Request, socketAddr string) error {
// Check if response supports flushing (required for streaming)
flusher, ok := w.(http.Flusher)
if !ok {
return fmt.Errorf("streaming not supported by response writer")
}
// Set headers for streaming response
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("X-Content-Type-Options", "nosniff")
// Parse socket address and dial raw connection with retry logic
conn, err := varlinklib.DialVarlinkSocketWithRetry(socketAddr)
if err != nil {
p.writeError(w, http.StatusServiceUnavailable, fmt.Sprintf("Failed to connect to varlink service: %v", err))
return err
}
defer conn.Close()
if p.debug {
log.Printf("Connected to %s for request %s\n", socketAddr, r.URL.Path)
}
// Channel for errors from goroutines
errChan := make(chan error, 2)
// Goroutine: HTTP request → varlink socket
go func() {
if err := p.forwardHTTPToVarlink(r.Body, conn); err != nil {
errChan <- fmt.Errorf("HTTP->varlink: %w", err)
} else {
errChan <- nil
}
// Close write side to signal EOF to varlink
if tcpConn, ok := conn.(*net.UnixConn); ok {
tcpConn.CloseWrite()
}
}()
// Main goroutine: varlink socket → HTTP response
// This runs in the main goroutine so we can write to the response
go func() {
if err := p.forwardVarlinkToHTTP(w, conn, flusher); err != nil {
errChan <- fmt.Errorf("varlink->HTTP: %w", err)
} else {
errChan <- nil
}
}()
// Wait for both directions to complete (or error)
for range 2 {
if err := <-errChan; err != nil {
log.Printf("Streaming error: %v\n", err)
return err
}
}
if p.debug {
log.Printf("Request completed for %s\n", r.URL.Path)
}
return nil
}
// forwardHTTPToVarlink reads \0-delimited messages from HTTP request and forwards to varlink
func (p *Proxy) forwardHTTPToVarlink(httpBody io.Reader, varlinkConn net.Conn) error {
scanner := bufio.NewScanner(httpBody)
scanner.Split(scanNullTerminated)
for scanner.Scan() {
message := scanner.Bytes()
if p.debug {
log.Printf("HTTP->varlink: %s\n", message)
}
// Forward message to varlink socket with \0 terminator
toSend := append(message, 0)
if _, err := varlinkConn.Write(toSend); err != nil {
return fmt.Errorf("failed to write to varlink: %w", err)
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("scanner error: %w", err)
}
return nil
}
// forwardVarlinkToHTTP reads \0-delimited messages from varlink and forwards to HTTP response
func (p *Proxy) forwardVarlinkToHTTP(w io.Writer, varlinkConn net.Conn, flusher http.Flusher) error {
scanner := bufio.NewScanner(varlinkConn)
scanner.Split(scanNullTerminated)
for scanner.Scan() {
message := scanner.Bytes()
if p.debug {
log.Printf("varlink->HTTP: %s\n", message)
}
// Write message + \0 to HTTP response
if _, err := w.Write(message); err != nil {
return fmt.Errorf("failed to write to HTTP: %w", err)
}
if _, err := w.Write([]byte{0}); err != nil {
return fmt.Errorf("failed to write terminator: %w", err)
}
// CRITICAL: Flush immediately for streaming to work
flusher.Flush()
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("scanner error: %w", err)
}
return nil
}
// scanNullTerminated is a split function for bufio.Scanner that splits on \0 bytes
func scanNullTerminated(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Look for null byte
for i := range data {
if data[i] == 0 {
// Found null terminator, return everything before it
return i + 1, data[0:i], nil
}
}
// If we're at EOF and have data, return it
if atEOF && len(data) > 0 {
return len(data), data, nil
}
// Need more data
return 0, nil, nil
}
// handleFormSubmission handles form submissions from the HTML UI
func (p *Proxy) handleFormSubmission(w http.ResponseWriter, r *http.Request, interfaceName, socketAddr string) {
if err := r.ParseForm(); err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
renderErrorHTML(w, "Form Parse Error", fmt.Sprintf("Failed to parse form: %v", err))
return
}
methodName := r.Form.Get("method")
if methodName == "" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
renderErrorHTML(w, "Missing Method", "Form must include 'method' field")
return
}
// Build parameters from form data
// Always use nested field parser to support dotted notation (e.g., "scope.mailbox_dir")
// This works for both IDL-defined methods and HATEOAS-discovered methods
params := parseNestedFormFields(r.Form)
// Special handling for InvokeAction: wrap action-specific params into "parameters" object
if methodName == "InvokeAction" {
// Extract token and action from top-level params
token, hasToken := params["token"]
action, hasAction := params["action"]
if hasToken && hasAction {
// Create new parameters object with just token, action, and wrapped parameters
actionParams := make(map[string]any)
// Move all other fields (except token and action) into nested "parameters"
for key, value := range params {
if key != "token" && key != "action" {
actionParams[key] = value
}
}
// Rebuild params structure for InvokeAction
params = map[string]any{
"token": token,
"action": action,
"parameters": actionParams,
}
}
}
// Make varlink call
fullMethodName := interfaceName + "." + methodName
varlinkCall := map[string]any{
"method": fullMethodName,
"parameters": params,
}
callJSON, err := json.Marshal(varlinkCall)
if err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
renderErrorHTML(w, "Internal Error", fmt.Sprintf("Failed to marshal call: %v", err))
return
}
if p.debug {
log.Printf("Form submission: %s\n", string(callJSON))
}
// Call varlink service with retry logic
conn, err := varlinklib.DialVarlinkSocketWithRetry(socketAddr)
if err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusServiceUnavailable)
renderErrorHTML(w, "Service Unavailable", fmt.Sprintf("Failed to connect: %v", err))
return
}
defer conn.Close()
// Send call
callWithNull := append(callJSON, 0)
if _, err := conn.Write(callWithNull); err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
renderErrorHTML(w, "Call Failed", fmt.Sprintf("Failed to send call: %v", err))
return
}
// Read response
scanner := bufio.NewScanner(conn)
scanner.Split(scanNullTerminated)
if !scanner.Scan() {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
renderErrorHTML(w, "No Response", "Failed to read response from service")
return
}
responseBytes := scanner.Bytes()
if p.debug {
log.Printf("Form response: %s\n", string(responseBytes))
}
// Parse response
var varlinkReply map[string]any
if err := json.Unmarshal(responseBytes, &varlinkReply); err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
renderErrorHTML(w, "Parse Error", fmt.Sprintf("Failed to parse response: %v", err))
return
}
// URL-encode the response and redirect to results page
responseJSON, err := json.Marshal(varlinkReply)
if err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
renderErrorHTML(w, "Encoding Error", fmt.Sprintf("Failed to encode response: %v", err))
return
}
// Also encode the original parameters for resource URL generation
paramsJSON, err := json.Marshal(params)
if err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
renderErrorHTML(w, "Encoding Error", fmt.Sprintf("Failed to encode parameters: %v", err))
return
}
// Build redirect URL with query parameters
resultsURL := fmt.Sprintf("/results?interface=%s&method=%s&response=%s&request_params=%s",
url.QueryEscape(interfaceName),
url.QueryEscape(methodName),
url.QueryEscape(string(responseJSON)),
url.QueryEscape(string(paramsJSON)))
// Redirect using 303 See Other (POST -> GET redirect)
http.Redirect(w, r, resultsURL, http.StatusSeeOther)
}
// handleResults handles the GET /results page
func (p *Proxy) handleResults(w http.ResponseWriter, r *http.Request) {
// Parse query parameters
interfaceName := r.URL.Query().Get("interface")
methodName := r.URL.Query().Get("method")
responseStr := r.URL.Query().Get("response")
requestParamsStr := r.URL.Query().Get("request_params")
if interfaceName == "" || methodName == "" || responseStr == "" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
renderErrorHTML(w, "Missing Parameters", "Required query parameters: interface, method, response")
return
}
// Decode the response JSON
var varlinkReply map[string]any
if err := json.Unmarshal([]byte(responseStr), &varlinkReply); err != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
renderErrorHTML(w, "Invalid Response", fmt.Sprintf("Failed to decode response: %v", err))
return
}
// Decode the request parameters if provided
var requestParams map[string]any
if requestParamsStr != "" {
if err := json.Unmarshal([]byte(requestParamsStr), &requestParams); err != nil {
if p.debug {
log.Printf("Failed to decode request parameters: %v\n", err)
}
// Not fatal - continue without resource URL generation
}
}
// Generate resource URLs if we have request params and resources in the response
var resourceURLs map[string]string // maps resource path to full URL
if requestParams != nil {
if params, ok := varlinkReply["parameters"].(map[string]any); ok {
if resourceType, ok := params["resource_type"].(string); ok && resourceType == "http_listing" {
if resources, ok := params["resources"].([]any); ok {
resourceURLs = make(map[string]string)
socketAddr := p.services[interfaceName]
fullMethodName := interfaceName + "." + methodName
for _, res := range resources {
if resMap, ok := res.(map[string]any); ok {
if path, ok := resMap["path"].(string); ok {
// Build resource request
resourceReq := varlinklib.ResourceRequest{
Service: socketAddr,
Method: fullMethodName,
Parameters: requestParams,
Path: path,
}
// Encode to URL
if encodedURL, err := varlinklib.EncodeResourceURL(resourceReq); err == nil {
resourceURLs[path] = encodedURL
} else if p.debug {
log.Printf("Failed to encode resource URL for path %s: %v\n", path, err)
}
}
}
}
}
}
}
}
// Check for errors in the varlink reply
hasError := false
if _, hasErr := varlinkReply["error"]; hasErr {
hasError = true
}
// Render the results page
w.Header().Set("Content-Type", "text/html; charset=utf-8")
renderResultsHTML(w, interfaceName, methodName, varlinkReply, hasError, resourceURLs)
}
// autoConvertValue automatically converts a form value to the appropriate type
// by trying to parse it as int, float, bool, JSON, or defaulting to string
func autoConvertValue(value string) any {
// Try parsing as int
if intVal, err := strconv.ParseInt(value, 10, 64); err == nil {
return intVal
}
// Try parsing as float
if floatVal, err := strconv.ParseFloat(value, 64); err == nil {
return floatVal
}
// Try parsing as bool
if value == "true" {
return true
}
if value == "false" {
return false
}
// Try parsing as JSON (for arrays, complex objects from textareas)
var jsonVal any
if err := json.Unmarshal([]byte(value), &jsonVal); err == nil {
return jsonVal
}
// Default to string
return value
}
// parseNestedFormFields converts dotted field names back into nested objects and arrays
// e.g., "scope.mailbox_dir" and "scope.max_age_days" -> {"scope": {"mailbox_dir": "...", "max_age_days": 7}}
// Array indices: "messages.[0]", "messages.[1]" -> {"messages": ["...", "..."]}
func parseNestedFormFields(formData map[string][]string) map[string]any {
result := make(map[string]any)
for key, values := range formData {
if key == "method" {
continue // Skip the method field
}
if len(values) == 0 || values[0] == "" {
continue // Skip empty values
}
value := values[0]
// Split on dots to get path
parts := strings.Split(key, ".")
// Navigate/create nested structure
current := result
for i, part := range parts {
// Check if this part is an array index like [0]
if strings.HasPrefix(part, "[") && strings.HasSuffix(part, "]") {
// Extract the numeric index
indexStr := part[1 : len(part)-1]
// Use the index string as the key (will be converted to array later)
part = indexStr
}
if i == len(parts)-1 {
// Last part - set the value with type conversion
current[part] = autoConvertValue(value)
} else {
// Intermediate part - ensure map exists
if _, exists := current[part]; !exists {
current[part] = make(map[string]any)
}
// Type assertion with safety check
if nested, ok := current[part].(map[string]any); ok {
current = nested
} else {
// Conflict: this path was already set as a non-map value
// Skip this field to avoid overwriting
break
}
}
}
}
// Post-process: convert objects with all-numeric keys to arrays
converted := convertNumericMapsToArrays(result)
if resultMap, ok := converted.(map[string]any); ok {
return resultMap
}
// Should never happen since we start with a map
return result
}
// convertNumericMapsToArrays recursively converts maps with all-numeric keys to arrays
func convertNumericMapsToArrays(data any) any {
switch v := data.(type) {
case map[string]any:
// Check if all keys are numeric
allNumeric := true
maxIndex := -1
for key := range v {
if index, err := strconv.Atoi(key); err == nil && index >= 0 {
if index > maxIndex {
maxIndex = index
}
} else {
allNumeric = false
break
}
}
if allNumeric && len(v) > 0 {
// Convert to array
arr := make([]any, maxIndex+1)
for key, value := range v {
index, _ := strconv.Atoi(key)
arr[index] = convertNumericMapsToArrays(value)
}
return arr
}
// Regular object - recursively process values
result := make(map[string]any)
for key, value := range v {
result[key] = convertNumericMapsToArrays(value)
}
return result
case []any:
// Recursively process array elements
result := make([]any, len(v))
for i, item := range v {
result[i] = convertNumericMapsToArrays(item)
}
return result
default:
// Primitive values - return as-is
return v
}
}
// convertFormValue converts a form string value to the appropriate type
func convertFormValue(value string, t *idl.Type) (any, error) {
switch t.Kind {
case idl.TypeBool:
return value == "true" || value == "on", nil
case idl.TypeInt:
return strconv.ParseInt(value, 10, 64)
case idl.TypeFloat:
return strconv.ParseFloat(value, 64)
case idl.TypeString:
return value, nil
case idl.TypeMaybe:
if t.ElementType != nil {
return convertFormValue(value, t.ElementType)
}
return value, nil
default:
// For complex types, try to parse as JSON
var result any
if err := json.Unmarshal([]byte(value), &result); err != nil {
return nil, fmt.Errorf("failed to parse as JSON: %w", err)
}
return result, nil
}
}
// writeError writes an error message to the HTTP response
func (p *Proxy) writeError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(status)
fmt.Fprintf(w, "Error: %s\n", message)
}
// rewriteResourceURLs rewrites resource paths to full /r/{encoded} URLs
func (p *Proxy) rewriteResourceURLs(resources []any, socketAddr, method string, originalParams map[string]any) {
for _, res := range resources {
resMap, ok := res.(map[string]any)
if !ok {
continue
}
// Get the resource path
path, ok := resMap["path"].(string)
if !ok {
continue
}
// Build resource request
resourceReq := varlinklib.ResourceRequest{
Service: socketAddr,
Method: method,
Parameters: originalParams,
Path: path,
}
// Encode to URL
encodedURL, err := varlinklib.EncodeResourceURL(resourceReq)
if err != nil {
log.Printf("Failed to encode resource URL: %v\n", err)
continue
}
// Replace path with full URL
resMap["url"] = encodedURL
if p.debug {
log.Printf("Rewrote resource path %s -> %s\n", path, encodedURL)
}
}
}
// handleResourceRequest handles GET /r?request={encoded} requests for binary resources
func (p *Proxy) handleResourceRequest(w http.ResponseWriter, r *http.Request) {
// Decode the resource URL (includes query parameters)
fullURL := r.URL.Path
if r.URL.RawQuery != "" {
fullURL = fullURL + "?" + r.URL.RawQuery
}
req, err := varlinklib.DecodeResourceURL(fullURL)
if err != nil {
p.writeError(w, http.StatusBadRequest, fmt.Sprintf("Invalid resource URL: %v", err))
return
}
if p.debug {
log.Printf("Resource request: service=%s method=%s path=%s\n", req.Service, req.Method, req.Path)
}
// Connect to varlink service
conn, err := varlinklib.DialVarlinkSocketWithRetry(req.Service)
if err != nil {
p.writeError(w, http.StatusServiceUnavailable, fmt.Sprintf("Failed to connect to service: %v", err))
return
}
defer conn.Close()
// Add upgrade_to_http_serve=true to parameters
// For InvokeAction calls, upgrade_to_http_serve goes in the nested parameters object
if strings.HasSuffix(req.Method, ".InvokeAction") {
if actionParams, ok := req.Parameters["parameters"].(map[string]any); ok {
actionParams["upgrade_to_http_serve"] = true
}
} else {
// For direct method calls, add at top level
req.Parameters["upgrade_to_http_serve"] = true
}
// Build and send varlink call
varlinkCall := map[string]any{
"method": req.Method,
"parameters": req.Parameters,
}
callJSON, err := json.Marshal(varlinkCall)
if err != nil {
p.writeError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to marshal call: %v", err))
return
}
// Send varlink call
if _, err := conn.Write(append(callJSON, 0)); err != nil {
p.writeError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to send call: %v", err))
return
}
// Read varlink reply (upgrade confirmation)
scanner := bufio.NewScanner(conn)
scanner.Split(scanNullTerminated)
if !scanner.Scan() {
p.writeError(w, http.StatusInternalServerError, "Failed to read upgrade confirmation")
return
}
var reply map[string]any
if err := json.Unmarshal(scanner.Bytes(), &reply); err != nil {
p.writeError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to parse reply: %v", err))
return
}
// Check for error in reply
if errMsg, hasErr := reply["error"]; hasErr {
p.writeError(w, http.StatusBadRequest, fmt.Sprintf("Varlink error: %v", errMsg))
return
}
// Verify upgrade happened
// Check in parameters for upgraded flag
var upgraded bool
if params, ok := reply["parameters"].(map[string]any); ok {
upgraded, _ = params["upgraded"].(bool)
}
if !upgraded {
p.writeError(w, http.StatusInternalServerError, "Service did not confirm upgrade")
return
}
if p.debug {
log.Printf("Connection upgraded, requesting HTTP path: %s\n", req.Path)
}
// Now connection is in HTTP mode - send HTTP GET request
httpReq := fmt.Sprintf("GET %s HTTP/1.1\r\nHost: localhost\r\n\r\n", req.Path)
if _, err := conn.Write([]byte(httpReq)); err != nil {
p.writeError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to send HTTP request: %v", err))
return
}
// Read HTTP response from connection
httpResp, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
p.writeError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to read HTTP response: %v", err))
return
}
defer httpResp.Body.Close()
// Copy headers from service response
for key, values := range httpResp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
// Write status code
w.WriteHeader(httpResp.StatusCode)
// Stream body to client
if _, err := io.Copy(w, httpResp.Body); err != nil {
log.Printf("Error streaming response body: %v\n", err)
}
if p.debug {
log.Printf("Resource request completed: %s\n", req.Path)
}
}
|