-
Notifications
You must be signed in to change notification settings - Fork 4
/
session.c
1917 lines (1563 loc) · 43.1 KB
/
session.c
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
/* Copyright 2023 Google LLC
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd */
#include "third_party/st/wcwidth.h"
#include "shared.h"
#include "font.h"
#include "outstreams.h"
#include "test/raw/data.h"
#include <md4c-html.h>
#include "wts.h"
#include "http.h"
#include "spawner.h"
#include "dtachctx.h"
#include "tm.c"
#include "third_party/st/plat.h"
#include "third_party/st/tmeng"
#include <sys/wait.h>
#include <libgen.h>
#include <sys/stat.h>
#include <stdint.h>
#include <limits.h>
#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <err.h>
#include <stdarg.h>
#include <dirent.h>
static char *argv0, *termid, *logview, *sblvl, *dtachlog;
static const char *qs;
static size_t argv0sz;
/* Terminal Machine (TM...) functions are implemented in both Javascript and C.
* They consider arguments to be untrusted - memory access must be guarded.
* This means out-of-bounds checking to prevent an uncaught exception in
* Javascript, and avoiding illegal accesses or UB in C.
*
* Code that exists above the VM... layer should be syntax-neutral between C and
* Javascript. IOW, code that calls it will be executed in Javascript on the
* client and in C on the server.
*/
static void TMpokettl(int toff, int b)
{
if (toff >= 0 && toff < sizeof(wts.ttl)) wts.ttl[toff] = b;
}
void Xsetcolor(int trm, int pi, int rgb) {/* no-op */}
/* No-ops because server is headless */
void Xicontitl(TMint deq, TMint off) {}
void Xsettitle(TMint deq, TMint off) {}
void Xbell(int trm) {}
void Xsetpointermotion(int set) {}
void Xdrawglyph(int trm, int gf, int x, int y) {}
void Xosc52copy(TMint trm, TMint deq, TMint byti) {}
void Xdrawrect(TMint clor, TMint x0, TMint y0, TMint w, TMint h) {}
void Xdrawline(TMint trm, int x1, int y1, int x2) {}
void Xfinishdraw(TMint trm) {}
void Xximspot(TMint trm, int cx, int cy) {}
void Now(int ms) { fld(ms,0) = 0; fld(ms,1) = 0; }
void Xprint(TMint deq)
{
full_write(&(struct wrides){2,"Xprint"}, deqtostring(deq, 0),
deqsiz(deq));
}
void Ttywriteraw(int trm, int dq, int of, int sz)
{
fdb_routs(&therout, deqtostring(dq, of), sz);
}
struct fdbuf therout;
void process_tty_out(void *buf, ssize_t len)
{
static int d;
int sbbuf;
if (len < 0) len = strlen(buf);
if (wts.writerawlg) full_write(&wts.rawlogde, buf, len);
if (!wts.t) {
wts.t = term_new();
tnew(wts.t, 80, 25);
if (wts.writelg) term(wts.t,sbbuf) = deqmk();
}
d = deqsetutf8(d ? d:deqmk(), buf, len);
twrite(wts.t, d, -1, 0);
fdb_routs(&therout, buf, len);
fdb_apnc(&therout, '\n');
if (wts.writelg) {
sbbuf = term(wts.t,sbbuf);
if (deqsiz(sbbuf)) {
full_write(&wts.logde, deqtostring(sbbuf, 0),
deqbytsiz(sbbuf));
deqclear(sbbuf);
}
}
}
static void recounttitl(struct wrides *de)
{
struct fdbuf b = {.de = de};
fdb_apnd(&b, "\\@title:", -1);
if (wts.clnttl) fdb_apnd(&b, wts.ttl, ttl_len());
fdb_apnc(&b, '\n');
fdb_finsh(&b);
}
static int parsequeryarg(const char *pref, char **dest)
{
size_t preflen;
const char *end;
char *dscur;
int byte, bcnt;
preflen = strlen(pref);
if (strncmp(qs, pref, preflen)) return 0;
qs += preflen;
end = strchrnul(qs, '&');
free(*dest);
dscur = *dest = malloc(end - qs + 1);
while (qs != end) {
byte = *qs++;
if (byte == '%') {
bcnt = 0;
if (sscanf(qs, "%2x%n", &byte, &bcnt) && bcnt == 2)
qs += 2;
}
*dscur++ = byte;
}
*dscur = 0;
return 1;
}
int dtach_logging(void) { return !!dtachlog; }
#define ILLEGALTERMIDCHARS "&?+% =/\\\"<>"
static void checktid(void)
{
char *tc;
for (tc = termid; *tc; tc++) {
if (strchr(ILLEGALTERMIDCHARS, *tc))
exit_msg("e", "termid query arg illegal char: ", *tc);
}
}
static void processquerystr(const char *fullqs)
{
if (!fullqs) return;
qs = fullqs;
while (1) {
if (*qs == '&') qs++;
if (!*qs) break;
if (parsequeryarg("termid=", &termid )) continue;
if (parsequeryarg("logview=", &logview )) continue;
if (parsequeryarg("sblvl=", &sblvl )) continue;
if (parsequeryarg("dtachlog=", &dtachlog )) continue;
fprintf(stderr,
"invalid query string arg at char pos %zu in '%s'\n",
qs - fullqs, fullqs);
qs = strchrnul(qs, '&');
}
}
static void cdhome(void)
{
const char *home;
home = getenv("HOME");
if (!home) warnx("HOME is not set");
else if (-1 == chdir(home)) warn("chdir to home: '%s'", home);
}
void _Noreturn subproc_main(Dtachctx dc)
{
const char *shell;
if (dc->spargs) { set_argv0(dc, 's'); spawner(dc->spargs); }
shell = getenv("SHELL");
if (!shell) {
shell = "/bin/sh";
warnx("$SHELL is not set, defaulting to %s", shell);
}
setenv("TERM", "xterm-256color", 1);
execl(shell, shell, NULL);
err(1, "execl $SHELL, which is: %s", shell ? shell : "<undef>");
}
static const char *socksdir(void)
{
static char *sd;
const char *sockenv;
if (sd) return sd;
sockenv = getenv("WERMSOCKSDIR");
if (sockenv)
sd = strdup(sockenv);
else
xasprintf(&sd, "%s/socks", state_dir());
if (mkdir(sd, 0700) && errno != EEXIST) err(1, "cannot create %s", sd);
return sd;
}
static void appenddir(char **p, int nmb)
{
char *ch;
xasprintf(&ch, "%s/%02d", *p, nmb);
free(*p);
*p = ch;
if (mkdir(*p, 0700) && errno != EEXIST) err(1, "cannot create %s", *p);
}
static int opnforlog(const struct tm *tim, const char *suff)
{
int fd;
char *dir, *fn;
dir = strdup(state_dir());
appenddir(&dir, tim->tm_year+1900);
appenddir(&dir, tim->tm_mon+1);
appenddir(&dir, tim->tm_mday);
xasprintf(&fn, "%s/%s%s", dir, termid, suff);
free(dir);
fd = open(fn, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0) {
warn("open %s", fn);
fd = 0;
}
free(fn);
return fd;
}
void open_logs(void)
{
time_t now;
struct tm tim;
now = time(NULL);
if (!localtime_r(&now, &tim)) err(1, "cannot get time");
/* sblvl configures scrollback logging. If the string has "p" then plain
* logging is on, if "r" then raw logging is on. */
if (!sblvl) sblvl = strdup("p");
if (strchr(sblvl, 'p')) {
wts.writelg = 1;
wts.logde.fd = opnforlog(&tim, "");
}
if (strchr(sblvl, 'r')) {
wts.writerawlg = 1;
wts.rawlogde.fd = opnforlog(&tim, ".raw");
}
}
static Dtachctx prepfordtach(void)
{
Dtachctx dc = calloc(1, sizeof(*dc));
char *dtlogfn = 0;
int lgfd = -1, ok;
struct fdbuf sp = {0};
/* sp is a predictable string to use in the socket name or related
process names. A percent is used in this string to separate the
profile name from the prefix since % is not allowed in profile
names. */
fdb_apnd(&sp, socksdir(), -1);
if (termid) {fdb_apnd(&sp, "/prs%", -1); fdb_apnd(&sp, termid, -1);}
else {fdb_apnd(&sp, "/eph%", -1); fdb_itoa(&sp, getpid());}
fdb_apnc(&sp, 0);
dc->sockpath = (char *) sp.bf;
sp.bf = 0;
fdb_finsh(&sp);
dc->isephem = !termid;
if (!dtachlog) return dc;
ok = 0;
xasprintf(&dtlogfn, "/tmp/dtachlog.%lld", (long long) getpid());
if (0 > (lgfd = open(dtlogfn, O_WRONLY | O_CREAT | O_APPEND, 0600)))
perror("open");
else if (0 > dup2(lgfd, 2))
perror("dup2");
else ok = 1;
fprintf(stderr, "opened %s for dtach logging? %d\n", dtlogfn, ok);
if (lgfd > 0) close(lgfd);
free(dtlogfn);
return dc;
}
struct iterprofspec {
/* where to send any non-log, non-diagnostic output. */
struct fdbuf *sigb;
/* output new sessionm link for each profile to sigfd */
unsigned newsessin : 1;
unsigned sendauxjs : 1; /* send auxiliary js list to sigfd */
unsigned sendpream : 1; /* send preamble for termid to sigfd */
/* diagnostic logging, not used during tests as it is not deterministic.
* Always sent to stderr
*/
unsigned diaglog : 1;
};
static void newsessinhtml(struct iterprofspec *spc, char k, const void *nmarg)
{
const char *litext = nmarg, *litrid = nmarg;
if (!spc->newsessin) return;
switch (k) {
case 's': /* start of profile group */
fdb_apnd(spc->sigb, "<ul id=\"ctl-", -1);
fdb_apnd(spc->sigb, nmarg, -1);
fdb_apnd(spc->sigb, "\" class=\"newsessin-list\">", -1);
break;
case 'b': /* automatic basic item, which has empty terminal ID */
litext = "<em>basic</em>";
litrid = "";
case 'i': /* profile item */
fdb_apnd(spc->sigb,
"<li><a class=\"newsessin-link\" href=\"/?termid=",
-1);
fdb_apnd(spc->sigb, litrid, -1);
fdb_apnd(spc->sigb, "\">", -1);
fdb_apnd(spc->sigb, litext, -1);
fdb_apnd(spc->sigb, "</a>", -1);
break;
case 'e': /* end of profile group */
fdb_apnd(spc->sigb, "</ul>\n", -1);
break;
default: abort();
}
}
static int proflines(
const char *grpname, const char *prffn, struct iterprofspec *spc)
{
const char *cmpname;
int lineno = 0, namematc = 0, namerr = 0;
char fld, eofield, namemat, err = 0, startedjs;
char begunprenam, c;
struct fdbuf nmbuf = {0};
FILE *pff = fopen(prffn, "r");
if (!pff) {
perror("fopen for profile");
fprintf(stderr, "prpath=%s group=%s\n", prffn, grpname);
return 0;
}
newsessinhtml(spc, 's', grpname);
c = '\n';
do {
if (c == '\n') {
cmpname = termid ? termid : "";
namemat = 0;
fld = 'n';
startedjs = 0;
begunprenam = 0;
nmbuf.len = 0;
namerr = 0;
lineno++;
}
clearerr(pff);
c = getc(pff);
if (c == EOF && ferror(pff)) {
perror("getc for profile def file");
break;
}
eofield = c == '\n' || c == EOF || c == '\t';
switch (fld) {
/* n = name field, p = preamble, j = auxjs list */
case 'n':
if (eofield) {
namemat = cmpname &&
(!*cmpname || '.' == *cmpname);
namematc += namemat;
fld = 'p';
if (spc->newsessin && !namerr && nmbuf.len) {
fdb_apnc(&nmbuf, 0);
newsessinhtml(spc, 'i', nmbuf.bf);
}
break;
}
if (strchr(ILLEGALTERMIDCHARS ".", c)) {
fprintf(stderr,
"illegal char '%c' in profile name", c);
err = 1;
namerr = 1;
cmpname = NULL;
}
if (cmpname && *cmpname++ != c) cmpname = NULL;
fdb_apnc(&nmbuf, c);
break;
case 'p':
if (eofield) {
fld = 'j';
if (begunprenam) fdb_apnc(spc->sigb, '\n');
break;
}
if (namemat && spc->sendpream) {
fdb_apnc(spc->sigb, c);
begunprenam = 1;
}
break;
case 'j':
if (eofield) {
if (startedjs) fdb_apnc(spc->sigb, '\n');
break;
}
if (namemat && spc->sendauxjs) {
if (!startedjs)
fdb_apnd(spc->sigb, "\\@auxjs:", -1);
startedjs = 1;
fdb_apnc(spc->sigb, c);
}
break;
default: errx(1, "BUG unexpected field type %d", fld);
}
if (err) {
fprintf(stderr, " group=%s line=%d\n",
grpname, lineno);
err = 0;
}
} while (c != EOF);
newsessinhtml(spc, 'e', 0);
fdb_finsh(&nmbuf);
fclose(pff);
return namematc;
}
static void iterprofs(const char *ppaths_, struct iterprofspec *spc)
{
DIR *pd;
char *ppaths = strdup(ppaths_), *tkn, *savepp, *ppitr, *ffn = 0;
struct dirent *den;
int namematc = 0;
/* "--" prefix to sort this category first. This hack can be removed
* once the sorting logic is moved out of shell. */
newsessinhtml(spc, 's', "--basic");
newsessinhtml(spc, 'b', 0);
newsessinhtml(spc, 'e', 0);
for (ppitr = ppaths; ; ppitr = NULL) {
if (!(tkn = strtok_r(ppitr, ":", &savepp))) break;
fprintf(stderr, "reading profile dir at: %s\n", tkn);
pd = opendir(tkn);
if (!pd) {
perror("opendir");
continue;
}
for (;;) {
errno = 0;
den = readdir(pd);
if (!den) {
if (errno) perror("readdir");
break;
}
free(ffn);
xasprintf(&ffn, "%s/%s", tkn, den->d_name);
if (den->d_name[0] == '.') {
if (spc->diaglog)
fprintf(stderr,
" skipped file '%s'\n",
den->d_name);
continue;
}
if (spc->diaglog)
fprintf(stderr, " group %s\n", den->d_name);
namematc += proflines(den->d_name, ffn, spc);
}
closedir(pd);
}
free(ppaths);
free(ffn);
if (namematc || !termid || !*termid) return;
if (spc->sendauxjs || spc->sendpream)
fprintf(stderr, "profile with name '%s' not found\n", termid);
}
static const char *profpathsavd;
static const char *profpath(void)
{
const char *p = profpathsavd;
char *def;
if (!p) p = getenv("WERMPROFPATH");
if (!p) {
xasprintf(&def, "%s/profiles:%s/.config/werm/profiles",
getenv("WERMSRCDIR"), getenv("HOME"));
p = def;
}
return profpathsavd=p;
}
static void tmstate4cli(struct wrides *de)
{
struct tmobj *o0, *o1;
int *f0, *f1;
struct fdbuf sigb = {de, .cap = 1024};
if (!wts.t) return;
fdb_apnd(&sigb, "\\@state:{\"bs\":[", -1);
o0 = tmobjs.objel;
o1 = tmobjs.objel+tmobjs.capac;
for (;;) {
if (o0==o1) break;
if (o0!=tmobjs.objel) fdb_apnc(&sigb, ',');
if (!o0->fs) { fdb_itoa(&sigb, o0->fct); goto nexo; }
f0 = o0->fs;
f1 = o0->fs + o0->fct;
fdb_apnc(&sigb, '[');
for (;;) {
if (f0==f1) break;
if (f0!=o0->fs) fdb_apnc(&sigb, ',');
fdb_itoa(&sigb, *f0++);
}
fdb_apnc(&sigb, ']');
nexo:
o0++;
}
fdb_apnd(&sigb, "],\"fh\":", -1);
fdb_itoa(&sigb, tmobjs.bufsfreehead);
fdb_apnd(&sigb, ",\"t\":", -1);
fdb_itoa(&sigb, wts.t);
fdb_apnd(&sigb, "}\n", -1);
fdb_finsh(&sigb);
}
static void simpdump4cl(struct wrides *de)
{
struct fdbuf sigb = {de};
if (!wts.t) return;
fdb_apnd(&sigb, MODE_ALTSCREEN & term(wts.t,mode) ? "\\s2":"\\s1", -1);
fdb_finsh(&sigb);
}
static void profinfo4cli(struct wrides *de)
{
struct fdbuf sigb = {de};
iterprofs(profpath(), &((struct iterprofspec){
.sigb = &sigb,
.sendauxjs = 1,
.diaglog = 1,
}));
fdb_finsh(&sigb);
}
void send_pream(int fd)
{
struct fdbuf ob = {&(struct wrides){fd}};
if (logview) {
fdb_apnd(&ob, ". $WERMSRCDIR/util/logview ", -1);
fdb_apnd(&ob, logview, -1);
fdb_apnd(&ob, "\r", -1);
}
else {
iterprofs(profpath(), &((struct iterprofspec){
.sigb = &ob,
.sendpream = 1,
.diaglog = 1,
}));
}
fdb_finsh(&ob);
}
static void linetitl(struct fdbuf *o)
{
int td = deqmk(), y = curs_y(term(wts.t,curs));
for (;;) {
td = tpushlinestr(wts.t, td, y);
if (--y < 0 || deqbytsiz(td)) break;
}
fdb_json(o, deqtostring(td, 0), deqbytsiz(td));
tmfree(td);
}
/* Array with elements:
0: print_atch_clis() array
1: termid string
2: title string */
static void atchstatejson(Dtachctx dc, struct wrides *cliutd)
{
struct fdbuf hbuf = {cliutd};
fdb_apnc(&hbuf, '[');
print_atch_clis(dc, &hbuf);
fdb_apnc(&hbuf, ',');
fdb_json(&hbuf, termid ? termid : "", -1);
fdb_apnc(&hbuf, ',');
if (wts.clnttl) fdb_json(&hbuf, wts.ttl, ttl_len());
else linetitl(&hbuf);
fdb_apnd(&hbuf, "]\n", -1);
fdb_finsh(&hbuf);
}
static void fwdlinetobuf(int fd, struct fdbuf *ob)
{
int rdn;
char buf[512];
for (;;) {
rdn = read(fd, buf, sizeof(buf));
if (rdn < 0) {
if (errno == EINTR) continue;
perror("read line from socket");
break;
}
fdb_apnd(ob, buf, rdn);
if (buf[rdn-1] == '\n') break;
}
}
static void atchsesnlis(struct wrides *de)
{
DIR *skd;
struct dirent *sken;
char *spth = 0;
int sc, firs = 1;
struct fdbuf rb = {0};
if (!(skd = opendir(socksdir()))) {
perror("opendir: socks");
puts("error opening socks directory");
exit(1);
}
fdb_apnc(&rb, '[');
for (;;) {
errno = 0;
sken = readdir(skd);
if (!sken) {
if (errno) perror("readdir: socks");
break;
}
if (strncmp(sken->d_name, "prs%", 4) &&
strncmp(sken->d_name, "eph%", 4))
continue;
xasprintf(&spth, "%s/%s", socksdir(), sken->d_name);
sc = connect_uds_as_client(spth);
free(spth);
if (sc < 0) continue;
if (!firs) fdb_apnc(&rb, ',');
firs = 0;
full_write(&(struct wrides){sc}, "\\A", -1);
fwdlinetobuf(sc, &rb);
close(sc);
}
fdb_apnc(&rb, ']');
resp_dynamc(de, 'j', 200, rb.bf, rb.len);
fdb_finsh(&rb);
closedir(skd);
}
static void writetosubproccore(
/* Where to send output for the process; this is raw keyboard input. */
struct wrides *procde,
/* Where to send output for attached client. */
struct wrides *clioutde,
Dtachctx dc,
struct clistate *cls,
/* Data received from client which is the escaped keyboard input. */
const unsigned char *buf,
unsigned bufsz)
{
unsigned wi;
unsigned char byte, cursmvbyte;
struct fdbuf kbdb = {procde};
wts.sendsigwin = 0;
wi = 0;
while (bufsz--) {
byte = *buf++;
switch (wts.escp) {
case 0:
if (byte == '\n') continue;
if (byte == '\\')
wts.escp = '1';
else
fdb_apnc(&kbdb, byte);
break;
case '1':
cursmvbyte = 0;
wts.escp = 0;
switch (byte) {
case 'n':
fdb_apnc(&kbdb, '\n');
break;
case '\\':
fdb_apnc(&kbdb, '\\');
break;
case 'w':
case 't':
case 'i':
wts.altbufsz = 0;
wts.escp = byte;
break;
case 'd':
/* TODO: dump tmeng state */
dump_wts();
break;
/* escape that alerts master we want to see terminal
output, and to alert master that it's OK to read
from subproc since there is a client ready to read
the output. */
case 'N':
cls->wantsoutput=1;
if (wts.ttl[0]) recounttitl(clioutde);
if (wts.allowtmstate) tmstate4cli(clioutde);
else simpdump4cl(clioutde);
profinfo4cli(clioutde);
break;
case 'A': atchstatejson(dc, clioutde); break;
/* directions, home, end */
case '^': cursmvbyte = 'A'; break;
case 'v': cursmvbyte = 'B'; break;
case '>': cursmvbyte = 'C'; break;
case '<': cursmvbyte = 'D'; break;
case 'e': cursmvbyte = 'F'; break;
case 'h': cursmvbyte = 'H'; break;
default:
warnx("unknown escape: %d\n", byte);
}
if (!cursmvbyte) break;
fdb_apnc(&kbdb, 033);
/* application cursor mode does O rather than [ */
fdb_apnc(&kbdb, wts.t &&
MODE_APPCURSOR & term(wts.t,mode)
? 'O' : '[');
fdb_apnc(&kbdb, cursmvbyte);
break;
case 'w':
wts.winsize[wts.altbufsz++] = byte;
if (wts.altbufsz != sizeof(wts.winsize)) break;
wts.sendsigwin = (
2 == sscanf(wts.winsize, "%4hu%4hu",
&wts.swrow, &wts.swcol));
if (!wts.sendsigwin)
warn("invalid winsize: %.8s", wts.winsize);
wts.escp = 0;
break;
case 't':
if (byte == '\n') {
wts.escp = 0;
byte = 0;
wts.clnttl = !!wts.altbufsz;
}
TMpokettl(wts.altbufsz++, byte);
if (!byte) recounttitl(clioutde);
break;
case 'i':
if (wts.altbufsz >= sizeof cls->endpnt) abort();
cls->endpnt[wts.altbufsz] = byte;
if (++wts.altbufsz == sizeof cls->endpnt) wts.escp = 0;
break;
default: errx(1, "unknown escape: %d", wts.escp);
}
}
fdb_finsh(&kbdb);
if (wts.t && wts.sendsigwin) tresize(wts.t, wts.swcol, wts.swrow);
}
void process_kbd(int clioutfd, Dtachctx dc, struct clistate *cls,
unsigned char *buf, size_t bufsz)
{
struct wrides ptyde = { dc->the_pty.fd }, clide = { clioutfd };
struct winsize ws = {0};
writetosubproccore(&ptyde, &clide, dc, cls, buf, bufsz);
if (!wts.sendsigwin) return;
ws.ws_row = wts.swrow;
ws.ws_col = wts.swcol;
if (0 > ioctl(dc->the_pty.fd, TIOCSWINSZ, &ws))
warn("setting window size");
}
static void putrwout(void)
{
struct wrides de = {1, "putrwout"};
full_write(&de, therout.bf, therout.len);
therout.len = 0;
}
static Dtachctx testdc(char op)
{
static Dtachctx dc;
switch (op) {
case 'g': if (!dc) abort();
break; case 'r':
free(dc);
dc = calloc(1, sizeof(*dc));
break; default: abort();
}
return dc;
}
static struct clistate *testclistate(char op)
{
static struct clistate *s;
switch (op) {
case 'g':
if (!s) abort();
break;
case 'r':
free(s);
s = calloc(1, sizeof(*s));
break;
case 'i':
full_write(&(struct wrides){1, "endpnt"},
s->endpnt, sizeof(s->endpnt));
break;
case 'o':
printf("wantsoutput=%u\n", s->wantsoutput);
break;
default: abort();
}
return s;
}
static void testreset(void)
{
term_fre(wts.t);
memset(&wts, 0, sizeof(wts));
therout.len = 0;
free(termid); termid = 0;
free(logview); logview = 0;
free(sblvl); sblvl = 0;
profpathsavd = "";
testclistate('r');
testdc('r');
}
static void writetosp0term(const void *s)
{
struct wrides pty = {1, "pty"}, cli = {1, "cli"};
writetosubproccore(
&pty, &cli, testdc('g'), testclistate('g'), s, strlen(s));
if (wts.sendsigwin)
printf("sigwin r=%d c=%d\n", wts.swrow, wts.swcol);
}
static void tstdesc(const char *d) { printf("TEST: %s\n", d); }
static void testqrystring(void)
{
tstdesc("parse termid arg");
testreset();
processquerystr("termid=hello");
printf("%s\n", termid);
tstdesc("unrecognized query string arg");
testreset();
processquerystr("logview=test&huhtest=987");
printf("logview=%s\n", logview);
tstdesc("empty arg, escapes, and omitted arg");
testreset();
processquerystr("sblvl=&termid=%21escapes%7eand%45");
printf("%zu,%s,%d\n", strlen(sblvl), termid, !logview);
}
static void testiterprofs(void)
{
struct wrides sigde = {1, "profsig"};
struct fdbuf sigb = {&sigde, 512};