Imported Upstream version 2.2.15
[platform/upstream/gpg2.git] / common / stringhelp.c
1 /* stringhelp.c -  standard string helper functions
2  * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
3  *               2008, 2009, 2010  Free Software Foundation, Inc.
4  * Copyright (C) 2014 Werner Koch
5  * Copyright (C) 2015  g10 Code GmbH
6  *
7  * This file is part of GnuPG.
8  *
9  * GnuPG is free software; you can redistribute and/or modify this
10  * part of GnuPG under the terms of either
11  *
12  *   - the GNU Lesser General Public License as published by the Free
13  *     Software Foundation; either version 3 of the License, or (at
14  *     your option) any later version.
15  *
16  * or
17  *
18  *   - the GNU General Public License as published by the Free
19  *     Software Foundation; either version 2 of the License, or (at
20  *     your option) any later version.
21  *
22  * or both in parallel, as here.
23  *
24  * GnuPG is distributed in the hope that it will be useful, but
25  * WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27  * General Public License for more details.
28  *
29  * You should have received a copies of the GNU General Public License
30  * and the GNU Lesser General Public License along with this program;
31  * if not, see <https://www.gnu.org/licenses/>.
32  */
33
34 #include <config.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdarg.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #ifdef HAVE_PWD_H
41 # include <pwd.h>
42 #endif
43 #include <unistd.h>
44 #include <sys/types.h>
45 #ifdef HAVE_W32_SYSTEM
46 # ifdef HAVE_WINSOCK2_H
47 #  include <winsock2.h>
48 # endif
49 # include <windows.h>
50 #endif
51 #include <assert.h>
52 #include <limits.h>
53
54 #include "util.h"
55 #include "common-defs.h"
56 #include "utf8conv.h"
57 #include "sysutils.h"
58 #include "stringhelp.h"
59
60 #define tohex_lower(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'a'))
61
62
63 /* Sometimes we want to avoid mixing slashes and backslashes on W32
64    and prefer backslashes.  There is usual no problem with mixing
65    them, however a very few W32 API calls can't grok plain slashes.
66    Printing filenames with mixed slashes also looks a bit strange.
67    This function has no effext on POSIX. */
68 static inline char *
69 change_slashes (char *name)
70 {
71 #ifdef HAVE_DOSISH_SYSTEM
72   char *p;
73
74   if (strchr (name, '\\'))
75     {
76       for (p=name; *p; p++)
77         if (*p == '/')
78           *p = '\\';
79     }
80 #endif /*HAVE_DOSISH_SYSTEM*/
81   return name;
82 }
83
84
85 /*
86  * Check whether STRING starts with KEYWORD.  The keyword is
87  * delimited by end of string, a space or a tab.  Returns NULL if not
88  * found or a pointer into STRING to the next non-space character
89  * after the KEYWORD (which may be end of string).
90  */
91 char *
92 has_leading_keyword (const char *string, const char *keyword)
93 {
94   size_t n = strlen (keyword);
95
96   if (!strncmp (string, keyword, n)
97       && (!string[n] || string[n] == ' ' || string[n] == '\t'))
98     {
99       string += n;
100       while (*string == ' ' || *string == '\t')
101         string++;
102       return (char*)string;
103     }
104   return NULL;
105 }
106
107
108 /*
109  * Look for the substring SUB in buffer and return a pointer to that
110  * substring in BUFFER or NULL if not found.
111  * Comparison is case-insensitive.
112  */
113 const char *
114 memistr (const void *buffer, size_t buflen, const char *sub)
115 {
116   const unsigned char *buf = buffer;
117   const unsigned char *t = (const unsigned char *)buffer;
118   const unsigned char *s = (const unsigned char *)sub;
119   size_t n = buflen;
120
121   for ( ; n ; t++, n-- )
122     {
123       if ( toupper (*t) == toupper (*s) )
124         {
125           for ( buf=t++, buflen = n--, s++;
126                 n && toupper (*t) == toupper (*s); t++, s++, n-- )
127             ;
128           if (!*s)
129             return (const char*)buf;
130           t = buf;
131           s = (const unsigned char *)sub ;
132           n = buflen;
133         }
134     }
135   return NULL;
136 }
137
138 const char *
139 ascii_memistr ( const void *buffer, size_t buflen, const char *sub )
140 {
141   const unsigned char *buf = buffer;
142   const unsigned char *t = (const unsigned char *)buf;
143   const unsigned char *s = (const unsigned char *)sub;
144   size_t n = buflen;
145
146   for ( ; n ; t++, n-- )
147     {
148       if (ascii_toupper (*t) == ascii_toupper (*s) )
149         {
150           for ( buf=t++, buflen = n--, s++;
151                 n && ascii_toupper (*t) == ascii_toupper (*s); t++, s++, n-- )
152             ;
153           if (!*s)
154             return (const char*)buf;
155           t = (const unsigned char *)buf;
156           s = (const unsigned char *)sub ;
157           n = buflen;
158         }
159     }
160   return NULL;
161 }
162
163 /* This function is similar to strncpy().  However it won't copy more
164    than N - 1 characters and makes sure that a '\0' is appended. With
165    N given as 0, nothing will happen.  With DEST given as NULL, memory
166    will be allocated using xmalloc (i.e. if it runs out of core
167    the function terminates).  Returns DES or a pointer to the
168    allocated memory.
169  */
170 char *
171 mem2str( char *dest , const void *src , size_t n )
172 {
173     char *d;
174     const char *s;
175
176     if( n ) {
177         if( !dest )
178             dest = xmalloc( n ) ;
179         d = dest;
180         s = src ;
181         for(n--; n && *s; n-- )
182             *d++ = *s++;
183         *d = '\0' ;
184     }
185
186     return dest ;
187 }
188
189
190 /****************
191  * remove leading and trailing white spaces
192  */
193 char *
194 trim_spaces( char *str )
195 {
196     char *string, *p, *mark;
197
198     string = str;
199     /* find first non space character */
200     for( p=string; *p && isspace( *(byte*)p ) ; p++ )
201         ;
202     /* move characters */
203     for( (mark = NULL); (*string = *p); string++, p++ )
204         if( isspace( *(byte*)p ) ) {
205             if( !mark )
206                 mark = string ;
207         }
208         else
209             mark = NULL ;
210     if( mark )
211         *mark = '\0' ;  /* remove trailing spaces */
212
213     return str ;
214 }
215
216 /****************
217  * remove trailing white spaces
218  */
219 char *
220 trim_trailing_spaces( char *string )
221 {
222     char *p, *mark;
223
224     for( mark = NULL, p = string; *p; p++ ) {
225         if( isspace( *(byte*)p ) ) {
226             if( !mark )
227                 mark = p;
228         }
229         else
230             mark = NULL;
231     }
232     if( mark )
233         *mark = '\0' ;
234
235     return string ;
236 }
237
238
239 unsigned
240 trim_trailing_chars( byte *line, unsigned len, const char *trimchars )
241 {
242     byte *p, *mark;
243     unsigned n;
244
245     for(mark=NULL, p=line, n=0; n < len; n++, p++ ) {
246         if( strchr(trimchars, *p ) ) {
247             if( !mark )
248                 mark = p;
249         }
250         else
251             mark = NULL;
252     }
253
254     if( mark ) {
255         *mark = 0;
256         return mark - line;
257     }
258     return len;
259 }
260
261 /****************
262  * remove trailing white spaces and return the length of the buffer
263  */
264 unsigned
265 trim_trailing_ws( byte *line, unsigned len )
266 {
267     return trim_trailing_chars( line, len, " \t\r\n" );
268 }
269
270 size_t
271 length_sans_trailing_chars (const unsigned char *line, size_t len,
272                             const char *trimchars )
273 {
274   const unsigned char *p, *mark;
275   size_t n;
276
277   for( mark=NULL, p=line, n=0; n < len; n++, p++ )
278     {
279       if (strchr (trimchars, *p ))
280         {
281           if( !mark )
282             mark = p;
283         }
284       else
285         mark = NULL;
286     }
287
288   if (mark)
289     return mark - line;
290   return len;
291 }
292
293 /*
294  *  Return the length of line ignoring trailing white-space.
295  */
296 size_t
297 length_sans_trailing_ws (const unsigned char *line, size_t len)
298 {
299   return length_sans_trailing_chars (line, len, " \t\r\n");
300 }
301
302
303
304 /*
305  * Extract from a given path the filename component.  This function
306  * terminates the process on memory shortage.
307  */
308 char *
309 make_basename(const char *filepath, const char *inputpath)
310 {
311 #ifdef __riscos__
312     return riscos_make_basename(filepath, inputpath);
313 #else
314     char *p;
315
316     (void)inputpath; /* Only required for riscos.  */
317
318     if ( !(p=strrchr(filepath, '/')) )
319 #ifdef HAVE_DOSISH_SYSTEM
320         if ( !(p=strrchr(filepath, '\\')) )
321 #endif
322 #ifdef HAVE_DRIVE_LETTERS
323             if ( !(p=strrchr(filepath, ':')) )
324 #endif
325               {
326                 return xstrdup(filepath);
327               }
328
329     return xstrdup(p+1);
330 #endif
331 }
332
333
334
335 /*
336  * Extract from a given filename the path prepended to it.  If there
337  * isn't a path prepended to the filename, a dot is returned ('.').
338  * This function terminates the process on memory shortage.
339  */
340 char *
341 make_dirname(const char *filepath)
342 {
343     char *dirname;
344     int  dirname_length;
345     char *p;
346
347     if ( !(p=strrchr(filepath, '/')) )
348 #ifdef HAVE_DOSISH_SYSTEM
349         if ( !(p=strrchr(filepath, '\\')) )
350 #endif
351 #ifdef HAVE_DRIVE_LETTERS
352             if ( !(p=strrchr(filepath, ':')) )
353 #endif
354               {
355                 return xstrdup(".");
356               }
357
358     dirname_length = p-filepath;
359     dirname = xmalloc(dirname_length+1);
360     strncpy(dirname, filepath, dirname_length);
361     dirname[dirname_length] = 0;
362
363     return dirname;
364 }
365
366
367 \f
368 static char *
369 get_pwdir (int xmode, const char *name)
370 {
371   char *result = NULL;
372 #ifdef HAVE_PWD_H
373   struct passwd *pwd = NULL;
374
375   if (name)
376     {
377 #ifdef HAVE_GETPWNAM
378       /* Fixme: We should use getpwnam_r if available.  */
379       pwd = getpwnam (name);
380 #endif
381     }
382   else
383     {
384 #ifdef HAVE_GETPWUID
385       /* Fixme: We should use getpwuid_r if available.  */
386       pwd = getpwuid (getuid());
387 #endif
388     }
389   if (pwd)
390     {
391       if (xmode)
392         result = xstrdup (pwd->pw_dir);
393       else
394         result = xtrystrdup (pwd->pw_dir);
395     }
396 #else /*!HAVE_PWD_H*/
397   /* No support at all.  */
398   (void)xmode;
399   (void)name;
400 #endif /*HAVE_PWD_H*/
401   return result;
402 }
403
404
405 /* xmode 0 := Return NULL on error
406          1 := Terminate on error
407          2 := Make sure that name is absolute; return NULL on error
408          3 := Make sure that name is absolute; terminate on error
409  */
410 static char *
411 do_make_filename (int xmode, const char *first_part, va_list arg_ptr)
412 {
413   const char *argv[32];
414   int argc;
415   size_t n;
416   int skip = 1;
417   char *home_buffer = NULL;
418   char *name, *home, *p;
419   int want_abs;
420
421   want_abs = !!(xmode & 2);
422   xmode &= 1;
423
424   n = strlen (first_part) + 1;
425   argc = 0;
426   while ( (argv[argc] = va_arg (arg_ptr, const char *)) )
427     {
428       n += strlen (argv[argc]) + 1;
429       if (argc >= DIM (argv)-1)
430         {
431           if (xmode)
432             BUG ();
433           gpg_err_set_errno (EINVAL);
434           return NULL;
435         }
436       argc++;
437     }
438   n++;
439
440   home = NULL;
441   if (*first_part == '~')
442     {
443       if (first_part[1] == '/' || !first_part[1])
444         {
445           /* This is the "~/" or "~" case.  */
446           home = getenv("HOME");
447           if (!home)
448             home = home_buffer = get_pwdir (xmode, NULL);
449           if (home && *home)
450             n += strlen (home);
451         }
452       else
453         {
454           /* This is the "~username/" or "~username" case.  */
455           char *user;
456
457           if (xmode)
458             user = xstrdup (first_part+1);
459           else
460             {
461               user = xtrystrdup (first_part+1);
462               if (!user)
463                 return NULL;
464             }
465           p = strchr (user, '/');
466           if (p)
467             *p = 0;
468           skip = 1 + strlen (user);
469
470           home = home_buffer = get_pwdir (xmode, user);
471           xfree (user);
472           if (home)
473             n += strlen (home);
474           else
475             skip = 1;
476         }
477     }
478
479   if (xmode)
480     name = xmalloc (n);
481   else
482     {
483       name = xtrymalloc (n);
484       if (!name)
485         {
486           xfree (home_buffer);
487           return NULL;
488         }
489     }
490
491   if (home)
492     p = stpcpy (stpcpy (name, home), first_part + skip);
493   else
494     p = stpcpy (name, first_part);
495
496   xfree (home_buffer);
497   for (argc=0; argv[argc]; argc++)
498     {
499       /* Avoid a leading double slash if the first part was "/".  */
500       if (!argc && name[0] == '/' && !name[1])
501         p = stpcpy (p, argv[argc]);
502       else
503         p = stpcpy (stpcpy (p, "/"), argv[argc]);
504     }
505
506   if (want_abs)
507     {
508 #ifdef HAVE_DRIVE_LETTERS
509       p = strchr (name, ':');
510       if (p)
511         p++;
512       else
513         p = name;
514 #else
515       p = name;
516 #endif
517       if (*p != '/'
518 #ifdef HAVE_DRIVE_LETTERS
519           && *p != '\\'
520 #endif
521           )
522         {
523           home = gnupg_getcwd ();
524           if (!home)
525             {
526               if (xmode)
527                 {
528                   fprintf (stderr, "\nfatal: getcwd failed: %s\n",
529                            strerror (errno));
530                   exit(2);
531                 }
532               xfree (name);
533               return NULL;
534             }
535           n = strlen (home) + 1 + strlen (name) + 1;
536           if (xmode)
537             home_buffer = xmalloc (n);
538           else
539             {
540               home_buffer = xtrymalloc (n);
541               if (!home_buffer)
542                 {
543                   xfree (home);
544                   xfree (name);
545                   return NULL;
546                 }
547             }
548           if (p == name)
549             p = home_buffer;
550           else /* Windows case.  */
551             {
552               memcpy (home_buffer, p, p - name + 1);
553               p = home_buffer + (p - name + 1);
554             }
555
556           /* Avoid a leading double slash if the cwd is "/".  */
557           if (home[0] == '/' && !home[1])
558             strcpy (stpcpy (p, "/"), name);
559           else
560             strcpy (stpcpy (stpcpy (p, home), "/"), name);
561
562           xfree (home);
563           xfree (name);
564           name = home_buffer;
565           /* Let's do a simple compression to catch the most common
566              case of using "." for gpg's --homedir option.  */
567           n = strlen (name);
568           if (n > 2 && name[n-2] == '/' && name[n-1] == '.')
569             name[n-2] = 0;
570         }
571     }
572   return change_slashes (name);
573 }
574
575 /* Construct a filename from the NULL terminated list of parts.  Tilde
576    expansion is done for the first argument.  This function terminates
577    the process on memory shortage. */
578 char *
579 make_filename (const char *first_part, ... )
580 {
581   va_list arg_ptr;
582   char *result;
583
584   va_start (arg_ptr, first_part);
585   result = do_make_filename (1, first_part, arg_ptr);
586   va_end (arg_ptr);
587   return result;
588 }
589
590 /* Construct a filename from the NULL terminated list of parts.  Tilde
591    expansion is done for the first argument.  This function may return
592    NULL on error. */
593 char *
594 make_filename_try (const char *first_part, ... )
595 {
596   va_list arg_ptr;
597   char *result;
598
599   va_start (arg_ptr, first_part);
600   result = do_make_filename (0, first_part, arg_ptr);
601   va_end (arg_ptr);
602   return result;
603 }
604
605 /* Construct an absolute filename from the NULL terminated list of
606    parts.  Tilde expansion is done for the first argument.  This
607    function terminates the process on memory shortage. */
608 char *
609 make_absfilename (const char *first_part, ... )
610 {
611   va_list arg_ptr;
612   char *result;
613
614   va_start (arg_ptr, first_part);
615   result = do_make_filename (3, first_part, arg_ptr);
616   va_end (arg_ptr);
617   return result;
618 }
619
620 /* Construct an absolute filename from the NULL terminated list of
621    parts.  Tilde expansion is done for the first argument.  This
622    function may return NULL on error. */
623 char *
624 make_absfilename_try (const char *first_part, ... )
625 {
626   va_list arg_ptr;
627   char *result;
628
629   va_start (arg_ptr, first_part);
630   result = do_make_filename (2, first_part, arg_ptr);
631   va_end (arg_ptr);
632   return result;
633 }
634
635
636 \f
637 /* Compare whether the filenames are identical.  This is a
638    special version of strcmp() taking the semantics of filenames in
639    account.  Note that this function works only on the supplied names
640    without considering any context like the current directory.  See
641    also same_file_p(). */
642 int
643 compare_filenames (const char *a, const char *b)
644 {
645 #ifdef HAVE_DOSISH_SYSTEM
646   for ( ; *a && *b; a++, b++ )
647     {
648       if (*a != *b
649           && (toupper (*(const unsigned char*)a)
650               != toupper (*(const unsigned char*)b) )
651           && !((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/')))
652         break;
653     }
654   if ((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/'))
655     return 0;
656   else
657     return (toupper (*(const unsigned char*)a)
658             - toupper (*(const unsigned char*)b));
659 #else
660     return strcmp(a,b);
661 #endif
662 }
663
664
665 /* Convert a base-10 number in STRING into a 64 bit unsigned int
666  * value.  Leading white spaces are skipped but no error checking is
667  * done.  Thus it is similar to atoi(). */
668 uint64_t
669 string_to_u64 (const char *string)
670 {
671   uint64_t val = 0;
672
673   while (spacep (string))
674     string++;
675   for (; digitp (string); string++)
676     {
677       val *= 10;
678       val += *string - '0';
679     }
680   return val;
681 }
682
683
684 /* Convert 2 hex characters at S to a byte value.  Return this value
685    or -1 if there is an error. */
686 int
687 hextobyte (const char *s)
688 {
689   int c;
690
691   if ( *s >= '0' && *s <= '9' )
692     c = 16 * (*s - '0');
693   else if ( *s >= 'A' && *s <= 'F' )
694     c = 16 * (10 + *s - 'A');
695   else if ( *s >= 'a' && *s <= 'f' )
696     c = 16 * (10 + *s - 'a');
697   else
698     return -1;
699   s++;
700   if ( *s >= '0' && *s <= '9' )
701     c += *s - '0';
702   else if ( *s >= 'A' && *s <= 'F' )
703     c += 10 + *s - 'A';
704   else if ( *s >= 'a' && *s <= 'f' )
705     c += 10 + *s - 'a';
706   else
707     return -1;
708   return c;
709 }
710
711 /* Given a string containing an UTF-8 encoded text, return the number
712    of characters in this string.  It differs from strlen in that it
713    only counts complete UTF-8 characters.  SIZE is the maximum length
714    of the string in bytes.  If SIZE is -1, then a NUL character is
715    taken to be the end of the string.  Note, that this function does
716    not take combined characters into account.  */
717 size_t
718 utf8_charcount (const char *s, int len)
719 {
720   size_t n;
721
722   if (len == 0)
723     return 0;
724
725   for (n=0; *s; s++)
726     {
727       if ( (*s&0xc0) != 0x80 ) /* Exclude continuation bytes: 10xxxxxx */
728         n++;
729
730       if (len != -1)
731         {
732           len --;
733           if (len == 0)
734             break;
735         }
736     }
737
738   return n;
739 }
740
741
742 /****************************************************
743  **********  W32 specific functions  ****************
744  ****************************************************/
745
746 #ifdef HAVE_W32_SYSTEM
747 const char *
748 w32_strerror (int ec)
749 {
750   static char strerr[256];
751
752   if (ec == -1)
753     ec = (int)GetLastError ();
754 #ifdef HAVE_W32CE_SYSTEM
755   /* There is only a wchar_t FormatMessage.  It does not make much
756      sense to play the conversion game; we print only the code.  */
757   snprintf (strerr, sizeof strerr, "ec=%d", (int)GetLastError ());
758 #else
759   FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, ec,
760                  MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
761                  strerr, DIM (strerr)-1, NULL);
762 #endif
763   return strerr;
764 }
765 #endif /*HAVE_W32_SYSTEM*/
766
767
768 /****************************************************
769  ******** Locale insensitive ctype functions ********
770  ****************************************************/
771 /* FIXME: replace them by a table lookup and macros */
772 int
773 ascii_isupper (int c)
774 {
775     return c >= 'A' && c <= 'Z';
776 }
777
778 int
779 ascii_islower (int c)
780 {
781     return c >= 'a' && c <= 'z';
782 }
783
784 int
785 ascii_toupper (int c)
786 {
787     if (c >= 'a' && c <= 'z')
788         c &= ~0x20;
789     return c;
790 }
791
792 int
793 ascii_tolower (int c)
794 {
795     if (c >= 'A' && c <= 'Z')
796         c |= 0x20;
797     return c;
798 }
799
800 /* Lowercase all ASCII characters in S.  */
801 char *
802 ascii_strlwr (char *s)
803 {
804   char *p = s;
805
806   for (p=s; *p; p++ )
807     if (isascii (*p) && *p >= 'A' && *p <= 'Z')
808       *p |= 0x20;
809
810   return s;
811 }
812
813 /* Upcase all ASCII characters in S.  */
814 char *
815 ascii_strupr (char *s)
816 {
817   char *p = s;
818
819   for (p=s; *p; p++ )
820     if (isascii (*p) && *p >= 'a' && *p <= 'z')
821       *p &= ~0x20;
822
823   return s;
824 }
825
826 int
827 ascii_strcasecmp( const char *a, const char *b )
828 {
829     if (a == b)
830         return 0;
831
832     for (; *a && *b; a++, b++) {
833         if (*a != *b && ascii_toupper(*a) != ascii_toupper(*b))
834             break;
835     }
836     return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
837 }
838
839 int
840 ascii_strncasecmp (const char *a, const char *b, size_t n)
841 {
842   const unsigned char *p1 = (const unsigned char *)a;
843   const unsigned char *p2 = (const unsigned char *)b;
844   unsigned char c1, c2;
845
846   if (p1 == p2 || !n )
847     return 0;
848
849   do
850     {
851       c1 = ascii_tolower (*p1);
852       c2 = ascii_tolower (*p2);
853
854       if ( !--n || c1 == '\0')
855         break;
856
857       ++p1;
858       ++p2;
859     }
860   while (c1 == c2);
861
862   return c1 - c2;
863 }
864
865
866 int
867 ascii_memcasecmp (const void *a_arg, const void *b_arg, size_t n )
868 {
869   const char *a = a_arg;
870   const char *b = b_arg;
871
872   if (a == b)
873     return 0;
874   for ( ; n; n--, a++, b++ )
875     {
876       if( *a != *b  && ascii_toupper (*a) != ascii_toupper (*b) )
877         return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
878     }
879   return 0;
880 }
881
882 int
883 ascii_strcmp( const char *a, const char *b )
884 {
885     if (a == b)
886         return 0;
887
888     for (; *a && *b; a++, b++) {
889         if (*a != *b )
890             break;
891     }
892     return *a == *b? 0 : (*(signed char *)a - *(signed char *)b);
893 }
894
895
896 void *
897 ascii_memcasemem (const void *haystack, size_t nhaystack,
898                   const void *needle, size_t nneedle)
899 {
900
901   if (!nneedle)
902     return (void*)haystack; /* finding an empty needle is really easy */
903   if (nneedle <= nhaystack)
904     {
905       const char *a = haystack;
906       const char *b = a + nhaystack - nneedle;
907
908       for (; a <= b; a++)
909         {
910           if ( !ascii_memcasecmp (a, needle, nneedle) )
911             return (void *)a;
912         }
913     }
914   return NULL;
915 }
916
917 /*********************************************
918  ********** missing string functions *********
919  *********************************************/
920
921 #ifndef HAVE_STPCPY
922 char *
923 stpcpy(char *a,const char *b)
924 {
925     while( *b )
926         *a++ = *b++;
927     *a = 0;
928
929     return (char*)a;
930 }
931 #endif
932
933 #ifndef HAVE_STRPBRK
934 /* Find the first occurrence in S of any character in ACCEPT.
935    Code taken from glibc-2.6/string/strpbrk.c (LGPLv2.1+) and modified. */
936 char *
937 strpbrk (const char *s, const char *accept)
938 {
939   while (*s != '\0')
940     {
941       const char *a = accept;
942       while (*a != '\0')
943         if (*a++ == *s)
944           return (char *) s;
945       ++s;
946     }
947
948   return NULL;
949 }
950 #endif /*!HAVE_STRPBRK*/
951
952
953 #ifndef HAVE_STRSEP
954 /* Code taken from glibc-2.2.1/sysdeps/generic/strsep.c. */
955 char *
956 strsep (char **stringp, const char *delim)
957 {
958   char *begin, *end;
959
960   begin = *stringp;
961   if (begin == NULL)
962     return NULL;
963
964   /* A frequent case is when the delimiter string contains only one
965      character.  Here we don't need to call the expensive 'strpbrk'
966      function and instead work using 'strchr'.  */
967   if (delim[0] == '\0' || delim[1] == '\0')
968     {
969       char ch = delim[0];
970
971       if (ch == '\0')
972         end = NULL;
973       else
974         {
975           if (*begin == ch)
976             end = begin;
977           else if (*begin == '\0')
978             end = NULL;
979           else
980             end = strchr (begin + 1, ch);
981         }
982     }
983   else
984     /* Find the end of the token.  */
985     end = strpbrk (begin, delim);
986
987   if (end)
988     {
989       /* Terminate the token and set *STRINGP past NUL character.  */
990       *end++ = '\0';
991       *stringp = end;
992     }
993   else
994     /* No more delimiters; this is the last token.  */
995     *stringp = NULL;
996
997   return begin;
998 }
999 #endif /*HAVE_STRSEP*/
1000
1001
1002 #ifndef HAVE_STRLWR
1003 char *
1004 strlwr(char *s)
1005 {
1006     char *p;
1007     for(p=s; *p; p++ )
1008         *p = tolower(*p);
1009     return s;
1010 }
1011 #endif
1012
1013
1014 #ifndef HAVE_STRCASECMP
1015 int
1016 strcasecmp( const char *a, const char *b )
1017 {
1018     for( ; *a && *b; a++, b++ ) {
1019         if( *a != *b && toupper(*a) != toupper(*b) )
1020             break;
1021     }
1022     return *(const byte*)a - *(const byte*)b;
1023 }
1024 #endif
1025
1026
1027 /****************
1028  * mingw32/cpd has a memicmp()
1029  */
1030 #ifndef HAVE_MEMICMP
1031 int
1032 memicmp( const char *a, const char *b, size_t n )
1033 {
1034     for( ; n; n--, a++, b++ )
1035         if( *a != *b  && toupper(*(const byte*)a) != toupper(*(const byte*)b) )
1036             return *(const byte *)a - *(const byte*)b;
1037     return 0;
1038 }
1039 #endif
1040
1041
1042 #ifndef HAVE_MEMRCHR
1043 void *
1044 memrchr (const void *buffer, int c, size_t n)
1045 {
1046   const unsigned char *p = buffer;
1047
1048   for (p += n; n ; n--)
1049     if (*--p == c)
1050       return (void *)p;
1051   return NULL;
1052 }
1053 #endif /*HAVE_MEMRCHR*/
1054
1055 \f
1056 /* Percent-escape the string STR by replacing colons with '%3a'.  If
1057    EXTRA is not NULL all characters in EXTRA are also escaped.  */
1058 static char *
1059 do_percent_escape (const char *str, const char *extra, int die)
1060 {
1061   int i, j;
1062   char *ptr;
1063
1064   if (!str)
1065     return NULL;
1066
1067   for (i=j=0; str[i]; i++)
1068     if (str[i] == ':' || str[i] == '%' || str[i] == '\n'
1069         || (extra && strchr (extra, str[i])))
1070       j++;
1071   if (die)
1072     ptr = xmalloc (i + 2 * j + 1);
1073   else
1074     {
1075       ptr = xtrymalloc (i + 2 * j + 1);
1076       if (!ptr)
1077         return NULL;
1078     }
1079   i = 0;
1080   while (*str)
1081     {
1082       if (*str == ':')
1083         {
1084           ptr[i++] = '%';
1085           ptr[i++] = '3';
1086           ptr[i++] = 'a';
1087         }
1088       else if (*str == '%')
1089         {
1090           ptr[i++] = '%';
1091           ptr[i++] = '2';
1092           ptr[i++] = '5';
1093         }
1094       else if (*str == '\n')
1095         {
1096           /* The newline is problematic in a line-based format.  */
1097           ptr[i++] = '%';
1098           ptr[i++] = '0';
1099           ptr[i++] = 'a';
1100         }
1101       else if (extra && strchr (extra, *str))
1102         {
1103           ptr[i++] = '%';
1104           ptr[i++] = tohex_lower ((*str>>4)&15);
1105           ptr[i++] = tohex_lower (*str&15);
1106         }
1107       else
1108         ptr[i++] = *str;
1109       str++;
1110     }
1111   ptr[i] = '\0';
1112
1113   return ptr;
1114 }
1115
1116 /* Percent-escape the string STR by replacing colons with '%3a'.  If
1117    EXTRA is not NULL all characters in EXTRA are also escaped.  This
1118    function terminates the process on memory shortage.  */
1119 char *
1120 percent_escape (const char *str, const char *extra)
1121 {
1122   return do_percent_escape (str, extra, 1);
1123 }
1124
1125 /* Same as percent_escape but return NULL instead of exiting on memory
1126    error. */
1127 char *
1128 try_percent_escape (const char *str, const char *extra)
1129 {
1130   return do_percent_escape (str, extra, 0);
1131 }
1132
1133
1134
1135 static char *
1136 do_strconcat (const char *s1, va_list arg_ptr)
1137 {
1138   const char *argv[48];
1139   size_t argc;
1140   size_t needed;
1141   char *buffer, *p;
1142
1143   argc = 0;
1144   argv[argc++] = s1;
1145   needed = strlen (s1);
1146   while (((argv[argc] = va_arg (arg_ptr, const char *))))
1147     {
1148       needed += strlen (argv[argc]);
1149       if (argc >= DIM (argv)-1)
1150         {
1151           gpg_err_set_errno (EINVAL);
1152           return NULL;
1153         }
1154       argc++;
1155     }
1156   needed++;
1157   buffer = xtrymalloc (needed);
1158   if (buffer)
1159     {
1160       for (p = buffer, argc=0; argv[argc]; argc++)
1161         p = stpcpy (p, argv[argc]);
1162     }
1163   return buffer;
1164 }
1165
1166
1167 /* Concatenate the string S1 with all the following strings up to a
1168    NULL.  Returns a malloced buffer with the new string or NULL on a
1169    malloc error or if too many arguments are given.  */
1170 char *
1171 strconcat (const char *s1, ...)
1172 {
1173   va_list arg_ptr;
1174   char *result;
1175
1176   if (!s1)
1177     result = xtrystrdup ("");
1178   else
1179     {
1180       va_start (arg_ptr, s1);
1181       result = do_strconcat (s1, arg_ptr);
1182       va_end (arg_ptr);
1183     }
1184   return result;
1185 }
1186
1187 /* Same as strconcat but terminate the process with an error message
1188    if something goes wrong.  */
1189 char *
1190 xstrconcat (const char *s1, ...)
1191 {
1192   va_list arg_ptr;
1193   char *result;
1194
1195   if (!s1)
1196     result = xstrdup ("");
1197   else
1198     {
1199       va_start (arg_ptr, s1);
1200       result = do_strconcat (s1, arg_ptr);
1201       va_end (arg_ptr);
1202     }
1203   if (!result)
1204     {
1205       if (errno == EINVAL)
1206         fputs ("\nfatal: too many args for xstrconcat\n", stderr);
1207       else
1208         fputs ("\nfatal: out of memory\n", stderr);
1209       exit (2);
1210     }
1211   return result;
1212 }
1213
1214 /* Split a string into fields at DELIM.  REPLACEMENT is the character
1215    to replace the delimiter with (normally: '\0' so that each field is
1216    NUL terminated).  The caller is responsible for freeing the result.
1217    Note: this function modifies STRING!  If you need the original
1218    value, then you should pass a copy to this function.
1219
1220    If malloc fails, this function returns NULL.  */
1221 char **
1222 strsplit (char *string, char delim, char replacement, int *count)
1223 {
1224   int fields = 1;
1225   char *t;
1226   char **result;
1227
1228   /* First, count the number of fields.  */
1229   for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
1230     fields ++;
1231
1232   result = xtrycalloc ((fields + 1), sizeof (*result));
1233   if (! result)
1234     return NULL;
1235
1236   result[0] = string;
1237   fields = 1;
1238   for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
1239     {
1240       result[fields ++] = t + 1;
1241       *t = replacement;
1242     }
1243
1244   if (count)
1245     *count = fields;
1246
1247   return result;
1248 }
1249
1250
1251 /* Tokenize STRING using the set of delimiters in DELIM.  Leading
1252  * spaces and tabs are removed from all tokens.  The caller must xfree
1253  * the result.
1254  *
1255  * Returns: A malloced and NULL delimited array with the tokens.  On
1256  *          memory error NULL is returned and ERRNO is set.
1257  */
1258 char **
1259 strtokenize (const char *string, const char *delim)
1260 {
1261   const char *s;
1262   size_t fields;
1263   size_t bytes, n;
1264   char *buffer;
1265   char *p, *px, *pend;
1266   char **result;
1267
1268   /* Count the number of fields.  */
1269   for (fields = 1, s = strpbrk (string, delim); s; s = strpbrk (s + 1, delim))
1270     fields++;
1271   fields++; /* Add one for the terminating NULL.  */
1272
1273   /* Allocate an array for all fields, a terminating NULL, and space
1274      for a copy of the string.  */
1275   bytes = fields * sizeof *result;
1276   if (bytes / sizeof *result != fields)
1277     {
1278       gpg_err_set_errno (ENOMEM);
1279       return NULL;
1280     }
1281   n = strlen (string) + 1;
1282   bytes += n;
1283   if (bytes < n)
1284     {
1285       gpg_err_set_errno (ENOMEM);
1286       return NULL;
1287     }
1288   result = xtrymalloc (bytes);
1289   if (!result)
1290     return NULL;
1291   buffer = (char*)(result + fields);
1292
1293   /* Copy and parse the string.  */
1294   strcpy (buffer, string);
1295   for (n = 0, p = buffer; (pend = strpbrk (p, delim)); p = pend + 1)
1296     {
1297       *pend = 0;
1298       while (spacep (p))
1299         p++;
1300       for (px = pend - 1; px >= p && spacep (px); px--)
1301         *px = 0;
1302       result[n++] = p;
1303     }
1304   while (spacep (p))
1305     p++;
1306   for (px = p + strlen (p) - 1; px >= p && spacep (px); px--)
1307     *px = 0;
1308   result[n++] = p;
1309   result[n] = NULL;
1310
1311   assert ((char*)(result + n + 1) == buffer);
1312
1313   return result;
1314 }
1315
1316
1317 /* Split a string into space delimited fields and remove leading and
1318  * trailing spaces from each field.  A pointer to each field is stored
1319  * in ARRAY.  Stop splitting at ARRAYSIZE fields.  The function
1320  * modifies STRING.  The number of parsed fields is returned.
1321  * Example:
1322  *
1323  *   char *fields[2];
1324  *   if (split_fields (string, fields, DIM (fields)) < 2)
1325  *     return  // Not enough args.
1326  *   foo (fields[0]);
1327  *   foo (fields[1]);
1328  */
1329 int
1330 split_fields (char *string, char **array, int arraysize)
1331 {
1332   int n = 0;
1333   char *p, *pend;
1334
1335   for (p = string; *p == ' '; p++)
1336     ;
1337   do
1338     {
1339       if (n == arraysize)
1340         break;
1341       array[n++] = p;
1342       pend = strchr (p, ' ');
1343       if (!pend)
1344         break;
1345       *pend++ = 0;
1346       for (p = pend; *p == ' '; p++)
1347         ;
1348     }
1349   while (*p);
1350
1351   return n;
1352 }
1353
1354
1355 /* Split a string into colon delimited fields A pointer to each field
1356  * is stored in ARRAY.  Stop splitting at ARRAYSIZE fields.  The
1357  * function modifies STRING.  The number of parsed fields is returned.
1358  * Note that leading and trailing spaces are not removed from the fields.
1359  * Example:
1360  *
1361  *   char *fields[2];
1362  *   if (split_fields (string, fields, DIM (fields)) < 2)
1363  *     return  // Not enough args.
1364  *   foo (fields[0]);
1365  *   foo (fields[1]);
1366  */
1367 int
1368 split_fields_colon (char *string, char **array, int arraysize)
1369 {
1370   int n = 0;
1371   char *p, *pend;
1372
1373   p = string;
1374   do
1375     {
1376       if (n == arraysize)
1377         break;
1378       array[n++] = p;
1379       pend = strchr (p, ':');
1380       if (!pend)
1381         break;
1382       *pend++ = 0;
1383       p = pend;
1384     }
1385   while (*p);
1386
1387   return n;
1388 }
1389
1390
1391 \f
1392 /* Version number parsing.  */
1393
1394 /* This function parses the first portion of the version number S and
1395    stores it in *NUMBER.  On success, this function returns a pointer
1396    into S starting with the first character, which is not part of the
1397    initial number portion; on failure, NULL is returned.  */
1398 static const char*
1399 parse_version_number (const char *s, int *number)
1400 {
1401   int val = 0;
1402
1403   if (*s == '0' && digitp (s+1))
1404     return NULL;  /* Leading zeros are not allowed.  */
1405   for (; digitp (s); s++)
1406     {
1407       val *= 10;
1408       val += *s - '0';
1409     }
1410   *number = val;
1411   return val < 0 ? NULL : s;
1412 }
1413
1414
1415 /* This function breaks up the complete string-representation of the
1416    version number S, which is of the following struture: <major
1417    number>.<minor number>[.<micro number>]<patch level>.  The major,
1418    minor, and micro number components will be stored in *MAJOR, *MINOR
1419    and *MICRO.  If MICRO is not given 0 is used instead.
1420
1421    On success, the last component, the patch level, will be returned;
1422    in failure, NULL will be returned.  */
1423 static const char *
1424 parse_version_string (const char *s, int *major, int *minor, int *micro)
1425 {
1426   s = parse_version_number (s, major);
1427   if (!s || *s != '.')
1428     return NULL;
1429   s++;
1430   s = parse_version_number (s, minor);
1431   if (!s)
1432     return NULL;
1433   if (*s == '.')
1434     {
1435       s++;
1436       s = parse_version_number (s, micro);
1437       if (!s)
1438         return NULL;
1439     }
1440   else
1441     *micro = 0;
1442   return s;  /* Patchlevel.  */
1443 }
1444
1445
1446 /* Compare the version string MY_VERSION to the version string
1447  * REQ_VERSION.  Returns -1, 0, or 1 if MY_VERSION is found,
1448  * respectively, to be less than, to match, or be greater than
1449  * REQ_VERSION.  This function works for three and two part version
1450  * strings; for a two part version string the micro part is assumed to
1451  * be 0.  Patch levels are compared as strings.  If a version number
1452  * is invalid INT_MIN is returned.  If REQ_VERSION is given as NULL
1453  * the function returns 0 if MY_VERSION is parsable version string. */
1454 int
1455 compare_version_strings (const char *my_version, const char *req_version)
1456 {
1457   int my_major, my_minor, my_micro;
1458   int rq_major, rq_minor, rq_micro;
1459   const char *my_patch, *rq_patch;
1460   int result;
1461
1462   if (!my_version)
1463     return INT_MIN;
1464
1465   my_patch = parse_version_string (my_version, &my_major, &my_minor, &my_micro);
1466   if (!my_patch)
1467     return INT_MIN;
1468   if (!req_version)
1469     return 0; /* MY_VERSION can be parsed.  */
1470   rq_patch = parse_version_string (req_version, &rq_major, &rq_minor,&rq_micro);
1471   if (!rq_patch)
1472     return INT_MIN;
1473
1474   if (my_major == rq_major)
1475     {
1476       if (my_minor == rq_minor)
1477         {
1478           if (my_micro == rq_micro)
1479             result = strcmp (my_patch, rq_patch);
1480           else
1481             result = my_micro - rq_micro;
1482         }
1483       else
1484         result = my_minor - rq_minor;
1485     }
1486   else
1487     result = my_major - rq_major;
1488
1489   return !result? 0 : result < 0 ? -1 : 1;
1490 }
1491
1492
1493 \f
1494 /* Format a string so that it fits within about TARGET_COLS columns.
1495  * TEXT_IN is copied to a new buffer, which is returned.  Normally,
1496  * target_cols will be 72 and max_cols is 80.  On error NULL is
1497  * returned and ERRNO is set. */
1498 char *
1499 format_text (const char *text_in, int target_cols, int max_cols)
1500 {
1501   /* const int do_debug = 0; */
1502
1503   /* The character under consideration.  */
1504   char *p;
1505   /* The start of the current line.  */
1506   char *line;
1507   /* The last space that we saw.  */
1508   char *last_space = NULL;
1509   int last_space_cols = 0;
1510   int copied_last_space = 0;
1511   char *text;
1512
1513   text = xtrystrdup (text_in);
1514   if (!text)
1515     return NULL;
1516
1517   p = line = text;
1518   while (1)
1519     {
1520       /* The number of columns including any trailing space.  */
1521       int cols;
1522
1523       p = p + strcspn (p, "\n ");
1524       if (! p)
1525         /* P now points to the NUL character.  */
1526         p = &text[strlen (text)];
1527
1528       if (*p == '\n')
1529         /* Pass through any newlines.  */
1530         {
1531           p ++;
1532           line = p;
1533           last_space = NULL;
1534           last_space_cols = 0;
1535           copied_last_space = 1;
1536           continue;
1537         }
1538
1539       /* Have a space or a NUL.  Note: we don't count the trailing
1540          space.  */
1541       cols = utf8_charcount (line, (uintptr_t) p - (uintptr_t) line);
1542       if (cols < target_cols)
1543         {
1544           if (! *p)
1545             /* Nothing left to break.  */
1546             break;
1547
1548           last_space = p;
1549           last_space_cols = cols;
1550           p ++;
1551           /* Skip any immediately following spaces.  If we break:
1552              "... foo bar ..." between "foo" and "bar" then we want:
1553              "... foo\nbar ...", which means that the left space has
1554              to be the first space after foo, not the last space
1555              before bar.  */
1556           while (*p == ' ')
1557             p ++;
1558         }
1559       else
1560         {
1561           int cols_with_left_space;
1562           int cols_with_right_space;
1563           int left_penalty;
1564           int right_penalty;
1565
1566           cols_with_left_space = last_space_cols;
1567           cols_with_right_space = cols;
1568
1569           /* if (do_debug) */
1570           /*   log_debug ("Breaking: '%.*s'\n", */
1571           /*              (int) ((uintptr_t) p - (uintptr_t) line), line); */
1572
1573           /* The number of columns away from TARGET_COLS.  We prefer
1574              to underflow than to overflow.  */
1575           left_penalty = target_cols - cols_with_left_space;
1576           right_penalty = 2 * (cols_with_right_space - target_cols);
1577
1578           if (cols_with_right_space > max_cols)
1579             /* Add a large penalty for each column that exceeds
1580                max_cols.  */
1581             right_penalty += 4 * (cols_with_right_space - max_cols);
1582
1583           /* if (do_debug) */
1584           /*   log_debug ("Left space => %d cols (penalty: %d); " */
1585           /*              "right space => %d cols (penalty: %d)\n", */
1586           /*              cols_with_left_space, left_penalty, */
1587           /*              cols_with_right_space, right_penalty); */
1588           if (last_space_cols && left_penalty <= right_penalty)
1589             {
1590               /* Prefer the left space.  */
1591               /* if (do_debug) */
1592               /*   log_debug ("Breaking at left space.\n"); */
1593               p = last_space;
1594             }
1595           else
1596             {
1597               /* if (do_debug) */
1598               /*   log_debug ("Breaking at right space.\n"); */
1599             }
1600
1601           if (! *p)
1602             break;
1603
1604           *p = '\n';
1605           p ++;
1606           if (*p == ' ')
1607             {
1608               int spaces;
1609               for (spaces = 1; p[spaces] == ' '; spaces ++)
1610                 ;
1611               memmove (p, &p[spaces], strlen (&p[spaces]) + 1);
1612             }
1613           line = p;
1614           last_space = NULL;
1615           last_space_cols = 0;
1616           copied_last_space = 0;
1617         }
1618     }
1619
1620   /* Chop off any trailing space.  */
1621   trim_trailing_chars (text, strlen (text), " ");
1622   /* If we inserted the trailing newline, then remove it.  */
1623   if (! copied_last_space && *text && text[strlen (text) - 1] == '\n')
1624     text[strlen (text) - 1] = '\0';
1625
1626   return text;
1627 }