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