function to fill buffer with random values
[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     { "a", 31536000000000LL /* year */ },
315     { NULL, 0}
316   };
317   int ret;
318   unsigned long long val;
319
320   if (0 == strcasecmp ("forever", fancy_time))
321   {
322     *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
323     return GNUNET_OK;
324   }
325   ret = convert_with_table (fancy_time,
326                             table,
327                             &val);
328   rtime->rel_value_us = (uint64_t) val;
329   return ret;
330 }
331
332
333 /**
334  * Convert a given fancy human-readable time to our internal
335  * representation. The human-readable time is expected to be
336  * in local time, whereas the returned value will be in UTC.
337  *
338  * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
339  * @param atime set to the absolute time
340  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
341  */
342 int
343 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
344                                        struct GNUNET_TIME_Absolute *atime)
345 {
346   struct tm tv;
347   time_t t;
348
349   if (0 == strcasecmp ("end of time", fancy_time))
350   {
351     *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
352     return GNUNET_OK;
353   }
354   memset (&tv, 0, sizeof (tv));
355   if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
356        (NULL == strptime (fancy_time, "%c", &tv)) &&
357        (NULL == strptime (fancy_time, "%Ec", &tv)) &&
358        (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
359        (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
360        (NULL == strptime (fancy_time, "%x", &tv)) &&
361        (NULL == strptime (fancy_time, "%Ex", &tv)) &&
362        (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
363        (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
364        (NULL == strptime (fancy_time, "%Y", &tv)) )
365     return GNUNET_SYSERR;
366   t = mktime (&tv);
367   atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
368 #if LINUX
369   atime->abs_value_us -= 1000LL * 1000LL * timezone;
370 #elif defined 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, char** output)
503 {
504   uint8_t *tmp_in;
505   size_t len;
506
507   tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
508                        NULL, UNINORM_NFD, NULL, &len);
509   memcpy(*output, tmp_in, len);
510   (*output)[len] = '\0';
511   free(tmp_in);
512 }
513
514
515 /**
516  * Convert the utf-8 input string to uppercase
517  * Output needs to be allocated appropriately
518  *
519  * @param input input string
520  * @param output output buffer
521  */
522 void
523 GNUNET_STRINGS_utf8_toupper(const char* input, char** output)
524 {
525   uint8_t *tmp_in;
526   size_t len;
527
528   tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
529                        NULL, UNINORM_NFD, NULL, &len);
530   memcpy(*output, tmp_in, len);
531   (*output)[len] = '\0';
532   free(tmp_in);
533 }
534
535
536 /**
537  * Complete filename (a la shell) from abbrevition.
538  * @param fil the name of the file, may contain ~/ or
539  *        be relative to the current directory
540  * @returns the full file name,
541  *          NULL is returned on error
542  */
543 char *
544 GNUNET_STRINGS_filename_expand (const char *fil)
545 {
546   char *buffer;
547 #ifndef MINGW
548   size_t len;
549   size_t n;
550   char *fm;
551   const char *fil_ptr;
552 #else
553   char *fn;
554   long lRet;
555 #endif
556
557   if (fil == NULL)
558     return NULL;
559
560 #ifndef MINGW
561   if (fil[0] == DIR_SEPARATOR)
562     /* absolute path, just copy */
563     return GNUNET_strdup (fil);
564   if (fil[0] == '~')
565   {
566     fm = getenv ("HOME");
567     if (fm == NULL)
568     {
569       LOG (GNUNET_ERROR_TYPE_WARNING,
570            _("Failed to expand `$HOME': environment variable `HOME' not set"));
571       return NULL;
572     }
573     fm = GNUNET_strdup (fm);
574     /* do not copy '~' */
575     fil_ptr = fil + 1;
576
577     /* skip over dir seperator to be consistent */
578     if (fil_ptr[0] == DIR_SEPARATOR)
579       fil_ptr++;
580   }
581   else
582   {
583     /* relative path */
584     fil_ptr = fil;
585     len = 512;
586     fm = NULL;
587     while (1)
588     {
589       buffer = GNUNET_malloc (len);
590       if (getcwd (buffer, len) != NULL)
591       {
592         fm = buffer;
593         break;
594       }
595       if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
596       {
597         len *= 2;
598         GNUNET_free (buffer);
599         continue;
600       }
601       GNUNET_free (buffer);
602       break;
603     }
604     if (fm == NULL)
605     {
606       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
607       buffer = getenv ("PWD");  /* alternative */
608       if (buffer != NULL)
609         fm = GNUNET_strdup (buffer);
610     }
611     if (fm == NULL)
612       fm = GNUNET_strdup ("./");        /* give up */
613   }
614   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
615   buffer = GNUNET_malloc (n);
616   GNUNET_snprintf (buffer, n, "%s%s%s", fm,
617                    (fm[strlen (fm) - 1] ==
618                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
619   GNUNET_free (fm);
620   return buffer;
621 #else
622   fn = GNUNET_malloc (MAX_PATH + 1);
623
624   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
625   {
626     SetErrnoFromWinError (lRet);
627     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
628     return NULL;
629   }
630   /* is the path relative? */
631   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
632   {
633     char szCurDir[MAX_PATH + 1];
634
635     lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
636     if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
637     {
638       SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
639       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
640       return NULL;
641     }
642     buffer = GNUNET_malloc (MAX_PATH + 1);
643     GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
644     GNUNET_free (fn);
645     fn = buffer;
646   }
647
648   return fn;
649 #endif
650 }
651
652
653 /**
654  * Give relative time in human-readable fancy format.
655  * This is one of the very few calls in the entire API that is
656  * NOT reentrant!
657  *
658  * @param delta time in milli seconds
659  * @param do_round are we allowed to round a bit?
660  * @return time as human-readable string
661  */
662 const char *
663 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
664                                         int do_round)
665 {
666   static char buf[128];
667   const char *unit = _( /* time unit */ "µs");
668   uint64_t dval = delta.rel_value_us;
669
670   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
671     return _("forever");
672   if (0 == delta.rel_value_us)
673     return _("0 ms");
674   if ( ( (GNUNET_YES == do_round) &&
675          (dval > 5 * 1000) ) ||
676        (0 == (dval % 1000) ))
677   {
678     dval = dval / 1000;
679     unit = _( /* time unit */ "ms");
680     if ( ( (GNUNET_YES == do_round) &&
681            (dval > 5 * 1000) ) ||
682          (0 == (dval % 1000) ))
683     {
684       dval = dval / 1000;
685       unit = _( /* time unit */ "s");
686       if ( ( (GNUNET_YES == do_round) &&
687              (dval > 5 * 60) ) ||
688            (0 == (dval % 60) ) )
689       {
690         dval = dval / 60;
691         unit = _( /* time unit */ "m");
692         if ( ( (GNUNET_YES == do_round) &&
693                (dval > 5 * 60) ) ||
694              (0 == (dval % 60) ))
695         {
696           dval = dval / 60;
697           unit = _( /* time unit */ "h");
698           if ( ( (GNUNET_YES == do_round) &&
699                  (dval > 5 * 24) ) ||
700                (0 == (dval % 24)) )
701           {
702             dval = dval / 24;
703             if (1 == dval)
704               unit = _( /* time unit */ "day");
705             else
706               unit = _( /* time unit */ "days");
707           }
708         }
709       }
710     }
711   }
712   GNUNET_snprintf (buf, sizeof (buf),
713                    "%llu %s", dval, unit);
714   return buf;
715 }
716
717
718 /**
719  * "asctime", except for GNUnet time.  Converts a GNUnet internal
720  * absolute time (which is in UTC) to a string in local time.
721  * Note that the returned value will be overwritten if this function
722  * is called again.
723  *
724  * @param t the absolute time to convert
725  * @return timestamp in human-readable form in local time
726  */
727 const char *
728 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
729 {
730   static char buf[255];
731   time_t tt;
732   struct tm *tp;
733
734   if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
735     return _("end of time");
736   tt = t.abs_value_us / 1000LL / 1000LL;
737   tp = gmtime (&tt);
738   strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
739   return buf;
740 }
741
742
743 /**
744  * "man basename"
745  * Returns a pointer to a part of filename (allocates nothing)!
746  *
747  * @param filename filename to extract basename from
748  * @return short (base) name of the file (that is, everything following the
749  *         last directory separator in filename. If filename ends with a
750  *         directory separator, the result will be a zero-length string.
751  *         If filename has no directory separators, the result is filename
752  *         itself.
753  */
754 const char *
755 GNUNET_STRINGS_get_short_name (const char *filename)
756 {
757   const char *short_fn = filename;
758   const char *ss;
759   while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
760       && (ss[1] != '\0'))
761     short_fn = 1 + ss;
762   return short_fn;
763 }
764
765
766 /**
767  * Get the numeric value corresponding to a character.
768  *
769  * @param a a character
770  * @return corresponding numeric value
771  */
772 static unsigned int
773 getValue__ (unsigned char a)
774 {
775   if ((a >= '0') && (a <= '9'))
776     return a - '0';
777   if ((a >= 'A') && (a <= 'V'))
778     return (a - 'A' + 10);
779   return -1;
780 }
781
782
783 /**
784  * Convert binary data to ASCII encoding.  The ASCII encoding is rather
785  * GNUnet specific.  It was chosen such that it only uses characters
786  * in [0-9A-V], can be produced without complex arithmetics and uses a
787  * small number of characters.
788  * Does not append 0-terminator, but returns a pointer to the place where
789  * it should be placed, if needed.
790  *
791  * @param data data to encode
792  * @param size size of data (in bytes)
793  * @param out buffer to fill
794  * @param out_size size of the buffer. Must be large enough to hold
795  * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
796  * @return pointer to the next byte in 'out' or NULL on error.
797  */
798 char *
799 GNUNET_STRINGS_data_to_string (const void *data, size_t size, char *out, size_t out_size)
800 {
801   /**
802    * 32 characters for encoding
803    */
804   static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
805   unsigned int wpos;
806   unsigned int rpos;
807   unsigned int bits;
808   unsigned int vbit;
809   const unsigned char *udata;
810
811   GNUNET_assert (data != NULL);
812   GNUNET_assert (out != NULL);
813   udata = data;
814   if (out_size < (((size*8) + ((size*8) % 5)) % 5))
815   {
816     GNUNET_break (0);
817     return NULL;
818   }
819   vbit = 0;
820   wpos = 0;
821   rpos = 0;
822   bits = 0;
823   while ((rpos < size) || (vbit > 0))
824   {
825     if ((rpos < size) && (vbit < 5))
826     {
827       bits = (bits << 8) | udata[rpos++];   /* eat 8 more bits */
828       vbit += 8;
829     }
830     if (vbit < 5)
831     {
832       bits <<= (5 - vbit);      /* zero-padding */
833       GNUNET_assert (vbit == ((size * 8) % 5));
834       vbit = 5;
835     }
836     if (wpos >= out_size)
837     {
838       GNUNET_break (0);
839       return NULL;
840     }
841     out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
842     vbit -= 5;
843   }
844   GNUNET_assert (vbit == 0);
845   if (wpos < out_size)
846     out[wpos] = '\0';
847   return &out[wpos];
848 }
849
850
851 /**
852  * Convert ASCII encoding back to data
853  * out_size must match exactly the size of the data before it was encoded.
854  *
855  * @param enc the encoding
856  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
857  * @param out location where to store the decoded data
858  * @param out_size size of the output buffer
859  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
860  */
861 int
862 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
863                                void *out, size_t out_size)
864 {
865   unsigned int rpos;
866   unsigned int wpos;
867   unsigned int bits;
868   unsigned int vbit;
869   int ret;
870   int shift;
871   unsigned char *uout;
872   unsigned int encoded_len = out_size * 8;
873
874   if (0 == enclen)
875   {
876     if (0 == out_size)
877       return GNUNET_OK;
878     return GNUNET_SYSERR;
879   }
880   uout = out;
881   wpos = out_size;
882   rpos = enclen;
883   if ((encoded_len % 5) > 0)
884   {
885     vbit = encoded_len % 5; /* padding! */
886     shift = 5 - vbit;
887     bits = (ret = getValue__ (enc[--rpos])) >> (5 - (encoded_len % 5));
888   }
889   else
890   {
891     vbit = 5;
892     shift = 0;
893     bits = (ret = getValue__ (enc[--rpos]));
894   }
895   if ((encoded_len + shift) / 5 != enclen)
896     return GNUNET_SYSERR;
897   if (-1 == ret)
898     return GNUNET_SYSERR;
899   while (wpos > 0)
900   {
901     if (0 == rpos)
902     {
903       GNUNET_break (0);
904       return GNUNET_SYSERR;
905     }
906     bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
907     if (-1 == ret)
908       return GNUNET_SYSERR;
909     vbit += 5;
910     if (vbit >= 8)
911     {
912       uout[--wpos] = (unsigned char) bits;
913       bits >>= 8;
914       vbit -= 8;
915     }
916   }
917   if ( (0 != rpos) ||
918        (0 != vbit) )
919     return GNUNET_SYSERR;
920   return GNUNET_OK;
921 }
922
923
924 /**
925  * Parse a path that might be an URI.
926  *
927  * @param path path to parse. Must be NULL-terminated.
928  * @param scheme_part a pointer to 'char *' where a pointer to a string that
929  *        represents the URI scheme will be stored. Can be NULL. The string is
930  *        allocated by the function, and should be freed by GNUNET_free() when
931  *        it is no longer needed.
932  * @param path_part a pointer to 'const char *' where a pointer to the path
933  *        part of the URI will be stored. Can be NULL. Points to the same block
934  *        of memory as 'path', and thus must not be freed. Might point to '\0',
935  *        if path part is zero-length.
936  * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
937  *         an URI, '* scheme_part' and '*path_part' will remain unchanged
938  *         (if they weren't NULL).
939  */
940 int
941 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
942     const char **path_part)
943 {
944   size_t len;
945   int i, end;
946   int pp_state = 0;
947   const char *post_scheme_part = NULL;
948   len = strlen (path);
949   for (end = 0, i = 0; !end && i < len; i++)
950   {
951     switch (pp_state)
952     {
953     case 0:
954       if (path[i] == ':' && i > 0)
955       {
956         pp_state += 1;
957         continue;
958       }
959       if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
960           || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
961           || (path[i] == '.')))
962         end = 1;
963       break;
964     case 1:
965     case 2:
966       if (path[i] == '/')
967       {
968         pp_state += 1;
969         continue;
970       }
971       end = 1;
972       break;
973     case 3:
974       post_scheme_part = &path[i];
975       end = 1;
976       break;
977     default:
978       end = 1;
979     }
980   }
981   if (post_scheme_part == NULL)
982     return GNUNET_NO;
983   if (scheme_part)
984   {
985     *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
986     memcpy (*scheme_part, path, post_scheme_part - path);
987     (*scheme_part)[post_scheme_part - path] = '\0';
988   }
989   if (path_part)
990     *path_part = post_scheme_part;
991   return GNUNET_YES;
992 }
993
994
995 /**
996  * Check whether @a filename is absolute or not, and if it's an URI
997  *
998  * @param filename filename to check
999  * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1000  *        assume it's not URI
1001  * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1002  *        is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1003  *        not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1004  * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1005  *        The string is allocated by the function, and should be freed with
1006  *        GNUNET_free(). Can be NULL.
1007  * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1008  */
1009 int
1010 GNUNET_STRINGS_path_is_absolute (const char *filename,
1011                                  int can_be_uri,
1012                                  int *r_is_uri,
1013                                  char **r_uri_scheme)
1014 {
1015 #if WINDOWS
1016   size_t len;
1017 #endif
1018   const char *post_scheme_path;
1019   int is_uri;
1020   char * uri;
1021   /* consider POSIX paths to be absolute too, even on W32,
1022    * as plibc expansion will fix them for us.
1023    */
1024   if (filename[0] == '/')
1025     return GNUNET_YES;
1026   if (can_be_uri)
1027   {
1028     is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1029     if (r_is_uri)
1030       *r_is_uri = is_uri;
1031     if (is_uri)
1032     {
1033       if (r_uri_scheme)
1034         *r_uri_scheme = uri;
1035       else
1036         GNUNET_free_non_null (uri);
1037 #if WINDOWS
1038       len = strlen(post_scheme_path);
1039       /* Special check for file:///c:/blah
1040        * We want to parse 'c:/', not '/c:/'
1041        */
1042       if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1043         post_scheme_path = &post_scheme_path[1];
1044 #endif
1045       return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1046     }
1047   }
1048   else
1049   {
1050     if (r_is_uri)
1051       *r_is_uri = GNUNET_NO;
1052   }
1053 #if WINDOWS
1054   len = strlen (filename);
1055   if (len >= 3 &&
1056       ((filename[0] >= 'A' && filename[0] <= 'Z')
1057       || (filename[0] >= 'a' && filename[0] <= 'z'))
1058       && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1059     return GNUNET_YES;
1060 #endif
1061   return GNUNET_NO;
1062 }
1063
1064 #if MINGW
1065 #define         _IFMT           0170000 /* type of file */
1066 #define         _IFLNK          0120000 /* symbolic link */
1067 #define  S_ISLNK(m)     (((m)&_IFMT) == _IFLNK)
1068 #endif
1069
1070
1071 /**
1072  * Perform @a checks on @a filename.
1073  *
1074  * @param filename file to check
1075  * @param checks checks to perform
1076  * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1077  *         fails, #GNUNET_SYSERR when a check can't be performed
1078  */
1079 int
1080 GNUNET_STRINGS_check_filename (const char *filename,
1081                                enum GNUNET_STRINGS_FilenameCheck checks)
1082 {
1083   struct stat st;
1084   if ( (NULL == filename) || (filename[0] == '\0') )
1085     return GNUNET_SYSERR;
1086   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1087     if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1088       return GNUNET_NO;
1089   if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1090                       | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1091                       | GNUNET_STRINGS_CHECK_IS_LINK)))
1092   {
1093     if (0 != STAT (filename, &st))
1094     {
1095       if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1096         return GNUNET_NO;
1097       else
1098         return GNUNET_SYSERR;
1099     }
1100   }
1101   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1102     if (!S_ISDIR (st.st_mode))
1103       return GNUNET_NO;
1104   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1105     if (!S_ISLNK (st.st_mode))
1106       return GNUNET_NO;
1107   return GNUNET_YES;
1108 }
1109
1110
1111 /**
1112  * Tries to convert 'zt_addr' string to an IPv6 address.
1113  * The string is expected to have the format "[ABCD::01]:80".
1114  *
1115  * @param zt_addr 0-terminated string. May be mangled by the function.
1116  * @param addrlen length of @a zt_addr (not counting 0-terminator).
1117  * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1118  *        then its sin6_port, sin6_family and sin6_addr are set appropriately.
1119  * @return #GNUNET_OK if conversion succeded.
1120  *         #GNUNET_SYSERR otherwise, in which
1121  *         case the contents of @a r_buf are undefined.
1122  */
1123 int
1124 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1125                                 uint16_t addrlen,
1126                                 struct sockaddr_in6 *r_buf)
1127 {
1128   char zbuf[addrlen + 1];
1129   int ret;
1130   char *port_colon;
1131   unsigned int port;
1132
1133   if (addrlen < 6)
1134     return GNUNET_SYSERR;
1135   memcpy (zbuf, zt_addr, addrlen);
1136   if ('[' != zbuf[0])
1137   {
1138     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1139                 _("IPv6 address did not start with `['\n"));
1140     return GNUNET_SYSERR;
1141   }
1142   zbuf[addrlen] = '\0';
1143   port_colon = strrchr (zbuf, ':');
1144   if (NULL == port_colon)
1145   {
1146     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1147                 _("IPv6 address did contain ':' to separate port number\n"));
1148     return GNUNET_SYSERR;
1149   }
1150   if (']' != *(port_colon - 1))
1151   {
1152     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1153                 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1154     return GNUNET_SYSERR;
1155   }
1156   ret = SSCANF (port_colon, ":%u", &port);
1157   if ( (1 != ret) || (port > 65535) )
1158   {
1159     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1160                 _("IPv6 address did contain a valid port number after the last ':'\n"));
1161     return GNUNET_SYSERR;
1162   }
1163   *(port_colon-1) = '\0';
1164   memset (r_buf, 0, sizeof (struct sockaddr_in6));
1165   ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1166   if (ret <= 0)
1167   {
1168     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1169                 _("Invalid IPv6 address `%s': %s\n"),
1170                 &zbuf[1],
1171                 STRERROR (errno));
1172     return GNUNET_SYSERR;
1173   }
1174   r_buf->sin6_port = htons (port);
1175   r_buf->sin6_family = AF_INET6;
1176 #if HAVE_SOCKADDR_IN_SIN_LEN
1177   r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1178 #endif
1179   return GNUNET_OK;
1180 }
1181
1182
1183 /**
1184  * Tries to convert 'zt_addr' string to an IPv4 address.
1185  * The string is expected to have the format "1.2.3.4:80".
1186  *
1187  * @param zt_addr 0-terminated string. May be mangled by the function.
1188  * @param addrlen length of @a zt_addr (not counting 0-terminator).
1189  * @param r_buf a buffer to fill.
1190  * @return #GNUNET_OK if conversion succeded.
1191  *         #GNUNET_SYSERR otherwise, in which case
1192  *         the contents of @a r_buf are undefined.
1193  */
1194 int
1195 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1196                                 struct sockaddr_in *r_buf)
1197 {
1198   unsigned int temps[4];
1199   unsigned int port;
1200   unsigned int cnt;
1201
1202   if (addrlen < 9)
1203     return GNUNET_SYSERR;
1204   cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1205   if (5 != cnt)
1206     return GNUNET_SYSERR;
1207   for (cnt = 0; cnt < 4; cnt++)
1208     if (temps[cnt] > 0xFF)
1209       return GNUNET_SYSERR;
1210   if (port > 65535)
1211     return GNUNET_SYSERR;
1212   r_buf->sin_family = AF_INET;
1213   r_buf->sin_port = htons (port);
1214   r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1215                                   (temps[2] << 8) + temps[3]);
1216 #if HAVE_SOCKADDR_IN_SIN_LEN
1217   r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1218 #endif
1219   return GNUNET_OK;
1220 }
1221
1222
1223 /**
1224  * Tries to convert @a addr string to an IP (v4 or v6) address.
1225  * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1226  *
1227  * @param addr a string, may not be 0-terminated.
1228  * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1229  *        0-terminator should not be counted towards addrlen).
1230  * @param r_buf a buffer to fill.
1231  * @return #GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1232  *         case the contents of r_buf are undefined.
1233  */
1234 int
1235 GNUNET_STRINGS_to_address_ip (const char *addr,
1236                               uint16_t addrlen,
1237                               struct sockaddr_storage *r_buf)
1238 {
1239   if (addr[0] == '[')
1240     return GNUNET_STRINGS_to_address_ipv6 (addr,
1241                                            addrlen,
1242                                            (struct sockaddr_in6 *) r_buf);
1243   return GNUNET_STRINGS_to_address_ipv4 (addr,
1244                                          addrlen,
1245                                          (struct sockaddr_in *) r_buf);
1246 }
1247
1248
1249 /**
1250  * Makes a copy of argv that consists of a single memory chunk that can be
1251  * freed with a single call to GNUNET_free ();
1252  */
1253 static char *const *
1254 _make_continuous_arg_copy (int argc,
1255                            char *const *argv)
1256 {
1257   size_t argvsize = 0;
1258   int i;
1259   char **new_argv;
1260   char *p;
1261   for (i = 0; i < argc; i++)
1262     argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1263   new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1264   p = (char *) &new_argv[argc + 1];
1265   for (i = 0; i < argc; i++)
1266   {
1267     new_argv[i] = p;
1268     strcpy (p, argv[i]);
1269     p += strlen (argv[i]) + 1;
1270   }
1271   new_argv[argc] = NULL;
1272   return (char *const *) new_argv;
1273 }
1274
1275
1276 /**
1277  * Returns utf-8 encoded arguments.
1278  * Does nothing (returns a copy of argc and argv) on any platform
1279  * other than W32.
1280  * Returned argv has u8argv[u8argc] == NULL.
1281  * Returned argv is a single memory block, and can be freed with a single
1282  *   GNUNET_free () call.
1283  *
1284  * @param argc argc (as given by main())
1285  * @param argv argv (as given by main())
1286  * @param u8argc a location to store new argc in (though it's th same as argc)
1287  * @param u8argv a location to store new argv in
1288  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1289  */
1290 int
1291 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1292 {
1293 #if WINDOWS
1294   wchar_t *wcmd;
1295   wchar_t **wargv;
1296   int wargc;
1297   int i;
1298   char **split_u8argv;
1299
1300   wcmd = GetCommandLineW ();
1301   if (NULL == wcmd)
1302     return GNUNET_SYSERR;
1303   wargv = CommandLineToArgvW (wcmd, &wargc);
1304   if (NULL == wargv)
1305     return GNUNET_SYSERR;
1306
1307   split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1308
1309   for (i = 0; i < wargc; i++)
1310   {
1311     size_t strl;
1312     /* Hopefully it will allocate us NUL-terminated strings... */
1313     split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1314     if (NULL == split_u8argv[i])
1315     {
1316       int j;
1317       for (j = 0; j < i; j++)
1318         free (split_u8argv[j]);
1319       GNUNET_free (split_u8argv);
1320       LocalFree (wargv);
1321       return GNUNET_SYSERR;
1322     }
1323   }
1324
1325   *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1326   *u8argc = wargc;
1327
1328   for (i = 0; i < wargc; i++)
1329     free (split_u8argv[i]);
1330   free (split_u8argv);
1331   return GNUNET_OK;
1332 #else
1333   char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1334   *u8argv = new_argv;
1335   *u8argc = argc;
1336   return GNUNET_OK;
1337 #endif
1338 }
1339
1340
1341 /**
1342  * Parse the given port policy.  The format is
1343  * "[!]SPORT[-DPORT]".
1344  *
1345  * @param port_policy string to parse
1346  * @param pp policy to fill in
1347  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1348  *         @a port_policy is malformed
1349  */
1350 static int
1351 parse_port_policy (const char *port_policy,
1352                    struct GNUNET_STRINGS_PortPolicy *pp)
1353 {
1354   const char *pos;
1355   int s;
1356   int e;
1357   char eol[2];
1358
1359   pos = port_policy;
1360   if ('!' == *pos)
1361   {
1362     pp->negate_portrange = GNUNET_YES;
1363     pos++;
1364   }
1365   if (2 == sscanf (pos,
1366                    "%u-%u%1s",
1367                    &s, &e, eol))
1368   {
1369     if ( (0 == s) ||
1370          (s > 0xFFFF) ||
1371          (e < s) ||
1372          (e > 0xFFFF) )
1373     {
1374       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1375                   _("Port not in range\n"));
1376       return GNUNET_SYSERR;
1377     }
1378     pp->start_port = (uint16_t) s;
1379     pp->end_port = (uint16_t) e;
1380     return GNUNET_OK;
1381   }
1382   if (1 == sscanf (pos,
1383                    "%u%1s",
1384                    &s,
1385                    eol))
1386   {
1387     if ( (0 == s) ||
1388          (s > 0xFFFF) )
1389     {
1390       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1391                   _("Port not in range\n"));
1392       return GNUNET_SYSERR;
1393     }
1394
1395     pp->start_port = (uint16_t) s;
1396     pp->end_port = (uint16_t) s;
1397     return GNUNET_OK;
1398   }
1399   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1400               _("Malformed port policy `%s'\n"),
1401               port_policy);
1402   return GNUNET_SYSERR;
1403 }
1404
1405
1406 /**
1407  * Parse an IPv4 network policy. The argument specifies a list of
1408  * subnets. The format is
1409  * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1410  * be terminated with a semicolon). The network must be given in
1411  * dotted-decimal notation. The netmask can be given in CIDR notation
1412  * (/16) or in dotted-decimal (/255.255.0.0).
1413  *
1414  * @param routeListX a string specifying the IPv4 subnets
1415  * @return the converted list, terminated with all zeros;
1416  *         NULL if the synatx is flawed
1417  */
1418 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1419 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1420 {
1421   unsigned int count;
1422   unsigned int i;
1423   unsigned int j;
1424   unsigned int len;
1425   int cnt;
1426   unsigned int pos;
1427   unsigned int temps[8];
1428   int slash;
1429   struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1430   int colon;
1431   int end;
1432   char *routeList;
1433
1434   if (NULL == routeListX)
1435     return NULL;
1436   len = strlen (routeListX);
1437   if (0 == len)
1438     return NULL;
1439   routeList = GNUNET_strdup (routeListX);
1440   count = 0;
1441   for (i = 0; i < len; i++)
1442     if (routeList[i] == ';')
1443       count++;
1444   result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1445   i = 0;
1446   pos = 0;
1447   while (i < count)
1448   {
1449     for (colon = pos; ':' != routeList[colon]; colon++)
1450       if ( (';' == routeList[colon]) ||
1451            ('\0' == routeList[colon]) )
1452         break;
1453     end = colon;
1454     for (end = colon; ';' != routeList[end]; end++)
1455       if ('\0' == routeList[end])
1456         break;
1457     if ('\0' == routeList[end])
1458       break;
1459     routeList[end] = '\0';
1460     if (':' == routeList[colon])
1461     {
1462       routeList[colon] = '\0';
1463       if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1464                                           &result[i].pp))
1465         break;
1466     }
1467     cnt =
1468         SSCANF (&routeList[pos],
1469                 "%u.%u.%u.%u/%u.%u.%u.%u",
1470                 &temps[0],
1471                 &temps[1],
1472                 &temps[2],
1473                 &temps[3],
1474                 &temps[4],
1475                 &temps[5],
1476                 &temps[6],
1477                 &temps[7]);
1478     if (8 == cnt)
1479     {
1480       for (j = 0; j < 8; j++)
1481         if (temps[j] > 0xFF)
1482         {
1483           LOG (GNUNET_ERROR_TYPE_WARNING,
1484                _("Invalid format for IP: `%s'\n"),
1485                &routeList[pos]);
1486           GNUNET_free (result);
1487           GNUNET_free (routeList);
1488           return NULL;
1489         }
1490       result[i].network.s_addr =
1491           htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1492                  temps[3]);
1493       result[i].netmask.s_addr =
1494           htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1495                  temps[7]);
1496       pos = end + 1;
1497       i++;
1498       continue;
1499     }
1500     /* try second notation */
1501     cnt =
1502         SSCANF (&routeList[pos],
1503                 "%u.%u.%u.%u/%u",
1504                 &temps[0],
1505                 &temps[1],
1506                 &temps[2],
1507                 &temps[3],
1508                 &slash);
1509     if (5 == cnt)
1510     {
1511       for (j = 0; j < 4; j++)
1512         if (temps[j] > 0xFF)
1513         {
1514           LOG (GNUNET_ERROR_TYPE_WARNING,
1515                _("Invalid format for IP: `%s'\n"),
1516                &routeList[pos]);
1517           GNUNET_free (result);
1518           GNUNET_free (routeList);
1519           return NULL;
1520         }
1521       result[i].network.s_addr =
1522           htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1523                  temps[3]);
1524       if ((slash <= 32) && (slash >= 0))
1525       {
1526         result[i].netmask.s_addr = 0;
1527         while (slash > 0)
1528         {
1529           result[i].netmask.s_addr =
1530               (result[i].netmask.s_addr >> 1) + 0x80000000;
1531           slash--;
1532         }
1533         result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1534         pos = end + 1;
1535         i++;
1536         continue;
1537       }
1538       else
1539       {
1540         LOG (GNUNET_ERROR_TYPE_WARNING,
1541              _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1542              slash);
1543         GNUNET_free (result);
1544           GNUNET_free (routeList);
1545         return NULL;            /* error */
1546       }
1547     }
1548     /* try third notation */
1549     slash = 32;
1550     cnt =
1551         SSCANF (&routeList[pos],
1552                 "%u.%u.%u.%u",
1553                 &temps[0],
1554                 &temps[1],
1555                 &temps[2],
1556                 &temps[3]);
1557     if (4 == cnt)
1558     {
1559       for (j = 0; j < 4; j++)
1560         if (temps[j] > 0xFF)
1561         {
1562           LOG (GNUNET_ERROR_TYPE_WARNING,
1563                _("Invalid format for IP: `%s'\n"),
1564                &routeList[pos]);
1565           GNUNET_free (result);
1566           GNUNET_free (routeList);
1567           return NULL;
1568         }
1569       result[i].network.s_addr =
1570           htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1571                  temps[3]);
1572       result[i].netmask.s_addr = 0;
1573       while (slash > 0)
1574       {
1575         result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1576         slash--;
1577       }
1578       result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1579       pos = end + 1;
1580       i++;
1581       continue;
1582     }
1583     LOG (GNUNET_ERROR_TYPE_WARNING,
1584          _("Invalid format for IP: `%s'\n"),
1585          &routeList[pos]);
1586     GNUNET_free (result);
1587     GNUNET_free (routeList);
1588     return NULL;                /* error */
1589   }
1590   if (pos < strlen (routeList))
1591   {
1592     LOG (GNUNET_ERROR_TYPE_WARNING,
1593          _("Invalid format: `%s'\n"),
1594          &routeListX[pos]);
1595     GNUNET_free (result);
1596     GNUNET_free (routeList);
1597     return NULL;                /* oops */
1598   }
1599   GNUNET_free (routeList);
1600   return result;                /* ok */
1601 }
1602
1603
1604 /**
1605  * Parse an IPv6 network policy. The argument specifies a list of
1606  * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1607  * (no whitespace, must be terminated with a semicolon). The network
1608  * must be given in colon-hex notation.  The netmask must be given in
1609  * CIDR notation (/16) or can be omitted to specify a single host.
1610  * Note that the netmask is mandatory if ports are specified.
1611  *
1612  * @param routeListX a string specifying the policy
1613  * @return the converted list, 0-terminated, NULL if the synatx is flawed
1614  */
1615 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1616 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1617 {
1618   unsigned int count;
1619   unsigned int i;
1620   unsigned int len;
1621   unsigned int pos;
1622   int start;
1623   int slash;
1624   int ret;
1625   char *routeList;
1626   struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1627   unsigned int bits;
1628   unsigned int off;
1629   int save;
1630   int colon;
1631
1632   if (NULL == routeListX)
1633     return NULL;
1634   len = strlen (routeListX);
1635   if (0 == len)
1636     return NULL;
1637   routeList = GNUNET_strdup (routeListX);
1638   count = 0;
1639   for (i = 0; i < len; i++)
1640     if (';' == routeList[i])
1641       count++;
1642   if (';' != routeList[len - 1])
1643   {
1644     LOG (GNUNET_ERROR_TYPE_WARNING,
1645          _("Invalid network notation (does not end with ';': `%s')\n"),
1646          routeList);
1647     GNUNET_free (routeList);
1648     return NULL;
1649   }
1650
1651   result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1652   i = 0;
1653   pos = 0;
1654   while (i < count)
1655   {
1656     start = pos;
1657     while (';' != routeList[pos])
1658       pos++;
1659     slash = pos;
1660     while ((slash >= start) && (routeList[slash] != '/'))
1661       slash--;
1662
1663     if (slash < start)
1664     {
1665       memset (&result[i].netmask,
1666               0xFF,
1667               sizeof (struct in6_addr));
1668       slash = pos;
1669     }
1670     else
1671     {
1672       routeList[pos] = '\0';
1673       for (colon = pos; ':' != routeList[colon]; colon--)
1674         if ('/' == routeList[colon])
1675           break;
1676       if (':' == routeList[colon])
1677       {
1678         routeList[colon] = '\0';
1679         if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1680                                             &result[i].pp))
1681         {
1682           GNUNET_free (result);
1683           GNUNET_free (routeList);
1684           return NULL;
1685         }
1686       }
1687       ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1688       if (ret <= 0)
1689       {
1690         save = errno;
1691         if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1692         {
1693           if (0 == ret)
1694             LOG (GNUNET_ERROR_TYPE_WARNING,
1695                  _("Wrong format `%s' for netmask\n"),
1696                  &routeList[slash + 1]);
1697           else
1698           {
1699             errno = save;
1700             LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1701           }
1702           GNUNET_free (result);
1703           GNUNET_free (routeList);
1704           return NULL;
1705         }
1706         off = 0;
1707         while (bits > 8)
1708         {
1709           result[i].netmask.s6_addr[off++] = 0xFF;
1710           bits -= 8;
1711         }
1712         while (bits > 0)
1713         {
1714           result[i].netmask.s6_addr[off] =
1715               (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1716           bits--;
1717         }
1718       }
1719     }
1720     routeList[slash] = '\0';
1721     ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1722     if (ret <= 0)
1723     {
1724       if (0 == ret)
1725         LOG (GNUNET_ERROR_TYPE_WARNING,
1726              _("Wrong format `%s' for network\n"),
1727              &routeList[slash + 1]);
1728       else
1729         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1730                       "inet_pton");
1731       GNUNET_free (result);
1732       GNUNET_free (routeList);
1733       return NULL;
1734     }
1735     pos++;
1736     i++;
1737   }
1738   GNUNET_free (routeList);
1739   return result;
1740 }
1741
1742
1743 /* end of strings.c */