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