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