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