summaryrefslogtreecommitdiffstats
path: root/common/stringhelp.c
blob: 5baaa1b2b00cb70035ecb000ce0fdc0dc8a3ac25 (plain)
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
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
/* stringhelp.c -  standard string helper functions
 * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
 *               2008, 2009, 2010  Free Software Foundation, Inc.
 * Copyright (C) 2014 Werner Koch
 * Copyright (C) 2015, 2021  g10 Code GmbH
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute and/or modify this
 * part of GnuPG under the terms of either
 *
 *   - the GNU Lesser General Public License as published by the Free
 *     Software Foundation; either version 3 of the License, or (at
 *     your option) any later version.
 *
 * or
 *
 *   - the GNU General Public License as published by the Free
 *     Software Foundation; either version 2 of the License, or (at
 *     your option) any later version.
 *
 * or both in parallel, as here.
 *
 * GnuPG is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copies of the GNU General Public License
 * and the GNU Lesser General Public License along with this program;
 * if not, see <https://www.gnu.org/licenses/>.
 * SPDX-License-Identifier: (LGPL-3.0-or-later OR GPL-2.0-or-later)
 */

#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <errno.h>
#ifdef HAVE_PWD_H
# include <pwd.h>
#endif
#include <unistd.h>
#include <sys/types.h>
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_WINSOCK2_H
#  include <winsock2.h>
# endif
# include <windows.h>
#endif
#include <limits.h>

#include "util.h"
#include "common-defs.h"
#include "utf8conv.h"
#include "sysutils.h"
#include "stringhelp.h"

#define tohex_lower(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'a'))


/* Sometimes we want to avoid mixing slashes and backslashes on W32
   and prefer backslashes.  There is usual no problem with mixing
   them, however a very few W32 API calls can't grok plain slashes.
   Printing filenames with mixed slashes also looks a bit strange.
   This function has no effext on POSIX. */
static inline char *
change_slashes (char *name)
{
#ifdef HAVE_DOSISH_SYSTEM
  char *p;

  if (strchr (name, '\\'))
    {
      for (p=name; *p; p++)
        if (*p == '/')
          *p = '\\';
    }
#endif /*HAVE_DOSISH_SYSTEM*/
  return name;
}


/*
 * Check whether STRING starts with KEYWORD.  The keyword is
 * delimited by end of string, a space or a tab.  Returns NULL if not
 * found or a pointer into STRING to the next non-space character
 * after the KEYWORD (which may be end of string).
 */
char *
has_leading_keyword (const char *string, const char *keyword)
{
  size_t n = strlen (keyword);

  if (!strncmp (string, keyword, n)
      && (!string[n] || string[n] == ' ' || string[n] == '\t'))
    {
      string += n;
      while (*string == ' ' || *string == '\t')
        string++;
      return (char*)string;
    }
  return NULL;
}


/*
 * Look for the substring SUB in buffer and return a pointer to that
 * substring in BUFFER or NULL if not found.
 * Comparison is case-insensitive.
 */
const char *
memistr (const void *buffer, size_t buflen, const char *sub)
{
  const unsigned char *buf = buffer;
  const unsigned char *t = (const unsigned char *)buffer;
  const unsigned char *s = (const unsigned char *)sub;
  size_t n = buflen;

  for ( ; n ; t++, n-- )
    {
      if ( toupper (*t) == toupper (*s) )
        {
          for ( buf=t++, buflen = n--, s++;
                n && toupper (*t) == toupper (*s); t++, s++, n-- )
            ;
          if (!*s)
            return (const char*)buf;
          t = buf;
          s = (const unsigned char *)sub ;
          n = buflen;
	}
    }
  return NULL;
}

const char *
ascii_memistr ( const void *buffer, size_t buflen, const char *sub )
{
  const unsigned char *buf = buffer;
  const unsigned char *t = (const unsigned char *)buf;
  const unsigned char *s = (const unsigned char *)sub;
  size_t n = buflen;

  for ( ; n ; t++, n-- )
    {
      if (ascii_toupper (*t) == ascii_toupper (*s) )
        {
          for ( buf=t++, buflen = n--, s++;
                n && ascii_toupper (*t) == ascii_toupper (*s); t++, s++, n-- )
            ;
          if (!*s)
            return (const char*)buf;
          t = (const unsigned char *)buf;
          s = (const unsigned char *)sub ;
          n = buflen;
	}
    }
  return NULL;
}

/* This function is similar to strncpy().  However it won't copy more
   than N - 1 characters and makes sure that a '\0' is appended. With
   N given as 0, nothing will happen.  With DEST given as NULL, memory
   will be allocated using xmalloc (i.e. if it runs out of core
   the function terminates).  Returns DES or a pointer to the
   allocated memory.
 */
char *
mem2str( char *dest , const void *src , size_t n )
{
    char *d;
    const char *s;

    if( n ) {
	if( !dest )
	    dest = xmalloc( n ) ;
	d = dest;
	s = src ;
	for(n--; n && *s; n-- )
	    *d++ = *s++;
	*d = '\0' ;
    }

    return dest ;
}


/****************
 * remove leading and trailing white spaces
 */
char *
trim_spaces( char *str )
{
    char *string, *p, *mark;

    string = str;
    /* find first non space character */
    for( p=string; *p && isspace( *(byte*)p ) ; p++ )
	;
    /* move characters */
    for( (mark = NULL); (*string = *p); string++, p++ )
	if( isspace( *(byte*)p ) ) {
	    if( !mark )
		mark = string ;
	}
	else
	    mark = NULL ;
    if( mark )
	*mark = '\0' ;  /* remove trailing spaces */

    return str ;
}


/* Same as trim_spaces but only consider, space, tab, cr and lf as space.  */
char *
ascii_trim_spaces (char *str)
{
  char *string, *p, *mark;

  string = str;

  /* Find first non-ascii space character.  */
  for (p=string; *p && ascii_isspace (*p); p++)
    ;
  /* Move characters.  */
  for (mark=NULL; (*string = *p); string++, p++ )
    {
      if (ascii_isspace (*p))
        {
          if (!mark)
            mark = string;
        }
      else
        mark = NULL ;
    }
  if (mark)
    *mark = '\0' ;  /* Remove trailing spaces. */

  return str ;
}


/****************
 * remove trailing white spaces
 */
char *
trim_trailing_spaces( char *string )
{
    char *p, *mark;

    for( mark = NULL, p = string; *p; p++ ) {
	if( isspace( *(byte*)p ) ) {
	    if( !mark )
		mark = p;
	}
	else
	    mark = NULL;
    }
    if( mark )
	*mark = '\0' ;

    return string ;
}


unsigned
trim_trailing_chars( byte *line, unsigned len, const char *trimchars )
{
    byte *p, *mark;
    unsigned n;

    for(mark=NULL, p=line, n=0; n < len; n++, p++ ) {
	if( strchr(trimchars, *p ) ) {
	    if( !mark )
		mark = p;
	}
	else
	    mark = NULL;
    }

    if( mark ) {
	*mark = 0;
	return mark - line;
    }
    return len;
}

/****************
 * remove trailing white spaces and return the length of the buffer
 */
unsigned
trim_trailing_ws( byte *line, unsigned len )
{
    return trim_trailing_chars( line, len, " \t\r\n" );
}

size_t
length_sans_trailing_chars (const unsigned char *line, size_t len,
                            const char *trimchars )
{
  const unsigned char *p, *mark;
  size_t n;

  for( mark=NULL, p=line, n=0; n < len; n++, p++ )
    {
      if (strchr (trimchars, *p ))
        {
          if( !mark )
            mark = p;
        }
      else
        mark = NULL;
    }

  if (mark)
    return mark - line;
  return len;
}

/*
 *  Return the length of line ignoring trailing white-space.
 */
size_t
length_sans_trailing_ws (const unsigned char *line, size_t len)
{
  return length_sans_trailing_chars (line, len, " \t\r\n");
}



/*
 * Extract from a given path the filename component.  This function
 * terminates the process on memory shortage.
 */
char *
make_basename(const char *filepath, const char *inputpath)
{
#ifdef __riscos__
    return riscos_make_basename(filepath, inputpath);
#else
    char *p;

    (void)inputpath; /* Only required for riscos.  */

    if ( !(p=strrchr(filepath, '/')) )
#ifdef HAVE_DOSISH_SYSTEM
	if ( !(p=strrchr(filepath, '\\')) )
#endif
#ifdef HAVE_DRIVE_LETTERS
	    if ( !(p=strrchr(filepath, ':')) )
#endif
	      {
		return xstrdup(filepath);
	      }

    return xstrdup(p+1);
#endif
}



/*
 * Extract from a given filename the path prepended to it.  If there
 * isn't a path prepended to the filename, a dot is returned ('.').
 * This function terminates the process on memory shortage.
 */
char *
make_dirname(const char *filepath)
{
    char *dirname;
    int  dirname_length;
    char *p;

    if ( !(p=strrchr(filepath, '/')) )
#ifdef HAVE_DOSISH_SYSTEM
	if ( !(p=strrchr(filepath, '\\')) )
#endif
#ifdef HAVE_DRIVE_LETTERS
	    if ( !(p=strrchr(filepath, ':')) )
#endif
	      {
		return xstrdup(".");
	      }

    dirname_length = p-filepath;
    dirname = xmalloc(dirname_length+1);
    strncpy(dirname, filepath, dirname_length);
    dirname[dirname_length] = 0;

    return dirname;
}



static char *
get_pwdir (int xmode, const char *name)
{
  char *result = NULL;
#ifdef HAVE_PWD_H
  struct passwd *pwd = NULL;

  if (name)
    {
#ifdef HAVE_GETPWNAM
      /* Fixme: We should use getpwnam_r if available.  */
      pwd = getpwnam (name);
#endif
    }
  else
    {
#ifdef HAVE_GETPWUID
      /* Fixme: We should use getpwuid_r if available.  */
      pwd = getpwuid (getuid());
#endif
    }
  if (pwd)
    {
      if (xmode)
        result = xstrdup (pwd->pw_dir);
      else
        result = xtrystrdup (pwd->pw_dir);
    }
#else /*!HAVE_PWD_H*/
  /* No support at all.  */
  (void)xmode;
  (void)name;
#endif /*HAVE_PWD_H*/
  return result;
}


/* xmode 0 := Return NULL on error
         1 := Terminate on error
         2 := Make sure that name is absolute; return NULL on error
         3 := Make sure that name is absolute; terminate on error
 */
static char *
do_make_filename (int xmode, const char *first_part, va_list arg_ptr)
{
  const char *argv[32];
  int argc;
  size_t n;
  int skip = 1;
  char *home_buffer = NULL;
  char *name, *home, *p;
  int want_abs;

  want_abs = !!(xmode & 2);
  xmode &= 1;

  n = strlen (first_part) + 1;
  argc = 0;
  while ( (argv[argc] = va_arg (arg_ptr, const char *)) )
    {
      n += strlen (argv[argc]) + 1;
      if (argc >= DIM (argv)-1)
        {
          if (xmode)
            BUG ();
          gpg_err_set_errno (EINVAL);
          return NULL;
        }
      argc++;
    }
  n++;

  home = NULL;
  if (*first_part == '~')
    {
      if (first_part[1] == '/' || !first_part[1])
        {
          /* This is the "~/" or "~" case.  */
          home = getenv("HOME");
          if (!home)
            home = home_buffer = get_pwdir (xmode, NULL);
          if (home && *home)
            n += strlen (home);
        }
      else
        {
          /* This is the "~username/" or "~username" case.  */
          char *user;

          if (xmode)
            user = xstrdup (first_part+1);
          else
            {
              user = xtrystrdup (first_part+1);
              if (!user)
                return NULL;
            }
          p = strchr (user, '/');
          if (p)
            *p = 0;
          skip = 1 + strlen (user);

          home = home_buffer = get_pwdir (xmode, user);
          xfree (user);
          if (home)
            n += strlen (home);
          else
            skip = 1;
        }
    }

  if (xmode)
    name = xmalloc (n);
  else
    {
      name = xtrymalloc (n);
      if (!name)
        {
          xfree (home_buffer);
          return NULL;
        }
    }

  if (home)
    p = stpcpy (stpcpy (name, home), first_part + skip);
  else
    p = stpcpy (name, first_part);

  xfree (home_buffer);
  for (argc=0; argv[argc]; argc++)
    {
      /* Avoid a leading double slash if the first part was "/".  */
      if (!argc && name[0] == '/' && !name[1])
        p = stpcpy (p, argv[argc]);
      else
        p = stpcpy (stpcpy (p, "/"), argv[argc]);
    }

  if (want_abs)
    {
#ifdef HAVE_DRIVE_LETTERS
      p = strchr (name, ':');
      if (p)
        p++;
      else
        p = name;
#else
      p = name;
#endif
      if (*p != '/'
#ifdef HAVE_DRIVE_LETTERS
          && *p != '\\'
#endif
          )
        {
          home = gnupg_getcwd ();
          if (!home)
            {
              if (xmode)
                {
                  fprintf (stderr, "\nfatal: getcwd failed: %s\n",
                           strerror (errno));
                  exit(2);
                }
              xfree (name);
              return NULL;
            }
          n = strlen (home) + 1 + strlen (name) + 1;
          if (xmode)
            home_buffer = xmalloc (n);
          else
            {
              home_buffer = xtrymalloc (n);
              if (!home_buffer)
                {
                  xfree (home);
                  xfree (name);
                  return NULL;
                }
            }
          if (p == name)
            p = home_buffer;
          else /* Windows case.  */
            {
              memcpy (home_buffer, p, p - name + 1);
              p = home_buffer + (p - name + 1);
            }

          /* Avoid a leading double slash if the cwd is "/".  */
          if (home[0] == '/' && !home[1])
            strcpy (stpcpy (p, "/"), name);
          else
            strcpy (stpcpy (stpcpy (p, home), "/"), name);

          xfree (home);
          xfree (name);
          name = home_buffer;
          /* Let's do a simple compression to catch the most common
             case of using "." for gpg's --homedir option.  */
          n = strlen (name);
          if (n > 2 && name[n-2] == '/' && name[n-1] == '.')
            name[n-2] = 0;
        }
    }
  return change_slashes (name);
}

/* Construct a filename from the NULL terminated list of parts.  Tilde
   expansion is done for the first argument.  This function terminates
   the process on memory shortage. */
char *
make_filename (const char *first_part, ... )
{
  va_list arg_ptr;
  char *result;

  va_start (arg_ptr, first_part);
  result = do_make_filename (1, first_part, arg_ptr);
  va_end (arg_ptr);
  return result;
}

/* Construct a filename from the NULL terminated list of parts.  Tilde
   expansion is done for the first argument.  This function may return
   NULL on error. */
char *
make_filename_try (const char *first_part, ... )
{
  va_list arg_ptr;
  char *result;

  va_start (arg_ptr, first_part);
  result = do_make_filename (0, first_part, arg_ptr);
  va_end (arg_ptr);
  return result;
}

/* Construct an absolute filename from the NULL terminated list of
   parts.  Tilde expansion is done for the first argument.  This
   function terminates the process on memory shortage. */
char *
make_absfilename (const char *first_part, ... )
{
  va_list arg_ptr;
  char *result;

  va_start (arg_ptr, first_part);
  result = do_make_filename (3, first_part, arg_ptr);
  va_end (arg_ptr);
  return result;
}

/* Construct an absolute filename from the NULL terminated list of
   parts.  Tilde expansion is done for the first argument.  This
   function may return NULL on error. */
char *
make_absfilename_try (const char *first_part, ... )
{
  va_list arg_ptr;
  char *result;

  va_start (arg_ptr, first_part);
  result = do_make_filename (2, first_part, arg_ptr);
  va_end (arg_ptr);
  return result;
}



/* Compare whether the filenames are identical.  This is a
   special version of strcmp() taking the semantics of filenames in
   account.  Note that this function works only on the supplied names
   without considering any context like the current directory.  See
   also same_file_p(). */
int
compare_filenames (const char *a, const char *b)
{
#ifdef HAVE_DOSISH_SYSTEM
  for ( ; *a && *b; a++, b++ )
    {
      if (*a != *b
          && (toupper (*(const unsigned char*)a)
              != toupper (*(const unsigned char*)b) )
          && !((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/')))
        break;
    }
  if ((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/'))
    return 0;
  else
    return (toupper (*(const unsigned char*)a)
            - toupper (*(const unsigned char*)b));
#else
    return strcmp(a,b);
#endif
}


/* Convert a base-10 number in STRING into a 64 bit unsigned int
 * value.  Leading white spaces are skipped but no error checking is
 * done.  Thus it is similar to atoi(). */
uint64_t
string_to_u64 (const char *string)
{
  uint64_t val = 0;

  while (spacep (string))
    string++;
  for (; digitp (string); string++)
    {
      val *= 10;
      val += *string - '0';
    }
  return val;
}


/* Convert 2 hex characters at S to a byte value.  Return this value
   or -1 if there is an error. */
int
hextobyte (const char *s)
{
  int c;

  if ( *s >= '0' && *s <= '9' )
    c = 16 * (*s - '0');
  else if ( *s >= 'A' && *s <= 'F' )
    c = 16 * (10 + *s - 'A');
  else if ( *s >= 'a' && *s <= 'f' )
    c = 16 * (10 + *s - 'a');
  else
    return -1;
  s++;
  if ( *s >= '0' && *s <= '9' )
    c += *s - '0';
  else if ( *s >= 'A' && *s <= 'F' )
    c += 10 + *s - 'A';
  else if ( *s >= 'a' && *s <= 'f' )
    c += 10 + *s - 'a';
  else
    return -1;
  return c;
}

/* Given a string containing an UTF-8 encoded text, return the number
   of characters in this string.  It differs from strlen in that it
   only counts complete UTF-8 characters.  SIZE is the maximum length
   of the string in bytes.  If SIZE is -1, then a NUL character is
   taken to be the end of the string.  Note, that this function does
   not take combined characters into account.  */
size_t
utf8_charcount (const char *s, int len)
{
  size_t n;

  if (len == 0)
    return 0;

  for (n=0; *s; s++)
    {
      if ( (*s&0xc0) != 0x80 ) /* Exclude continuation bytes: 10xxxxxx */
        n++;

      if (len != -1)
        {
          len --;
          if (len == 0)
            break;
        }
    }

  return n;
}


/****************************************************
 **********  W32 specific functions  ****************
 ****************************************************/

#ifdef HAVE_W32_SYSTEM
const char *
w32_strerror (int ec)
{
  static char strerr[256];

  if (ec == -1)
    ec = (int)GetLastError ();
#ifdef HAVE_W32CE_SYSTEM
  /* There is only a wchar_t FormatMessage.  It does not make much
     sense to play the conversion game; we print only the code.  */
  snprintf (strerr, sizeof strerr, "ec=%d", (int)GetLastError ());
#else
  FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, ec,
                 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
                 strerr, DIM (strerr)-1, NULL);
  {
    /* Strip the CR,LF - we want just the string.  */
    size_t n = strlen (strerr);
    if (n > 2 && strerr[n-2] == '\r' && strerr[n-1] == '\n' )
      strerr[n-2] = 0;
  }
#endif
  return strerr;
}
#endif /*HAVE_W32_SYSTEM*/


/****************************************************
 ******** Locale insensitive ctype functions ********
 ****************************************************/
/* FIXME: replace them by a table lookup and macros */
int
ascii_isupper (int c)
{
    return c >= 'A' && c <= 'Z';
}

int
ascii_islower (int c)
{
    return c >= 'a' && c <= 'z';
}

int
ascii_toupper (int c)
{
    if (c >= 'a' && c <= 'z')
        c &= ~0x20;
    return c;
}

int
ascii_tolower (int c)
{
    if (c >= 'A' && c <= 'Z')
        c |= 0x20;
    return c;
}

/* Lowercase all ASCII characters in S.  */
char *
ascii_strlwr (char *s)
{
  char *p = s;

  for (p=s; *p; p++ )
    if (isascii (*p) && *p >= 'A' && *p <= 'Z')
      *p |= 0x20;

  return s;
}

/* Upcase all ASCII characters in S.  */
char *
ascii_strupr (char *s)
{
  char *p = s;

  for (p=s; *p; p++ )
    if (isascii (*p) && *p >= 'a' && *p <= 'z')
      *p &= ~0x20;

  return s;
}

int
ascii_strcasecmp( const char *a, const char *b )
{
    if (a == b)
        return 0;

    for (; *a && *b; a++, b++) {
	if (*a != *b && ascii_toupper(*a) != ascii_toupper(*b))
	    break;
    }
    return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
}

int
ascii_strncasecmp (const char *a, const char *b, size_t n)
{
  const unsigned char *p1 = (const unsigned char *)a;
  const unsigned char *p2 = (const unsigned char *)b;
  unsigned char c1, c2;

  if (p1 == p2 || !n )
    return 0;

  do
    {
      c1 = ascii_tolower (*p1);
      c2 = ascii_tolower (*p2);

      if ( !--n || c1 == '\0')
	break;

      ++p1;
      ++p2;
    }
  while (c1 == c2);

  return c1 - c2;
}


int
ascii_memcasecmp (const void *a_arg, const void *b_arg, size_t n )
{
  const char *a = a_arg;
  const char *b = b_arg;

  if (a == b)
    return 0;
  for ( ; n; n--, a++, b++ )
    {
      if( *a != *b  && ascii_toupper (*a) != ascii_toupper (*b) )
        return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
    }
  return 0;
}

int
ascii_strcmp( const char *a, const char *b )
{
    if (a == b)
        return 0;

    for (; *a && *b; a++, b++) {
	if (*a != *b )
	    break;
    }
    return *a == *b? 0 : (*(signed char *)a - *(signed char *)b);
}


void *
ascii_memcasemem (const void *haystack, size_t nhaystack,
                  const void *needle, size_t nneedle)
{

  if (!nneedle)
    return (void*)haystack; /* finding an empty needle is really easy */
  if (nneedle <= nhaystack)
    {
      const char *a = haystack;
      const char *b = a + nhaystack - nneedle;

      for (; a <= b; a++)
        {
          if ( !ascii_memcasecmp (a, needle, nneedle) )
            return (void *)a;
        }
    }
  return NULL;
}

/*********************************************
 ********** missing string functions *********
 *********************************************/

#ifndef HAVE_STPCPY
char *
stpcpy(char *a,const char *b)
{
    while( *b )
	*a++ = *b++;
    *a = 0;

    return (char*)a;
}
#endif

#ifndef HAVE_STRPBRK
/* Find the first occurrence in S of any character in ACCEPT.
   Code taken from glibc-2.6/string/strpbrk.c (LGPLv2.1+) and modified. */
char *
strpbrk (const char *s, const char *accept)
{
  while (*s != '\0')
    {
      const char *a = accept;
      while (*a != '\0')
	if (*a++ == *s)
	  return (char *) s;
      ++s;
    }

  return NULL;
}
#endif /*!HAVE_STRPBRK*/


#ifndef HAVE_STRSEP
/* Code taken from glibc-2.2.1/sysdeps/generic/strsep.c. */
char *
strsep (char **stringp, const char *delim)
{
  char *begin, *end;

  begin = *stringp;
  if (begin == NULL)
    return NULL;

  /* A frequent case is when the delimiter string contains only one
     character.  Here we don't need to call the expensive 'strpbrk'
     function and instead work using 'strchr'.  */
  if (delim[0] == '\0' || delim[1] == '\0')
    {
      char ch = delim[0];

      if (ch == '\0')
        end = NULL;
      else
        {
          if (*begin == ch)
            end = begin;
          else if (*begin == '\0')
            end = NULL;
          else
            end = strchr (begin + 1, ch);
        }
    }
  else
    /* Find the end of the token.  */
    end = strpbrk (begin, delim);

  if (end)
    {
      /* Terminate the token and set *STRINGP past NUL character.  */
      *end++ = '\0';
      *stringp = end;
    }
  else
    /* No more delimiters; this is the last token.  */
    *stringp = NULL;

  return begin;
}
#endif /*HAVE_STRSEP*/


#ifndef HAVE_STRLWR
char *
strlwr(char *s)
{
    char *p;
    for(p=s; *p; p++ )
	*p = tolower(*p);
    return s;
}
#endif


#ifndef HAVE_STRCASECMP
int
strcasecmp( const char *a, const char *b )
{
    for( ; *a && *b; a++, b++ ) {
	if( *a != *b && toupper(*a) != toupper(*b) )
	    break;
    }
    return *(const byte*)a - *(const byte*)b;
}
#endif


/****************
 * mingw32/cpd has a memicmp()
 */
#ifndef HAVE_MEMICMP
int
memicmp( const char *a, const char *b, size_t n )
{
    for( ; n; n--, a++, b++ )
	if( *a != *b  && toupper(*(const byte*)a) != toupper(*(const byte*)b) )
	    return *(const byte *)a - *(const byte*)b;
    return 0;
}
#endif


#ifndef HAVE_MEMRCHR
void *
memrchr (const void *buffer, int c, size_t n)
{
  const unsigned char *p = buffer;

  for (p += n; n ; n--)
    if (*--p == c)
      return (void *)p;
  return NULL;
}
#endif /*HAVE_MEMRCHR*/


/* Percent-escape the string STR by replacing colons with '%3a'.  If
   EXTRA is not NULL all characters in EXTRA are also escaped.  */
static char *
do_percent_escape (const char *str, const char *extra, int die)
{
  int i, j;
  char *ptr;

  if (!str)
    return NULL;

  for (i=j=0; str[i]; i++)
    if (str[i] == ':' || str[i] == '%' || str[i] == '\n'
        || (extra && strchr (extra, str[i])))
      j++;
  if (die)
    ptr = xmalloc (i + 2 * j + 1);
  else
    {
      ptr = xtrymalloc (i + 2 * j + 1);
      if (!ptr)
        return NULL;
    }
  i = 0;
  while (*str)
    {
      if (*str == ':')
	{
	  ptr[i++] = '%';
	  ptr[i++] = '3';
	  ptr[i++] = 'a';
	}
      else if (*str == '%')
	{
	  ptr[i++] = '%';
	  ptr[i++] = '2';
	  ptr[i++] = '5';
	}
      else if (*str == '\n')
	{
	  /* The newline is problematic in a line-based format.  */
	  ptr[i++] = '%';
	  ptr[i++] = '0';
	  ptr[i++] = 'a';
	}
      else if (extra && strchr (extra, *str))
        {
	  ptr[i++] = '%';
          ptr[i++] = tohex_lower ((*str>>4)&15);
          ptr[i++] = tohex_lower (*str&15);
        }
      else
	ptr[i++] = *str;
      str++;
    }
  ptr[i] = '\0';

  return ptr;
}

/* Percent-escape the string STR by replacing colons with '%3a'.  If
   EXTRA is not NULL all characters in EXTRA are also escaped.  This
   function terminates the process on memory shortage.  */
char *
percent_escape (const char *str, const char *extra)
{
  return do_percent_escape (str, extra, 1);
}

/* Same as percent_escape but return NULL instead of exiting on memory
   error. */
char *
try_percent_escape (const char *str, const char *extra)
{
  return do_percent_escape (str, extra, 0);
}


/* Same as strconcat but takes a va_list.  Returns EINVAL if the list
 * is too long, all other errors are due to an ENOMEM condition.  */
char *
vstrconcat (const char *s1, va_list arg_ptr)
{
  const char *argv[48];
  size_t argc;
  size_t needed;
  char *buffer, *p;

  argc = 0;
  argv[argc++] = s1;
  needed = strlen (s1);
  while (((argv[argc] = va_arg (arg_ptr, const char *))))
    {
      needed += strlen (argv[argc]);
      if (argc >= DIM (argv)-1)
        {
          gpg_err_set_errno (EINVAL);
          return NULL;
        }
      argc++;
    }
  needed++;
  buffer = xtrymalloc (needed);
  if (buffer)
    {
      for (p = buffer, argc=0; argv[argc]; argc++)
        p = stpcpy (p, argv[argc]);
    }
  return buffer;
}


/* Concatenate the string S1 with all the following strings up to a
   NULL.  Returns a malloced buffer with the new string or NULL on a
   malloc error or if too many arguments are given.  */
char *
strconcat (const char *s1, ...)
{
  va_list arg_ptr;
  char *result;

  if (!s1)
    result = xtrystrdup ("");
  else
    {
      va_start (arg_ptr, s1);
      result = vstrconcat (s1, arg_ptr);
      va_end (arg_ptr);
    }
  return result;
}

/* Same as strconcat but terminate the process with an error message
   if something goes wrong.  */
char *
xstrconcat (const char *s1, ...)
{
  va_list arg_ptr;
  char *result;

  if (!s1)
    result = xstrdup ("");
  else
    {
      va_start (arg_ptr, s1);
      result = vstrconcat (s1, arg_ptr);
      va_end (arg_ptr);
    }
  if (!result)
    {
      if (errno == EINVAL)
        fputs ("\nfatal: too many args for xstrconcat\n", stderr);
      else
        fputs ("\nfatal: out of memory\n", stderr);
      exit (2);
    }
  return result;
}

/* Split a string into fields at DELIM.  REPLACEMENT is the character
   to replace the delimiter with (normally: '\0' so that each field is
   NUL terminated).  The caller is responsible for freeing the result.
   Note: this function modifies STRING!  If you need the original
   value, then you should pass a copy to this function.

   If malloc fails, this function returns NULL.  */
char **
strsplit (char *string, char delim, char replacement, int *count)
{
  int fields = 1;
  char *t;
  char **result;

  /* First, count the number of fields.  */
  for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
    fields ++;

  result = xtrycalloc ((fields + 1), sizeof (*result));
  if (! result)
    return NULL;

  result[0] = string;
  fields = 1;
  for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
    {
      result[fields ++] = t + 1;
      *t = replacement;
    }

  if (count)
    *count = fields;

  return result;
}


/* Tokenize STRING using the set of delimiters in DELIM.  Leading
 * spaces and tabs are removed from all tokens.  The caller must xfree
 * the result.
 *
 * Returns: A malloced and NULL delimited array with the tokens.  On
 *          memory error NULL is returned and ERRNO is set.
 */
static char **
do_strtokenize (const char *string, const char *delim, int trim)
{
  const char *s;
  size_t fields;
  size_t bytes, n;
  char *buffer;
  char *p, *px, *pend;
  char **result;

  /* Count the number of fields.  */
  for (fields = 1, s = strpbrk (string, delim); s; s = strpbrk (s + 1, delim))
    fields++;
  fields++; /* Add one for the terminating NULL.  */

  /* Allocate an array for all fields, a terminating NULL, and space
     for a copy of the string.  */
  bytes = fields * sizeof *result;
  if (bytes / sizeof *result != fields)
    {
      gpg_err_set_errno (ENOMEM);
      return NULL;
    }
  n = strlen (string) + 1;
  bytes += n;
  if (bytes < n)
    {
      gpg_err_set_errno (ENOMEM);
      return NULL;
    }
  result = xtrymalloc (bytes);
  if (!result)
    return NULL;
  buffer = (char*)(result + fields);

  /* Copy and parse the string.  */
  strcpy (buffer, string);
  for (n = 0, p = buffer; (pend = strpbrk (p, delim)); p = pend + 1)
    {
      *pend = 0;
      if (trim)
        {
          while (spacep (p))
            p++;
          for (px = pend - 1; px >= p && spacep (px); px--)
            *px = 0;
        }
      result[n++] = p;
    }
  if (trim)
    {
      while (spacep (p))
        p++;
      for (px = p + strlen (p) - 1; px >= p && spacep (px); px--)
        *px = 0;
    }
  result[n++] = p;
  result[n] = NULL;

  log_assert ((char*)(result + n + 1) == buffer);

  return result;
}

/* Tokenize STRING using the set of delimiters in DELIM.  Leading
 * spaces and tabs are removed from all tokens.  The caller must xfree
 * the result.
 *
 * Returns: A malloced and NULL delimited array with the tokens.  On
 *          memory error NULL is returned and ERRNO is set.
 */
char **
strtokenize (const char *string, const char *delim)
{
  return do_strtokenize (string, delim, 1);
}

/* Same as strtokenize but does not trim leading and trailing spaces
 * from the fields.  */
char **
strtokenize_nt (const char *string, const char *delim)
{
  return do_strtokenize (string, delim, 0);
}


/* Split a string into space delimited fields and remove leading and
 * trailing spaces from each field.  A pointer to each field is stored
 * in ARRAY.  Stop splitting at ARRAYSIZE fields.  The function
 * modifies STRING.  The number of parsed fields is returned.
 * Example:
 *
 *   char *fields[2];
 *   if (split_fields (string, fields, DIM (fields)) < 2)
 *     return  // Not enough args.
 *   foo (fields[0]);
 *   foo (fields[1]);
 */
int
split_fields (char *string, char **array, int arraysize)
{
  int n = 0;
  char *p, *pend;

  for (p = string; *p == ' '; p++)
    ;
  do
    {
      if (n == arraysize)
        break;
      array[n++] = p;
      pend = strchr (p, ' ');
      if (!pend)
        break;
      *pend++ = 0;
      for (p = pend; *p == ' '; p++)
        ;
    }
  while (*p);

  return n;
}


/* Split a string into colon delimited fields A pointer to each field
 * is stored in ARRAY.  Stop splitting at ARRAYSIZE fields.  The
 * function modifies STRING.  The number of parsed fields is returned.
 * Note that leading and trailing spaces are not removed from the fields.
 * Example:
 *
 *   char *fields[2];
 *   if (split_fields (string, fields, DIM (fields)) < 2)
 *     return  // Not enough args.
 *   foo (fields[0]);
 *   foo (fields[1]);
 */
int
split_fields_colon (char *string, char **array, int arraysize)
{
  int n = 0;
  char *p, *pend;

  p = string;
  do
    {
      if (n == arraysize)
        break;
      array[n++] = p;
      pend = strchr (p, ':');
      if (!pend)
        break;
      *pend++ = 0;
      p = pend;
    }
  while (*p);

  return n;
}



/* Version number parsing.  */

/* This function parses the first portion of the version number S and
   stores it in *NUMBER.  On success, this function returns a pointer
   into S starting with the first character, which is not part of the
   initial number portion; on failure, NULL is returned.  */
static const char*
parse_version_number (const char *s, int *number)
{
  int val = 0;

  if (*s == '0' && digitp (s+1))
    return NULL;  /* Leading zeros are not allowed.  */
  for (; digitp (s); s++)
    {
      val *= 10;
      val += *s - '0';
    }
  *number = val;
  return val < 0 ? NULL : s;
}


/* This function breaks up the complete string-representation of the
   version number S, which is of the following struture: <major
   number>.<minor number>[.<micro number>]<patch level>.  The major,
   minor, and micro number components will be stored in *MAJOR, *MINOR
   and *MICRO.  If MICRO is not given 0 is used instead.

   On success, the last component, the patch level, will be returned;
   in failure, NULL will be returned.  */
static const char *
parse_version_string (const char *s, int *major, int *minor, int *micro)
{
  s = parse_version_number (s, major);
  if (!s || *s != '.')
    return NULL;
  s++;
  s = parse_version_number (s, minor);
  if (!s)
    return NULL;
  if (*s == '.')
    {
      s++;
      s = parse_version_number (s, micro);
      if (!s)
        return NULL;
    }
  else
    *micro = 0;
  return s;  /* Patchlevel.  */
}


/* Compare the version string MY_VERSION to the version string
 * REQ_VERSION.  Returns -1, 0, or 1 if MY_VERSION is found,
 * respectively, to be less than, to match, or be greater than
 * REQ_VERSION.  This function works for three and two part version
 * strings; for a two part version string the micro part is assumed to
 * be 0.  Patch levels are compared as strings.  If a version number
 * is invalid INT_MIN is returned.  If REQ_VERSION is given as NULL
 * the function returns 0 if MY_VERSION is parsable version string. */
int
compare_version_strings (const char *my_version, const char *req_version)
{
  int my_major, my_minor, my_micro;
  int rq_major, rq_minor, rq_micro;
  const char *my_patch, *rq_patch;
  int result;

  if (!my_version)
    return INT_MIN;

  my_patch = parse_version_string (my_version, &my_major, &my_minor, &my_micro);
  if (!my_patch)
    return INT_MIN;
  if (!req_version)
    return 0; /* MY_VERSION can be parsed.  */
  rq_patch = parse_version_string (req_version, &rq_major, &rq_minor,&rq_micro);
  if (!rq_patch)
    return INT_MIN;

  if (my_major == rq_major)
    {
      if (my_minor == rq_minor)
        {
          if (my_micro == rq_micro)
            result = strcmp (my_patch, rq_patch);
          else
            result = my_micro - rq_micro;
        }
      else
        result = my_minor - rq_minor;
    }
  else
    result = my_major - rq_major;

  return !result? 0 : result < 0 ? -1 : 1;
}



/* Format a string so that it fits within about TARGET_COLS columns.
 * TEXT_IN is copied to a new buffer, which is returned.  Normally,
 * target_cols will be 72 and max_cols is 80.  On error NULL is
 * returned and ERRNO is set. */
char *
format_text (const char *text_in, int target_cols, int max_cols)
{
  /* const int do_debug = 0; */

  /* The character under consideration.  */
  char *p;
  /* The start of the current line.  */
  char *line;
  /* The last space that we saw.  */
  char *last_space = NULL;
  int last_space_cols = 0;
  int copied_last_space = 0;
  char *text;

  text = xtrystrdup (text_in);
  if (!text)
    return NULL;

  p = line = text;
  while (1)
    {
      /* The number of columns including any trailing space.  */
      int cols;

      p = p + strcspn (p, "\n ");
      if (! p)
        /* P now points to the NUL character.  */
        p = &text[strlen (text)];

      if (*p == '\n')
        /* Pass through any newlines.  */
        {
          p ++;
          line = p;
          last_space = NULL;
          last_space_cols = 0;
          copied_last_space = 1;
          continue;
        }

      /* Have a space or a NUL.  Note: we don't count the trailing
         space.  */
      cols = utf8_charcount (line, (uintptr_t) p - (uintptr_t) line);
      if (cols < target_cols)
        {
          if (! *p)
            /* Nothing left to break.  */
            break;

          last_space = p;
          last_space_cols = cols;
          p ++;
          /* Skip any immediately following spaces.  If we break:
             "... foo bar ..." between "foo" and "bar" then we want:
             "... foo\nbar ...", which means that the left space has
             to be the first space after foo, not the last space
             before bar.  */
          while (*p == ' ')
            p ++;
        }
      else
        {
          int cols_with_left_space;
          int cols_with_right_space;
          int left_penalty;
          int right_penalty;

          cols_with_left_space = last_space_cols;
          cols_with_right_space = cols;

          /* if (do_debug) */
          /*   log_debug ("Breaking: '%.*s'\n", */
          /*              (int) ((uintptr_t) p - (uintptr_t) line), line); */

          /* The number of columns away from TARGET_COLS.  We prefer
             to underflow than to overflow.  */
          left_penalty = target_cols - cols_with_left_space;
          right_penalty = 2 * (cols_with_right_space - target_cols);

          if (cols_with_right_space > max_cols)
            /* Add a large penalty for each column that exceeds
               max_cols.  */
            right_penalty += 4 * (cols_with_right_space - max_cols);

          /* if (do_debug) */
          /*   log_debug ("Left space => %d cols (penalty: %d); " */
          /*              "right space => %d cols (penalty: %d)\n", */
          /*              cols_with_left_space, left_penalty, */
          /*              cols_with_right_space, right_penalty); */
          if (last_space_cols && left_penalty <= right_penalty)
            {
              /* Prefer the left space.  */
              /* if (do_debug) */
              /*   log_debug ("Breaking at left space.\n"); */
              p = last_space;
            }
          else
            {
              /* if (do_debug) */
              /*   log_debug ("Breaking at right space.\n"); */
            }

          if (! *p)
            break;

          *p = '\n';
          p ++;
          if (*p == ' ')
            {
              int spaces;
              for (spaces = 1; p[spaces] == ' '; spaces ++)
                ;
              memmove (p, &p[spaces], strlen (&p[spaces]) + 1);
            }
          line = p;
          last_space = NULL;
          last_space_cols = 0;
          copied_last_space = 0;
        }
    }

  /* Chop off any trailing space.  */
  trim_trailing_chars (text, strlen (text), " ");
  /* If we inserted the trailing newline, then remove it.  */
  if (! copied_last_space && *text && text[strlen (text) - 1] == '\n')
    text[strlen (text) - 1] = '\0';

  return text;
}


/* Substitute environment variables in STRING and return a new string.
 * On error the function returns NULL.  */
char *
substitute_envvars (const char *string)
{
  char *line, *p, *pend;
  const char *value;
  size_t valuelen, n;
  char *result = NULL;

  result = line = xtrystrdup (string);
  if (!result)
    return NULL; /* Ooops */

  while (*line)
    {
      p = strchr (line, '$');
      if (!p)
        goto leave; /* No or no more variables.  */

      if (p[1] == '$') /* Escaped dollar sign. */
        {
          memmove (p, p+1, strlen (p+1)+1);
          line = p + 1;
          continue;
        }

      if (p[1] == '{')
        {
          int count = 0;

          for (pend=p+2; *pend; pend++)
            {
              if (*pend == '{')
                count++;
              else if (*pend == '}')
                {
                  if (--count < 0)
                    break;
                }
            }
          if (!*pend)
            goto leave; /* Unclosed - don't substitute.  */
        }
      else
        {
          for (pend = p+1; *pend && (alnump (pend) || *pend == '_'); pend++)
            ;
        }

      if (p[1] == '{' && *pend == '}')
        {
          int save = *pend;
          *pend = 0;
          value = getenv (p+2);
          *pend++ = save;
        }
      else
        {
          int save = *pend;
          *pend = 0;
          value = getenv (p+1);
          *pend = save;
        }

      if (!value)
        value = "";
      valuelen = strlen (value);
      if (valuelen <= pend - p)
        {
          memcpy (p, value, valuelen);
          p += valuelen;
          n = pend - p;
          if (n)
            memmove (p, p+n, strlen (p+n)+1);
          line = p;
        }
      else
        {
          char *src = result;
          char *dst;

          dst = xtrymalloc (strlen (src) + valuelen + 1);
          if (!dst)
            {
              xfree (result);
              return NULL;
            }
          n = p - src;
          memcpy (dst, src, n);
          memcpy (dst + n, value, valuelen);
          n += valuelen;
          strcpy (dst + n, pend);
          line = dst + n;
          xfree (result);
          result = dst;
        }
    }

 leave:
  return result;
}