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