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