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