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