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