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