glitch in the license text detected by hyazinthe, thank you!
[oweals/gnunet.git] / src / util / strings.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2005-2017 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      Affero General Public License for more details.
14 */
15 /**
16  * @file util/strings.c
17  * @brief string functions
18  * @author Nils Durner
19  * @author Christian Grothoff
20  */
21
22 #include "platform.h"
23 #if HAVE_ICONV
24 #include <iconv.h>
25 #endif
26 #include "gnunet_crypto_lib.h"
27 #include "gnunet_strings_lib.h"
28 #include <unicase.h>
29 #include <unistr.h>
30 #include <uniconv.h>
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "util-strings", __VA_ARGS__)
33
34 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-strings", syscall)
35
36
37 /**
38  * Fill a buffer of the given size with
39  * count 0-terminated strings (given as varargs).
40  * If "buffer" is NULL, only compute the amount of
41  * space required (sum of "strlen(arg)+1").
42  *
43  * Unlike using "snprintf" with "%s", this function
44  * will add 0-terminators after each string.  The
45  * #GNUNET_string_buffer_tokenize() function can be
46  * used to parse the buffer back into individual
47  * strings.
48  *
49  * @param buffer the buffer to fill with strings, can
50  *               be NULL in which case only the necessary
51  *               amount of space will be calculated
52  * @param size number of bytes available in buffer
53  * @param count number of strings that follow
54  * @param ... count 0-terminated strings to copy to buffer
55  * @return number of bytes written to the buffer
56  *         (or number of bytes that would have been written)
57  */
58 size_t
59 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
60 {
61   size_t needed;
62   size_t slen;
63   const char *s;
64   va_list ap;
65
66   needed = 0;
67   va_start (ap, count);
68   while (count > 0)
69   {
70     s = va_arg (ap, const char *);
71
72     slen = strlen (s) + 1;
73     if (buffer != NULL)
74     {
75       GNUNET_assert (needed + slen <= size);
76       GNUNET_memcpy (&buffer[needed], s, slen);
77     }
78     needed += slen;
79     count--;
80   }
81   va_end (ap);
82   return needed;
83 }
84
85
86 /**
87  * Convert a peer path to a human-readable string.
88  *
89  * @param pids array of PIDs to convert to a string
90  * @param num_pids length of the @a pids array
91  * @return string representing the array of @a pids
92  */
93 char *
94 GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids,
95                      unsigned int num_pids)
96 {
97   char *buf;
98   size_t off;
99   size_t plen = num_pids * 5 + 1;
100
101   off = 0;
102   buf = GNUNET_malloc (plen);
103   for (unsigned int i = 0;
104        i < num_pids;
105        i++)
106   {
107     off += GNUNET_snprintf (&buf[off],
108                             plen - off,
109                             "%s%s",
110                             GNUNET_i2s (&pids[i]),
111                             (i == num_pids -1) ? "" : "-");
112   }
113   return buf;
114 }
115
116
117 /**
118  * Given a buffer of a given size, find "count"
119  * 0-terminated strings in the buffer and assign
120  * the count (varargs) of type "const char**" to the
121  * locations of the respective strings in the
122  * buffer.
123  *
124  * @param buffer the buffer to parse
125  * @param size size of the buffer
126  * @param count number of strings to locate
127  * @return offset of the character after the last 0-termination
128  *         in the buffer, or 0 on error.
129  */
130 unsigned int
131 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
132                                 unsigned int count, ...)
133 {
134   unsigned int start;
135   unsigned int needed;
136   const char **r;
137   va_list ap;
138
139   needed = 0;
140   va_start (ap, count);
141   while (count > 0)
142   {
143     r = va_arg (ap, const char **);
144
145     start = needed;
146     while ((needed < size) && (buffer[needed] != '\0'))
147       needed++;
148     if (needed == size)
149     {
150       va_end (ap);
151       return 0;                 /* error */
152     }
153     *r = &buffer[start];
154     needed++;                   /* skip 0-termination */
155     count--;
156   }
157   va_end (ap);
158   return needed;
159 }
160
161
162 /**
163  * Convert a given filesize into a fancy human-readable format.
164  *
165  * @param size number of bytes
166  * @return fancy representation of the size (possibly rounded) for humans
167  */
168 char *
169 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
170 {
171   const char *unit = _( /* size unit */ "b");
172   char *ret;
173
174   if (size > 5 * 1024)
175   {
176     size = size / 1024;
177     unit = "KiB";
178     if (size > 5 * 1024)
179     {
180       size = size / 1024;
181       unit = "MiB";
182       if (size > 5 * 1024)
183       {
184         size = size / 1024;
185         unit = "GiB";
186         if (size > 5 * 1024)
187         {
188           size = size / 1024;
189           unit = "TiB";
190         }
191       }
192     }
193   }
194   ret = GNUNET_malloc (32);
195   GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
196   return ret;
197 }
198
199
200 /**
201  * Unit conversion table entry for 'convert_with_table'.
202  */
203 struct ConversionTable
204 {
205   /**
206    * Name of the unit (or NULL for end of table).
207    */
208   const char *name;
209
210   /**
211    * Factor to apply for this unit.
212    */
213   unsigned long long value;
214 };
215
216
217 /**
218  * Convert a string of the form "4 X 5 Y" into a numeric value
219  * by interpreting "X" and "Y" as units and then multiplying
220  * the numbers with the values associated with the respective
221  * unit from the conversion table.
222  *
223  * @param input input string to parse
224  * @param table table with the conversion of unit names to numbers
225  * @param output where to store the result
226  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
227  */
228 static int
229 convert_with_table (const char *input,
230                     const struct ConversionTable *table,
231                     unsigned long long *output)
232 {
233   unsigned long long ret;
234   char *in;
235   const char *tok;
236   unsigned long long last;
237   unsigned int i;
238
239   ret = 0;
240   last = 0;
241   in = GNUNET_strdup (input);
242   for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
243   {
244     do
245     {
246       i = 0;
247       while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
248         i++;
249       if (table[i].name != NULL)
250       {
251         last *= table[i].value;
252         break; /* next tok */
253       }
254       else
255       {
256         char *endptr;
257         ret += last;
258         errno = 0;
259         last = strtoull (tok, &endptr, 10);
260         if ((0 != errno) || (endptr == tok))
261         {
262           GNUNET_free (in);
263           return GNUNET_SYSERR;   /* expected number */
264         }
265         if ('\0' == endptr[0])
266           break; /* next tok */
267         else
268           tok = endptr; /* and re-check (handles times like "10s") */
269       }
270     } while (GNUNET_YES);
271   }
272   ret += last;
273   *output = ret;
274   GNUNET_free (in);
275   return GNUNET_OK;
276 }
277
278
279 /**
280  * Convert a given fancy human-readable size to bytes.
281  *
282  * @param fancy_size human readable string (i.e. 1 MB)
283  * @param size set to the size in bytes
284  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
285  */
286 int
287 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
288                                     unsigned long long *size)
289 {
290   static const struct ConversionTable table[] =
291   {
292     { "B", 1},
293     { "KiB", 1024},
294     { "kB", 1000},
295     { "MiB", 1024 * 1024},
296     { "MB", 1000 * 1000},
297     { "GiB", 1024 * 1024 * 1024},
298     { "GB", 1000 * 1000 * 1000},
299     { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
300     { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
301     { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
302     { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
303     { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
304     { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
305     { NULL, 0}
306   };
307
308   return convert_with_table (fancy_size,
309                              table,
310                              size);
311 }
312
313
314 /**
315  * Convert a given fancy human-readable time to our internal
316  * representation.
317  *
318  * @param fancy_time human readable string (i.e. 1 minute)
319  * @param rtime set to the relative time
320  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
321  */
322 int
323 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
324                                        struct GNUNET_TIME_Relative *rtime)
325 {
326   static const struct ConversionTable table[] =
327   {
328     { "us", 1},
329     { "ms", 1000 },
330     { "s", 1000 * 1000LL },
331     { "\"", 1000  * 1000LL },
332     { "m", 60 * 1000  * 1000LL},
333     { "min", 60 * 1000  * 1000LL},
334     { "minute", 60 * 1000  * 1000LL},
335     { "minutes", 60 * 1000  * 1000LL},
336     { "'", 60 * 1000  * 1000LL},
337     { "h", 60 * 60 * 1000  * 1000LL},
338     { "hour", 60 * 60 * 1000  * 1000LL},
339     { "hours", 60 * 60 * 1000  * 1000LL},
340     { "d", 24 * 60 * 60 * 1000LL * 1000LL},
341     { "day", 24 * 60 * 60 * 1000LL * 1000LL},
342     { "days", 24 * 60 * 60 * 1000LL * 1000LL},
343     { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
344     { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
345     { "year", 31536000000000LL /* year */ },
346     { "years", 31536000000000LL /* year */ },
347     { "a", 31536000000000LL /* year */ },
348     { NULL, 0}
349   };
350   int ret;
351   unsigned long long val;
352
353   if (0 == strcasecmp ("forever", fancy_time))
354   {
355     *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
356     return GNUNET_OK;
357   }
358   ret = convert_with_table (fancy_time,
359                             table,
360                             &val);
361   rtime->rel_value_us = (uint64_t) val;
362   return ret;
363 }
364
365
366 /**
367  * Convert a given fancy human-readable time to our internal
368  * representation. The human-readable time is expected to be
369  * in local time, whereas the returned value will be in UTC.
370  *
371  * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
372  * @param atime set to the absolute time
373  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
374  */
375 int
376 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
377                                        struct GNUNET_TIME_Absolute *atime)
378 {
379   struct tm tv;
380   time_t t;
381
382   if (0 == strcasecmp ("end of time",
383                        fancy_time))
384   {
385     *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
386     return GNUNET_OK;
387   }
388   memset (&tv, 0, sizeof (tv));
389   if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
390        (NULL == strptime (fancy_time, "%c", &tv)) &&
391        (NULL == strptime (fancy_time, "%Ec", &tv)) &&
392        (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
393        (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
394        (NULL == strptime (fancy_time, "%x", &tv)) &&
395        (NULL == strptime (fancy_time, "%Ex", &tv)) &&
396        (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
397        (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
398        (NULL == strptime (fancy_time, "%Y", &tv)) )
399     return GNUNET_SYSERR;
400   t = mktime (&tv);
401   atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
402   return GNUNET_OK;
403 }
404
405
406 /**
407  * Convert the len characters long character sequence
408  * given in input that is in the given input charset
409  * to a string in given output charset.
410  *
411  * @param input input string
412  * @param len number of bytes in @a input
413  * @param input_charset character set used for @a input
414  * @param output_charset desired character set for the return value
415  * @return the converted string (0-terminated),
416  *  if conversion fails, a copy of the orignal
417  *  string is returned.
418  */
419 char *
420 GNUNET_STRINGS_conv (const char *input,
421                      size_t len,
422                      const char *input_charset,
423                      const char *output_charset)
424 {
425   char *ret;
426   uint8_t *u8_string;
427   char *encoded_string;
428   size_t u8_string_length;
429   size_t encoded_string_length;
430
431   u8_string = u8_conv_from_encoding (input_charset,
432                                      iconveh_error,
433                                      input, len,
434                                      NULL, NULL,
435                                      &u8_string_length);
436   if (NULL == u8_string)
437   {
438     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
439     goto fail;
440   }
441   if (0 == strcmp (output_charset, "UTF-8"))
442   {
443     ret = GNUNET_malloc (u8_string_length + 1);
444     GNUNET_memcpy (ret, u8_string, u8_string_length);
445     ret[u8_string_length] = '\0';
446     free (u8_string);
447     return ret;
448   }
449   encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
450                                         u8_string, u8_string_length,
451                                         NULL, NULL,
452                                         &encoded_string_length);
453   free (u8_string);
454   if (NULL == encoded_string)
455   {
456     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
457     goto fail;
458   }
459   ret = GNUNET_malloc (encoded_string_length + 1);
460   GNUNET_memcpy (ret, encoded_string, encoded_string_length);
461   ret[encoded_string_length] = '\0';
462   free (encoded_string);
463   return ret;
464  fail:
465   LOG (GNUNET_ERROR_TYPE_WARNING,
466        _("Character sets requested were `%s'->`%s'\n"),
467        "UTF-8", output_charset);
468   ret = GNUNET_malloc (len + 1);
469   GNUNET_memcpy (ret, input, len);
470   ret[len] = '\0';
471   return ret;
472 }
473
474
475 /**
476  * Convert the len characters long character sequence
477  * given in input that is in the given charset
478  * to UTF-8.
479  *
480  * @param input the input string (not necessarily 0-terminated)
481  * @param len the number of bytes in the @a input
482  * @param charset character set to convert from
483  * @return the converted string (0-terminated),
484  *  if conversion fails, a copy of the orignal
485  *  string is returned.
486  */
487 char *
488 GNUNET_STRINGS_to_utf8 (const char *input,
489                         size_t len,
490                         const char *charset)
491 {
492   return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
493 }
494
495
496 /**
497  * Convert the len bytes-long UTF-8 string
498  * given in input to the given charset.
499  *
500  * @param input the input string (not necessarily 0-terminated)
501  * @param len the number of bytes in the @a input
502  * @param charset character set to convert to
503  * @return the converted string (0-terminated),
504  *  if conversion fails, a copy of the orignal
505  *  string is returned.
506  */
507 char *
508 GNUNET_STRINGS_from_utf8 (const char *input,
509                           size_t len,
510                           const char *charset)
511 {
512   return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
513 }
514
515
516 /**
517  * Convert the utf-8 input string to lowercase.
518  * Output needs to be allocated appropriately.
519  *
520  * @param input input string
521  * @param output output buffer
522  */
523 void
524 GNUNET_STRINGS_utf8_tolower (const char *input,
525                              char *output)
526 {
527   uint8_t *tmp_in;
528   size_t len;
529
530   tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
531                        NULL, UNINORM_NFD, NULL, &len);
532   GNUNET_memcpy(output, tmp_in, len);
533   output[len] = '\0';
534   free(tmp_in);
535 }
536
537
538 /**
539  * Convert the utf-8 input string to uppercase.
540  * Output needs to be allocated appropriately.
541  *
542  * @param input input string
543  * @param output output buffer
544  */
545 void
546 GNUNET_STRINGS_utf8_toupper(const char *input,
547                             char *output)
548 {
549   uint8_t *tmp_in;
550   size_t len;
551
552   tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
553                        NULL, UNINORM_NFD, NULL, &len);
554   GNUNET_memcpy (output, tmp_in, len);
555   output[len] = '\0';
556   free (tmp_in);
557 }
558
559
560 /**
561  * Complete filename (a la shell) from abbrevition.
562  * @param fil the name of the file, may contain ~/ or
563  *        be relative to the current directory
564  * @returns the full file name,
565  *          NULL is returned on error
566  */
567 char *
568 GNUNET_STRINGS_filename_expand (const char *fil)
569 {
570   char *buffer;
571 #ifndef MINGW
572   size_t len;
573   char *fm;
574   const char *fil_ptr;
575 #else
576   char *fn;
577   long lRet;
578 #endif
579
580   if (fil == NULL)
581     return NULL;
582
583 #ifndef MINGW
584   if (fil[0] == DIR_SEPARATOR)
585     /* absolute path, just copy */
586     return GNUNET_strdup (fil);
587   if (fil[0] == '~')
588   {
589     fm = getenv ("HOME");
590     if (fm == NULL)
591     {
592       LOG (GNUNET_ERROR_TYPE_WARNING,
593            _("Failed to expand `$HOME': environment variable `HOME' not set"));
594       return NULL;
595     }
596     fm = GNUNET_strdup (fm);
597     /* do not copy '~' */
598     fil_ptr = fil + 1;
599
600     /* skip over dir seperator to be consistent */
601     if (fil_ptr[0] == DIR_SEPARATOR)
602       fil_ptr++;
603   }
604   else
605   {
606     /* relative path */
607     fil_ptr = fil;
608     len = 512;
609     fm = NULL;
610     while (1)
611     {
612       buffer = GNUNET_malloc (len);
613       if (getcwd (buffer, len) != NULL)
614       {
615         fm = buffer;
616         break;
617       }
618       if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
619       {
620         len *= 2;
621         GNUNET_free (buffer);
622         continue;
623       }
624       GNUNET_free (buffer);
625       break;
626     }
627     if (fm == NULL)
628     {
629       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
630                     "getcwd");
631       buffer = getenv ("PWD");  /* alternative */
632       if (buffer != NULL)
633         fm = GNUNET_strdup (buffer);
634     }
635     if (fm == NULL)
636       fm = GNUNET_strdup ("./");        /* give up */
637   }
638   GNUNET_asprintf (&buffer,
639                    "%s%s%s",
640                    fm,
641                    (fm[strlen (fm) - 1] ==
642                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
643   GNUNET_free (fm);
644   return buffer;
645 #else
646   fn = GNUNET_malloc (MAX_PATH + 1);
647
648   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
649   {
650     SetErrnoFromWinError (lRet);
651     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
652                   "plibc_conv_to_win_path");
653     return NULL;
654   }
655   /* is the path relative? */
656   if ( (0 != strncmp (fn + 1, ":\\", 2)) &&
657        (0 != strncmp (fn, "\\\\", 2)) )
658   {
659     char szCurDir[MAX_PATH + 1];
660
661     lRet = GetCurrentDirectory (MAX_PATH + 1,
662                                 szCurDir);
663     if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
664     {
665       SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
666       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
667                     "GetCurrentDirectory");
668       return NULL;
669     }
670     GNUNET_asprintf (&buffer,
671                      "%s\\%s",
672                      szCurDir,
673                      fn);
674     GNUNET_free (fn);
675     fn = buffer;
676   }
677
678   return fn;
679 #endif
680 }
681
682
683 /**
684  * Give relative time in human-readable fancy format.
685  * This is one of the very few calls in the entire API that is
686  * NOT reentrant!
687  *
688  * @param delta time in milli seconds
689  * @param do_round are we allowed to round a bit?
690  * @return time as human-readable string
691  */
692 const char *
693 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
694                                         int do_round)
695 {
696   static char buf[128];
697   const char *unit = _( /* time unit */ "µs");
698   uint64_t dval = delta.rel_value_us;
699
700   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
701     return _("forever");
702   if (0 == delta.rel_value_us)
703     return _("0 ms");
704   if ( ( (GNUNET_YES == do_round) &&
705          (dval > 5 * 1000) ) ||
706        (0 == (dval % 1000) ))
707   {
708     dval = dval / 1000;
709     unit = _( /* time unit */ "ms");
710     if ( ( (GNUNET_YES == do_round) &&
711            (dval > 5 * 1000) ) ||
712          (0 == (dval % 1000) ))
713     {
714       dval = dval / 1000;
715       unit = _( /* time unit */ "s");
716       if ( ( (GNUNET_YES == do_round) &&
717              (dval > 5 * 60) ) ||
718            (0 == (dval % 60) ) )
719       {
720         dval = dval / 60;
721         unit = _( /* time unit */ "m");
722         if ( ( (GNUNET_YES == do_round) &&
723                (dval > 5 * 60) ) ||
724              (0 == (dval % 60) ))
725         {
726           dval = dval / 60;
727           unit = _( /* time unit */ "h");
728           if ( ( (GNUNET_YES == do_round) &&
729                  (dval > 5 * 24) ) ||
730                (0 == (dval % 24)) )
731           {
732             dval = dval / 24;
733             if (1 == dval)
734               unit = _( /* time unit */ "day");
735             else
736               unit = _( /* time unit */ "days");
737           }
738         }
739       }
740     }
741   }
742   GNUNET_snprintf (buf, sizeof (buf),
743                    "%llu %s", dval, unit);
744   return buf;
745 }
746
747
748 /**
749  * "asctime", except for GNUnet time.  Converts a GNUnet internal
750  * absolute time (which is in UTC) to a string in local time.
751  * Note that the returned value will be overwritten if this function
752  * is called again.
753  *
754  * @param t the absolute time to convert
755  * @return timestamp in human-readable form in local time
756  */
757 const char *
758 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
759 {
760   static char buf[255];
761   time_t tt;
762   struct tm *tp;
763
764   if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
765     return _("end of time");
766   tt = t.abs_value_us / 1000LL / 1000LL;
767   tp = localtime (&tt);
768   /* This is hacky, but i don't know a way to detect libc character encoding.
769    * Just expect utf8 from glibc these days.
770    * As for msvcrt, use the wide variant, which always returns utf16
771    * (otherwise we'd have to detect current codepage or use W32API character
772    * set conversion routines to convert to UTF8).
773    */
774 #ifndef WINDOWS
775   strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
776 #else
777   {
778     static wchar_t wbuf[255];
779     uint8_t *conved;
780     size_t ssize;
781
782     wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
783         L"%a %b %d %H:%M:%S %Y", tp);
784
785     ssize = sizeof (buf);
786     conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
787         (uint8_t *) buf, &ssize);
788     if (conved != (uint8_t *) buf)
789     {
790       strncpy (buf, (char *) conved, sizeof (buf));
791       buf[255 - 1] = '\0';
792       free (conved);
793     }
794   }
795 #endif
796   return buf;
797 }
798
799
800 /**
801  * "man basename"
802  * Returns a pointer to a part of filename (allocates nothing)!
803  *
804  * @param filename filename to extract basename from
805  * @return short (base) name of the file (that is, everything following the
806  *         last directory separator in filename. If filename ends with a
807  *         directory separator, the result will be a zero-length string.
808  *         If filename has no directory separators, the result is filename
809  *         itself.
810  */
811 const char *
812 GNUNET_STRINGS_get_short_name (const char *filename)
813 {
814   const char *short_fn = filename;
815   const char *ss;
816
817   while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
818       && (ss[1] != '\0'))
819     short_fn = 1 + ss;
820   return short_fn;
821 }
822
823
824 /**
825  * Get the decoded value corresponding to a character according to Crockford
826  * Base32 encoding.
827  *
828  * @param a a character
829  * @return corresponding numeric value
830  */
831 static unsigned int
832 getValue__ (unsigned char a)
833 {
834   unsigned int dec;
835
836   switch (a)
837   {
838   case 'O':
839   case 'o':
840     a = '0';
841     break;
842   case 'i':
843   case 'I':
844   case 'l':
845   case 'L':
846     a = '1';
847     break;
848     /* also consider U to be V */
849   case 'u':
850   case 'U':
851     a = 'V';
852     break;
853   default:
854     break;
855   }
856   if ((a >= '0') && (a <= '9'))
857     return a - '0';
858   if ((a >= 'a') && (a <= 'z'))
859     a = toupper (a);
860     /* return (a - 'a' + 10); */
861   dec = 0;
862   if ((a >= 'A') && (a <= 'Z'))
863   {
864     if ('I' < a)
865       dec++;
866     if ('L' < a)
867       dec++;
868     if ('O' < a)
869       dec++;
870     if ('U' < a)
871       dec++;
872     return (a - 'A' + 10 - dec);
873   }
874   return -1;
875 }
876
877
878 /**
879  * Convert binary data to ASCII encoding using Crockford Base32 encoding.
880  * Returns a pointer to the byte after the last byte in the string, that
881  * is where the 0-terminator was placed if there was room.
882  *
883  * @param data data to encode
884  * @param size size of data (in bytes)
885  * @param out buffer to fill
886  * @param out_size size of the buffer. Must be large enough to hold
887  * (size * 8 + 4) / 5 bytes
888  * @return pointer to the next byte in @a out or NULL on error.
889  */
890 char *
891 GNUNET_STRINGS_data_to_string (const void *data,
892                                size_t size,
893                                char *out,
894                                size_t out_size)
895 {
896   /**
897    * 32 characters for encoding
898    */
899   static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
900   unsigned int wpos;
901   unsigned int rpos;
902   unsigned int bits;
903   unsigned int vbit;
904   const unsigned char *udata;
905
906   udata = data;
907   if (out_size < (size * 8 + 4) / 5)
908   {
909     GNUNET_break (0);
910     return NULL;
911   }
912   vbit = 0;
913   wpos = 0;
914   rpos = 0;
915   bits = 0;
916   while ((rpos < size) || (vbit > 0))
917   {
918     if ((rpos < size) && (vbit < 5))
919     {
920       bits = (bits << 8) | udata[rpos++];   /* eat 8 more bits */
921       vbit += 8;
922     }
923     if (vbit < 5)
924     {
925       bits <<= (5 - vbit);      /* zero-padding */
926       GNUNET_assert (vbit == ((size * 8) % 5));
927       vbit = 5;
928     }
929     if (wpos >= out_size)
930     {
931       GNUNET_break (0);
932       return NULL;
933     }
934     out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
935     vbit -= 5;
936   }
937   GNUNET_assert (0 == vbit);
938   if (wpos < out_size)
939     out[wpos] = '\0';
940   return &out[wpos];
941 }
942
943
944 /**
945  * Return the base32crockford encoding of the given buffer.
946  *
947  * The returned string will be freshly allocated, and must be free'd
948  * with GNUNET_free().
949  *
950  * @param buffer with data
951  * @param size size of the buffer
952  * @return freshly allocated, null-terminated string
953  */
954 char *
955 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
956                                      size_t size)
957 {
958   char *str_buf;
959   size_t len = size * 8;
960   char *end;
961
962   if (len % 5 > 0)
963     len += 5 - len % 5;
964   len /= 5;
965   str_buf = GNUNET_malloc (len + 1);
966   end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
967   if (NULL == end)
968   {
969     GNUNET_free (str_buf);
970     return NULL;
971   }
972   *end = '\0';
973   return str_buf;
974 }
975
976
977 /**
978  * Convert Crockford Base32hex encoding back to data.
979  * @a out_size must match exactly the size of the data before it was encoded.
980  *
981  * @param enc the encoding
982  * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
983  * @param out location where to store the decoded data
984  * @param out_size size of the output buffer @a out
985  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
986  */
987 int
988 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
989                                void *out, size_t out_size)
990 {
991   unsigned int rpos;
992   unsigned int wpos;
993   unsigned int bits;
994   unsigned int vbit;
995   int ret;
996   int shift;
997   unsigned char *uout;
998   unsigned int encoded_len = out_size * 8;
999
1000   if (0 == enclen)
1001   {
1002     if (0 == out_size)
1003       return GNUNET_OK;
1004     return GNUNET_SYSERR;
1005   }
1006   uout = out;
1007   wpos = out_size;
1008   rpos = enclen;
1009   if ((encoded_len % 5) > 0)
1010   {
1011     vbit = encoded_len % 5; /* padding! */
1012     shift = 5 - vbit;
1013     bits = (ret = getValue__ (enc[--rpos])) >> shift;
1014   }
1015   else
1016   {
1017     vbit = 5;
1018     shift = 0;
1019     bits = (ret = getValue__ (enc[--rpos]));
1020   }
1021   if ((encoded_len + shift) / 5 != enclen)
1022     return GNUNET_SYSERR;
1023   if (-1 == ret)
1024     return GNUNET_SYSERR;
1025   while (wpos > 0)
1026   {
1027     if (0 == rpos)
1028     {
1029       GNUNET_break (0);
1030       return GNUNET_SYSERR;
1031     }
1032     bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1033     if (-1 == ret)
1034       return GNUNET_SYSERR;
1035     vbit += 5;
1036     if (vbit >= 8)
1037     {
1038       uout[--wpos] = (unsigned char) bits;
1039       bits >>= 8;
1040       vbit -= 8;
1041     }
1042   }
1043   if ( (0 != rpos) ||
1044        (0 != vbit) )
1045     return GNUNET_SYSERR;
1046   return GNUNET_OK;
1047 }
1048
1049
1050 /**
1051  * Parse a path that might be an URI.
1052  *
1053  * @param path path to parse. Must be NULL-terminated.
1054  * @param scheme_part a pointer to 'char *' where a pointer to a string that
1055  *        represents the URI scheme will be stored. Can be NULL. The string is
1056  *        allocated by the function, and should be freed by GNUNET_free() when
1057  *        it is no longer needed.
1058  * @param path_part a pointer to 'const char *' where a pointer to the path
1059  *        part of the URI will be stored. Can be NULL. Points to the same block
1060  *        of memory as 'path', and thus must not be freed. Might point to '\0',
1061  *        if path part is zero-length.
1062  * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1063  *         an URI, '* scheme_part' and '*path_part' will remain unchanged
1064  *         (if they weren't NULL).
1065  */
1066 int
1067 GNUNET_STRINGS_parse_uri (const char *path,
1068                           char **scheme_part,
1069                           const char **path_part)
1070 {
1071   size_t len;
1072   size_t i;
1073   int end;
1074   int pp_state = 0;
1075   const char *post_scheme_part = NULL;
1076   len = strlen (path);
1077   for (end = 0, i = 0; !end && i < len; i++)
1078   {
1079     switch (pp_state)
1080     {
1081     case 0:
1082       if ( (path[i] == ':') && (i > 0) )
1083       {
1084         pp_state += 1;
1085         continue;
1086       }
1087       if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1088           || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1089           || (path[i] == '.')))
1090         end = 1;
1091       break;
1092     case 1:
1093     case 2:
1094       if (path[i] == '/')
1095       {
1096         pp_state += 1;
1097         continue;
1098       }
1099       end = 1;
1100       break;
1101     case 3:
1102       post_scheme_part = &path[i];
1103       end = 1;
1104       break;
1105     default:
1106       end = 1;
1107     }
1108   }
1109   if (post_scheme_part == NULL)
1110     return GNUNET_NO;
1111   if (scheme_part)
1112   {
1113     *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1114     GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1115     (*scheme_part)[post_scheme_part - path] = '\0';
1116   }
1117   if (path_part)
1118     *path_part = post_scheme_part;
1119   return GNUNET_YES;
1120 }
1121
1122
1123 /**
1124  * Check whether @a filename is absolute or not, and if it's an URI
1125  *
1126  * @param filename filename to check
1127  * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1128  *        assume it's not URI
1129  * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1130  *        is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1131  *        not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1132  * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1133  *        The string is allocated by the function, and should be freed with
1134  *        GNUNET_free(). Can be NULL.
1135  * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1136  */
1137 int
1138 GNUNET_STRINGS_path_is_absolute (const char *filename,
1139                                  int can_be_uri,
1140                                  int *r_is_uri,
1141                                  char **r_uri_scheme)
1142 {
1143 #if WINDOWS
1144   size_t len;
1145 #endif
1146   const char *post_scheme_path;
1147   int is_uri;
1148   char * uri;
1149   /* consider POSIX paths to be absolute too, even on W32,
1150    * as plibc expansion will fix them for us.
1151    */
1152   if (filename[0] == '/')
1153     return GNUNET_YES;
1154   if (can_be_uri)
1155   {
1156     is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1157     if (r_is_uri)
1158       *r_is_uri = is_uri;
1159     if (is_uri)
1160     {
1161       if (r_uri_scheme)
1162         *r_uri_scheme = uri;
1163       else
1164         GNUNET_free_non_null (uri);
1165 #if WINDOWS
1166       len = strlen(post_scheme_path);
1167       /* Special check for file:///c:/blah
1168        * We want to parse 'c:/', not '/c:/'
1169        */
1170       if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1171         post_scheme_path = &post_scheme_path[1];
1172 #endif
1173       return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1174     }
1175   }
1176   else
1177   {
1178     if (r_is_uri)
1179       *r_is_uri = GNUNET_NO;
1180   }
1181 #if WINDOWS
1182   len = strlen (filename);
1183   if (len >= 3 &&
1184       ((filename[0] >= 'A' && filename[0] <= 'Z')
1185       || (filename[0] >= 'a' && filename[0] <= 'z'))
1186       && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1187     return GNUNET_YES;
1188 #endif
1189   return GNUNET_NO;
1190 }
1191
1192 #if MINGW
1193 #define         _IFMT           0170000 /* type of file */
1194 #define         _IFLNK          0120000 /* symbolic link */
1195 #define  S_ISLNK(m)     (((m)&_IFMT) == _IFLNK)
1196 #endif
1197
1198
1199 /**
1200  * Perform @a checks on @a filename.
1201  *
1202  * @param filename file to check
1203  * @param checks checks to perform
1204  * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1205  *         fails, #GNUNET_SYSERR when a check can't be performed
1206  */
1207 int
1208 GNUNET_STRINGS_check_filename (const char *filename,
1209                                enum GNUNET_STRINGS_FilenameCheck checks)
1210 {
1211   struct stat st;
1212   if ( (NULL == filename) || (filename[0] == '\0') )
1213     return GNUNET_SYSERR;
1214   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1215     if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1216       return GNUNET_NO;
1217   if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1218                       | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1219                       | GNUNET_STRINGS_CHECK_IS_LINK)))
1220   {
1221     if (0 != STAT (filename, &st))
1222     {
1223       if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1224         return GNUNET_NO;
1225       else
1226         return GNUNET_SYSERR;
1227     }
1228   }
1229   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1230     if (!S_ISDIR (st.st_mode))
1231       return GNUNET_NO;
1232   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1233     if (!S_ISLNK (st.st_mode))
1234       return GNUNET_NO;
1235   return GNUNET_YES;
1236 }
1237
1238
1239 /**
1240  * Tries to convert @a zt_addr string to an IPv6 address.
1241  * The string is expected to have the format "[ABCD::01]:80".
1242  *
1243  * @param zt_addr 0-terminated string. May be mangled by the function.
1244  * @param addrlen length of @a zt_addr (not counting 0-terminator).
1245  * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1246  *        then its sin6_port, sin6_family and sin6_addr are set appropriately.
1247  * @return #GNUNET_OK if conversion succeded.
1248  *         #GNUNET_SYSERR otherwise, in which
1249  *         case the contents of @a r_buf are undefined.
1250  */
1251 int
1252 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1253                                 uint16_t addrlen,
1254                                 struct sockaddr_in6 *r_buf)
1255 {
1256   char zbuf[addrlen + 1];
1257   int ret;
1258   char *port_colon;
1259   unsigned int port;
1260
1261   if (addrlen < 6)
1262     return GNUNET_SYSERR;
1263   GNUNET_memcpy (zbuf, zt_addr, addrlen);
1264   if ('[' != zbuf[0])
1265   {
1266     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1267                 _("IPv6 address did not start with `['\n"));
1268     return GNUNET_SYSERR;
1269   }
1270   zbuf[addrlen] = '\0';
1271   port_colon = strrchr (zbuf, ':');
1272   if (NULL == port_colon)
1273   {
1274     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1275                 _("IPv6 address did contain ':' to separate port number\n"));
1276     return GNUNET_SYSERR;
1277   }
1278   if (']' != *(port_colon - 1))
1279   {
1280     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1281                 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1282     return GNUNET_SYSERR;
1283   }
1284   ret = SSCANF (port_colon, ":%u", &port);
1285   if ( (1 != ret) || (port > 65535) )
1286   {
1287     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1288                 _("IPv6 address did contain a valid port number after the last ':'\n"));
1289     return GNUNET_SYSERR;
1290   }
1291   *(port_colon-1) = '\0';
1292   memset (r_buf, 0, sizeof (struct sockaddr_in6));
1293   ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1294   if (ret <= 0)
1295   {
1296     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1297                 _("Invalid IPv6 address `%s': %s\n"),
1298                 &zbuf[1],
1299                 STRERROR (errno));
1300     return GNUNET_SYSERR;
1301   }
1302   r_buf->sin6_port = htons (port);
1303   r_buf->sin6_family = AF_INET6;
1304 #if HAVE_SOCKADDR_IN_SIN_LEN
1305   r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1306 #endif
1307   return GNUNET_OK;
1308 }
1309
1310
1311 /**
1312  * Tries to convert 'zt_addr' string to an IPv4 address.
1313  * The string is expected to have the format "1.2.3.4:80".
1314  *
1315  * @param zt_addr 0-terminated string. May be mangled by the function.
1316  * @param addrlen length of @a zt_addr (not counting 0-terminator).
1317  * @param r_buf a buffer to fill.
1318  * @return #GNUNET_OK if conversion succeded.
1319  *         #GNUNET_SYSERR otherwise, in which case
1320  *         the contents of @a r_buf are undefined.
1321  */
1322 int
1323 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1324                                 uint16_t addrlen,
1325                                 struct sockaddr_in *r_buf)
1326 {
1327   unsigned int temps[4];
1328   unsigned int port;
1329   unsigned int cnt;
1330
1331   if (addrlen < 9)
1332     return GNUNET_SYSERR;
1333   cnt = SSCANF (zt_addr,
1334                 "%u.%u.%u.%u:%u",
1335                 &temps[0],
1336                 &temps[1],
1337                 &temps[2],
1338                 &temps[3],
1339                 &port);
1340   if (5 != cnt)
1341     return GNUNET_SYSERR;
1342   for (cnt = 0; cnt < 4; cnt++)
1343     if (temps[cnt] > 0xFF)
1344       return GNUNET_SYSERR;
1345   if (port > 65535)
1346     return GNUNET_SYSERR;
1347   r_buf->sin_family = AF_INET;
1348   r_buf->sin_port = htons (port);
1349   r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1350                                   (temps[2] << 8) + temps[3]);
1351 #if HAVE_SOCKADDR_IN_SIN_LEN
1352   r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1353 #endif
1354   return GNUNET_OK;
1355 }
1356
1357
1358 /**
1359  * Tries to convert @a addr string to an IP (v4 or v6) address.
1360  * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1361  *
1362  * @param addr a string, may not be 0-terminated.
1363  * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1364  *        0-terminator should not be counted towards addrlen).
1365  * @param r_buf a buffer to fill.
1366  * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1367  *         case the contents of @a r_buf are undefined.
1368  */
1369 int
1370 GNUNET_STRINGS_to_address_ip (const char *addr,
1371                               uint16_t addrlen,
1372                               struct sockaddr_storage *r_buf)
1373 {
1374   if (addr[0] == '[')
1375     return GNUNET_STRINGS_to_address_ipv6 (addr,
1376                                            addrlen,
1377                                            (struct sockaddr_in6 *) r_buf);
1378   return GNUNET_STRINGS_to_address_ipv4 (addr,
1379                                          addrlen,
1380                                          (struct sockaddr_in *) r_buf);
1381 }
1382
1383
1384 /**
1385  * Parse an address given as a string into a
1386  * `struct sockaddr`.
1387  *
1388  * @param addr the address
1389  * @param[out] af set to the parsed address family (i.e. AF_INET)
1390  * @param[out] sa set to the parsed address
1391  * @return 0 on error, otherwise number of bytes in @a sa
1392  */
1393 size_t
1394 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1395                                   uint8_t *af,
1396                                   struct sockaddr **sa)
1397 {
1398   char *cp = GNUNET_strdup (addr);
1399
1400   *af = AF_UNSPEC;
1401   if ('[' == *addr)
1402   {
1403     /* IPv6 */
1404     *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1405     if (GNUNET_OK !=
1406         GNUNET_STRINGS_to_address_ipv6 (cp,
1407                                         strlen (cp),
1408                                         (struct sockaddr_in6 *) *sa))
1409     {
1410       GNUNET_free (*sa);
1411       *sa = NULL;
1412       GNUNET_free (cp);
1413       return 0;
1414     }
1415     *af = AF_INET6;
1416     GNUNET_free (cp);
1417     return sizeof (struct sockaddr_in6);
1418   }
1419   else
1420   {
1421     /* IPv4 */
1422     *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1423     if (GNUNET_OK !=
1424         GNUNET_STRINGS_to_address_ipv4 (cp,
1425                                         strlen (cp),
1426                                         (struct sockaddr_in *) *sa))
1427     {
1428       GNUNET_free (*sa);
1429       *sa = NULL;
1430       GNUNET_free (cp);
1431       return 0;
1432     }
1433     *af = AF_INET;
1434     GNUNET_free (cp);
1435     return sizeof (struct sockaddr_in);
1436   }
1437 }
1438
1439
1440 /**
1441  * Makes a copy of argv that consists of a single memory chunk that can be
1442  * freed with a single call to GNUNET_free();
1443  */
1444 static char *const *
1445 _make_continuous_arg_copy (int argc,
1446                            char *const *argv)
1447 {
1448   size_t argvsize = 0;
1449   int i;
1450   char **new_argv;
1451   char *p;
1452   for (i = 0; i < argc; i++)
1453     argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1454   new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1455   p = (char *) &new_argv[argc + 1];
1456   for (i = 0; i < argc; i++)
1457   {
1458     new_argv[i] = p;
1459     strcpy (p, argv[i]);
1460     p += strlen (argv[i]) + 1;
1461   }
1462   new_argv[argc] = NULL;
1463   return (char *const *) new_argv;
1464 }
1465
1466
1467 /**
1468  * Returns utf-8 encoded arguments.
1469  * Does nothing (returns a copy of argc and argv) on any platform
1470  * other than W32.
1471  * Returned argv has u8argv[u8argc] == NULL.
1472  * Returned argv is a single memory block, and can be freed with a single
1473  *   GNUNET_free() call.
1474  *
1475  * @param argc argc (as given by main())
1476  * @param argv argv (as given by main())
1477  * @param u8argc a location to store new argc in (though it's th same as argc)
1478  * @param u8argv a location to store new argv in
1479  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1480  */
1481 int
1482 GNUNET_STRINGS_get_utf8_args (int argc,
1483                               char *const *argv,
1484                               int *u8argc,
1485                               char *const **u8argv)
1486 {
1487 #if WINDOWS
1488   wchar_t *wcmd;
1489   wchar_t **wargv;
1490   int wargc;
1491   int i;
1492   char **split_u8argv;
1493
1494   wcmd = GetCommandLineW ();
1495   if (NULL == wcmd)
1496     return GNUNET_SYSERR;
1497   wargv = CommandLineToArgvW (wcmd, &wargc);
1498   if (NULL == wargv)
1499     return GNUNET_SYSERR;
1500
1501   split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1502
1503   for (i = 0; i < wargc; i++)
1504   {
1505     size_t strl;
1506     /* Hopefully it will allocate us NUL-terminated strings... */
1507     split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1508     if (NULL == split_u8argv[i])
1509     {
1510       int j;
1511       for (j = 0; j < i; j++)
1512         free (split_u8argv[j]);
1513       GNUNET_free (split_u8argv);
1514       LocalFree (wargv);
1515       return GNUNET_SYSERR;
1516     }
1517   }
1518
1519   *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1520   *u8argc = wargc;
1521
1522   for (i = 0; i < wargc; i++)
1523     free (split_u8argv[i]);
1524   free (split_u8argv);
1525   return GNUNET_OK;
1526 #else
1527   char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1528   *u8argv = new_argv;
1529   *u8argc = argc;
1530   return GNUNET_OK;
1531 #endif
1532 }
1533
1534
1535 /**
1536  * Parse the given port policy.  The format is
1537  * "[!]SPORT[-DPORT]".
1538  *
1539  * @param port_policy string to parse
1540  * @param pp policy to fill in
1541  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1542  *         @a port_policy is malformed
1543  */
1544 static int
1545 parse_port_policy (const char *port_policy,
1546                    struct GNUNET_STRINGS_PortPolicy *pp)
1547 {
1548   const char *pos;
1549   int s;
1550   int e;
1551   char eol[2];
1552
1553   pos = port_policy;
1554   if ('!' == *pos)
1555   {
1556     pp->negate_portrange = GNUNET_YES;
1557     pos++;
1558   }
1559   if (2 == sscanf (pos,
1560                    "%u-%u%1s",
1561                    &s, &e, eol))
1562   {
1563     if ( (0 == s) ||
1564          (s > 0xFFFF) ||
1565          (e < s) ||
1566          (e > 0xFFFF) )
1567     {
1568       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1569                   _("Port not in range\n"));
1570       return GNUNET_SYSERR;
1571     }
1572     pp->start_port = (uint16_t) s;
1573     pp->end_port = (uint16_t) e;
1574     return GNUNET_OK;
1575   }
1576   if (1 == sscanf (pos,
1577                    "%u%1s",
1578                    &s,
1579                    eol))
1580   {
1581     if ( (0 == s) ||
1582          (s > 0xFFFF) )
1583     {
1584       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1585                   _("Port not in range\n"));
1586       return GNUNET_SYSERR;
1587     }
1588
1589     pp->start_port = (uint16_t) s;
1590     pp->end_port = (uint16_t) s;
1591     return GNUNET_OK;
1592   }
1593   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1594               _("Malformed port policy `%s'\n"),
1595               port_policy);
1596   return GNUNET_SYSERR;
1597 }
1598
1599
1600 /**
1601  * Parse an IPv4 network policy. The argument specifies a list of
1602  * subnets. The format is
1603  * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1604  * be terminated with a semicolon). The network must be given in
1605  * dotted-decimal notation. The netmask can be given in CIDR notation
1606  * (/16) or in dotted-decimal (/255.255.0.0).
1607  *
1608  * @param routeListX a string specifying the IPv4 subnets
1609  * @return the converted list, terminated with all zeros;
1610  *         NULL if the synatx is flawed
1611  */
1612 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1613 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1614 {
1615   unsigned int count;
1616   unsigned int i;
1617   unsigned int j;
1618   unsigned int len;
1619   int cnt;
1620   unsigned int pos;
1621   unsigned int temps[8];
1622   int slash;
1623   struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1624   int colon;
1625   int end;
1626   char *routeList;
1627
1628   if (NULL == routeListX)
1629     return NULL;
1630   len = strlen (routeListX);
1631   if (0 == len)
1632     return NULL;
1633   routeList = GNUNET_strdup (routeListX);
1634   count = 0;
1635   for (i = 0; i < len; i++)
1636     if (routeList[i] == ';')
1637       count++;
1638   result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1639   i = 0;
1640   pos = 0;
1641   while (i < count)
1642   {
1643     for (colon = pos; ':' != routeList[colon]; colon++)
1644       if ( (';' == routeList[colon]) ||
1645            ('\0' == routeList[colon]) )
1646         break;
1647     for (end = colon; ';' != routeList[end]; end++)
1648       if ('\0' == routeList[end])
1649         break;
1650     if ('\0' == routeList[end])
1651       break;
1652     routeList[end] = '\0';
1653     if (':' == routeList[colon])
1654     {
1655       routeList[colon] = '\0';
1656       if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1657                                           &result[i].pp))
1658         break;
1659     }
1660     cnt =
1661         SSCANF (&routeList[pos],
1662                 "%u.%u.%u.%u/%u.%u.%u.%u",
1663                 &temps[0],
1664                 &temps[1],
1665                 &temps[2],
1666                 &temps[3],
1667                 &temps[4],
1668                 &temps[5],
1669                 &temps[6],
1670                 &temps[7]);
1671     if (8 == cnt)
1672     {
1673       for (j = 0; j < 8; j++)
1674         if (temps[j] > 0xFF)
1675         {
1676           LOG (GNUNET_ERROR_TYPE_WARNING,
1677                _("Invalid format for IP: `%s'\n"),
1678                &routeList[pos]);
1679           GNUNET_free (result);
1680           GNUNET_free (routeList);
1681           return NULL;
1682         }
1683       result[i].network.s_addr =
1684           htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1685                  temps[3]);
1686       result[i].netmask.s_addr =
1687           htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1688                  temps[7]);
1689       pos = end + 1;
1690       i++;
1691       continue;
1692     }
1693     /* try second notation */
1694     cnt =
1695         SSCANF (&routeList[pos],
1696                 "%u.%u.%u.%u/%u",
1697                 &temps[0],
1698                 &temps[1],
1699                 &temps[2],
1700                 &temps[3],
1701                 &slash);
1702     if (5 == cnt)
1703     {
1704       for (j = 0; j < 4; j++)
1705         if (temps[j] > 0xFF)
1706         {
1707           LOG (GNUNET_ERROR_TYPE_WARNING,
1708                _("Invalid format for IP: `%s'\n"),
1709                &routeList[pos]);
1710           GNUNET_free (result);
1711           GNUNET_free (routeList);
1712           return NULL;
1713         }
1714       result[i].network.s_addr =
1715           htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1716                  temps[3]);
1717       if ((slash <= 32) && (slash >= 0))
1718       {
1719         result[i].netmask.s_addr = 0;
1720         while (slash > 0)
1721         {
1722           result[i].netmask.s_addr =
1723               (result[i].netmask.s_addr >> 1) + 0x80000000;
1724           slash--;
1725         }
1726         result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1727         pos = end + 1;
1728         i++;
1729         continue;
1730       }
1731       else
1732       {
1733         LOG (GNUNET_ERROR_TYPE_WARNING,
1734              _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1735              slash);
1736         GNUNET_free (result);
1737           GNUNET_free (routeList);
1738         return NULL;            /* error */
1739       }
1740     }
1741     /* try third notation */
1742     slash = 32;
1743     cnt =
1744         SSCANF (&routeList[pos],
1745                 "%u.%u.%u.%u",
1746                 &temps[0],
1747                 &temps[1],
1748                 &temps[2],
1749                 &temps[3]);
1750     if (4 == cnt)
1751     {
1752       for (j = 0; j < 4; j++)
1753         if (temps[j] > 0xFF)
1754         {
1755           LOG (GNUNET_ERROR_TYPE_WARNING,
1756                _("Invalid format for IP: `%s'\n"),
1757                &routeList[pos]);
1758           GNUNET_free (result);
1759           GNUNET_free (routeList);
1760           return NULL;
1761         }
1762       result[i].network.s_addr =
1763           htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1764                  temps[3]);
1765       result[i].netmask.s_addr = 0;
1766       while (slash > 0)
1767       {
1768         result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1769         slash--;
1770       }
1771       result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1772       pos = end + 1;
1773       i++;
1774       continue;
1775     }
1776     LOG (GNUNET_ERROR_TYPE_WARNING,
1777          _("Invalid format for IP: `%s'\n"),
1778          &routeList[pos]);
1779     GNUNET_free (result);
1780     GNUNET_free (routeList);
1781     return NULL;                /* error */
1782   }
1783   if (pos < strlen (routeList))
1784   {
1785     LOG (GNUNET_ERROR_TYPE_WARNING,
1786          _("Invalid format: `%s'\n"),
1787          &routeListX[pos]);
1788     GNUNET_free (result);
1789     GNUNET_free (routeList);
1790     return NULL;                /* oops */
1791   }
1792   GNUNET_free (routeList);
1793   return result;                /* ok */
1794 }
1795
1796
1797 /**
1798  * Parse an IPv6 network policy. The argument specifies a list of
1799  * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1800  * (no whitespace, must be terminated with a semicolon). The network
1801  * must be given in colon-hex notation.  The netmask must be given in
1802  * CIDR notation (/16) or can be omitted to specify a single host.
1803  * Note that the netmask is mandatory if ports are specified.
1804  *
1805  * @param routeListX a string specifying the policy
1806  * @return the converted list, 0-terminated, NULL if the synatx is flawed
1807  */
1808 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1809 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1810 {
1811   unsigned int count;
1812   unsigned int i;
1813   unsigned int len;
1814   unsigned int pos;
1815   int start;
1816   int slash;
1817   int ret;
1818   char *routeList;
1819   struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1820   unsigned int bits;
1821   unsigned int off;
1822   int save;
1823   int colon;
1824
1825   if (NULL == routeListX)
1826     return NULL;
1827   len = strlen (routeListX);
1828   if (0 == len)
1829     return NULL;
1830   routeList = GNUNET_strdup (routeListX);
1831   count = 0;
1832   for (i = 0; i < len; i++)
1833     if (';' == routeList[i])
1834       count++;
1835   if (';' != routeList[len - 1])
1836   {
1837     LOG (GNUNET_ERROR_TYPE_WARNING,
1838          _("Invalid network notation (does not end with ';': `%s')\n"),
1839          routeList);
1840     GNUNET_free (routeList);
1841     return NULL;
1842   }
1843
1844   result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1845   i = 0;
1846   pos = 0;
1847   while (i < count)
1848   {
1849     start = pos;
1850     while (';' != routeList[pos])
1851       pos++;
1852     slash = pos;
1853     while ((slash >= start) && (routeList[slash] != '/'))
1854       slash--;
1855
1856     if (slash < start)
1857     {
1858       memset (&result[i].netmask,
1859               0xFF,
1860               sizeof (struct in6_addr));
1861       slash = pos;
1862     }
1863     else
1864     {
1865       routeList[pos] = '\0';
1866       for (colon = pos; ':' != routeList[colon]; colon--)
1867         if ('/' == routeList[colon])
1868           break;
1869       if (':' == routeList[colon])
1870       {
1871         routeList[colon] = '\0';
1872         if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1873                                             &result[i].pp))
1874         {
1875           GNUNET_free (result);
1876           GNUNET_free (routeList);
1877           return NULL;
1878         }
1879       }
1880       ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1881       if (ret <= 0)
1882       {
1883         save = errno;
1884         if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1885         {
1886           if (0 == ret)
1887             LOG (GNUNET_ERROR_TYPE_WARNING,
1888                  _("Wrong format `%s' for netmask\n"),
1889                  &routeList[slash + 1]);
1890           else
1891           {
1892             errno = save;
1893             LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1894           }
1895           GNUNET_free (result);
1896           GNUNET_free (routeList);
1897           return NULL;
1898         }
1899         off = 0;
1900         while (bits > 8)
1901         {
1902           result[i].netmask.s6_addr[off++] = 0xFF;
1903           bits -= 8;
1904         }
1905         while (bits > 0)
1906         {
1907           result[i].netmask.s6_addr[off] =
1908               (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1909           bits--;
1910         }
1911       }
1912     }
1913     routeList[slash] = '\0';
1914     ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1915     if (ret <= 0)
1916     {
1917       if (0 == ret)
1918         LOG (GNUNET_ERROR_TYPE_WARNING,
1919              _("Wrong format `%s' for network\n"),
1920              &routeList[slash + 1]);
1921       else
1922         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1923                       "inet_pton");
1924       GNUNET_free (result);
1925       GNUNET_free (routeList);
1926       return NULL;
1927     }
1928     pos++;
1929     i++;
1930   }
1931   GNUNET_free (routeList);
1932   return result;
1933 }
1934
1935
1936
1937 /** ******************** Base64 encoding ***********/
1938
1939 #define FILLCHAR '='
1940 static char *cvt =
1941     "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1942
1943
1944 /**
1945  * Encode into Base64.
1946  *
1947  * @param data the data to encode
1948  * @param len the length of the input
1949  * @param output where to write the output (*output should be NULL,
1950  *   is allocated)
1951  * @return the size of the output
1952  */
1953 size_t
1954 GNUNET_STRINGS_base64_encode (const char *data,
1955                               size_t len,
1956                               char **output)
1957 {
1958   size_t i;
1959   char c;
1960   size_t ret;
1961   char *opt;
1962
1963   ret = 0;
1964   opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1965   *output = opt;
1966   for (i = 0; i < len; ++i)
1967   {
1968     c = (data[i] >> 2) & 0x3f;
1969     opt[ret++] = cvt[(int) c];
1970     c = (data[i] << 4) & 0x3f;
1971     if (++i < len)
1972       c |= (data[i] >> 4) & 0x0f;
1973     opt[ret++] = cvt[(int) c];
1974     if (i < len)
1975     {
1976       c = (data[i] << 2) & 0x3f;
1977       if (++i < len)
1978         c |= (data[i] >> 6) & 0x03;
1979       opt[ret++] = cvt[(int) c];
1980     }
1981     else
1982     {
1983       ++i;
1984       opt[ret++] = FILLCHAR;
1985     }
1986     if (i < len)
1987     {
1988       c = data[i] & 0x3f;
1989       opt[ret++] = cvt[(int) c];
1990     }
1991     else
1992     {
1993       opt[ret++] = FILLCHAR;
1994     }
1995   }
1996   opt[ret++] = FILLCHAR;
1997   return ret;
1998 }
1999
2000 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
2001                    :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
2002                    :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
2003            :((a) == '+') ? 62\
2004            :((a) == '/') ? 63 : -1)
2005
2006
2007 /**
2008  * Decode from Base64.
2009  *
2010  * @param data the data to encode
2011  * @param len the length of the input
2012  * @param output where to write the output (*output should be NULL,
2013  *   is allocated)
2014  * @return the size of the output
2015  */
2016 size_t
2017 GNUNET_STRINGS_base64_decode (const char *data,
2018                               size_t len, char **output)
2019 {
2020   size_t i;
2021   char c;
2022   char c1;
2023   size_t ret = 0;
2024
2025 #define CHECK_CRLF  while (data[i] == '\r' || data[i] == '\n') {\
2026                         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
2027                         i++; \
2028                         if (i >= len) goto END;  \
2029                 }
2030
2031   *output = GNUNET_malloc ((len * 3 / 4) + 8);
2032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2033               "base64_decode decoding len=%d\n",
2034               (int) len);
2035   for (i = 0; i < len; ++i)
2036   {
2037     CHECK_CRLF;
2038     if (FILLCHAR == data[i])
2039       break;
2040     c = (char) cvtfind (data[i]);
2041     ++i;
2042     CHECK_CRLF;
2043     c1 = (char) cvtfind (data[i]);
2044     c = (c << 2) | ((c1 >> 4) & 0x3);
2045     (*output)[ret++] = c;
2046     if (++i < len)
2047     {
2048       CHECK_CRLF;
2049       c = data[i];
2050       if (FILLCHAR == c)
2051         break;
2052       c = (char) cvtfind (c);
2053       c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2054       (*output)[ret++] = c1;
2055     }
2056     if (++i < len)
2057     {
2058       CHECK_CRLF;
2059       c1 = data[i];
2060       if (FILLCHAR == c1)
2061         break;
2062
2063       c1 = (char) cvtfind (c1);
2064       c = ((c << 6) & 0xc0) | c1;
2065       (*output)[ret++] = c;
2066     }
2067   }
2068 END:
2069   return ret;
2070 }
2071
2072
2073
2074
2075
2076 /* end of strings.c */