~ubuntu-branches/ubuntu/gutsy/edbrowse/gutsy

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
/* stringfile.c: manage strings, files, and directories for edbrowse.
* Copyright (c) Karl Dahlke, 2006
* This file is part of the edbrowse project, released under GPL.
 */

#include "eb.h"

#include <sys/stat.h>
#ifdef DOSLIKE
#include <dos.h>
#else
#include <dirent.h>
#ifdef SYSBSD
#include <termios.h>
typedef struct termios termstruct;
#define TTY_GET_COMMAND TIOCGETA
#define TTY_SET_COMMAND TIOCSETA
#else
#include <termio.h>
typedef struct termio termstruct;
#define TTY_GET_COMMAND TCGETA
#define TTY_SET_COMMAND TCSETA
#endif
#include <sys/utsname.h>
#endif
#include <pcre.h>


/*********************************************************************
Allocate and manage memory.
Allocate and copy strings.
If we're out of memory, the program aborts.  No error legs.
*********************************************************************/

void *
allocMem(unsigned n)
{
    void *s;
    if(!n)
	return EMPTYSTRING;
    if(!(s = malloc(n)))
	errorPrint("@error allocating %u bytes", n);
    return s;
}				/* allocMem */

void *
allocZeroMem(unsigned n)
{
    void *s;
    if(!n)
	return EMPTYSTRING;
    if(!(s = calloc(n, 1)))
	errorPrint("@error callocating %u bytes", n);
    return s;
}				/* allocZeroMem */

void *
reallocMem(void *p, unsigned n)
{
    void *s;
    if(!n)
	errorPrint("@reallocMem(p,0)");
    if(!p)
	errorPrint("@reallocMem(0,%d)", n);
    if(p == EMPTYSTRING)
	return allocMem(n);
    if(!(s = realloc(p, n)))
	errorPrint("@error re-allocating %u bytes", n);
    return s;
}				/* reallocMem */

void
nzFree(void *s)
{
    if(s && s != EMPTYSTRING)
	free(s);
}				/* nzFree */

uchar
fromHex(char d, char e)
{
    d |= 0x20, e |= 0x20;
    if(d >= 'a')
	d -= ('a' - '9' - 1);
    if(e >= 'a')
	e -= ('a' - '9' - 1);
    d -= '0', e -= '0';
    return ((((uchar) d) << 4) | (uchar) e);
}				/* fromHex */

char *
appendString(char *s, const char *p)
{
    int slen = strlen(s);
    int plen = strlen(p);
    s = reallocMem(s, slen + plen + 1);
    strcpy(s + slen, p);
    return s;
}				/* appendstring */

char *
prependString(char *s, const char *p)
{
    int slen = strlen(s);
    int plen = strlen(p);
    char *t = allocMem(slen + plen + 1);
    strcpy(t, p);
    strcpy(t + plen, s);
    nzFree(s);
    return t;
}				/* prependstring */

void
skipWhite(const char **s)
{
    const char *t = *s;
    while(isspaceByte(*t))
	++t;
    *s = t;
}				/* skipWhite */

void
stripWhite(char *s)
{
    const char *t = s;
    char *u;
    skipWhite(&t);
    if(t > s)
	strcpy(s, t);
    u = s + strlen(s);
    while(u > s && isspaceByte(u[-1]))
	--u;
    *u = 0;
}				/* stripWhite */

/* compress white space */
void
spaceCrunch(char *s, bool onespace, bool unprint)
{
    int i, j;
    char c;
    bool space = true;
    for(i = j = 0; c = s[i]; ++i) {
	if(isspaceByte(c)) {
	    if(!onespace)
		continue;
	    if(!space)
		s[j++] = ' ', space = true;
	    continue;
	}
	if(unprint && !isprintByte(c))
	    continue;
	s[j++] = c, space = false;
    }
    if(space && j)
	--j;			/* drop trailing space */
    s[j] = 0;
}				/* spaceCrunch */

/* OO has a lot of unnecessary overhead, and a few inconveniences,
 * but I really miss it right now.  The following
 * routines make up for the lack of simple string concatenation in C.
 * The string space allocated is always a power of 2 - 1, starting with 1.
 * Each of these routines puts an extra 0 on the end of the "string". */

char *
initString(int *l)
{
    *l = 0;
    return EMPTYSTRING;
}

void
stringAndString(char **s, int *l, const char *t)
{
    char *p = *s;
    int oldlen, newlen, x;
    oldlen = *l;
    newlen = oldlen + strlen(t);
    *l = newlen;
    ++newlen;			/* room for the 0 */
    x = oldlen ^ newlen;
    if(x > oldlen) {		/* must realloc */
	newlen |= (newlen >> 1);
	newlen |= (newlen >> 2);
	newlen |= (newlen >> 4);
	newlen |= (newlen >> 8);
	newlen |= (newlen >> 16);
	p = reallocMem(p, newlen);
	*s = p;
    }
    strcpy(p + oldlen, t);
}				/* stringAndString */

void
stringAndBytes(char **s, int *l, const char *t, int cnt)
{
    char *p = *s;
    int oldlen, newlen, x;
    oldlen = *l;
    newlen = oldlen + cnt;
    *l = newlen;
    ++newlen;
    x = oldlen ^ newlen;
    if(x > oldlen) {		/* must realloc */
	newlen |= (newlen >> 1);
	newlen |= (newlen >> 2);
	newlen |= (newlen >> 4);
	newlen |= (newlen >> 8);
	newlen |= (newlen >> 16);
	p = reallocMem(p, newlen);
	*s = p;
    }
    memcpy(p + oldlen, t, cnt);
    p[oldlen + cnt] = 0;
}				/* stringAndBytes */

void
stringAndChar(char **s, int *l, char c)
{
    char *p = *s;
    int oldlen, newlen, x;
    oldlen = *l;
    newlen = oldlen + 1;
    *l = newlen;
    ++newlen;
    x = oldlen ^ newlen;
    if(x > oldlen) {		/* must realloc */
	newlen |= (newlen >> 1);
	newlen |= (newlen >> 2);
	newlen |= (newlen >> 4);
	newlen |= (newlen >> 8);
	newlen |= (newlen >> 16);
	p = reallocMem(p, newlen);
	*s = p;
    }
    p[oldlen] = c;
    p[oldlen + 1] = 0;
}				/* stringAndChar */

void
stringAndNum(char **s, int *l, int n)
{
    char a[16];
    sprintf(a, "%d", n);
    stringAndString(s, l, a);
}				/* stringAndNum */

/* 64M 16K etc */
void
stringAndKnum(char **s, int *l, int n)
{
    char a[16];
    if(n && n / (1024 * 1024) * (1024 * 1024) == n)
	sprintf(a, "%dM", n / (1024 * 1024));
    else if(n && n / 1024 * 1024 == n)
	sprintf(a, "%dK", n / 1024);
    else
	sprintf(a, "%d", n);
    stringAndString(s, l, a);
}				/* stringAndKnum */

char *
cloneString(const char *s)
{
    char *t;
    unsigned len;

    if(!s)
	return 0;
    if(!*s)
	return EMPTYSTRING;
    len = strlen(s) + 1;
    t = allocMem(len);
    strcpy(t, s);
    return t;
}				/* cloneString */

char *
cloneMemory(const char *s, int n)
{
    char *t = allocMem(n);
    if(n)
	memcpy(t, s, n);
    return t;
}				/* cloneMemory */

void
clipString(char *s)
{
    int len;
    if(!s)
	return;
    len = strlen(s);
    while(--len >= 0)
	if(!isspaceByte(s[len]))
	    break;
    s[len + 1] = 0;
}				/* clipString */

char *
Cify(const char *s, int n)
{
    char *u;
    char *t = allocMem(n + 1);
    if(n)
	memcpy(t, s, n);
    for(u = t; u < t + n; ++u)
	if(*u == 0)
	    *u = ' ';
    *u = 0;
    return t;
}				/* Cify */

/* pull a substring out of a larger string,
 * and make it its own allocated string */
char *
pullString(const char *s, int l)
{
    char *t;
    if(!l)
	return EMPTYSTRING;
    t = allocMem(l + 1);
    memcpy(t, s, l);
    t[l] = 0;
    return t;
}				/* pullString */

char *
pullString1(const char *s, const char *t)
{
    return pullString(s, t - s);
}

int
stringIsNum(const char *s)
{
    int n;
    if(!isdigitByte(s[0]))
	return -1;
    n = strtol(s, (char **)&s, 10);
    if(*s)
	return -1;
    return n;
}				/* stringIsNum */

bool
stringIsFloat(const char *s, double *dp)
{
    const char *t;
    *dp = strtod(s, (char **)&t);
    if(*t)
	return false;		/* extra stuff at the end */
    return true;
}				/* stringIsFloat */

bool
isSQL(const char *s)
{
    char c;
    const char *c1 = 0, *c2 = 0;
    c = *s;
    if(!isalphaByte(c))
	goto no;
    for(++s; c = *s; ++s) {
	if(c == '_')
	    continue;
	if(isalnumByte(c))
	    continue;
	if(c == ':') {
	    if(c1)
		goto no;
	    c1 = s;
	    continue;
	}
	if(c == ']') {
	    c2 = s;
	    goto yes;
	}
    }
  no:
    return false;
  yes:
    return true;
}				/* isSQL */

bool
memEqualCI(const char *s, const char *t, int len)
{
    char c, d;
    while(len--) {
	c = *s, d = *t;
	if(islowerByte(c))
	    c = toupper(c);
	if(islowerByte(d))
	    d = toupper(d);
	if(c != d)
	    return false;
	++s, ++t;
    }
    return true;
}				/* memEqualCI */

char *
strstrCI(const char *base, const char *search)
{
    int l = strlen(search);
    while(*base) {
	if(memEqualCI(base, search, l))
	    return (char *)base;
	++base;
    }
    return 0;
}				/* strstrCI */

bool
stringEqualCI(const char *s, const char *t)
{
    char c, d;
    while((c = *s) && (d = *t)) {
	if(islowerByte(c))
	    c = toupper(c);
	if(islowerByte(d))
	    d = toupper(d);
	if(c != d)
	    return false;
	++s, ++t;
    }
    if(*s)
	return false;
    if(*t)
	return false;
    return true;
}				/* stringEqualCI */

int
stringInList(const char *const *list, const char *s)
{
    int i = 0;
    if(!list)
	errorPrint("@stringInList(null,...)");
    if(s)
	while(*list) {
	    if(stringEqual(s, *list))
		return i;
	    ++i;
	    ++list;
	}
    return -1;
}				/* stringInList */

int
stringInListCI(const char *const *list, const char *s)
{
    int i = 0;
    if(!list)
	errorPrint("@stringInListCI(null,...)");
    if(s)
	while(*list) {
	    if(stringEqualCI(s, *list))
		return i;
	    ++i;
	    ++list;
	}
    return -1;
}				/* stringInListCI */

int
charInList(const char *list, char c)
{
    char *s;
    if(!list)
	errorPrint("@charInList(null,...)");
    s = strchr(list, c);
    if(!s)
	return -1;
    return s - list;
}				/* charInList */

/* In an empty list, next and prev point back to the list, not to 0. */
/* We also allow zero. */
bool
listIsEmpty(const struct listHead * l)
{
    return l->next == l || l->next == 0;
}				/* listIsEmpty */

void
initList(struct listHead *l)
{
    l->prev = l->next = l;
}				/* initList */

void
delFromList(void *x)
{
    struct listHead *xh = x;
    ((struct listHead *)xh->next)->prev = xh->prev;
    ((struct listHead *)xh->prev)->next = xh->next;
}				/* delFromList */

void
addToListFront(struct listHead *l, void *x)
{
    struct listHead *xh = x;
    xh->next = l->next;
    xh->prev = l;
    l->next = x;
    ((struct listHead *)xh->next)->prev = x;
}				/* addToListFront */

void
addToListBack(struct listHead *l, void *x)
{
    struct listHead *xh = x;
    xh->prev = l->prev;
    xh->next = l;
    l->prev = x;
    ((struct listHead *)xh->prev)->next = x;
}				/* addToListBack */

void
addAtPosition(void *p, void *x)
{
    struct listHead *xh = x;
    struct listHead *ph = p;
    xh->prev = p;
    xh->next = ph->next;
    ph->next = x;
    ((struct listHead *)xh->next)->prev = x;
}				/* addAtPosition */

void
freeList(struct listHead *l)
{
    while(!listIsEmpty(l)) {
	void *p = l->next;
	delFromList(p);
	nzFree(p);
    }
}				/* freeList */

/* like isalnumByte, but allows _ and - */
bool
isA(char c)
{
    if(isalnumByte(c))
	return true;
    return (c == '_' || c == '-');
}				/* isA */

bool
isquote(char c)
{
    return c == '"' || c == '\'';
}				/* isquote */

/* Gather at most 5 parameters from a vararg list
 * and place them in local variables.
 * Only take as many as indicated by the percents in a sprintf string.
 * If we blindly take more, we risk core dumps, at least on the Sun. */

void
varargLocals(va_list p, const char *msg, long *locals)
{
    const char *s = msg;
    int cnt;

    for(cnt = 0; cnt < 5; msg = s) {
	s = strchr(msg, '%');
	if(!s)
	    break;
	++s;
	if(*s == '%') {
	    ++s;
	    continue;
	}
	if(strchr("-.0123456789lhusdfxco", *s)) {
	    long n = va_arg(p, long);
	    locals[cnt++] = n;
	}
    }				/* while finding percents in msg */

/* a little protection, in case they pass too few arguments */
    while(cnt < 5)
	locals[cnt++] = (long)"argmissing";
}				/* varargLocals */

/* print an error message */
void
errorPrint(const char *msg, ...)
{
    char bailflag = 0;
    va_list p;
    long a[5];
    va_start(p, msg);
    varargLocals(p, msg, a);
    va_end(p);

    if(*msg == '@') {
	++msg;
	bailflag = 1;
	fprintf(stderr, "disaster, ");
    } else if(isdigitByte(*msg)) {
	++msg;
	bailflag = *msg - '0';
    }

    fprintf(stderr, msg, a[0], a[1], a[2], a[3], a[4]);
    fprintf(stderr, "\n");

    if(bailflag)
	exit(bailflag);
}				/* errorPrint */

void
debugPrint(int lev, const char *msg, ...)
{
    va_list p;
    long a[5];
    if(lev > debugLevel)
	return;
    va_start(p, msg);
    varargLocals(p, msg, a);
    va_end(p);
    printf(msg, a[0], a[1], a[2], a[3], a[4]);
    printf("\n");
    if(lev == 0 && !memcmp(msg, "warning", 7))
	eeCheck();
}				/* debugPrint */

char errorMsg[4000];
/* Show the error message, not just the question mark, after these commands. */
static const char showerror_cmd[] = "AbefMqrw^";

/* Set the error message.  Type h to see the message. */
void
setError(const char *msg, ...)
{
    va_list p;
    long a[5];

    if(!msg) {
	errorMsg[0] = 0;
	return;
    }

    va_start(p, msg);
    varargLocals(p, msg, a);
    va_end(p);
/* Yeah I know, there's a va_list sprintf call; this is old code. */
    sprintf(errorMsg, msg, a[0], a[1], a[2], a[3], a[4]);

/* sanity check */
    if(strlen(errorMsg) >= sizeof (errorMsg)) {
	printf("disaster, error message, length %d is too long\n",
	   strlen(errorMsg));
	puts(errorMsg);
	exit(1);
    }
}				/* setError */

void
showError(void)
{
    printf("%s\n", errorMsg[0] ? errorMsg : "no errors");
}				/* showError */

void
showErrorConditional(char cmd)
{
    if(helpMessagesOn || strchr(showerror_cmd, cmd))
	showError();
    else
	printf("?\n");
}				/* showErrorConditional */

void
showErrorAbort(void)
{
    errorPrint("1%s", errorMsg);
}				/* showErrorAbort */

void
browseError(const char *msg, ...)
{
    va_list p;
    long a[5];
    if(ismc)
	return;
    if(browseLocal != 1)
	return;
    va_start(p, msg);
    varargLocals(p, msg, a);
    va_end(p);
    if(browseLine) {
	printf("line %d: ", browseLine);
	cw->labels[4] = browseLine;
    } else
	printf("browse error: ");
    printf(msg, a[0], a[1], a[2], a[3], a[4]);
    printf("\n");
    browseLocal = 2;
}				/* browseError */

/* Javascript errors, we need to see these no matter what. */
void
runningError(const char *msg, ...)
{
    va_list p;
    long a[5];
    if(ismc)
	return;
    va_start(p, msg);
    varargLocals(p, msg, a);
    va_end(p);
    if(browseLine) {
	printf("line %d: ", browseLine);
	cw->labels[4] = browseLine;
    }
    printf(msg, a[0], a[1], a[2], a[3], a[4]);
    printf("\n");
    browseLocal = 2;
}				/* runningError */

/* Turn perl string into C string, and complain about nulls. */
int
perl2c(char *t)
{
    int n = 0;
    while(*t != '\n') {
	if(*t == 0)
	    ++n;
	++t;
    }
    *t = 0;			/* now it's a C string */
    return n;			/* number of nulls */
}				/* perl2c */

/* The length of a perl string includes its terminating newline */
unsigned
pstLength(pst s)
{
    pst t;
    if(!s)
	errorPrint("@null pointer in pstLength");
    t = s;
    while(*t != '\n')
	++t;
    return t + 1 - s;
}				/* pstLength */

pst
clonePstring(pst s)
{
    pst t;
    unsigned len;
    if(!s)
	return s;
    len = pstLength(s);
    t = allocMem(len);
    memcpy(t, s, len);
    return t;
}				/* clonePstring */

void
copyPstring(pst s, const pst t)
{
    int len = pstLength(t);
    memcpy(s, t, len);
}				/* copyPstring */

bool
fileIntoMemory(const char *filename, char **data, int *len)
{
    int length, n, fh;
    char *buf;
    char ftype = fileTypeByName(filename, false);
    if(ftype && ftype != 'f') {
	setError("%s is not a regular file", filename);
	return false;
    }
    fh = open(filename, O_RDONLY | O_BINARY);
    if(fh < 0) {
	setError("cannot open %s", filename);
	return false;
    }
    length = fileSizeByName(filename);
    if(length < 0) {
	close(fh);
	return false;
    }				/* should never hapen */
    if(length > maxFileSize) {
	setError("file is too large, limit 40MB");
	close(fh);
	return false;
    }
    buf = allocMem(length + 2);
    n = 0;
    if(length)
	n = read(fh, buf, length);
    close(fh);			/* don't need that any more */
    if(n < length) {
	setError("cannot read the contents of %s", filename);
	free(buf);
	return false;
    }
    *data = buf;
    *len = length;
    return true;
}				/* fileIntoMemory */

/* shift string to upper, lower, or mixed case */
/* action is u, l, or m. */
void
caseShift(char *s, char action)
{
    char c;
    int mc = 0;
    bool ws = true;

    for(; c = *s; ++s) {
	if(action == 'u') {
	    if(isalphaByte(c))
		*s = toupper(c);
	    continue;
	}
	if(action == 'l') {
	    if(isalphaByte(c))
		*s = tolower(c);
	    continue;
	}
/* mixed case left */
	if(isalphaByte(c)) {
	    if(ws)
		c = toupper(c);
	    else
		c = tolower(c);
	    if(ws && c == 'M')
		mc = 1;
	    else if(mc == 1 && c == 'c')
		mc = 2;
	    else if(mc == 2) {
		c = toupper(c);
		mc = 0;
	    } else
		mc = 0;
	    *s = c;
	    ws = false;
	    continue;
	}
	ws = true, mc = 0;
    }				/* loop */
}				/* caseShift */


/*********************************************************************
Manage files, directories, and terminal IO.
You'll see some conditional compilation when this program
is ported to other operating systems.
*********************************************************************/

/* Return the type of a file.
 * Make it a capital letter if you are going through a link.
 * I think this will work on Windows, not sure.
 * But the link feature is Unix specific. */

char
fileTypeByName(const char *name, bool showlink)
{
    struct stat buf;
    bool islink = false;
    char c;
    int mode;
    if(lstat(name, &buf)) {
	setError("cannot access %s", name);
	return 0;
    }
    mode = buf.st_mode & S_IFMT;
    if(mode == S_IFLNK) {	/* symbolic link */
	islink = true;
/* If this fails, I'm guessing it's just a file. */
	if(stat(name, &buf))
	    return (showlink ? 'F' : 0);
	mode = buf.st_mode & S_IFMT;
    }
    c = 'f';
    if(mode == S_IFDIR)
	c = 'd';
#ifndef DOSLIKE
/* I don't think these are Windows constructs. */
    if(mode == S_IFBLK)
	c = 'b';
    if(mode == S_IFCHR)
	c = 'c';
    if(mode == S_IFIFO)
	c = 'p';
    if(mode == S_IFSOCK)
	c = 's';
#endif
    if(islink & showlink)
	c = toupper(c);
    return c;
}				/* fileTypeByName */

int
fileSizeByName(const char *name)
{
    struct stat buf;
    if(stat(name, &buf)) {
	setError("cannot access %s", name);
	return -1;
    }
    return buf.st_size;
}				/* fileSizeByName */

time_t
fileTimeByName(const char *name)
{
    struct stat buf;
    if(stat(name, &buf)) {
	setError("cannot access %s", name);
	return -1;
    }
    return buf.st_mtime;
}				/* fileSizeByName */

#ifndef DOSLIKE

static termstruct savettybuf;
void
ttySaveSettings(void)
{
    isInteractive = isatty(0);
    if(isInteractive) {
	if(ioctl(0, TTY_GET_COMMAND, &savettybuf))
	    errorPrint("@canot use ioctl() to manage the tty");
    }
}				/* ttySaveSettings */

static void
ttyRestoreSettings(void)
{
    if(isInteractive)
	ioctl(0, TTY_SET_COMMAND, &savettybuf);
}				/* ttyRestoreSettings */

/* put the tty in raw mode.
 * Review your Unix manual on termio.
 * min>0 time>0:  return min chars, or as many as you have received
 *   when time/10 seconds have elapsed between characters.
 * min>0 time=0:  block until min chars are received.
 * min=0 time>0:  return 1 char, or 0 if the timer expires.
 * min=0 time=0:  nonblocking, return whatever chars have been received. */
static void
ttyRaw(int charcount, int timeout, bool isecho)
{
    termstruct buf = savettybuf;	/* structure copy */
    buf.c_cc[VMIN] = charcount;
    buf.c_cc[VTIME] = timeout;
    buf.c_lflag &= ~(ICANON | ECHO);
    if(isecho)
	buf.c_lflag |= ECHO;
    ioctl(0, TTY_SET_COMMAND, &buf);
}				/* ttyRaw */

/* simulate MSDOS getche() system call */
int
getche(void)
{
    char c;
    fflush(stdout);
    ttyRaw(1, 0, true);
    read(0, &c, 1);
    ttyRestoreSettings();
    return c;
}				/* getche */

int
getch(void)
{
    char c;
    fflush(stdout);
    ttyRaw(1, 0, false);
    read(0, &c, 1);
    ttyRestoreSettings();
    return c;
}				/* getche */

#endif

char
getLetter(const char *s)
{
    char c;
    while(true) {
	c = getch();
	if(strchr(s, c))
	    break;
	printf("\a\b");
	fflush(stdout);
    }
    printf("%c", c);
    return c;
}				/* getLetter */

/* loop through the files in a directory */
/* Hides the differences between DOS, Unix, and NT. */
static bool dirstart = true;

char *
nextScanFile(const char *base)
{
    char *s;
#ifdef DOSLIKE
    static char global[] = "/*.*";
    bool rc;
    short len;
    char *p;
    bool allocate = false;
#ifdef MSDOS
    static struct _find_t dta;
#else
    static struct _finddata_t dta;
    static int handle;
#endif
#else
    struct dirent *de;
    static DIR *df;
#endif

#ifdef DOSLIKE
    if(dirstart) {
	if(base) {
	    len = strlen(base) - 1;
	    p = allocMem(len + 6);
	    strcpy(p, base);
	    allocate = true;
	    if(p[len] == '/' || p[len] == '\\')
		p[len] = 0;
	    strcat(p, global);
	} else
	    p = global +1;
#ifdef MSDOS
	rc = _dos_findfirst(p, (showHiddenFiles ? 077 : 073), &dta);
#else
	rc = false;
	handle = _findfirst(p, &dta);
	if(handle < 0)
	    rc = true;
#endif
	if(allocate)
	    nzFree(p);
    }
#else
    if(!df) {
	if(!base)
	    base = ".";
	df = opendir(base);
	if(!df) {
	    puts
	       ("warning, the directory is inaccessible - the listing will be empty");
	    return 0;
	}
    }
#endif

#ifdef DOSLIKE
    while(true) {
/* read the next file */
	if(!dirStart) {
#ifdef MSDOS
	    rc = _dos_findnext(&dta);
#else
	    rc = _findnext(handle, &dta);
#endif
	    dirstart = false;
	}
	if(rc)
	    break;
/* extract the base name */
	s = strrchr(dta.name, '/');
	s = s ? s + 1 : dta.name;
/* weed out unwanted directories */
	if(stringEqual(s, "."))
	    continue;
	if(stringEqual(s, ".."))
	    continue;
	return s;
    }				/* end loop over files in directory */
#else
    while(de = readdir(df)) {
	if(de->d_ino == 0)
	    continue;
	if(de->d_name[0] == '.') {
	    if(!showHiddenFiles)
		continue;
	    if(de->d_name[1] == 0)
		continue;
	    if(de->d_name[1] == '.' && de->d_name[2] == 0)
		continue;
	}
	return de->d_name;
    }				/* end loop over files in directory */
    closedir(df);
    df = 0;
#endif

    return 0;
}				/* nextScanFile */

/* Sorted directory list.  Uses textLines[]. */
bool
sortedDirList(const char *dir, int *start, int *end)
{
    char *f;
    int j;
    bool change;

    *start = *end = textLinesCount;

    while(f = nextScanFile(dir)) {
	if(!linesComing(1))
	    return false;
	textLines[textLinesCount] = allocMem(strlen(f) + 3);
	strcpy((char *)textLines[textLinesCount], f);
	textLinesCount++;
    }

    *end = textLinesCount;
    if(*end == *start)
	return true;

/* Bubble sort, the list shouldn't be too long. */
    change = true;
    while(change) {
	change = false;
	for(j = *start; j < *end - 1; ++j) {
	    if(strcmp((char *)textLines[j], (char *)textLines[j + 1]) > 0) {
		pst swap = textLines[j];
		textLines[j] = textLines[j + 1];
		textLines[j + 1] = swap;
		change = true;
	    }
	}
    }

    return true;
}				/* sortedDirList */

/* Expand environment variables, then wild cards.
 * But the result should be one and only one file.
 * Return the new expanded line.
 * Neither the original line nore the new line is allocated.
 * They are static char buffers that are just plain long enough. */

bool
envFile(const char *line, const char **expanded)
{
    static char line1[MAXTTYLINE];
    static char line2[MAXTTYLINE];
    const char *s, *value, *basedir;
    char *t, *dollar, *cut, *file;
    char c;
    bool cc, badBrackets;
    int filecount;
    char re[MAXRE + 20];
    const char *re_error;
    int re_offset, re_count, re_vector[3];

    pcre *re_cc;

/* ` supresses this stuff */
    if(*line == '`') {
	*expanded = line + 1;
	return true;
    }

/* quick check, nothing to do */
    if(!strpbrk(line, "$[*?") && line[0] != '~') {
	*expanded = line;
	return true;
    }

/* first the env variables */
    s = line;
    t = line1;
    dollar = 0;
    while(true) {
	if(t >= line1 + sizeof (line1))
	    goto longvar;
	c = *s;
	if(c == '~' && s == line && (s[1] == '/' || s[1] == 0)) {
	    if(strlen(home) >= sizeof (line1) - 1)
		goto longvar;
	    strcpy(t, home);
	    t = t + strlen(t);
	    ++s;
	    continue;
	}
	if(dollar && !isalnumByte(c) && c != '_') {
	    *t = 0;
	    value = getenv(dollar + 1);
	    if(!value) {
		setError("environement variable %s not set", dollar + 1);
		return false;
	    }
	    if(dollar + strlen(value) >= line1 + sizeof (line1) - 1)
		goto longvar;
	    strcpy(dollar, value);
	    t = dollar + strlen(dollar);
	    dollar = 0;
	}
	if(c == '$' && (s[1] == '_' || isalphaByte(s[1])))
	    dollar = t;
	*t++ = c;
	if(!c)
	    break;
	++s;
    }

/* Wildcard expansion, but somewhat limited.
 * The directory has to be hard coded;
 * we only expand stars in the filename. */

    cut = dollar = 0;
    for(t = line1; *t; ++t) {
	c = *t;
	if(c == '/')
	    cut = t;
	if(c == '[' || c == '*' || c == '?')
	    dollar = t;
    }
    if(!dollar) {		/* nothing meta */
	*expanded = line1;
	return true;
    }
    if(cut && dollar < cut) {
	setError("cannot expand * ? or [] prior to the last /");
	return false;
    }

/* Make sure its a directory, and build a perl regexp for the pattern. */
    if(cut) {
	*cut = 0;
	if(cut > line1 && fileTypeByName(line1, false) != 'd') {
	    setError("%s is not an accessible directory", line1);
	    return false;
	}
    }

    s = cut ? cut + 1 : line1;
    t = re;
    *t++ = '^';
    cc = badBrackets = false;
    while(c = *s) {
	if(t >= re + sizeof (re) - 3) {
	    setError("shell pattern is too long");
	    return false;
	}
	if(c == '\\') {
	    setError
	       ("sorry, I don't know how to expand filenames with \\ in them");
	    return false;
	}
/* things we need to escape */
	if(strchr("().+|", c))
	    *t++ = '\\';
	if(c == '?')
	    c = '.';
	if(c == '*')
	    *t++ = '.';
	*t++ = c;
	if(c == '[') {
	    if(cc)
		badBrackets = true;
	    cc = true;
	}
	if(c == ']') {
	    if(!cc)
		badBrackets = true;
	    cc = false;
	}
	++s;
    }				/* loop over shell pattern */
    *t++ = '$';
    *t = 0;
    if(badBrackets | cc) {
	setError("improperly formed [] pattern");
	return false;
    }

    debugPrint(7, "shell regexp %s", re);
    re_cc = pcre_compile(re, 0, &re_error, &re_offset, 0);
    if(!re_cc) {
	setError("error compiling the shell pattern, %s", re_error);
	return false;
    }

    filecount = 0;
    cc = false;			/* long flag */
    basedir = 0;
    if(cut) {
	if(cut == line1)
	    basedir = "/";
	else
	    basedir = line1;
    }
    while(file = nextScanFile(basedir)) {
	if(filecount > 1)
	    continue;
	re_count = pcre_exec(re_cc, 0, file, strlen(file), 0, 0, re_vector, 3);
	if(re_count < -1) {
	    pcre_free(re_cc);
	    setError("unexpected error while evaluating the shell pattern");
	    return false;
	}
	if(re_count < 0)
	    continue;
	++filecount;
	if(filecount > 1)
	    continue;
	if((cut ? strlen(line1) : 0) + strlen(file) >= sizeof (line2) - 2)
	    cc = true;
	else if(cut)
	    sprintf(line2, "%s/%s", line1, file);
	else
	    strcpy(line2, file);
    }
    pcre_free(re_cc);
    if(filecount != 1) {
	setError(filecount ? "shell pattern matches more than one file" :
	   "shell pattern does not match any files");
	return false;
    }
    if(cc)
	goto longvar;

    *expanded = line2;
    return true;

  longvar:
    setError("line becomes too long when shell variables are expanded");
    return false;
}				/* envFile */

static struct utsname utsbuf;

const char *
currentOS(void)
{
    uname(&utsbuf);
    return utsbuf.sysname;
}				/* currentOS */

const char *
currentMachine(void)
{
    uname(&utsbuf);
    return utsbuf.machine;
}				/* currentMachine */

FILE *
efopen(const char *name, const char *mode)
{
    FILE *f;

    if(name[0] == '-' && name[1] == 0) {
	if(*mode == 'r')
	    return stdin;
	if(*mode == 'w' || *mode == 'a')
	    return stdout;
    }

    f = fopen(name, mode);
    if(f)
	return f;

    if(*mode == 'r')
	errorPrint("2cannot open %s", name);
    else if(*mode == 'w' || *mode == 'a')
	errorPrint("2cannot create or write to %s", name);
    else
	errorPrint("@calling fopen() with invalid mode %s", mode);
    return 0;
}				/* efopen */

void
appendFile(const char *fname, const char *message, ...)
{
    FILE *f;
    va_list p;
    long a[5];

    va_start(p, message);
    varargLocals(p, message, a);
    va_end(p);

    f = efopen(fname, "a");
    fprintf(f, message, a[0], a[1], a[2], a[3], a[4]);
    fprintf(f, "\n");
    fclose(f);
}				/* appendFile */

/* like the above, but no formatting */
void
appendFileNF(const char *filename, const char *msg)
{
    FILE *f = efopen(filename, "a");
    fprintf(f, "%s\n", msg);
    fclose(f);
}				/* appendFileNF */