forked from pterodactyl/wings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbetterconsole.patch
More file actions
1669 lines (1628 loc) · 50.3 KB
/
Copy pathbetterconsole.patch
File metadata and controls
1669 lines (1628 loc) · 50.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
diff --git a/config/config.go b/config/config.go
index b133123..c66b9c8 100644
--- a/config/config.go
+++ b/config/config.go
@@ -69,6 +69,13 @@ type SftpConfiguration struct {
Port int `default:"2022" json:"bind_port" yaml:"bind_port"`
// If set to true, no write actions will be allowed on the SFTP server.
ReadOnly bool `default:"false" yaml:"read_only"`
+ // Shell controls the optional interactive SSH shell exposed through the SFTP listener.
+ Shell SftpShellConfiguration `yaml:"shell"`
+}
+
+type SftpShellConfiguration struct {
+ // Enabled allows authenticated SFTP users to open the Better Console SSH CLI.
+ Enabled bool `default:"true" yaml:"enabled"`
}
// ApiConfiguration defines the configuration for the internal API that is
diff --git a/environment/docker/betterconsole_pull_progress.go b/environment/docker/betterconsole_pull_progress.go
new file mode 100644
index 0000000..8ed965d
--- /dev/null
+++ b/environment/docker/betterconsole_pull_progress.go
@@ -0,0 +1,171 @@
+package docker
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "strings"
+
+ "github.com/buger/jsonparser"
+)
+
+func betterConsoleDockerPullProgress(img string, b []byte) string {
+ id, _ := jsonparser.GetString(b, "id")
+ status, _ := jsonparser.GetString(b, "status")
+ progress, _ := jsonparser.GetString(b, "progress")
+ current, currentErr := jsonparser.GetInt(b, "progressDetail", "current")
+ total, totalErr := jsonparser.GetInt(b, "progressDetail", "total")
+ status = strings.TrimSpace(status)
+ if status == "" && id == "" {
+ return ""
+ }
+
+ displayStatus, phase := betterConsoleDockerPullStatus(status)
+ hasProgressDetail := currentErr == nil && totalErr == nil
+ percent := betterConsoleDockerPullPercent(current, total, phase == "complete")
+ line := betterConsoleDockerPullLine(displayStatus, current, total, hasProgressDetail)
+ image := betterConsoleDockerPullSafeImageRef(img)
+
+ payload, err := json.Marshal(map[string]interface{}{
+ "id": betterConsoleDockerPullSafeText(id),
+ "image": image,
+ "label": betterConsoleDockerPullImageLabel(image),
+ "phase": phase,
+ "status": displayStatus,
+ "progress": betterConsoleDockerPullSafeText(progress),
+ "current": current,
+ "total": total,
+ "percent": percent,
+ "line": line,
+ })
+ if err != nil {
+ return line
+ }
+
+ return string(payload)
+}
+
+func betterConsoleDockerPullStatus(status string) (string, string) {
+ normalized := strings.ToLower(strings.TrimSpace(status))
+ switch normalized {
+ case "downloading":
+ return "Downloading", "pulling"
+ case "extracting":
+ return "Extracting", "extracting"
+ case "download complete":
+ return "Download complete", "complete"
+ case "pull complete":
+ return "Pull complete", "complete"
+ case "already exists":
+ return "Already exists", "complete"
+ default:
+ if status == "" {
+ return "Pulling", "pulling"
+ }
+ return betterConsoleDockerPullSafeText(status), "status"
+ }
+}
+
+func betterConsoleDockerPullPercent(current int64, total int64, complete bool) float64 {
+ if complete {
+ return 100
+ }
+ if total <= 0 || current <= 0 {
+ return 0
+ }
+
+ percent := (float64(current) / float64(total)) * 100
+ if percent > 100 {
+ return 100
+ }
+ if percent < 0 {
+ return 0
+ }
+
+ return percent
+}
+
+func betterConsoleDockerPullLine(status string, current int64, total int64, complete bool) string {
+ if !complete {
+ return strings.TrimSpace(status)
+ }
+
+ percent := betterConsoleDockerPullPercent(current, total, false)
+ width := 50 - len(status)
+ if width < 8 {
+ width = 8
+ }
+
+ return fmt.Sprintf(
+ "%s %s %.2f%% of %s",
+ status,
+ betterConsoleDockerPullBar(width, percent),
+ percent,
+ betterConsoleDockerPullBytes(total),
+ )
+}
+
+func betterConsoleDockerPullBar(width int, percent float64) string {
+ completed := int(math.Round((percent / 100) * float64(width)))
+ if completed >= width {
+ return "[" + strings.Repeat("=", width) + "]"
+ }
+ if completed < 0 {
+ completed = 0
+ }
+
+ return "[" + strings.Repeat("=", completed) + ">" + strings.Repeat(" ", width-completed-1) + "]"
+}
+
+func betterConsoleDockerPullBytes(value int64) string {
+ if value <= 0 {
+ return "0 B"
+ }
+
+ units := []string{"B", "KiB", "MiB", "GiB", "TiB"}
+ size := float64(value)
+ unit := 0
+ for size >= 1024 && unit < len(units)-1 {
+ size /= 1024
+ unit++
+ }
+
+ if unit == 0 {
+ return fmt.Sprintf("%d B", value)
+ }
+
+ return fmt.Sprintf("%.1f %s", size, units[unit])
+}
+
+func betterConsoleDockerPullImageLabel(img string) string {
+ parts := strings.Split(strings.TrimSpace(img), "/")
+ if len(parts) == 0 || parts[len(parts)-1] == "" {
+ return "Docker image"
+ }
+
+ return parts[len(parts)-1]
+}
+
+func betterConsoleDockerPullSafeImageRef(img string) string {
+ img = strings.TrimSpace(img)
+ slash := strings.IndexByte(img, '/')
+ if slash <= 0 {
+ return img
+ }
+
+ registry := img[:slash]
+ if at := strings.LastIndex(registry, "@"); at >= 0 {
+ registry = registry[at+1:]
+ }
+
+ return registry + "/" + img[slash+1:]
+}
+
+func betterConsoleDockerPullSafeText(value string) string {
+ return strings.Map(func(r rune) rune {
+ if r == '\t' || r >= 32 {
+ return r
+ }
+ return -1
+ }, strings.TrimSpace(value))
+}
diff --git a/environment/docker/betterconsole_pull_progress_test.go b/environment/docker/betterconsole_pull_progress_test.go
new file mode 100644
index 0000000..af0cc2d
--- /dev/null
+++ b/environment/docker/betterconsole_pull_progress_test.go
@@ -0,0 +1,58 @@
+package docker
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestBetterConsoleDockerPullProgressWithProgressDetail(t *testing.T) {
+ payload := betterConsoleDockerPullProgress("ghcr.io/ptero-eggs/yolks:nodejs_22", []byte(`{"id":"layer","status":"Downloading","progressDetail":{"current":512,"total":1024}}`))
+
+ var parsed struct {
+ Line string `json:"line"`
+ Percent float64 `json:"percent"`
+ }
+ if err := json.Unmarshal([]byte(payload), &parsed); err != nil {
+ t.Fatal(err)
+ }
+ if parsed.Percent != 50 {
+ t.Fatalf("expected 50 percent, got %f", parsed.Percent)
+ }
+ if !strings.HasPrefix(parsed.Line, "Downloading [") {
+ t.Fatalf("expected progress bar line, got %q", parsed.Line)
+ }
+}
+
+func TestBetterConsoleDockerPullProgressWithoutProgressDetail(t *testing.T) {
+ payload := betterConsoleDockerPullProgress("ghcr.io/ptero-eggs/yolks:nodejs_22", []byte(`{"status":"Status: Image is up to date for ghcr.io/ptero-eggs/yolks:nodejs_22"}`))
+
+ var parsed struct {
+ Line string `json:"line"`
+ }
+ if err := json.Unmarshal([]byte(payload), &parsed); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(parsed.Line, "0 B") || strings.Contains(parsed.Line, "[") {
+ t.Fatalf("expected plain status without fake bar, got %q", parsed.Line)
+ }
+}
+
+func TestBetterConsoleDockerPullProgressSanitizesImageCredentials(t *testing.T) {
+ payload := betterConsoleDockerPullProgress("user:secret@registry.example.com/private/image:latest", []byte(`{"id":"layer","status":"Downloading","progressDetail":{"current":512,"total":1024}}`))
+
+ if strings.Contains(payload, "secret") || strings.Contains(payload, "user:") {
+ t.Fatalf("expected sanitized image payload, got %q", payload)
+ }
+ if !strings.Contains(payload, "registry.example.com/private/image:latest") {
+ t.Fatalf("expected sanitized image reference in payload, got %q", payload)
+ }
+}
+
+func TestBetterConsoleDockerPullProgressStripsControlCharacters(t *testing.T) {
+ payload := betterConsoleDockerPullProgress("ghcr.io/ptero-eggs/yolks:nodejs_22", []byte("{\"id\":\"lay\u001ber\",\"status\":\"Pull\u001b complete\",\"progress\":\"10\u001b%\"}"))
+
+ if strings.Contains(payload, "\u001b") {
+ t.Fatalf("expected control characters to be stripped, got %q", payload)
+ }
+}
diff --git a/environment/docker/container.go b/environment/docker/container.go
index f503af1..775cdfa 100644
--- a/environment/docker/container.go
+++ b/environment/docker/container.go
@@ -11,7 +11,6 @@ import (
"emperror.dev/errors"
"github.com/apex/log"
- "github.com/buger/jsonparser"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
@@ -346,9 +345,6 @@ func (e *Environment) Readlog(lines int) ([]string, error) {
// of that. I'd imagine in a lot of cases an outage shouldn't affect users too
// badly. It'll at least keep existing servers working correctly if anything.
func (e *Environment) ensureImageExists(img string) error {
- e.Events().Publish(environment.DockerImagePullStarted, "")
- defer e.Events().Publish(environment.DockerImagePullCompleted, "")
-
// Images prefixed with a ~ are local images that we do not need to try and pull.
if strings.HasPrefix(img, "~") {
return nil
@@ -378,6 +374,7 @@ func (e *Environment) ensureImageExists(img string) error {
}
out, err := e.client.ImagePull(ctx, img, imagePullOptions)
+ safeImage := betterConsoleDockerPullSafeImageRef(img)
if err != nil {
images, ierr := e.client.ImageList(ctx, image.ListOptions{})
if ierr != nil {
@@ -393,7 +390,7 @@ func (e *Environment) ensureImageExists(img string) error {
}
log.WithFields(log.Fields{
- "image": img,
+ "image": safeImage,
"container_id": e.Id,
"err": err.Error(),
}).Warn("unable to pull requested image from remote source, however the image exists locally")
@@ -404,29 +401,30 @@ func (e *Environment) ensureImageExists(img string) error {
}
}
- return errors.Wrapf(err, "environment/docker: failed to pull \"%s\" image for server", img)
+ return errors.Wrapf(err, "environment/docker: failed to pull \"%s\" image for server", safeImage)
}
defer out.Close()
- log.WithField("image", img).Debug("pulling docker image... this could take a bit of time")
+ e.Events().Publish(environment.DockerImagePullStarted, "")
+ defer e.Events().Publish(environment.DockerImagePullCompleted, "")
+
+ log.WithField("image", safeImage).Debug("pulling docker image... this could take a bit of time")
// I'm not sure what the best approach here is, but this will block execution until the image
// is done being pulled, which is what we need.
scanner := bufio.NewScanner(out)
for scanner.Scan() {
- b := scanner.Bytes()
- status, _ := jsonparser.GetString(b, "status")
- progress, _ := jsonparser.GetString(b, "progress")
-
- e.Events().Publish(environment.DockerImagePullStatus, status+" "+progress)
+ if payload := betterConsoleDockerPullProgress(img, scanner.Bytes()); payload != "" {
+ e.Events().Publish(environment.DockerImagePullStatus, payload)
+ }
}
if err := scanner.Err(); err != nil {
return err
}
- log.WithField("image", img).Debug("completed docker image pull")
+ log.WithField("image", safeImage).Debug("completed docker image pull")
return nil
}
diff --git a/router/websocket/betterconsole_events.go b/router/websocket/betterconsole_events.go
new file mode 100644
index 0000000..3fa992f
--- /dev/null
+++ b/router/websocket/betterconsole_events.go
@@ -0,0 +1,16 @@
+package websocket
+
+import "github.com/pterodactyl/wings/server"
+
+var betterConsoleListenerEvents = []string{
+ server.ImagePullStartedEvent,
+ server.ImagePullProgressEvent,
+ server.ImagePullCompletedEvent,
+}
+
+func isBetterConsoleInstallOutputEvent(event Event) bool {
+ return event == server.InstallOutputEvent ||
+ event == server.ImagePullStartedEvent ||
+ event == server.ImagePullProgressEvent ||
+ event == server.ImagePullCompletedEvent
+}
diff --git a/router/websocket/listeners.go b/router/websocket/listeners.go
index 12e5f81..d3f639e 100644
--- a/router/websocket/listeners.go
+++ b/router/websocket/listeners.go
@@ -3,6 +3,7 @@ package websocket
import (
"context"
"encoding/json"
+ "strings"
"sync"
"time"
@@ -66,7 +67,7 @@ func (h *Handler) listenForExpiration(ctx context.Context) {
}
}
-var e = []string{
+var e = append([]string{
server.StatsEvent,
server.StatusEvent,
server.ConsoleOutputEvent,
@@ -78,7 +79,15 @@ var e = []string{
server.BackupRestoreCompletedEvent,
server.TransferLogsEvent,
server.TransferStatusEvent,
-}
+}, betterConsoleListenerEvents...)
+
+var allowedServerEvents = func() map[string]struct{} {
+ events := make(map[string]struct{}, len(e))
+ for _, event := range e {
+ events[event] = struct{}{}
+ }
+ return events
+}()
// ListenForServerEvents will listen for different events happening on a server
// and send them along to the connected websocket client. This function will
@@ -93,10 +102,16 @@ func (h *Handler) listenForServerEvents(ctx context.Context) error {
eventChan := make(chan []byte)
logOutput := make(chan []byte, 8)
installOutput := make(chan []byte, 4)
+ canReceiveInstall := false
+ if jwt := h.GetJwt(); jwt != nil {
+ canReceiveInstall = jwt.HasPermission(PermissionReceiveInstall)
+ }
h.server.Events().On(eventChan) // TODO: make a sinky
h.server.Sink(system.LogSink).On(logOutput)
- h.server.Sink(system.InstallSink).On(installOutput)
+ if canReceiveInstall {
+ h.server.Sink(system.InstallSink).On(installOutput)
+ }
onError := func(evt string, err2 error) {
h.Logger().WithField("event", evt).WithField("error", err2).Error("failed to send event over server websocket")
@@ -130,6 +145,9 @@ func (h *Handler) listenForServerEvents(ctx context.Context) error {
if err := events.DecodeTo(b, &e); err != nil {
continue
}
+ if _, ok := allowedServerEvents[e.Topic]; !ok && !strings.HasPrefix(e.Topic, server.BackupCompletedEvent+":") {
+ continue
+ }
var sendErr error
message := Message{Event: Event(e.Topic)}
if str, ok := e.Data.(string); ok {
@@ -157,7 +175,9 @@ func (h *Handler) listenForServerEvents(ctx context.Context) error {
// These functions will automatically close the channel if it hasn't been already.
h.server.Events().Off(eventChan)
h.server.Sink(system.LogSink).Off(logOutput)
- h.server.Sink(system.InstallSink).Off(installOutput)
+ if canReceiveInstall {
+ h.server.Sink(system.InstallSink).Off(installOutput)
+ }
// If the internal context is stopped it is either because the parent context
// got canceled or because we ran into an error. If the "err" variable is nil
diff --git a/router/websocket/listeners_test.go b/router/websocket/listeners_test.go
new file mode 100644
index 0000000..bc47188
--- /dev/null
+++ b/router/websocket/listeners_test.go
@@ -0,0 +1,16 @@
+package websocket
+
+import (
+ "testing"
+
+ "github.com/pterodactyl/wings/server"
+)
+
+func TestAllowedServerEvents(t *testing.T) {
+ if _, ok := allowedServerEvents[server.ImagePullProgressEvent]; !ok {
+ t.Fatalf("expected image pull progress event to be allowed")
+ }
+ if _, ok := allowedServerEvents["unexpected internal event"]; ok {
+ t.Fatalf("expected unknown internal event to be blocked")
+ }
+}
diff --git a/router/websocket/websocket.go b/router/websocket/websocket.go
index 4482667..c1a2300 100644
--- a/router/websocket/websocket.go
+++ b/router/websocket/websocket.go
@@ -147,7 +147,7 @@ func (h *Handler) SendJson(v Message) error {
if j := h.GetJwt(); j != nil {
// If we're sending installation output but the user does not have the required
// permissions to see the output, don't send it down the line.
- if v.Event == server.InstallOutputEvent {
+ if isBetterConsoleInstallOutputEvent(v.Event) {
if !j.HasPermission(PermissionReceiveInstall) {
return nil
}
diff --git a/server/betterconsole_events.go b/server/betterconsole_events.go
new file mode 100644
index 0000000..aebd975
--- /dev/null
+++ b/server/betterconsole_events.go
@@ -0,0 +1,7 @@
+package server
+
+const (
+ ImagePullStartedEvent = "image pull started"
+ ImagePullProgressEvent = "image pull progress"
+ ImagePullCompletedEvent = "image pull completed"
+)
diff --git a/server/betterconsole_pull_progress.go b/server/betterconsole_pull_progress.go
new file mode 100644
index 0000000..7766b99
--- /dev/null
+++ b/server/betterconsole_pull_progress.go
@@ -0,0 +1,195 @@
+package server
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "strings"
+
+ "github.com/buger/jsonparser"
+)
+
+func betterConsoleDockerPullProgress(img string, b []byte) string {
+ id, _ := jsonparser.GetString(b, "id")
+ status, _ := jsonparser.GetString(b, "status")
+ progress, _ := jsonparser.GetString(b, "progress")
+ current, currentErr := jsonparser.GetInt(b, "progressDetail", "current")
+ total, totalErr := jsonparser.GetInt(b, "progressDetail", "total")
+ status = strings.TrimSpace(status)
+ if status == "" && id == "" {
+ return ""
+ }
+
+ displayStatus, phase := betterConsoleDockerPullStatus(status)
+ hasProgressDetail := currentErr == nil && totalErr == nil
+ percent := betterConsoleDockerPullPercent(current, total, phase == "complete")
+ line := betterConsoleDockerPullLine(displayStatus, current, total, hasProgressDetail)
+ image := betterConsoleDockerPullSafeImageRef(img)
+
+ payload, err := json.Marshal(map[string]interface{}{
+ "id": betterConsoleDockerPullSafeText(id),
+ "image": image,
+ "label": betterConsoleDockerPullImageLabel(image),
+ "phase": phase,
+ "status": displayStatus,
+ "progress": betterConsoleDockerPullSafeText(progress),
+ "current": current,
+ "total": total,
+ "percent": percent,
+ "line": line,
+ })
+ if err != nil {
+ return line
+ }
+
+ return string(payload)
+}
+
+func betterConsoleDockerPullInstallLine(b []byte) string {
+ line, _ := jsonparser.GetString(b, "line")
+ if strings.TrimSpace(line) != "" {
+ return strings.TrimSpace(line)
+ }
+
+ status, _ := jsonparser.GetString(b, "status")
+ current, currentErr := jsonparser.GetInt(b, "progressDetail", "current")
+ total, totalErr := jsonparser.GetInt(b, "progressDetail", "total")
+
+ status = strings.TrimSpace(status)
+ if status == "" {
+ return ""
+ }
+
+ displayStatus, phase := betterConsoleDockerPullStatus(status)
+ line = betterConsoleDockerPullLine(displayStatus, current, total, currentErr == nil && totalErr == nil)
+ if phase == "complete" && line == "" {
+ return displayStatus
+ }
+
+ return line
+}
+
+func betterConsoleDockerPullStatus(status string) (string, string) {
+ normalized := strings.ToLower(strings.TrimSpace(status))
+ switch normalized {
+ case "downloading":
+ return "Downloading", "pulling"
+ case "extracting":
+ return "Extracting", "extracting"
+ case "download complete":
+ return "Download complete", "complete"
+ case "pull complete":
+ return "Pull complete", "complete"
+ case "already exists":
+ return "Already exists", "complete"
+ default:
+ if status == "" {
+ return "Pulling", "pulling"
+ }
+ return betterConsoleDockerPullSafeText(status), "status"
+ }
+}
+
+func betterConsoleDockerPullPercent(current int64, total int64, complete bool) float64 {
+ if complete {
+ return 100
+ }
+ if total <= 0 || current <= 0 {
+ return 0
+ }
+
+ percent := (float64(current) / float64(total)) * 100
+ if percent > 100 {
+ return 100
+ }
+ if percent < 0 {
+ return 0
+ }
+
+ return percent
+}
+
+func betterConsoleDockerPullLine(status string, current int64, total int64, complete bool) string {
+ if !complete {
+ return strings.TrimSpace(status)
+ }
+
+ percent := betterConsoleDockerPullPercent(current, total, false)
+ width := 50 - len(status)
+ if width < 8 {
+ width = 8
+ }
+
+ return fmt.Sprintf(
+ "%s %s %.2f%% of %s",
+ status,
+ betterConsoleDockerPullBar(width, percent),
+ percent,
+ betterConsoleDockerPullBytes(total),
+ )
+}
+
+func betterConsoleDockerPullBar(width int, percent float64) string {
+ completed := int(math.Round((percent / 100) * float64(width)))
+ if completed >= width {
+ return "[" + strings.Repeat("=", width) + "]"
+ }
+ if completed < 0 {
+ completed = 0
+ }
+
+ return "[" + strings.Repeat("=", completed) + ">" + strings.Repeat(" ", width-completed-1) + "]"
+}
+
+func betterConsoleDockerPullBytes(value int64) string {
+ if value <= 0 {
+ return "0 B"
+ }
+
+ units := []string{"B", "KiB", "MiB", "GiB", "TiB"}
+ size := float64(value)
+ unit := 0
+ for size >= 1024 && unit < len(units)-1 {
+ size /= 1024
+ unit++
+ }
+
+ if unit == 0 {
+ return fmt.Sprintf("%d B", value)
+ }
+
+ return fmt.Sprintf("%.1f %s", size, units[unit])
+}
+
+func betterConsoleDockerPullImageLabel(img string) string {
+ parts := strings.Split(strings.TrimSpace(img), "/")
+ if len(parts) == 0 || parts[len(parts)-1] == "" {
+ return "Docker image"
+ }
+
+ return parts[len(parts)-1]
+}
+
+func betterConsoleDockerPullSafeImageRef(img string) string {
+ img = strings.TrimSpace(img)
+ slash := strings.IndexByte(img, '/')
+ if slash <= 0 {
+ return img
+ }
+
+ registry := img[:slash]
+ if at := strings.LastIndex(registry, "@"); at >= 0 {
+ registry = registry[at+1:]
+ }
+
+ return registry + "/" + img[slash+1:]
+}
+
+func betterConsoleDockerPullSafeText(value string) string {
+ return strings.Map(func(r rune) rune {
+ if r == '\t' || r >= 32 {
+ return r
+ }
+ return -1
+ }, strings.TrimSpace(value))
+}
diff --git a/server/betterconsole_pull_progress_test.go b/server/betterconsole_pull_progress_test.go
new file mode 100644
index 0000000..6831ade
--- /dev/null
+++ b/server/betterconsole_pull_progress_test.go
@@ -0,0 +1,44 @@
+package server
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestBetterConsoleDockerPullInstallLineWithProgressDetail(t *testing.T) {
+ line := betterConsoleDockerPullInstallLine([]byte(`{"status":"Downloading","progressDetail":{"current":512,"total":1024}}`))
+
+ if !strings.HasPrefix(line, "Downloading [") {
+ t.Fatalf("expected downloading progress bar, got %q", line)
+ }
+ if !strings.Contains(line, "50.00% of 1.0 KiB") {
+ t.Fatalf("expected calculated percentage and total bytes, got %q", line)
+ }
+}
+
+func TestBetterConsoleDockerPullInstallLineWithoutProgressDetail(t *testing.T) {
+ line := betterConsoleDockerPullInstallLine([]byte(`{"status":"Pull complete"}`))
+
+ if line != "Pull complete" {
+ t.Fatalf("expected plain status without fake 0 B bar, got %q", line)
+ }
+}
+
+func TestBetterConsoleDockerPullProgressSanitizesImageCredentials(t *testing.T) {
+ payload := betterConsoleDockerPullProgress("user:secret@registry.example.com/private/image:latest", []byte(`{"id":"layer","status":"Downloading","progressDetail":{"current":512,"total":1024}}`))
+
+ if strings.Contains(payload, "secret") || strings.Contains(payload, "user:") {
+ t.Fatalf("expected sanitized image payload, got %q", payload)
+ }
+ if !strings.Contains(payload, "registry.example.com/private/image:latest") {
+ t.Fatalf("expected sanitized image reference in payload, got %q", payload)
+ }
+}
+
+func TestBetterConsoleDockerPullProgressStripsControlCharacters(t *testing.T) {
+ payload := betterConsoleDockerPullProgress("ghcr.io/ptero-eggs/yolks:nodejs_22", []byte("{\"id\":\"lay\u001ber\",\"status\":\"Pull\u001b complete\",\"progress\":\"10\u001b%\"}"))
+
+ if strings.Contains(payload, "\u001b") {
+ t.Fatalf("expected control characters to be stripped, got %q", payload)
+ }
+}
diff --git a/server/install.go b/server/install.go
index 0d31d50..e964c2f 100644
--- a/server/install.go
+++ b/server/install.go
@@ -270,6 +270,7 @@ func (ip *InstallationProcess) pullInstallationImage() error {
}
r, err := ip.client.ImagePull(ip.Server.Context(), ip.Script.ContainerImage, imagePullOptions)
+ safeImage := betterConsoleDockerPullSafeImageRef(ip.Script.ContainerImage)
if err != nil {
images, ierr := ip.client.ImageList(ip.Server.Context(), image.ListOptions{})
if ierr != nil {
@@ -285,7 +286,7 @@ func (ip *InstallationProcess) pullInstallationImage() error {
}
log.WithFields(log.Fields{
- "image": ip.Script.ContainerImage,
+ "image": safeImage,
"err": err.Error(),
}).Warn("unable to pull requested image from remote source, however the image exists locally")
@@ -299,12 +300,21 @@ func (ip *InstallationProcess) pullInstallationImage() error {
}
defer r.Close()
- log.WithField("image", ip.Script.ContainerImage).Debug("pulling docker image... this could take a bit of time")
+ log.WithField("image", safeImage).Debug("pulling docker image... this could take a bit of time")
+ ip.Server.Events().Publish(ImagePullStartedEvent, "")
+ defer ip.Server.Events().Publish(ImagePullCompletedEvent, "")
// Block continuation until the image has been pulled successfully.
scanner := bufio.NewScanner(r)
for scanner.Scan() {
- log.Debug(scanner.Text())
+ log.Debug(betterConsoleDockerPullSafeText(scanner.Text()))
+ payload := betterConsoleDockerPullProgress(ip.Script.ContainerImage, scanner.Bytes())
+ if payload != "" {
+ ip.Server.Events().Publish(ImagePullProgressEvent, payload)
+ }
+ if line := betterConsoleDockerPullInstallLine(scanner.Bytes()); line != "" {
+ ip.Server.Sink(system.InstallSink).Push([]byte(line))
+ }
}
if err := scanner.Err(); err != nil {
@@ -516,13 +526,32 @@ func (ip *InstallationProcess) StreamOutput(ctx context.Context, id string) erro
}
defer reader.Close()
- err = system.ScanReader(reader, ip.Server.Sink(system.InstallSink).Push)
+ err = ip.streamRawInstallOutput(reader)
if err != nil && !errors.Is(err, context.Canceled) {
ip.Server.Log().WithFields(log.Fields{"container_id": id, "error": err}).Warn("error processing install output lines")
}
return nil
}
+func (ip *InstallationProcess) streamRawInstallOutput(reader io.Reader) error {
+ buf := make([]byte, 4096)
+ for {
+ n, err := reader.Read(buf)
+ if n > 0 {
+ chunk := make([]byte, n)
+ copy(chunk, buf[:n])
+ ip.Server.Sink(system.InstallSink).Push(chunk)
+ }
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+
+ return err
+ }
+ }
+}
+
// resourceLimits returns resource limits for the installation container. This
// looks at the globally defined install container limits and attempts to use
// the higher of the two (defined limits & server limits). This allows for servers
diff --git a/server/listeners.go b/server/listeners.go
index d39e664..639ef16 100644
--- a/server/listeners.go
+++ b/server/listeners.go
@@ -127,10 +127,17 @@ func (s *Server) StartEventListeners() {
s.OnStateChange()
}
case environment.DockerImagePullStatus:
- s.Events().Publish(InstallOutputEvent, e.Data)
+ s.Events().Publish(ImagePullProgressEvent, e.Data)
+ if str, ok := e.Data.(string); ok {
+ if line := betterConsoleDockerPullInstallLine([]byte(str)); line != "" {
+ s.Sink(system.LogSink).Push([]byte(line))
+ }
+ }
case environment.DockerImagePullStarted:
+ s.Events().Publish(ImagePullStartedEvent, "")
s.PublishConsoleOutputFromDaemon("Pulling Docker container image, this could take a few minutes to complete...")
case environment.DockerImagePullCompleted:
+ s.Events().Publish(ImagePullCompletedEvent, "")
s.PublishConsoleOutputFromDaemon("Finished pulling Docker container image")
default:
}
diff --git a/sftp/betterconsole_shell.go b/sftp/betterconsole_shell.go
new file mode 100644
index 0000000..249d77d
--- /dev/null
+++ b/sftp/betterconsole_shell.go
@@ -0,0 +1,470 @@
+package sftp
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "io"
+ "strings"
+ "sync"
+ "unicode"
+ "unicode/utf8"
+
+ "golang.org/x/crypto/ssh"
+
+ "github.com/pterodactyl/wings/environment"
+ "github.com/pterodactyl/wings/events"
+ "github.com/pterodactyl/wings/internal/models"
+ "github.com/pterodactyl/wings/server"
+ "github.com/pterodactyl/wings/system"
+)
+
+const betterConsoleShellCliName = ".wings"
+const betterConsoleShellMaxLineBytes = 4096
+
+func (c *SFTPServer) serveBetterConsoleCli(channel ssh.Channel, srv *server.Server, handler *Handler, ip string) {
+ logOutput := make(chan []byte, 128)
+ installOutput := make(chan []byte, 32)
+ eventOutput := make(chan []byte, 32)
+ done := make(chan struct{})
+ canReceiveInstall := handler.can("admin.websocket.install")
+ activity := srv.NewRequestActivity(handler.User(), ip)
+
+ srv.Sink(system.LogSink).On(logOutput)
+ if canReceiveInstall {
+ srv.Sink(system.InstallSink).On(installOutput)
+ }
+ srv.Events().On(eventOutput)
+ defer srv.Sink(system.LogSink).Off(logOutput)
+ if canReceiveInstall {
+ defer srv.Sink(system.InstallSink).Off(installOutput)
+ }
+ defer srv.Events().Off(eventOutput)
+
+ term := &betterConsoleSshTerminal{channel: channel}
+ term.writeLine("Better Console live server console")
+ term.writeLine("Connected to Wings. Type a server command and press enter.")
+ term.writeLine("Type \"" + betterConsoleShellCliName + " help\" for daemon commands or \"exit\" to close this SSH console session.")
+ if lines, err := srv.Environment.Readlog(75); err == nil && len(lines) > 0 {
+ for _, line := range lines {
+ term.writeHistory(line)
+ }
+ }
+ term.prompt()
+
+ go func() {
+ for {
+ select {
+ case <-done:
+ return
+ case line, ok := <-logOutput:
+ if !ok {
+ logOutput = nil
+ continue
+ }
+ term.writeConsole(string(line))
+ case line, ok := <-installOutput:
+ if !ok {
+ installOutput = nil
+ continue
+ }
+ term.writeConsole(string(line))
+ case raw, ok := <-eventOutput:
+ if !ok {
+ eventOutput = nil
+ continue
+ }
+ var e events.Event
+ if err := events.DecodeTo(raw, &e); err != nil {
+ continue
+ }
+ if e.Topic == server.InstallOutputEvent && !canReceiveInstall {
+ continue
+ }
+ if e.Topic != server.ConsoleOutputEvent && e.Topic != server.DaemonMessageEvent && e.Topic != server.InstallOutputEvent {
+ continue
+ }
+ term.writeConsole(betterConsoleEventString(e.Data))
+ }
+ }
+ }()
+
+ reader := bufio.NewReader(channel)
+ for {
+ b, err := reader.ReadByte()
+ if err != nil {
+ close(done)
+ if err != io.EOF {
+ term.writeLine("Session closed.")
+ }
+ return
+ }
+
+ switch b {
+ case '\r', '\n':
+ line := strings.TrimSpace(term.commitLine())
+ if line == "" {
+ term.prompt()
+ continue
+ }
+ if line == "exit" || line == "quit" {
+ close(done)
+ term.writeLine("Disconnected from Better Console.")
+ return
+ }
+ if strings.HasPrefix(line, betterConsoleShellCliName) {
+ c.handleBetterConsoleShellCliCommand(term, srv, handler, activity, line)
+ } else if !handler.can("control.console") {
+ term.writeLine("Permission denied: control.console")
+ } else if srv.IsInstalling() {
+ term.writeLine("The server is currently installing.")
+ } else if srv.Environment.State() == environment.ProcessOfflineState {
+ term.writeLine("The server is currently offline.")
+ } else if err := srv.Environment.SendCommand(line); err != nil {
+ term.writeLine("Unable to send command: " + err.Error())
+ } else {
+ srv.SaveActivity(activity, server.ActivityConsoleCommand, models.ActivityMeta{"command": line})
+ }
+ term.prompt()
+ case 0x03:
+ term.cancelLine()
+ term.prompt()
+ case 0x04:
+ close(done)
+ term.writeLine("Disconnected from Better Console.")
+ return
+ case 0x7f, '\b':
+ term.backspace()
+ default:
+ if b < 32 || (b >= 0x80 && b <= 0x9f) {
+ continue
+ }
+ if !term.appendByte(b) {
+ term.writeLine("Command line is too long.")
+ term.clearLine()
+ term.prompt()
+ }
+ }
+ }
+}
+
+func (c *SFTPServer) handleBetterConsoleShellCliCommand(term *betterConsoleSshTerminal, srv *server.Server, handler *Handler, activity server.RequestActivity, line string) {
+ parts := strings.Fields(line)
+ if len(parts) < 2 {
+ term.writeLine("Usage: " + betterConsoleShellCliName + " <help|power|stats>")
+ return
+ }
+