File: mystring.c

package info (click to toggle)
prayer 1.3.5-dfsg1-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,596 kB
  • sloc: ansic: 43,163; makefile: 817; sh: 445; perl: 166
file content (1518 lines) | stat: -rw-r--r-- 40,154 bytes parent folder | download | duplicates (4)
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
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
/* $Cambridge: hermes/src/prayer/lib/mystring.c,v 1.6 2012/01/08 20:18:27 dpc22 Exp $ */
/************************************************
 *    Prayer - a Webmail Interface              *
 ************************************************/

/* Copyright (c) University of Cambridge 2000 - 2008 */
/* See the file NOTICE for conditions of use and distribution. */

#include "lib.h"

/* Some simple string (i.e: char *) manipulation routines */

/* string_itoa() ********************************************************
 *
 * Convert number into string using named pool as target
 *   pool: scratch pool
 *  value: value to convert
 *
 * Returns: text representation of number
 ***********************************************************************/

char *string_itoa(struct pool *pool, unsigned long value)
{
    unsigned long tmp, weight, nodigits;
    char *result, *s;

    /* All numbers contain at least one digit.
     * Find weight of most significant digit. */
    weight = 1;
    nodigits = 1;
    tmp = value / 10;
    while (tmp > 0) {
        weight *= 10;
        tmp /= 10;
        nodigits++;
    }

    result = pool_alloc(pool, nodigits + 1);

    for (s = result; weight > 0; weight /= 10) {
        if (value >= weight) {  /* Strictly speaking redundant... */
            *s++ = '0' + (value / weight);      /* Digit other than zero */
            value -= weight * (value / weight); /* Calculate remainder */
        } else
            *s++ = '0';
    }
    *s = '\0';

    return (result);
}

/* string_itoa_tmp() ****************************************************
 *
 * Convert number into string using (static) scratch buffer
 *  value: value to convert
 *
 * Returns: text representation of number.
 ***********************************************************************/

char *string_itoa_tmp(unsigned long value)
{
    static char result[64];     /* Larger than 64-bit int */
    char *s;
    unsigned long weight, tmp;

    /* All numbers contain at least one digit.
     * Find weight of most significant digit. */

    weight = 1;
    tmp = value / 10;
    while (tmp > 0) {
        weight *= 10;
        tmp /= 10;
    }

    for (s = result; weight > 0; weight /= 10) {
        if (value >= weight) {  /* Strictly speaking redundant... */
            *s++ = '0' + (value / weight);      /* Digit other than zero */
            value -= weight * (value / weight); /* Calculate remainder */
        } else
            *s++ = '0';
    }
    *s = '\0';

    return (result);
}

/* string_isnumber() *****************************************************
 *
 * Check that string is non-negative integer
 *************************************************************************/

BOOL
string_isnumber(char *s)
{
    if (!Uisdigit(*s))
        return(NIL);

    while (*s) {
        if (!Uisdigit(*s))
            return(NIL);
        s++;
    }
    return(T);
}

/* ====================================================================== */

/* ishex() **************************************************************
 *
 * Check for valid hexidecimal digit
 *  value: Character to check.
 *
 * Returns: T if character was valid hex digit.
 ***********************************************************************/

BOOL ishex(char value)
{
    if (Uisdigit(value))
        return (T);

    if ((value >= 'A') && (value <= 'F'))
        return (T);

    if ((value >= 'a') && (value <= 'f'))
        return (T);

    return (NIL);
}

/* hex() ****************************************************************
 *
 * Convert single hex digit into number.
 *  value: Hex digit to convert
 *
 * Returns: Number between 0 and 15
 ***********************************************************************/

unsigned long hex(char value)
{
    if (Uisdigit(value))
        return (value - '0');

    if ((value >= 'A') && (value <= 'F'))
        return (10 + value - 'A');

    if ((value >= 'a') && (value <= 'f'))
        return (10 + value - 'a');

    log_fatal("hex() called with illegal value");
    return (0);                 /* NOTREACHED */
}

/* ====================================================================== */

/* RFC822 defines:
 *   specials    =  "(" / ")" / "<" / ">" / "@"  ; Must be in quoted-
 *                /  "," / ";" / ":" / "\" / <">  ;  string, to use
 *                /  "." / "[" / "]"              ;  within a word.
 */

/* string_atom_has_special() ********************************************
 *
 * Check if string contains significant RFC822 characters
 *   s: String to check
 *
 * Returns: T if strig contained significant characters.
 ***********************************************************************/

BOOL string_atom_has_special(char *s)
{
    char c;

    while ((c = *s++)) {
        switch (c) {
        case '(':
        case ')':
        case '<':
        case '>':
        case '@':
        case ',':
        case ';':
        case ':':
        case '\\':
        case '"':              /* NB: must use \" quoting if '"' used */
        case '.':
        case '[':
        case ']':
            return (T);
        }
    }
    return (NIL);
}

/* string_atom_quote() **************************************************
 *
 * Convert string to RFC822 quoted form.
 *  pool: Target pool.
 *     s: String to convert
 *
 * Returns: Quoted string
 ***********************************************************************/

char *string_atom_quote(struct pool *pool, char *s)
{
    char *result, *t;
    unsigned long count, len;

    /* Scan string for '"' chars, calculate length at the same time */
    count = 0;
    len = 0;
    for (t = s; *t; t++) {
        if (*t == '"')
            count++;
        len++;
    }

    if (count == 0)
        return (s);

    result = pool_alloc(pool, count + len + 1);

    t = result;
    while (*s) {
        if (*s == '"')
            *t++ = '\\';
        *t++ = *s++;
    }
    *t = '\0';

    return (result);
}

/* ====================================================================== */

/* string_filename_valid() ***********************************************
 *
 * Look for "/.." sequence in filenames
 *     s: String to check
 *
 * Returns: T if string contained invalid sequence
 ***********************************************************************/

BOOL string_filename_valid(char *s)
{
    /* Allow any sequence of characters: Cyrus will validate */
    /* Original concern was people playing silly buggers with Unix mailstore */
    return (T);
}

/* ====================================================================== */

/* string_prune() ********************************************************
 *
 * Generate pruned version of string if too long (replaces last three
 * characters with "...").
 *   pool: Target pool
 *      s: String to prune
 * maxlen: Maximum length of string before pruning applies.
 *
 * Returns: T if string contained invalid sequence
 ***********************************************************************/

char *string_prune(struct pool *pool, char *s, unsigned long maxlen)
{
    char *result;

    if (maxlen < (strlen("...") + 1))
        return (s);

    if (maxlen == 0)
        return (s);

    if (strlen(s) < maxlen)
        return (s);

    /* Make temporary copy of first maxlen chars of string */
    result = pool_alloc(pool, maxlen + 1);
    memcpy(result, s, maxlen);

    /* Replace last three characters with "..." */
    strcpy(result + maxlen - strlen("..."), "...");

    return (result);
}


/* ====================================================================== */

/* string_trim_whitespace() *********************************************
 *
 * Remove leading and trailing whitespace from a string
 *  string: String to prune
 *
 * Returns: Trimmed string.
 ***********************************************************************/

char *string_trim_whitespace(char *string)
{
    unsigned long len;

    /* Remove leading whitespace */
    while ((string[0] == ' ') ||
           (string[0] == '\t') ||
           (string[0] == '\015') || (string[0] == '\012'))
        string++;

    /* Remove traiing whitespace */
    len = strlen(string);
    while ((len > 0) &&
           ((string[len - 1] == ' ') ||
            (string[len - 1] == '\t') ||
            (string[len - 1] == '\015') || (string[len - 1] == '\012')))
        len--;

    /* Tie off the string */
    string[len] = '\0';

    return (string);
}

/* ====================================================================== */

/* String tokenisation routines */

/* string_isspace() *****************************************************
 *
 * Check if character is space character.
 ***********************************************************************/

BOOL string_isspace(char c)
{
    return ((c == ' ') || (c == '\t'));
}

/* string_isspace() *****************************************************
 *
 * Check if character is end of line
 ***********************************************************************/

BOOL string_iseol(char c)
{
    return ((c == '\0') || (c == '\015') || (c == '\012'));
}

/* string_next_token() **************************************************
 *
 * Find next token in string
 *    sp: Ptr to current string location (updated)
 *
 * Returns: Ptr to next token, NIL if none.
 ***********************************************************************/

char *string_next_token(char **sp)
{
    char *s = *sp;

    if (!s)
        return (NIL);

    while ((*s == ' ') || (*s == '\t')) /* Skip leading whitespace */
        s++;

    *sp = s;

    return ((*s) ? s : NIL);
}

/* string_get_token() ****************************************************
 *
 * Isolate next token in string
 *    sp: Ptr to current string location
 *        (updated to point to following token)
 *
 * Returns: Ptr to next token, NIL if none.
 ***********************************************************************/

char *string_get_token(char **sp)
{
    char *s = *sp, *result;

    if (!(s = string_next_token(sp)))
        return (NIL);

    /* Record position of this token */
    result = s;

    /* Find next whitespace character or end of string */
    while ((*s) && (*s != ' ') && (*s != '\t'))
        s++;

    /* Tie off the string unless \0 already reached */
    if (*s) {
        *s++ = '\0';

        while ((*s == ' ') || (*s == '\t'))
            s++;
    }

    /* Record position of first non-whitespace character for next caller */
    *sp = s;

    return (result);
}

/* string_skip_token() **************************************************
 *
 * Skip next token
 *    sp: Ptr to current string location
 *        (updated to point to following token)
 *
 * Returns: Ptr to next token, NIL if none.
 ***********************************************************************/

BOOL string_skip_token(char **sp)
{
    char *s;

    if (!(s = string_next_token(sp)))
        return (NIL);

    /* Find next whitespace character or end of string */
    while ((*s) && !string_isspace(*s))
        s++;

    /* Find next non-whitespace character */
    while ((*s == ' ') || (*s == '\t'))
        s++;

    /* Record position of first non-whitespace character for next caller */
    *sp = s;

    return (T);
}

/* ====================================================================== */

/* string_ustr() *********************************************************
 *
 * Case insensitive version of strstr()
 *
 ************************************************************************/

char *string_ustr(char *s, char *name)
{
    unsigned long len = strlen(name);

    while (*s && (strncasecmp(s, name, len) != 0))
        s++;

    return((*s) ? s : NIL);
}

/* string_get_value() ****************************************************
 *
 * Given \s*value\s+ or \s*"value" chop out the value.
 *
 ************************************************************************/

char *string_get_value(char **sp)
{
    char *s = *sp;
    char *value = NIL;

    while (isspace(*s))
        s++;

    if (*s == '"') {
        s++;
        value = s;
        while (*s && *s != '"')
            s++;
    } else {
        value = s;
        while (*s && *s != ' ' && *s != '\t')
            s++;
    }
    *s++ = '\0';

    *sp = s;
    return(value);
}

/* ====================================================================== */

/* string_next_line() ***************************************************
 *
 * Skip to next line
 *    sp: Ptr to current string location
 *        (updated to point to following line)
 *
 * Returns: Ptr to next line
 ***********************************************************************/

char *string_next_line(char **sp)
{
    char *s = *sp;
    char c;

    if (!(s && s[0]))
        return (NIL);

    while ((c = *s)) {
        if (c == '\015') {      /* CR */
            s++;
            if (*s == '\012')   /* CRLF */
                s++;
            break;
        } else if (c == '\012') {       /* LF */
            s++;
            break;
        }
        s++;
    }

    *sp = s;

    return (s);
}

/* string_get_line() *****************************************************
 *
 * Get a line
 *    sp: Ptr to current string location
 *        (updated to point to following line)
 *
 * Returns: Ptr to this line
 ***********************************************************************/

char *string_get_line(char **sp)
{
    char *s, c, *result;

    result = s = *sp;           /* Record position of this line */

    if (!(s && s[0]))
        return (NIL);

    while ((c = *s)) {
        if (c == '\015') {      /* CR */
            *s++ = '\0';
            if (*s == '\012')   /* CRLF */
                s++;
            break;
        } else if (c == '\012') {       /* LF */
            *s++ = '\0';
            break;
        }
        s++;
    }

    /* Record position of next line */
    *sp = s;

    return (result);
}

/* ====================================================================== */

/* string_get_lws_line() ************************************************
 *
 * Get a linear whitespace line (e.g: folded RFC822 or HTTP header line)
 *       sp: Ptr to current string location
 *           (updated to point to following line)
 *  squeeze: Remove superfluous spaces from result.
 *
 * Returns: Ptr to this line
 ***********************************************************************/

char *string_get_lws_line(char **sp, BOOL squeeze)
{
    char *s, *t, *result;
    BOOL quoted = NIL;

    s = *sp;

    if (!(s && s[0]))
        return (NIL);

    /* Skip leading whitespace */
    while ((*s == ' ') || (*s == '\t'))
        s++;

    /* Empty string before data proper starts? */
    if ((s[0] == '\0')) {
        *sp = s;
        return (s);
    }

    /* CR, LF or CRLF before data proper starts? */
    if ((s[0] == '\015') || (s[0] == '\012')) {
        result = s;
        if ((s[0] == '\015') && (s[1] == '\012')) {     /* CRLF */
            *s = '\0';
            s += 2;
        } else
            *s++ = '\0';        /* CR or LF */

        *sp = s;
        return (result);
    }

    result = t = s;             /* Record position of non-LWS */

    while (*s) {
        if ((*s == '\015') || (*s == '\012')) { /* CR, LF or CRLF */
            s += ((s[0] == '\015') && (s[1] == '\012')) ? 2 : 1;

            if ((*s != ' ') && (*s != '\t'))
                break;
            /* Is a continuation line */
            quoted = NIL;       /* Is "LWS" allowed? */
            if ((t > result) && (t[-1] != ' ')) {       /* Replace LWS with single SP */
                *t++ = ' ';
            }
        } else {
            if (*s == '"')
                quoted = (quoted) ? NIL : T;    /* Toggle quoted bit */

            if ((!quoted) && (squeeze) && ((*s == ' ') || (*s == '\t'))) {
                if ((t > result) && (t[-1] != ' '))
                    *t++ = ' ';
                s++;
            } else if (t < s)   /* Copy faithfully */
                *t++ = *s++;
            else {
                t++;
                s++;            /* Data hasn't moved yet */
            }
        }
    }

    /* Remove trailing whitespace. Easier to do this at the end */
    if (squeeze) {
        while ((t > result) && ((t[-1] == ' ') || (t[-1] == '\t')))
            t--;
    }
    *t = '\0';                  /* Tie off result string */

    *sp = s;                    /* Set up for next caller */

    return (result);
}

/* ====================================================================== */

/* Support routines for canon encoding */

static void canon_encode_char(unsigned char c, char **tp)
{
    unsigned char *t = (unsigned char *) *tp;
    static char hex[] = "0123456789abcdef";

    if (Uisalnum(c)) {
        *t++ = c;
    } else
        switch (c) {
        case '_':
        case '.':
        case '!':
        case '\'':
        case '(':
        case ')':
        case '-':
            *t++ = c;
            break;
        default:
            *t++ = '*';
            *t++ = hex[c >> 4];
            *t++ = hex[c & 15];
            break;
        }

    *tp = (char *) t;
}

static int canon_count_specials(char *s)
{
    unsigned long special_count = 0;
    char c;

    while ((c = *s++)) {
        if (!Uisalnum(c))
            switch (c) {
            case '_':
            case '.':
            case '!':
            case '\'':
            case '(':
            case ')':
            case '-':
                break;
            default:
                special_count++;
                break;
            }
    }
    return (special_count);
}

/* ====================================================================== */

/* string_canon_encode() ************************************************
 *
 * Encode string using canonical encoding for special characters
 *   pool: Target string
 *    arg: String to encode
 *
 * Returns: Encoded string
 ***********************************************************************/

char *string_canon_encode(struct pool *pool, char *arg)
{
    char *s, *result, *t;
    unsigned long specials;

    s = pool_strdup(pool, arg);

    /* Count special characters in string */
    if ((specials = canon_count_specials(s)) == 0)
        return (s);

    /* Need another copy, with space for encoded specials */
    result = pool_alloc(pool, strlen(s) + (2 * specials) + 1);

    /* Copy s to result, encoding specials */
    t = result;
    while (*s) {
        canon_encode_char((unsigned char) (*s), &t);
        s++;
    }
    *t = '\0';

    return (result);
}

/* string_canon_path_encode() *******************************************
 *
 * Encode (directory, file) combination using canonical encoding for
 * special characters.
 *   pool: Target string
 *    dir: Directory
 *   file: Filename
 *
 * Returns: Encoded string
 ***********************************************************************/

char *string_canon_path_encode(struct pool *pool, char *dir, char *file)
{
    char *s, *result, *t;
    unsigned long specials;

    if (file[0]) {
        if (dir && dir[0]) {
            s = pool_alloc(pool, strlen(dir) + 1 + strlen(file) + 1);
            strcpy(s, dir);
            t = s + strlen(s);
            *t++ = '/';
            strcpy(t, file);
        } else
            s = pool_strdup(pool, file);
    } else
        s = pool_strdup(pool, dir);

    /* Count special characters in string */
    if ((specials = canon_count_specials(s)) == 0)
        return (s);

    /* Need another copy, with space for encoded specials */
    result = pool_alloc(pool, strlen(s) + (2 * specials) + 1);

    /* Copy s to result, encoding specials */
    t = result;
    while (*s) {
        canon_encode_char(*s, &t);
        s++;
    }
    *t = '\0';

    return (result);
}

/* ====================================================================== */

/* string_canon_decode() ************************************************
 *
 * Decode string from canonical encoding (*XY hex-encoding for specials)
 * '*' choosen as a URL safe character: hopefully no browser will try
 * and URL enode this.
 *   string: Input string
 *
 * Returns: Decoded string, updating in place.
 ***********************************************************************/

char *string_canon_decode(char *string)
{
    char *s, *t;

    if (!string)
        return (NIL);

    /* Set all pointers to start of string */
    s = t = string;

    while (*t) {
        switch (*t) {
        case '*':
        case '%':
            if (ishex(t[1]) && ishex(t[2])) {   /* Better way to do this? */
                *s++ = (16 * hex(t[1])) + hex(t[2]);
                t += 3;
                continue;
            }
            /* Otherwise fall through to default behaviour */
        }

        if (s < t) {
            *s++ = *t++;        /* Copy string to new location */
        } else {
            s++;
            t++;                /* Just keep going */
        }
    }
    *s = '\0';                  /* Tie off string */

    return (string);
}

/* ====================================================================== */

/* Support routines for URL encoding */

static void url_encode_char(unsigned char c, char **tp)
{
    unsigned char *t = (unsigned char *) *tp;
    static char hex[] = "0123456789abcdef";

    if (Uisalnum(c)) {
        *t++ = c;
    } else
        switch (c) {
        case '_':
        case '.':
        case '!':
        case '*':
        case '\'':
        case '(':
        case ')':
        case '-':
            *t++ = c;
            break;
        default:
            *t++ = '%';
            *t++ = hex[c >> 4];
            *t++ = hex[c & 15];
            break;
        }

    *tp = (char *) t;
}

static int url_count_specials(char *s)
{
    unsigned long special_count = 0;
    char c;

    while ((c = *s++)) {
        if (!Uisalnum(c))
            switch (c) {
            case '_':
            case '.':
            case '!':
            case '*':
            case '\'':
            case '(':
            case ')':
            case '-':
                break;
            default:
                special_count++;
                break;
            }
    }
    return (special_count);
}

/* ====================================================================== */

/* string_url_encode() **************************************************
 *
 * Encode string using canonical encoding for special characters
 *   pool: Target string
 *    arg: String to encode
 *
 * Returns: Encoded string
 ***********************************************************************/

char *string_url_encode(struct pool *pool, char *arg)
{
    char *result, *t;
    unsigned long specials;

    /* Count special characters in string */
    if ((specials = url_count_specials(arg)) == 0)
        return (arg);

    /* Need another copy, with space for encoded specials */
    result = pool_alloc(pool, strlen(arg) + (2 * specials) + 1);

    /* Copy s to result, encoding specials */
    t = result;
    while (*arg) {
        url_encode_char(*arg, &t);
        arg++;
    }
    *t = '\0';

    return (result);
}

/* ====================================================================== */

/* string_url_decode() **************************************************
 *
 * Decode string from URL encoding (%XY hex-encoding for specials)
 *   string: Input string
 *
 * Returns: Decoded string, updating in place.
 ***********************************************************************/

char *string_url_decode(char *string)
{
    char *s, *t;

    if (!string)
        return (NIL);

    /* Set all pointers to start of string */
    s = t = string;

    while (*t) {
        switch (*t) {
        case '%':
            if (ishex(t[1]) && ishex(t[2])) {   /* Better way to do this? */
                *s++ = (16 * hex(t[1])) + hex(t[2]);
                t += 3;
                continue;
            }
            /* Otherwise fall through to default behaviour */
        }

        if (s < t) {
            *s++ = *t++;        /* Copy string to new location */
        } else {
            s++;
            t++;                /* Just keep going */
        }
    }
    *s = '\0';                  /* Tie off string */

    return (string);
}


/* ====================================================================== */

/* string_url_decode_component() ****************************************
 *
 * Decode single component of string from URL encoding (%XY hex-encoding
 * for specials)
 *      tp: Ptr to string (will be updated to point to next component)
 *     sep: Separator character (typically '/')
 * Returns: Decoded string, updating in place.
 ***********************************************************************/

char *string_url_decode_component(char **tp, char sep)
{
    char *s, *t, *result;

    /* Set all pointers to start of string */
    result = s = t = *tp;

    while ((*t) && (*t != sep)) {
        switch (*t) {
        case '+':              /* Is use of '+' documented anywhere? */
            *s++ = ' ';
            t++;
            continue;
        case '%':
            if (ishex(t[1]) && ishex(t[2])) {
                *s++ = (16 * hex(t[1])) + hex(t[2]);
                t += 3;
                continue;
            }
            /* Otherwise fall through to default behaviour */
        }

        if (s < t) {
            *s++ = *t++;        /* Copy string to new location */
        } else {
            s++;
            t++;                /* Just keep going */
        }
    }

    if (*t)                     /* Nuke '&' separator if it exists */
        *t++ = '\0';

    *s = '\0';                  /* Tie off string */

    *tp = t;                    /* Record location for next caller */

    return (result);
}

/* ====================================================================== */

/* string_filename_encode() *********************************************
 *
 * Mangle filename to URL friend form by replacing " " with "_". Only
 * needed because browsers appear to ignore filename parameters.
 *
 ***********************************************************************/

char *string_filename_encode(struct pool *pool, char *arg)
{
    char *result = pool_strdup(pool, arg);
    char *s = result;

    for (s = result; *s; s++) {
        if (*s == ' ')
            *s = '_';
    }

    return (result);
}

/* ====================================================================== */

/* Small malloc interface library */

/* string_malloc() ******************************************************
 *
 * Malloc space for string updating ptr argument
 *     ptr: Ptr to (void *) that will point to result.
 *    size: Number of bytes to allocated.
 ***********************************************************************/

void string_malloc(void **ptr, unsigned long size)
{
    if (*ptr)
        free(*ptr);

    if ((*ptr = malloc(size)))
        return;

    log_fatal("Out of memory!");
    /* NOTREACHED */
    abort();
}

/* string_strdup() ******************************************************
 *
 * Strdup string:
 *     ptr: Ptr to (void *) that will point to result.
 *  string: String to strdup
 ***********************************************************************/

void string_strdup(char **ptr, char *string)
{
    if (*ptr)
        free(*ptr);

    if (string == NIL) {
        *ptr = NIL;
        return;
    }

    if ((*ptr = strdup(string)))
        return;

    log_fatal("Out of memory!");
    /* NOTREACHED */
    abort();
}

/* string_free() ********************************************************
 *
 * Free string, clearing ptr in process.
 *     ptr: Ptr to (void *) that will be cleared after free
 ***********************************************************************/

void string_free(void **ptr)
{
    free(*ptr);
    *ptr = NIL;
}

/* string_ucase() *******************************************************
 *
 * Wrapper function to keep compiler happy
 * 
 ***********************************************************************/

char *string_ucase (char *s)
{
  unsigned char *t;
				/* if lowercase covert to upper */
  for (t = (unsigned char *)s; *t; t++) {
      if (!(*t & 0x80) && islower (*t))
          *t = toupper (*t);
  }
  return s;			/* return string */
}


/* string_lcase() *******************************************************
 *
 * Wrapper function to keep compiler happy
 * 
 ***********************************************************************/

char *string_lcase (char *s)
{
  unsigned char *t;
				/* if uppercase covert to lower */
  for (t = (unsigned char *)s; *t; t++) {
      if (!(*t & 0x80) && isupper (*t))
          *t = tolower (*t);
  }
  return s;			/* return string */
}

/* ====================================================================== */

/* string_has8bit() *******************************************************
 *
 * Does string contain 8 bit characters.
 *
 **************************************************************************/

BOOL string_has8bit(char *s0)
{
    unsigned char *s = (unsigned char *)s0;

    if (!s)
        return(NIL);

    while (*s) {
        if ((*s) & 0x80)
            return(T);
        s++;
    }
    return(NIL);
}

/* string_strip8bit() *****************************************************
 *
 * Strip all 8bit characters from string in place. Can cope with NIL input.
 *
 **************************************************************************/

void string_strip8bit(char *s0)
{
    unsigned char *s = (unsigned char *)s0;
    unsigned char *t;

    if (!s)
        return;

    while (*s && (((*s) & 0x80) == 0))
        s++;

    if (*s == '\0')
        return;

    /* Found an 8bit character */
    t = s;
    while (*s) {
        while (*s && ((*s) & 0x80))
            s++;

        while (*s && (((*s) & 0x80) == 0))
            *t++ = *s++;
        
    }
    if (*t != '\0')
        *t = '\0';
}

/* ====================================================================== */

/* Couple of utility routines stolen from c-client, just so that we
 * don't have to link the prayer frontend processes against c-client.
 *
 * These versions update in place rather allocating memory.
 */

static unsigned char myhex2byte(unsigned char c1,unsigned char c2)
{
				/* merge the two nybbles */
  return ((c1 -= (isdigit (c1) ? '0' : ((c1 <= 'Z') ? 'A' : 'a') - 10)) << 4) +
    (c2 - (isdigit (c2) ? '0' : ((c2 <= 'Z') ? 'A' : 'a') - 10));
}

/* Convert BASE64 contents to binary
 * Accepts: source
 *	    length of source
 *	    pointer to return destination length
 * Returns: destination as binary or NIL if error
 */

#define WSP 0176		/* NUL, TAB, LF, FF, CR, SPC */
#define JNK 0177
#define PAD 0100

void *
string_base64_decode(unsigned char *src,unsigned long srcl,unsigned long *len)
{
  char c;
  void *ret = src;
  char *d = (char *) ret;
  int e;
  static char decode[256] = {
   WSP,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,WSP,WSP,JNK,WSP,WSP,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   WSP,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,076,JNK,JNK,JNK,077,
   064,065,066,067,070,071,072,073,074,075,JNK,JNK,JNK,PAD,JNK,JNK,
   JNK,000,001,002,003,004,005,006,007,010,011,012,013,014,015,016,
   017,020,021,022,023,024,025,026,027,030,031,JNK,JNK,JNK,JNK,JNK,
   JNK,032,033,034,035,036,037,040,041,042,043,044,045,046,047,050,
   051,052,053,054,055,056,057,060,061,062,063,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,
   JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK,JNK
  };
  *len = 0;			/* in case we return an error */

				/* simple-minded decode */
  for (e = 0; srcl--; ) switch (c = decode[*src++]) {
  default:			/* valid BASE64 data character */
    switch (e++) {		/* install based on quantum position */
    case 0:
      *d = c << 2;		/* byte 1: high 6 bits */
      break;
    case 1:
      *d++ |= c >> 4;		/* byte 1: low 2 bits */
      *d = c << 4;		/* byte 2: high 4 bits */
      break;
    case 2:
      *d++ |= c >> 2;		/* byte 2: low 4 bits */
      *d = c << 6;		/* byte 3: high 2 bits */
      break;
    case 3:
      *d++ |= c;		/* byte 3: low 6 bits */
      e = 0;			/* reinitialize mechanism */
      break;
    }
    break;
  case WSP:			/* whitespace */
    break;
  case PAD:			/* padding */
    switch (e++) {		/* check quantum position */
    case 3:			/* one = is good enough in quantum 3 */
				/* make sure no data characters in remainder */
      for (; srcl; --srcl) switch (decode[*src++]) {
				/* ignore space, junk and extraneous padding */
      case WSP: case JNK: case PAD:
	break;
      default:			/* valid BASE64 data character */
	/* This indicates bad MIME.  One way that it can be caused is if
	   a single-section message was BASE64 encoded and then something
	   (e.g. a mailing list processor) appended text.  The problem is
	   that in 1 out of 3 cases, there is no padding and hence no way
	   to detect the end of the data.  Consequently, prudent software
	   will always encapsulate a BASE64 segment inside a MULTIPART.
	   */
          srcl = 1;		/* Bail out */
	break;
      }
      break;
    case 2:			/* expect a second = in quantum 2 */
      if (srcl && (*src == '=')) break;
    default:			/* impossible quantum position */
      return NIL;
    }
    break;
  case JNK:			/* junk character */
    return NIL;
  }
  *len = d - (char *) ret;	/* calculate data length */
  *d = '\0';			/* NUL terminate just in case */
  return ret;			/* return the string */
}

/* Convert QUOTED-PRINTABLE contents to 8BIT
 * Accepts: source
 *	    length of source
 * 	    pointer to return destination length
 * Returns: destination as 8-bit text or NIL if error
 */

unsigned char *
string_qprint_decode(unsigned char *src,unsigned long srcl,
                     unsigned long *len)
{
  unsigned char *ret = src;
  unsigned char *d = ret;
  unsigned char *t = d;
  unsigned char *s = src;
  unsigned char c,e;
  *len = 0;			/* in case we return an error */
				/* until run out of characters */
  while (((unsigned long) (s - src)) < srcl) {
    switch (c = *s++) {		/* what type of character is it? */
    case '=':			/* quoting character */
      if (((unsigned long) (s - src)) < srcl) switch (c = *s++) {
      case '\0':		/* end of data */
	s--;			/* back up pointer */
	break;
      case '\015':		/* non-significant line break */
	if ((((unsigned long) (s - src)) < srcl) && (*s == '\012')) s++;
      case '\012':		/* bare LF */
	t = d;			/* accept any leading spaces */
	break;
      default:			/* two hex digits then */
	if (!(isxdigit (c) && (((unsigned long) (s - src)) < srcl) &&
	      (e = *s++) && isxdigit (e))) {
	  /* This indicates bad MIME.  One way that it can be caused is if
	     a single-section message was QUOTED-PRINTABLE encoded and then
	     something (e.g. a mailing list processor) appended text.  The
	     problem is that there is no way to determine where the encoded
	     data ended and the appended crud began.  Consequently, prudent
	     software will always encapsulate a QUOTED-PRINTABLE segment
	     inside a MULTIPART.
	   */
	  *d++ = '=';		/* treat = as ordinary character */
	  *d++ = c;		/* and the character following */
	  t = d;		/* note point of non-space */
	  break;
	}
	*d++ = myhex2byte (c,e);/* merge the two hex digits */
	t = d;			/* note point of non-space */
	break;
      }
      break;
    case ' ':			/* space, possibly bogus */
      *d++ = c;			/* stash the space but don't update s */
      break;
    case '\015':		/* end of line */
    case '\012':		/* bare LF */
      d = t;			/* slide back to last non-space, drop in */
    default:
      *d++ = c;			/* stash the character */
      t = d;			/* note point of non-space */
    }      
  }
  *d = '\0';			/* tie off results */
  *len = d - ret;		/* calculate length */
  return ret;			/* return the string */
}

/* ====================================================================== */

/* string_expand() *******************************************************
 *
 * Expand $name and ${name} references in string using hash for lookups
 ************************************************************************/

char *string_expand(struct pool *pool, struct assoc *h, char *s)
{
    struct buffer *b = buffer_create(pool, 48); /* Typically short */
    char *t, *value;

    while (*s) {
        if (*s == '$') {
            if (s[1] == '{') {
                /* Find end of ${name} expansion */
                if (!(t = strchr(s, '}')))
                    return (NIL);

                s += 2;
                *t++ = '\0';
            } else {
                /* Find end of $name expansion (w/s ends token) */
                t = ++s;
                while (Uisalpha(*t))
                    t++;

                if (*t)
                    *t++ = '\0';
            }

            /* Attempt to expand value. Name not found => expansion fails */
            if (!(value = assoc_lookup(h, s)))
                return (NIL);
            bputs(b, value);
            s = t;
        } else if (*s == '\\') {
            /* Quoted character */
            s++;
            if (*s == '\0')
                return (NIL);
            switch (*s) {
            case 'n':
                bputc(b, '\n');
                break;
            case 'r':
                bputc(b, '\r');
                break;
            case 't':
                bputc(b, '\t');
                break;
            default:
                bputc(b, *s);
                break;
            }
            s++;
        } else {
            /* Simple character */
            bputc(b, *s++);
        }
    }
    return (buffer_fetch(b, 0, buffer_size(b), NIL));
}

/* ====================================================================== */

/* string_expand_crlf() ***************************************************
 *
 * Convert all CRLF, CR, LF sequences in a string into CRLF.
 ************************************************************************/

char *
string_expand_crlf(struct pool *pool, char *s)
{
    struct buffer *b = buffer_create(pool, 64);

    while (*s) {
        if ((s[0] == '\015') && (s[1] == '\012')) {
            bputs(b, ""CRLF);
            s += 2;
        } else if ((s[0] == '\015') || (s[0] == '\012')) {
            bputs(b, ""CRLF);
            s++;
        } else {
            bputc(b, *s);
            s++;
        }
    }
    return(buffer_fetch(b, 0, buffer_size(b), NIL));
}

/* string_string_crlf() **************************************************
 *
 * Replace all CRLF, CR, LF sequences in message with simple LF. Only
 * suitable if target platform is Unix: better to ship as is, use
 * string_expand_crlf on the way back for consistency.
 ************************************************************************/

void
string_strip_crlf(char *s)
{
    char *d = s;

    while (*s) {
        if ((s[0] == '\015') && (s[1] == '\012')) {
            *d++ = '\n';
            s += 2;
        } else if (d < s) {
            *d++ = *s++;
        } else {
            s++; d++;
        }
    }
    *d = '\0';
}

/* ====================================================================== */

/* Render "a,b,c" as "a, b, c" so the browser can wrap */

static int
string_email_split_len(char *s)
{
    int len = 0;

    while (*s) {
        len += (s[0] == ',' && !string_isspace(s[1])) ? 2 : 1;
        s++;
    }

    return(len);
}

char *
string_email_split(struct pool *pool, char *s)
{
    char *result = pool_alloc(pool, string_email_split_len(s)+1);
    char *t = result;

    while (*s) {
        if (s[0] == ',' && !string_isspace(s[1])) {
            *t++ = *s++;
            *t++ = ' ';
        } else {
            *t++ = *s++;
        }
    }
    *t = '\0';
    return(result);
}