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