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