-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1001 lines (970 loc) · 31.3 KB
/
Copy pathmain.go
File metadata and controls
1001 lines (970 loc) · 31.3 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
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto/rand"
"embed"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
//go:embed static/*
var staticFiles embed.FS
//go:embed snapshot.ps1
var snapshotScript string
const defaultPort = 22880
var (
capabilityToken string
snapshotSem = make(chan struct{}, 2)
wslSem = make(chan struct{}, 1)
reclaimSem = make(chan struct{}, 1)
wslConfigSem = make(chan struct{}, 1)
runtimeRestartSem = make(chan struct{}, 1)
)
// zero-alloc envelope validation types (H4T1)
type envelopeTop struct {
Data json.RawMessage `json:"data"`
LegacyMemory json.RawMessage `json:"Memory"`
}
type dataMem struct {
Memory json.RawMessage `json:"Memory"`
}
type memFields struct {
VisiblePhysicalBytes *int64 `json:"VisiblePhysicalBytes"`
InUseBytes *int64 `json:"InUseBytes"`
AvailableBytes *int64 `json:"AvailableBytes"`
}
func main() {
var headless bool
var once bool
var output string
var pretty bool
redact := true
flag.BoolVar(&headless, "headless", false, "Run in headless mode (write snapshot JSON to stdout or file, no HTTP server)")
flag.BoolVar(&once, "once", false, "Alias for --headless (run once then exit)")
flag.StringVar(&output, "output", "", "Output file for headless mode (default stdout)")
flag.BoolVar(&pretty, "pretty", false, "Pretty-print JSON in headless mode")
flag.BoolVar(&redact, "redact", true, "Redact CommandLine/Command fields in headless output (default true)")
portFlag := flag.Int("port", 0, "Explicit port to run the server on (overrides auto-detection)")
flag.Parse()
if headless || once {
runHeadless(output, pretty, redact)
return
}
var port int
if *portFlag > 0 {
ln, err := net.Listen("tcp", net.JoinHostPort(net.IPv4(127,0,0,1).String(), strconv.Itoa(*portFlag)))
if err != nil {
log.Fatalf("Port %d is already in use. Please select a different port.", *portFlag)
}
ln.Close()
port = *portFlag
} else {
port = findAvailablePort(defaultPort)
}
addr := net.JoinHostPort(net.IPv4(127,0,0,1).String(), strconv.Itoa(port))
capabilityToken = generateToken()
staticFS, err := fs.Sub(staticFiles, "static")
if err != nil {
log.Fatalf("Error sub-embedding static files: %v", err)
}
mux := http.NewServeMux()
mux.HandleFunc("/api/snapshot", handleSnapshot)
mux.HandleFunc("/api/wsl/shutdown", handleWslShutdown)
mux.HandleFunc("/api/wsl/config", handleWslConfig)
mux.HandleFunc("/api/reclaim/standby", handleReclaimStandby)
mux.HandleFunc("/api/runtime/restart", handleRuntimeRestart)
mux.HandleFunc("/api/config", handleConfig)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
path = "index.html"
}
if path != "index.html" {
if _, err := fs.Stat(staticFS, path); err != nil {
http.NotFound(w, r)
return
}
}
if path == "index.html" {
serveIndexWithToken(w, r, staticFS)
return
}
http.FileServer(http.FS(staticFS)).ServeHTTP(w, r)
})
server := &http.Server{
Addr: addr,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
serverUrl := fmt.Sprintf("http://localhost:%d", port)
fmt.Printf("=========================================\n")
fmt.Printf("SysView Diagnostics Utility\n")
fmt.Printf("Server listening on: %s\n", serverUrl)
fmt.Printf("Press Ctrl+C in this terminal to exit.\n")
fmt.Printf("=========================================\n")
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server failed to start: %v", err)
}
}()
openBrowser(serverUrl)
select {}
}
func generateToken() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
log.Fatalf("Failed to generate token: %v", err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
func serveIndexWithToken(w http.ResponseWriter, r *http.Request, fsys fs.FS) {
data, err := fs.ReadFile(fsys, "index.html")
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
html := string(data)
if strings.Contains(html, "__SYSVIEW_TOKEN__") {
html = strings.ReplaceAll(html, "__SYSVIEW_TOKEN__", capabilityToken)
} else {
inject := fmt.Sprintf(`<meta name="sysview-token" content="%s"><script>window.__SYSVIEW_TOKEN__="%s";</script>`, capabilityToken, capabilityToken)
html = strings.Replace(html, "</head>", inject+"</head>", 1)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-SysView-Token", capabilityToken)
_, _ = io.WriteString(w, html)
}
func handleConfig(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, `{"error":"Method not allowed"}`, http.StatusMethodNotAllowed)
return
}
if !isSameOrigin(r) {
http.Error(w, `{"error":"Forbidden origin"}`, http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]string{"token": capabilityToken})
}
func isSameOrigin(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin != "" {
if !(strings.HasPrefix(origin, "http://localhost:") || strings.HasPrefix(origin, "http://"+net.IPv4(127,0,0,1).String()+":")) {
return false
}
}
sfs := r.Header.Get("Sec-Fetch-Site")
if sfs != "" && sfs != "same-origin" && sfs != "none" {
if r.Method == http.MethodPost && sfs == "cross-site" {
return false
}
}
host := r.Host
if host != "" {
h, _, err := net.SplitHostPort(host)
if err != nil {
h = host
}
if h != "localhost" && h != net.IPv4(127,0,0,1).String() {
return false
}
}
return true
}
func requireToken(r *http.Request) bool {
tok := r.Header.Get("X-SysView-Token")
if tok == "" {
tok = r.Header.Get("X-Sysview-Token")
}
if tok == "" {
tok = r.URL.Query().Get("token")
}
return tok != "" && tok == capabilityToken
}
func validateEnvelope(raw []byte) error {
var env envelopeTop
if err := json.Unmarshal(raw, &env); err != nil {
return err
}
if env.Data == nil && env.LegacyMemory == nil {
return fmt.Errorf("missing data/Memory")
}
if env.Data != nil {
var dm dataMem
if err := json.Unmarshal(env.Data, &dm); err == nil {
if dm.Memory != nil {
return validateMemoryRaw(dm.Memory)
}
}
}
return nil
}
func validateMemoryRaw(memRaw json.RawMessage) error {
var mem memFields
if err := json.Unmarshal(memRaw, &mem); err != nil {
return err
}
if mem.VisiblePhysicalBytes == nil {
return fmt.Errorf("missing Memory.VisiblePhysicalBytes")
}
if mem.InUseBytes == nil {
return fmt.Errorf("missing Memory.InUseBytes")
}
if mem.AvailableBytes == nil {
return fmt.Errorf("missing Memory.AvailableBytes")
}
return nil
}
func handleSnapshot(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, `{"error":"Method not allowed. Use GET."}`, http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("X-Content-Type-Options", "nosniff")
select {
case snapshotSem <- struct{}{}:
defer func() { <-snapshotSem }()
default:
http.Error(w, `{"error":"Snapshot busy, try again"}`, http.StatusTooManyRequests)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
defer cancel()
tmpFile, err := os.CreateTemp("", "snapshot-*.ps1")
if err != nil {
http.Error(w, `{"error":"Failed to create temp file"}`, http.StatusInternalServerError)
return
}
if _, err := tmpFile.WriteString(snapshotScript); err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
http.Error(w, `{"error":"Failed to write temp file"}`, http.StatusInternalServerError)
return
}
tmpFile.Close()
defer os.Remove(tmpFile.Name())
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", tmpFile.Name())
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
http.Error(w, `{"error":"Snapshot timed out"}`, http.StatusGatewayTimeout)
return
}
if err != nil {
log.Printf("PowerShell Execution Error: %v\nStderr: %s\n", err, stderr.String())
http.Error(w, fmt.Sprintf(`{"error": "PowerShell collection failed", "details": %q}`, stderr.String()), http.StatusInternalServerError)
return
}
raw := stdout.Bytes()
if len(raw) > 10<<20 {
http.Error(w, `{"error":"Snapshot output too large"}`, http.StatusInternalServerError)
return
}
if len(raw) == 0 {
http.Error(w, `{"error":"Empty snapshot output"}`, http.StatusInternalServerError)
return
}
if err := validateEnvelope(raw); err != nil {
if err.Error() == "missing data/Memory" {
http.Error(w, `{"error":"Snapshot missing required fields"}`, http.StatusInternalServerError)
return
}
if strings.HasPrefix(err.Error(), "missing Memory.") {
k := strings.TrimPrefix(err.Error(), "missing Memory.")
http.Error(w, fmt.Sprintf(`{"error":"Snapshot missing Memory.%s"}`, k), http.StatusInternalServerError)
return
}
log.Printf("Snapshot produced invalid JSON: %v\nOutput: %s\n", err, string(raw[:min(2000, len(raw))]))
http.Error(w, fmt.Sprintf(`{"error":"Invalid snapshot JSON", "details":%q}`, err.Error()), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
if _, err = w.Write(raw); err != nil {
log.Printf("Error writing API response: %v", err)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func findAvailablePort(startPort int) int {
for port := startPort; port < startPort+100; port++ {
ln, err := net.Listen("tcp", net.JoinHostPort(net.IPv4(127,0,0,1).String(), strconv.Itoa(port)))
if err == nil {
ln.Close()
return port
}
}
ln, err := net.Listen("tcp", net.JoinHostPort(net.IPv4(127,0,0,1).String(), "0"))
if err != nil {
return startPort
}
defer ln.Close()
_, portStr, _ := net.SplitHostPort(ln.Addr().String())
p, _ := strconv.Atoi(portStr)
return p
}
func collectSnapshot(ctx context.Context) ([]byte, error) {
tmpFile, err := os.CreateTemp("", "snapshot-*.ps1")
if err != nil {
return nil, fmt.Errorf("create temp file: %w", err)
}
if _, err := tmpFile.WriteString(snapshotScript); err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return nil, fmt.Errorf("write temp file: %w", err)
}
tmpFile.Close()
defer os.Remove(tmpFile.Name())
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", tmpFile.Name())
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
return nil, fmt.Errorf("snapshot timed out")
}
if err != nil {
if stderr.Len() > 0 {
return nil, fmt.Errorf("powershell collection failed: %v: %s", err, stderr.String())
}
return nil, fmt.Errorf("powershell collection failed: %w", err)
}
raw := stdout.Bytes()
if len(raw) > 10<<20 {
return nil, fmt.Errorf("snapshot output too large")
}
if len(raw) == 0 {
return nil, fmt.Errorf("empty snapshot output")
}
return raw, nil
}
func applyRedaction(raw []byte) ([]byte, error) {
var env map[string]interface{}
if err := json.Unmarshal(raw, &env); err != nil {
return nil, err
}
data, ok := env["data"].(map[string]interface{})
if !ok {
return raw, nil
}
if arr, ok := data["WebViewProcesses"].([]interface{}); ok {
for _, v := range arr {
if m, ok := v.(map[string]interface{}); ok {
if _, has := m["CommandLine"]; has {
m["CommandLine"] = "[redacted]"
}
}
}
}
if arr, ok := data["AllProcesses"].([]interface{}); ok {
for _, v := range arr {
if m, ok := v.(map[string]interface{}); ok {
if _, has := m["CommandLine"]; has {
m["CommandLine"] = "[redacted]"
}
}
}
}
if arr, ok := data["Startup"].([]interface{}); ok {
for _, v := range arr {
if m, ok := v.(map[string]interface{}); ok {
if _, has := m["Command"]; has {
m["Command"] = "[redacted]"
}
}
}
}
return json.Marshal(env)
}
func runHeadless(output string, pretty, redact bool) {
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
raw, err := collectSnapshot(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "{\"error\":%q}\n", err.Error())
os.Exit(1)
}
if err := validateEnvelope(raw); err != nil {
fmt.Fprintf(os.Stderr, "{\"error\":\"validation failed\",\"details\":%q}\n", err.Error())
os.Exit(1)
}
out := raw
if redact {
if redacted, err := applyRedaction(raw); err == nil {
out = redacted
} else {
fmt.Fprintf(os.Stderr, "{\"error\":\"redaction failed\",\"details\":%q}\n", err.Error())
os.Exit(1)
}
}
if pretty {
var v interface{}
if err := json.Unmarshal(out, &v); err == nil {
if p, err := json.MarshalIndent(v, "", " "); err == nil {
out = p
}
}
}
if output != "" {
if err := os.WriteFile(output, out, 0644); err != nil {
fmt.Fprintf(os.Stderr, "{\"error\":\"write output failed\",\"details\":%q}\n", err.Error())
os.Exit(1)
}
} else {
os.Stdout.Write(out)
if len(out) > 0 && out[len(out)-1] != '\n' {
os.Stdout.Write([]byte("\n"))
}
}
os.Exit(0)
}
func openBrowser(url string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", url)
case "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
err := cmd.Start()
if err != nil {
fmt.Printf("Failed to open browser automatically: %v\n", err)
fmt.Printf("Please open your browser manually and navigate to: %s\n", url)
}
}
func handleWslShutdown(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != http.MethodPost {
http.Error(w, `{"error": "Method not allowed. Use POST."}`, http.StatusMethodNotAllowed)
return
}
if !isSameOrigin(r) {
http.Error(w, `{"error":"Forbidden origin"}`, http.StatusForbidden)
return
}
if !requireToken(r) {
http.Error(w, `{"error":"Missing or invalid capability token"}`, http.StatusForbidden)
return
}
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
var req map[string]json.RawMessage
if len(body) > 0 {
_ = json.Unmarshal(body, &req)
}
if raw, ok := req["confirm"]; ok {
var v bool
if err := json.Unmarshal(raw, &v); err != nil || !v {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
} else {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
select {
case wslSem <- struct{}{}:
defer func() { <-wslSem }()
default:
http.Error(w, `{"error":"WSL shutdown already in progress"}`, http.StatusTooManyRequests)
return
}
log.Println("Received request to shutdown WSL...")
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "wsl.exe", "--shutdown")
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
http.Error(w, `{"error":"WSL shutdown timed out"}`, http.StatusGatewayTimeout)
return
}
if err != nil {
log.Printf("Error running wsl --shutdown: %v, stderr: %s\n", err, stderr.String())
http.Error(w, fmt.Sprintf(`{"error": "Failed to shutdown WSL", "details": %q}`, stderr.String()), http.StatusInternalServerError)
return
}
log.Println("WSL VM successfully shut down.")
w.Write([]byte(`{"status": "success", "message": "WSL VM successfully shut down and memory released."}`))
}
func handleReclaimStandby(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != http.MethodPost {
http.Error(w, `{"error":"Method not allowed. Use POST."}`, http.StatusMethodNotAllowed)
return
}
if !isSameOrigin(r) {
http.Error(w, `{"error":"Forbidden origin"}`, http.StatusForbidden)
return
}
if !requireToken(r) {
http.Error(w, `{"error":"Missing or invalid capability token"}`, http.StatusForbidden)
return
}
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if len(body) == 0 {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
var req map[string]json.RawMessage
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
if raw, ok := req["confirm"]; ok {
var v bool
if err := json.Unmarshal(raw, &v); err != nil || !v {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
} else {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
select {
case reclaimSem <- struct{}{}:
defer func() { <-reclaimSem }()
default:
http.Error(w, `{"error":"Reclaim already in progress"}`, http.StatusTooManyRequests)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
defer cancel()
psScript := `
$ErrorActionPreference='Stop'
function Get-StandbyBytes {
$m = Get-CimInstance Win32_PerfFormattedData_PerfOS_Memory -ErrorAction Stop
return [int64]($m.StandbyCacheCoreBytes + $m.StandbyCacheNormalPriorityBytes + $m.StandbyCacheReserveBytes)
}
$before = Get-StandbyBytes
try {
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class NativeMem {
[DllImport("ntdll.dll")] public static extern int NtSetSystemInformation(int v, ref int a, int b);
[DllImport("advapi32.dll", SetLastError=true)] public static extern bool OpenProcessToken(IntPtr h, int a, out IntPtr t);
[DllImport("advapi32.dll", SetLastError=true)] public static extern bool LookupPrivilegeValue(string s, string n, out long id);
[DllImport("advapi32.dll", SetLastError=true)] public static extern bool AdjustTokenPrivileges(IntPtr t, bool d, ref long b, int c, IntPtr e, IntPtr f);
}
"@ -ErrorAction Stop
$tok=[IntPtr]::Zero
if ([NativeMem]::OpenProcessToken((Get-Process -Id $PID).Handle, 32, [ref]$tok)) {
$luid=0
if ([NativeMem]::LookupPrivilegeValue($null, "SeProfileSingleProcessPrivilege", [ref]$luid)) {
[void][NativeMem]::AdjustTokenPrivileges($tok, $false, [ref]$luid, 0, [IntPtr]::Zero, [IntPtr]::Zero)
}
}
$info=4
$st=[NativeMem]::NtSetSystemInformation(80, [ref]$info, 4)
if ($st -ne 0) {
if ($st -eq 1314 -or $st.ToString('X8') -eq 'C0000061') { Write-Error "REQUIRES_ADMIN"; exit 1 }
$msg=[System.ComponentModel.Win32Exception]::new($st).Message
if ($msg -match "privilege") { Write-Error "REQUIRES_ADMIN"; exit 1 }
Write-Error "RECLAIM_FAILED: NtSetSystemInformation status 0x$($st.ToString('X8')) $msg"
exit 1
}
} catch {
$msg=$_.Exception.Message
if ($msg -match "privilege" -or $msg -match "REQUIRES_ADMIN") { Write-Error "REQUIRES_ADMIN"; exit 1 }
if ($msg -match "REQUIRES_ADMIN") { Write-Error "REQUIRES_ADMIN"; exit 1 }
Write-Error "RECLAIM_FAILED: $msg"
exit 1
}
Start-Sleep -Milliseconds 200
$after = Get-StandbyBytes
$reclaimed = $before - $after
if ($reclaimed -lt 0) { $reclaimed = 0 }
@{beforeBytes=$before; afterBytes=$after; reclaimedBytes=$reclaimed} | ConvertTo-Json -Compress | Write-Host
`
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", psScript)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
http.Error(w, `{"error":"Reclaim timed out"}`, http.StatusGatewayTimeout)
return
}
stderrStr := stderr.String()
if strings.Contains(stderrStr, "REQUIRES_ADMIN") || strings.Contains(strings.ToLower(stderrStr), "privilege") {
http.Error(w, `{"error":"Requires Administrator","details":"Run SysView.exe as Administrator to reclaim standby"}`, http.StatusForbidden)
return
}
if strings.Contains(stderrStr, "RECLAIM_FAILED") {
http.Error(w, fmt.Sprintf(`{"error":"Reclaim failed","details":%q}`, stderrStr), http.StatusInternalServerError)
return
}
if err != nil {
http.Error(w, fmt.Sprintf(`{"error":"Reclaim failed","details":%q}`, stderrStr), http.StatusInternalServerError)
return
}
raw := stdout.Bytes()
raw = bytes.TrimSpace(raw)
if len(raw) == 0 {
http.Error(w, `{"error":"Reclaim failed","details":"empty output"}`, http.StatusInternalServerError)
return
}
if len(raw) > 1<<20 {
http.Error(w, `{"error":"Reclaim output too large"}`, http.StatusInternalServerError)
return
}
var res struct {
BeforeBytes *int64 `json:"beforeBytes"`
AfterBytes *int64 `json:"afterBytes"`
ReclaimedBytes *int64 `json:"reclaimedBytes"`
}
if err := json.Unmarshal(raw, &res); err != nil {
http.Error(w, fmt.Sprintf(`{"error":"Reclaim failed","details":%q}`, string(raw[:min(500, len(raw))])), http.StatusInternalServerError)
return
}
if res.BeforeBytes == nil || res.AfterBytes == nil || res.ReclaimedBytes == nil {
http.Error(w, `{"error":"Reclaim failed","details":"missing fields"}`, http.StatusInternalServerError)
return
}
beforeGB := float64(*res.BeforeBytes) / (1 << 30)
afterGB := float64(*res.AfterBytes) / (1 << 30)
freedMB := float64(*res.ReclaimedBytes) / (1 << 20)
msg := fmt.Sprintf("Standby reclaimed: %.2f GB \u2192 %.2f GB (%.0f MB freed)", beforeGB, afterGB, freedMB)
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"status": "success",
"beforeBytes": *res.BeforeBytes,
"afterBytes": *res.AfterBytes,
"reclaimedBytes": *res.ReclaimedBytes,
"message": msg,
})
}
func handleWslConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != http.MethodPost {
http.Error(w, `{"error":"Method not allowed. Use POST."}`, http.StatusMethodNotAllowed)
return
}
if !isSameOrigin(r) {
http.Error(w, `{"error":"Forbidden origin"}`, http.StatusForbidden)
return
}
if !requireToken(r) {
http.Error(w, `{"error":"Missing or invalid capability token"}`, http.StatusForbidden)
return
}
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
var req map[string]json.RawMessage
if len(body) > 0 {
_ = json.Unmarshal(body, &req)
}
rawConfirm, ok := req["confirm"]
if !ok {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
var confirm bool
if err := json.Unmarshal(rawConfirm, &confirm); err != nil || !confirm {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
rawMem, ok := req["memory"]
if !ok {
http.Error(w, `{"error":"Invalid memory value","details":"Expected e.g. 4GB, 4096MB"}`, http.StatusBadRequest)
return
}
var memStr string
if err := json.Unmarshal(rawMem, &memStr); err != nil {
// fallback: trim quotes/spaces if not a JSON string
s := strings.TrimSpace(string(rawMem))
s = strings.Trim(s, `"`)
s = strings.TrimSpace(s)
memStr = s
if memStr == "" {
http.Error(w, `{"error":"Invalid memory value","details":"Expected e.g. 4GB, 4096MB"}`, http.StatusBadRequest)
return
}
}
memStr = strings.TrimSpace(memStr)
reMem := regexp.MustCompile(`(?i)^\s*(\d+(?:\.\d+)?)\s*(GB|MB|G|M)?\s*$`)
m := reMem.FindStringSubmatch(memStr)
if m == nil {
http.Error(w, `{"error":"Invalid memory value","details":"Expected e.g. 4GB, 4096MB"}`, http.StatusBadRequest)
return
}
numStr := m[1]
unit := strings.ToUpper(strings.TrimSpace(m[2]))
switch unit {
case "G":
unit = "GB"
case "M":
unit = "MB"
case "":
unit = "GB"
}
memoryNormalized := numStr + unit
select {
case wslConfigSem <- struct{}{}:
defer func() { <-wslConfigSem }()
default:
http.Error(w, `{"error":"WSL config write already in progress"}`, http.StatusTooManyRequests)
return
}
homeDir, err := os.UserHomeDir()
if err != nil || homeDir == "" {
http.Error(w, fmt.Sprintf(`{"error":"Failed to write .wslconfig","details":%q}`, "cannot resolve home directory"), http.StatusInternalServerError)
return
}
wslConfigPath := filepath.Join(homeDir, ".wslconfig")
dir := filepath.Dir(wslConfigPath)
data, err := os.ReadFile(wslConfigPath)
var newContent string
if err != nil && os.IsNotExist(err) {
newContent = "[wsl2]\nmemory=" + memoryNormalized + "\n"
} else if err != nil {
http.Error(w, fmt.Sprintf(`{"error":"Failed to write .wslconfig","details":%q}`, err.Error()), http.StatusInternalServerError)
return
} else {
text := string(data)
lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
wsl2Exists := false
foundMemory := false
inWsl2 := false
wsl2End := -1
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
if strings.EqualFold(trimmed, "[wsl2]") {
wsl2Exists = true
inWsl2 = true
} else {
if inWsl2 {
wsl2End = i
inWsl2 = false
}
}
continue
}
if inWsl2 {
t := strings.TrimSpace(line)
if t == "" || strings.HasPrefix(t, "#") || strings.HasPrefix(t, ";") {
continue
}
lower := strings.ToLower(t)
if strings.HasPrefix(lower, "memory") {
rest := strings.TrimSpace(lower[len("memory"):])
if strings.HasPrefix(rest, "=") {
lines[i] = "memory=" + memoryNormalized
foundMemory = true
}
}
}
}
if !wsl2Exists {
content := strings.Join(lines, "\n")
content = strings.TrimRight(content, "\r\n")
if content != "" {
newContent = content + "\n[wsl2]\nmemory=" + memoryNormalized + "\n"
} else {
newContent = "[wsl2]\nmemory=" + memoryNormalized + "\n"
}
} else if !foundMemory {
insertAt := len(lines)
if wsl2End != -1 {
insertAt = wsl2End
}
newLines := make([]string, 0, len(lines)+1)
newLines = append(newLines, lines[:insertAt]...)
newLines = append(newLines, "memory="+memoryNormalized)
newLines = append(newLines, lines[insertAt:]...)
newContent = strings.Join(newLines, "\n")
if !strings.HasSuffix(newContent, "\n") {
newContent += "\n"
}
} else {
newContent = strings.Join(lines, "\n")
if !strings.HasSuffix(newContent, "\n") {
newContent += "\n"
}
}
}
tmpFile, err := os.CreateTemp(dir, ".wslconfig.tmp-*")
if err != nil {
http.Error(w, fmt.Sprintf(`{"error":"Failed to write .wslconfig","details":%q}`, err.Error()), http.StatusInternalServerError)
return
}
tmpName := tmpFile.Name()
if _, err := io.WriteString(tmpFile, newContent); err != nil {
tmpFile.Close()
os.Remove(tmpName)
http.Error(w, fmt.Sprintf(`{"error":"Failed to write .wslconfig","details":%q}`, err.Error()), http.StatusInternalServerError)
return
}
tmpFile.Close()
if err := os.Rename(tmpName, wslConfigPath); err != nil {
os.Remove(tmpName)
http.Error(w, fmt.Sprintf(`{"error":"Failed to write .wslconfig","details":%q}`, err.Error()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]string{
"status": "success",
"path": wslConfigPath,
"memory": memoryNormalized,
"message": "Wrote memory=" + memoryNormalized + " to .wslconfig",
})
}
func handleRuntimeRestart(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != http.MethodPost {
http.Error(w, `{"error":"Method not allowed. Use POST."}`, http.StatusMethodNotAllowed)
return
}
if !isSameOrigin(r) {
http.Error(w, `{"error":"Forbidden origin"}`, http.StatusForbidden)
return
}
if !requireToken(r) {
http.Error(w, `{"error":"Missing or invalid capability token"}`, http.StatusForbidden)
return
}
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
var req map[string]json.RawMessage
if len(body) > 0 {
_ = json.Unmarshal(body, &req)
}
rawConfirm, ok := req["confirm"]
if !ok {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
var confirm bool
if err := json.Unmarshal(rawConfirm, &confirm); err != nil || !confirm {
http.Error(w, `{"error":"Confirmation required"}`, http.StatusBadRequest)
return
}
rawHost, ok := req["host"]
if !ok {
http.Error(w, `{"error":"Host and PID required"}`, http.StatusBadRequest)
return
}
var host string
if err := json.Unmarshal(rawHost, &host); err != nil {
http.Error(w, `{"error":"Host and PID required"}`, http.StatusBadRequest)
return
}
host = strings.TrimSpace(host)
rawPid, ok := req["pid"]
if !ok {
http.Error(w, `{"error":"Host and PID required"}`, http.StatusBadRequest)
return
}
var pid int
if err := json.Unmarshal(rawPid, &pid); err != nil {
http.Error(w, `{"error":"Host and PID required"}`, http.StatusBadRequest)
return
}
if host == "" || pid <= 4 {
http.Error(w, `{"error":"Host and PID required"}`, http.StatusBadRequest)
return
}
select {
case runtimeRestartSem <- struct{}{}:
defer func() { <-runtimeRestartSem }()
default:
http.Error(w, `{"error":"Runtime restart already in progress"}`, http.StatusTooManyRequests)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
hostWithoutExe := strings.TrimSuffix(host, ".exe")
psScript := fmt.Sprintf(`
$ErrorActionPreference='Stop'
$p=Get-Process -Id %d -ErrorAction Stop
if(-not $p){throw "PID not found"}
if($p.Id -le 4){throw "Invalid PID"}
$expected=%q
if($expected -ne "" -and $p.ProcessName -ne $expected -and $p.ProcessName -ne %q){
# host mismatch is logged but still allow restart; do not block
Write-Host ("WARN: host mismatch expected "+$expected+" got "+$p.ProcessName)
}
Stop-Process -Id %d -Force -ErrorAction Stop
`, pid, hostWithoutExe, host, pid)
cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", psScript)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
http.Error(w, `{"error":"Gateway Timeout","details":"Runtime restart timed out"}`, http.StatusGatewayTimeout)
return
}
stderrStr := stderr.String()
stdoutStr := stdout.String()
if len(stdoutStr) > 1<<20 || len(stderrStr) > 1<<20 {
http.Error(w, `{"error":"Failed to restart host","details":"output too large"}`, http.StatusInternalServerError)
return
}
if err != nil {
lower := strings.ToLower(stderrStr)
if strings.Contains(stderrStr, "PID not found") || strings.Contains(lower, "cannot find a process") {
http.Error(w, `{"error":"PID not found"}`, http.StatusBadRequest)
return
}
if strings.Contains(stderrStr, "Invalid PID") {
http.Error(w, `{"error":"Not a runtime host"}`, http.StatusBadRequest)
return
}
http.Error(w, fmt.Sprintf(`{"error":"Failed to restart host","details":%q}`, stderrStr), http.StatusInternalServerError)
return
}
if strings.Contains(stderrStr, "PID not found") || strings.Contains(strings.ToLower(stderrStr), "cannot find a process") {
http.Error(w, `{"error":"PID not found"}`, http.StatusBadRequest)
return
}
if strings.Contains(stderrStr, "Invalid PID") {
http.Error(w, `{"error":"Not a runtime host"}`, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"status": "success",
"host": host,
"pid": pid,
"message": fmt.Sprintf("Sent restart signal to %s (PID %d)", host, pid),
})