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