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