- test for external iterator
[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_common.h"
33 #include "gnunet_strings_lib.h"
34 #include <unicase.h>
35 #include <unistr.h>
36 #include <uniconv.h>
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
39
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
41
42
43 /**
44  * Fill a buffer of the given size with
45  * count 0-terminated strings (given as varargs).
46  * If "buffer" is NULL, only compute the amount of
47  * space required (sum of "strlen(arg)+1").
48  *
49  * Unlike using "snprintf" with "%s", this function
50  * will add 0-terminators after each string.  The
51  * "GNUNET_string_buffer_tokenize" function can be
52  * used to parse the buffer back into individual
53  * strings.
54  *
55  * @param buffer the buffer to fill with strings, can
56  *               be NULL in which case only the necessary
57  *               amount of space will be calculated
58  * @param size number of bytes available in buffer
59  * @param count number of strings that follow
60  * @param ... count 0-terminated strings to copy to buffer
61  * @return number of bytes written to the buffer
62  *         (or number of bytes that would have been written)
63  */
64 size_t
65 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
66 {
67   size_t needed;
68   size_t slen;
69   const char *s;
70   va_list ap;
71
72   needed = 0;
73   va_start (ap, count);
74   while (count > 0)
75   {
76     s = va_arg (ap, const char *);
77
78     slen = strlen (s) + 1;
79     if (buffer != NULL)
80     {
81       GNUNET_assert (needed + slen <= size);
82       memcpy (&buffer[needed], s, slen);
83     }
84     needed += slen;
85     count--;
86   }
87   va_end (ap);
88   return needed;
89 }
90
91
92 /**
93  * Given a buffer of a given size, find "count"
94  * 0-terminated strings in the buffer and assign
95  * the count (varargs) of type "const char**" to the
96  * locations of the respective strings in the
97  * buffer.
98  *
99  * @param buffer the buffer to parse
100  * @param size size of the buffer
101  * @param count number of strings to locate
102  * @return offset of the character after the last 0-termination
103  *         in the buffer, or 0 on error.
104  */
105 unsigned int
106 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
107                                 unsigned int count, ...)
108 {
109   unsigned int start;
110   unsigned int needed;
111   const char **r;
112   va_list ap;
113
114   needed = 0;
115   va_start (ap, count);
116   while (count > 0)
117   {
118     r = va_arg (ap, const char **);
119
120     start = needed;
121     while ((needed < size) && (buffer[needed] != '\0'))
122       needed++;
123     if (needed == size)
124     {
125       va_end (ap);
126       return 0;                 /* error */
127     }
128     *r = &buffer[start];
129     needed++;                   /* skip 0-termination */
130     count--;
131   }
132   va_end (ap);
133   return needed;
134 }
135
136
137 /**
138  * Convert a given filesize into a fancy human-readable format.
139  *
140  * @param size number of bytes
141  * @return fancy representation of the size (possibly rounded) for humans
142  */
143 char *
144 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
145 {
146   const char *unit = _( /* size unit */ "b");
147   char *ret;
148
149   if (size > 5 * 1024)
150   {
151     size = size / 1024;
152     unit = "KiB";
153     if (size > 5 * 1024)
154     {
155       size = size / 1024;
156       unit = "MiB";
157       if (size > 5 * 1024)
158       {
159         size = size / 1024;
160         unit = "GiB";
161         if (size > 5 * 1024)
162         {
163           size = size / 1024;
164           unit = "TiB";
165         }
166       }
167     }
168   }
169   ret = GNUNET_malloc (32);
170   GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
171   return ret;
172 }
173
174
175 /**
176  * Unit conversion table entry for 'convert_with_table'.
177  */
178 struct ConversionTable
179 {
180   /**
181    * Name of the unit (or NULL for end of table).
182    */
183   const char *name;
184
185   /**
186    * Factor to apply for this unit.
187    */
188   unsigned long long value;
189 };
190
191
192 /**
193  * Convert a string of the form "4 X 5 Y" into a numeric value
194  * by interpreting "X" and "Y" as units and then multiplying
195  * the numbers with the values associated with the respective
196  * unit from the conversion table.
197  *
198  * @param input input string to parse
199  * @param table table with the conversion of unit names to numbers
200  * @param output where to store the result
201  * @return GNUNET_OK on success, GNUNET_SYSERR on error
202  */
203 static int
204 convert_with_table (const char *input,
205                     const struct ConversionTable *table,
206                     unsigned long long *output)
207 {
208   unsigned long long ret;
209   char *in;
210   const char *tok;
211   unsigned long long last;
212   unsigned int i;
213
214   ret = 0;
215   last = 0;
216   in = GNUNET_strdup (input);
217   for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
218   {
219     do
220     {
221       i = 0;
222       while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
223         i++;
224       if (table[i].name != NULL)
225       {
226         last *= table[i].value;
227         break; /* next tok */
228       }
229       else
230       {
231         char *endptr;
232         ret += last;
233         errno = 0;
234         last = strtoull (tok, &endptr, 10);
235         if ((0 != errno) || (endptr == tok))
236         {
237           GNUNET_free (in);
238           return GNUNET_SYSERR;   /* expected number */
239         }
240         if ('\0' == endptr[0])
241           break; /* next tok */
242         else
243           tok = endptr; /* and re-check (handles times like "10s") */
244       }
245     } while (GNUNET_YES);
246   }
247   ret += last;
248   *output = ret;
249   GNUNET_free (in);
250   return GNUNET_OK;
251 }
252
253
254 /**
255  * Convert a given fancy human-readable size to bytes.
256  *
257  * @param fancy_size human readable string (i.e. 1 MB)
258  * @param size set to the size in bytes
259  * @return GNUNET_OK on success, GNUNET_SYSERR on error
260  */
261 int
262 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
263                                     unsigned long long *size)
264 {
265   static const struct ConversionTable table[] =
266   {
267     { "B", 1},
268     { "KiB", 1024},
269     { "kB", 1000},
270     { "MiB", 1024 * 1024},
271     { "MB", 1000 * 1000},
272     { "GiB", 1024 * 1024 * 1024},
273     { "GB", 1000 * 1000 * 1000},
274     { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
275     { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
276     { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
277     { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
278     { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
279     { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
280     { NULL, 0}
281   };
282
283   return convert_with_table (fancy_size,
284                              table,
285                              size);
286 }
287
288
289 /**
290  * Convert a given fancy human-readable time to our internal
291  * representation.
292  *
293  * @param fancy_time human readable string (i.e. 1 minute)
294  * @param rtime set to the relative time
295  * @return GNUNET_OK on success, GNUNET_SYSERR on error
296  */
297 int
298 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
299                                        struct GNUNET_TIME_Relative *rtime)
300 {
301   static const struct ConversionTable table[] =
302   {
303     { "us", 1},
304     { "ms", 1000 },
305     { "s", 1000 * 1000LL },
306     { "\"", 1000  * 1000LL },
307     { "m", 60 * 1000  * 1000LL},
308     { "min", 60 * 1000  * 1000LL},
309     { "minutes", 60 * 1000  * 1000LL},
310     { "'", 60 * 1000  * 1000LL},
311     { "h", 60 * 60 * 1000  * 1000LL},
312     { "d", 24 * 60 * 60 * 1000LL * 1000LL},
313     { "day", 24 * 60 * 60 * 1000LL * 1000LL},
314     { "days", 24 * 60 * 60 * 1000LL * 1000LL},
315     { "a", 31536000000000LL /* year */ },
316     { NULL, 0}
317   };
318   int ret;
319   unsigned long long val;
320
321   if (0 == strcasecmp ("forever", fancy_time))
322   {
323     *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
324     return GNUNET_OK;
325   }
326   ret = convert_with_table (fancy_time,
327                             table,
328                             &val);
329   rtime->rel_value_us = (uint64_t) val;
330   return ret;
331 }
332
333
334 /**
335  * Convert a given fancy human-readable time to our internal
336  * representation.
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 #endif
371   return GNUNET_OK;
372 }
373
374
375 /**
376  * Convert the len characters long character sequence
377  * given in input that is in the given input charset
378  * to a string in given output charset.
379  * @return the converted string (0-terminated),
380  *  if conversion fails, a copy of the orignal
381  *  string is returned.
382  */
383 char *
384 GNUNET_STRINGS_conv (const char *input,
385                      size_t len, 
386                      const char *input_charset, 
387                      const char *output_charset)
388 {
389   char *ret;
390   uint8_t *u8_string;
391   char *encoded_string;
392   size_t u8_string_length;
393   size_t encoded_string_length;
394
395   u8_string = u8_conv_from_encoding (input_charset, 
396                                      iconveh_error, 
397                                      input, len, 
398                                      NULL, NULL, 
399                                      &u8_string_length);
400   if (NULL == u8_string)
401   {
402     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
403     goto fail;
404   }
405   if (0 == strcmp (output_charset, "UTF-8"))
406   {
407     ret = GNUNET_malloc (u8_string_length + 1);
408     memcpy (ret, u8_string, u8_string_length);
409     ret[u8_string_length] = '\0';
410     free (u8_string);
411     return ret;
412   }
413   encoded_string = u8_conv_to_encoding (output_charset, iconveh_error, 
414                                         u8_string, u8_string_length, 
415                                         NULL, NULL, 
416                                         &encoded_string_length);
417   free (u8_string);
418   if (NULL == encoded_string)
419   {
420     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
421     goto fail;
422   }
423   ret = GNUNET_malloc (encoded_string_length + 1);
424   memcpy (ret, encoded_string, encoded_string_length);
425   ret[encoded_string_length] = '\0';
426   free (encoded_string);
427   return ret;
428  fail:
429   LOG (GNUNET_ERROR_TYPE_WARNING, _("Character sets requested were `%s'->`%s'\n"),
430        "UTF-8", output_charset);
431   ret = GNUNET_malloc (len + 1);
432   memcpy (ret, input, len);
433   ret[len] = '\0';
434   return ret;
435 }
436
437
438 /**
439  * Convert the len characters long character sequence
440  * given in input that is in the given charset
441  * to UTF-8.
442  * @return the converted string (0-terminated),
443  *  if conversion fails, a copy of the orignal
444  *  string is returned.
445  */
446 char *
447 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
448 {
449   return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
450 }
451
452
453 /**
454  * Convert the len bytes-long UTF-8 string
455  * given in input to the given charset.
456  *
457  * @return the converted string (0-terminated),
458  *  if conversion fails, a copy of the orignal
459  *  string is returned.
460  */
461 char *
462 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
463 {
464   return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
465 }
466
467
468 /**
469  * Convert the utf-8 input string to lowercase
470  * Output needs to be allocated appropriately
471  *
472  * @param input input string
473  * @param output output buffer
474  */
475 void
476 GNUNET_STRINGS_utf8_tolower(const char* input, char** output)
477 {
478   uint8_t *tmp_in;
479   size_t len;
480
481   tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
482                        NULL, UNINORM_NFD, NULL, &len);
483   memcpy(*output, tmp_in, len);
484   (*output)[len] = '\0';
485   free(tmp_in);
486 }
487
488
489 /**
490  * Convert the utf-8 input string to uppercase
491  * Output needs to be allocated appropriately
492  *
493  * @param input input string
494  * @param output output buffer
495  */
496 void
497 GNUNET_STRINGS_utf8_toupper(const char* input, char** output)
498 {
499   uint8_t *tmp_in;
500   size_t len;
501
502   tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
503                        NULL, UNINORM_NFD, NULL, &len);
504   memcpy(*output, tmp_in, len);
505   (*output)[len] = '\0';
506   free(tmp_in);
507 }
508
509
510 /**
511  * Complete filename (a la shell) from abbrevition.
512  * @param fil the name of the file, may contain ~/ or
513  *        be relative to the current directory
514  * @returns the full file name,
515  *          NULL is returned on error
516  */
517 char *
518 GNUNET_STRINGS_filename_expand (const char *fil)
519 {
520   char *buffer;
521 #ifndef MINGW
522   size_t len;
523   size_t n;
524   char *fm;
525   const char *fil_ptr;
526 #else
527   char *fn;
528   long lRet;
529 #endif
530
531   if (fil == NULL)
532     return NULL;
533
534 #ifndef MINGW
535   if (fil[0] == DIR_SEPARATOR)
536     /* absolute path, just copy */
537     return GNUNET_strdup (fil);
538   if (fil[0] == '~')
539   {
540     fm = getenv ("HOME");
541     if (fm == NULL)
542     {
543       LOG (GNUNET_ERROR_TYPE_WARNING,
544            _("Failed to expand `$HOME': environment variable `HOME' not set"));
545       return NULL;
546     }
547     fm = GNUNET_strdup (fm);
548     /* do not copy '~' */
549     fil_ptr = fil + 1;
550
551     /* skip over dir seperator to be consistent */
552     if (fil_ptr[0] == DIR_SEPARATOR)
553       fil_ptr++;
554   }
555   else
556   {
557     /* relative path */
558     fil_ptr = fil;
559     len = 512;
560     fm = NULL;
561     while (1)
562     {
563       buffer = GNUNET_malloc (len);
564       if (getcwd (buffer, len) != NULL)
565       {
566         fm = buffer;
567         break;
568       }
569       if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
570       {
571         len *= 2;
572         GNUNET_free (buffer);
573         continue;
574       }
575       GNUNET_free (buffer);
576       break;
577     }
578     if (fm == NULL)
579     {
580       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
581       buffer = getenv ("PWD");  /* alternative */
582       if (buffer != NULL)
583         fm = GNUNET_strdup (buffer);
584     }
585     if (fm == NULL)
586       fm = GNUNET_strdup ("./");        /* give up */
587   }
588   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
589   buffer = GNUNET_malloc (n);
590   GNUNET_snprintf (buffer, n, "%s%s%s", fm,
591                    (fm[strlen (fm) - 1] ==
592                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
593   GNUNET_free (fm);
594   return buffer;
595 #else
596   fn = GNUNET_malloc (MAX_PATH + 1);
597
598   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
599   {
600     SetErrnoFromWinError (lRet);
601     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
602     return NULL;
603   }
604   /* is the path relative? */
605   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
606   {
607     char szCurDir[MAX_PATH + 1];
608
609     lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
610     if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
611     {
612       SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
613       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
614       return NULL;
615     }
616     buffer = GNUNET_malloc (MAX_PATH + 1);
617     GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
618     GNUNET_free (fn);
619     fn = buffer;
620   }
621
622   return fn;
623 #endif
624 }
625
626
627 /**
628  * Give relative time in human-readable fancy format.
629  * This is one of the very few calls in the entire API that is
630  * NOT reentrant!
631  *
632  * @param delta time in milli seconds
633  * @param do_round are we allowed to round a bit?
634  * @return time as human-readable string
635  */
636 const char *
637 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
638                                         int do_round)
639 {
640   static char buf[128];
641   const char *unit = _( /* time unit */ "µs");
642   uint64_t dval = delta.rel_value_us;
643
644   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
645     return _("forever");
646   if (0 == delta.rel_value_us)
647     return _("0 ms");
648   if ( ( (GNUNET_YES == do_round) && 
649          (dval > 5 * 1000) ) || 
650        (0 == (dval % 1000) ))
651   {
652     dval = dval / 1000;
653     unit = _( /* time unit */ "ms");
654     if ( ( (GNUNET_YES == do_round) && 
655            (dval > 5 * 1000) ) || 
656          (0 == (dval % 1000) ))
657     {
658       dval = dval / 1000;
659       unit = _( /* time unit */ "s");
660       if ( ( (GNUNET_YES == do_round) &&
661              (dval > 5 * 60) ) ||
662            (0 == (dval % 60) ) )
663       {
664         dval = dval / 60;
665         unit = _( /* time unit */ "m");
666         if ( ( (GNUNET_YES == do_round) &&
667                (dval > 5 * 60) ) || 
668              (0 == (dval % 60) ))
669         {
670           dval = dval / 60;
671           unit = _( /* time unit */ "h");
672           if ( ( (GNUNET_YES == do_round) &&
673                  (dval > 5 * 24) ) ||
674                (0 == (dval % 24)) )
675           {
676             dval = dval / 24;
677             if (1 == dval)
678               unit = _( /* time unit */ "day");
679             else
680               unit = _( /* time unit */ "days");
681           }
682         }
683       }
684     }
685   }
686   GNUNET_snprintf (buf, sizeof (buf),
687                    "%llu %s", dval, unit);
688   return buf;
689 }
690
691
692 /**
693  * "asctime", except for GNUnet time.
694  * This is one of the very few calls in the entire API that is
695  * NOT reentrant!
696  *
697  * @param t time to convert
698  * @return absolute time in human-readable format
699  */
700 const char *
701 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
702 {
703   static char buf[255];
704   time_t tt;
705   struct tm *tp;
706
707   if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
708     return _("end of time");
709   tt = t.abs_value_us / 1000LL / 1000LL;
710   tp = gmtime (&tt);
711   strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
712   return buf;
713 }
714
715
716 /**
717  * "man basename"
718  * Returns a pointer to a part of filename (allocates nothing)!
719  *
720  * @param filename filename to extract basename from
721  * @return short (base) name of the file (that is, everything following the
722  *         last directory separator in filename. If filename ends with a
723  *         directory separator, the result will be a zero-length string.
724  *         If filename has no directory separators, the result is filename
725  *         itself.
726  */
727 const char *
728 GNUNET_STRINGS_get_short_name (const char *filename)
729 {
730   const char *short_fn = filename;
731   const char *ss;
732   while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
733       && (ss[1] != '\0'))
734     short_fn = 1 + ss;
735   return short_fn;
736 }
737
738
739 /**
740  * Get the numeric value corresponding to a character.
741  *
742  * @param a a character
743  * @return corresponding numeric value
744  */
745 static unsigned int
746 getValue__ (unsigned char a)
747 {
748   if ((a >= '0') && (a <= '9'))
749     return a - '0';
750   if ((a >= 'A') && (a <= 'V'))
751     return (a - 'A' + 10);
752   return -1;
753 }
754
755
756 /**
757  * Convert binary data to ASCII encoding.  The ASCII encoding is rather
758  * GNUnet specific.  It was chosen such that it only uses characters
759  * in [0-9A-V], can be produced without complex arithmetics and uses a
760  * small number of characters.  
761  * Does not append 0-terminator, but returns a pointer to the place where
762  * it should be placed, if needed.
763  *
764  * @param data data to encode
765  * @param size size of data (in bytes)
766  * @param out buffer to fill
767  * @param out_size size of the buffer. Must be large enough to hold
768  * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
769  * @return pointer to the next byte in 'out' or NULL on error.
770  */
771 char *
772 GNUNET_STRINGS_data_to_string (const void *data, size_t size, char *out, size_t out_size)
773 {
774   /**
775    * 32 characters for encoding 
776    */
777   static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
778   unsigned int wpos;
779   unsigned int rpos;
780   unsigned int bits;
781   unsigned int vbit;
782   const unsigned char *udata;
783
784   GNUNET_assert (data != NULL);
785   GNUNET_assert (out != NULL);
786   udata = data;
787   if (out_size < (((size*8) + ((size*8) % 5)) % 5))
788   {
789     GNUNET_break (0);
790     return NULL;
791   }
792   vbit = 0;
793   wpos = 0;
794   rpos = 0;
795   bits = 0;
796   while ((rpos < size) || (vbit > 0))
797   {
798     if ((rpos < size) && (vbit < 5))
799     {
800       bits = (bits << 8) | udata[rpos++];   /* eat 8 more bits */
801       vbit += 8;
802     }
803     if (vbit < 5)
804     {
805       bits <<= (5 - vbit);      /* zero-padding */
806       GNUNET_assert (vbit == ((size * 8) % 5));
807       vbit = 5;
808     }
809     if (wpos >= out_size)
810     {
811       GNUNET_break (0);
812       return NULL;
813     }
814     out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
815     vbit -= 5;
816   }
817   GNUNET_assert (vbit == 0);
818   if (wpos < out_size)
819     out[wpos] = '\0';
820   return &out[wpos];
821 }
822
823
824 /**
825  * Convert ASCII encoding back to data
826  * out_size must match exactly the size of the data before it was encoded.
827  *
828  * @param enc the encoding
829  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
830  * @param out location where to store the decoded data
831  * @param out_size size of the output buffer
832  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
833  */
834 int
835 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
836                                void *out, size_t out_size)
837 {
838   unsigned int rpos;
839   unsigned int wpos;
840   unsigned int bits;
841   unsigned int vbit;
842   int ret;
843   int shift;
844   unsigned char *uout;
845   unsigned int encoded_len = out_size * 8;
846
847   if (0 == enclen)
848   {
849     if (0 == out_size)
850       return GNUNET_OK;
851     return GNUNET_SYSERR;
852   }
853   uout = out;
854   wpos = out_size;
855   rpos = enclen;
856   if ((encoded_len % 5) > 0)
857   {
858     vbit = encoded_len % 5; /* padding! */
859     shift = 5 - vbit;
860     bits = (ret = getValue__ (enc[--rpos])) >> (5 - (encoded_len % 5));
861   }
862   else
863   {
864     vbit = 5;
865     shift = 0;
866     bits = (ret = getValue__ (enc[--rpos]));
867   }
868   if ((encoded_len + shift) / 5 != enclen)
869     return GNUNET_SYSERR;
870   if (-1 == ret)
871     return GNUNET_SYSERR;
872   while (wpos > 0)
873   {
874     if (0 == rpos)
875     {
876       GNUNET_break (0);
877       return GNUNET_SYSERR;
878     }
879     bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
880     if (-1 == ret)
881       return GNUNET_SYSERR;
882     vbit += 5;
883     if (vbit >= 8)
884     {
885       uout[--wpos] = (unsigned char) bits;
886       bits >>= 8;
887       vbit -= 8;
888     }
889   }
890   if ( (0 != rpos) ||
891        (0 != vbit) )
892     return GNUNET_SYSERR;
893   return GNUNET_OK;
894 }
895
896
897 /**
898  * Parse a path that might be an URI.
899  *
900  * @param path path to parse. Must be NULL-terminated.
901  * @param scheme_part a pointer to 'char *' where a pointer to a string that
902  *        represents the URI scheme will be stored. Can be NULL. The string is
903  *        allocated by the function, and should be freed by GNUNET_free() when
904  *        it is no longer needed.
905  * @param path_part a pointer to 'const char *' where a pointer to the path
906  *        part of the URI will be stored. Can be NULL. Points to the same block
907  *        of memory as 'path', and thus must not be freed. Might point to '\0',
908  *        if path part is zero-length.
909  * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
910  *         an URI, '* scheme_part' and '*path_part' will remain unchanged
911  *         (if they weren't NULL).
912  */
913 int
914 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
915     const char **path_part)
916 {
917   size_t len;
918   int i, end;
919   int pp_state = 0;
920   const char *post_scheme_part = NULL;
921   len = strlen (path);
922   for (end = 0, i = 0; !end && i < len; i++)
923   {
924     switch (pp_state)
925     {
926     case 0:
927       if (path[i] == ':' && i > 0)
928       {
929         pp_state += 1;
930         continue;
931       }
932       if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
933           || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
934           || (path[i] == '.')))
935         end = 1;
936       break;
937     case 1:
938     case 2:
939       if (path[i] == '/')
940       {
941         pp_state += 1;
942         continue;
943       }
944       end = 1;
945       break;
946     case 3:
947       post_scheme_part = &path[i];
948       end = 1;
949       break;
950     default:
951       end = 1;
952     }
953   }
954   if (post_scheme_part == NULL)
955     return GNUNET_NO;
956   if (scheme_part)
957   {
958     *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
959     memcpy (*scheme_part, path, post_scheme_part - path);
960     (*scheme_part)[post_scheme_part - path] = '\0';
961   }
962   if (path_part)
963     *path_part = post_scheme_part;
964   return GNUNET_YES;
965 }
966
967
968 /**
969  * Check whether 'filename' is absolute or not, and if it's an URI
970  *
971  * @param filename filename to check
972  * @param can_be_uri GNUNET_YES to check for being URI, GNUNET_NO - to
973  *        assume it's not URI
974  * @param r_is_uri a pointer to an int that is set to GNUNET_YES if 'filename'
975  *        is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
976  *        not GNUNET_YES, *r_is_uri is set to GNUNET_NO.
977  * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
978  *        The string is allocated by the function, and should be freed with
979  *        GNUNET_free (). Can be NULL.
980  * @return GNUNET_YES if 'filename' is absolute, GNUNET_NO otherwise.
981  */
982 int
983 GNUNET_STRINGS_path_is_absolute (const char *filename, int can_be_uri,
984     int *r_is_uri, char **r_uri_scheme)
985 {
986 #if WINDOWS
987   size_t len;
988 #endif
989   const char *post_scheme_path;
990   int is_uri;
991   char * uri;
992   /* consider POSIX paths to be absolute too, even on W32,
993    * as plibc expansion will fix them for us.
994    */
995   if (filename[0] == '/')
996     return GNUNET_YES;
997   if (can_be_uri)
998   {
999     is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1000     if (r_is_uri)
1001       *r_is_uri = is_uri;
1002     if (is_uri)
1003     {
1004       if (r_uri_scheme)
1005         *r_uri_scheme = uri;
1006       else
1007         GNUNET_free_non_null (uri);
1008 #if WINDOWS
1009       len = strlen(post_scheme_path);
1010       /* Special check for file:///c:/blah
1011        * We want to parse 'c:/', not '/c:/'
1012        */
1013       if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1014         post_scheme_path = &post_scheme_path[1];
1015 #endif
1016       return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1017     }
1018   }
1019   else
1020   {
1021     if (r_is_uri)
1022       *r_is_uri = GNUNET_NO;
1023   }
1024 #if WINDOWS
1025   len = strlen (filename);
1026   if (len >= 3 &&
1027       ((filename[0] >= 'A' && filename[0] <= 'Z')
1028       || (filename[0] >= 'a' && filename[0] <= 'z'))
1029       && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1030     return GNUNET_YES;
1031 #endif
1032   return GNUNET_NO;
1033 }
1034
1035 #if MINGW
1036 #define         _IFMT           0170000 /* type of file */
1037 #define         _IFLNK          0120000 /* symbolic link */
1038 #define  S_ISLNK(m)     (((m)&_IFMT) == _IFLNK)
1039 #endif
1040
1041
1042 /**
1043  * Perform 'checks' on 'filename'
1044  * 
1045  * @param filename file to check
1046  * @param checks checks to perform
1047  * @return GNUNET_YES if all checks pass, GNUNET_NO if at least one of them
1048  *         fails, GNUNET_SYSERR when a check can't be performed
1049  */
1050 int
1051 GNUNET_STRINGS_check_filename (const char *filename,
1052                                enum GNUNET_STRINGS_FilenameCheck checks)
1053 {
1054   struct stat st;
1055   if ( (NULL == filename) || (filename[0] == '\0') )
1056     return GNUNET_SYSERR;
1057   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1058     if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1059       return GNUNET_NO;
1060   if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1061                       | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1062                       | GNUNET_STRINGS_CHECK_IS_LINK)))
1063   {
1064     if (0 != STAT (filename, &st))
1065     {
1066       if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1067         return GNUNET_NO;
1068       else
1069         return GNUNET_SYSERR;
1070     }
1071   }
1072   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1073     if (!S_ISDIR (st.st_mode))
1074       return GNUNET_NO;
1075   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1076     if (!S_ISLNK (st.st_mode))
1077       return GNUNET_NO;
1078   return GNUNET_YES;
1079 }
1080
1081
1082 /**
1083  * Tries to convert 'zt_addr' string to an IPv6 address.
1084  * The string is expected to have the format "[ABCD::01]:80".
1085  * 
1086  * @param zt_addr 0-terminated string. May be mangled by the function.
1087  * @param addrlen length of zt_addr (not counting 0-terminator).
1088  * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1089  *        then its sin6_port, sin6_family and sin6_addr are set appropriately.
1090  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1091  *         case the contents of r_buf are undefined.
1092  */
1093 int
1094 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr, 
1095                                 uint16_t addrlen,
1096                                 struct sockaddr_in6 *r_buf)
1097 {
1098   char zbuf[addrlen + 1];
1099   int ret;
1100   char *port_colon;
1101   unsigned int port;
1102
1103   if (addrlen < 6)
1104     return GNUNET_SYSERR;  
1105   memcpy (zbuf, zt_addr, addrlen);
1106   if ('[' != zbuf[0])
1107   {
1108     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1109                 _("IPv6 address did not start with `['\n"));
1110     return GNUNET_SYSERR;
1111   }
1112   zbuf[addrlen] = '\0';
1113   port_colon = strrchr (zbuf, ':');
1114   if (NULL == port_colon)
1115   {
1116     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1117                 _("IPv6 address did contain ':' to separate port number\n"));
1118     return GNUNET_SYSERR;
1119   }
1120   if (']' != *(port_colon - 1))
1121   {
1122     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1123                 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1124     return GNUNET_SYSERR;
1125   }
1126   ret = SSCANF (port_colon, ":%u", &port);
1127   if ( (1 != ret) || (port > 65535) )
1128   {
1129     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1130                 _("IPv6 address did contain a valid port number after the last ':'\n"));
1131     return GNUNET_SYSERR;
1132   }
1133   *(port_colon-1) = '\0';
1134   memset (r_buf, 0, sizeof (struct sockaddr_in6));
1135   ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1136   if (ret <= 0)
1137   {
1138     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1139                 _("Invalid IPv6 address `%s': %s\n"),
1140                 &zbuf[1],
1141                 STRERROR (errno));
1142     return GNUNET_SYSERR;
1143   }
1144   r_buf->sin6_port = htons (port);
1145   r_buf->sin6_family = AF_INET6;
1146 #if HAVE_SOCKADDR_IN_SIN_LEN
1147   r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1148 #endif
1149   return GNUNET_OK;
1150 }
1151
1152
1153 /**
1154  * Tries to convert 'zt_addr' string to an IPv4 address.
1155  * The string is expected to have the format "1.2.3.4:80".
1156  * 
1157  * @param zt_addr 0-terminated string. May be mangled by the function.
1158  * @param addrlen length of zt_addr (not counting 0-terminator).
1159  * @param r_buf a buffer to fill.
1160  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which case
1161  *         the contents of r_buf are undefined.
1162  */
1163 int
1164 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1165                                 struct sockaddr_in *r_buf)
1166 {
1167   unsigned int temps[4];
1168   unsigned int port;
1169   unsigned int cnt;
1170
1171   if (addrlen < 9)
1172     return GNUNET_SYSERR;
1173   cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1174   if (5 != cnt)
1175     return GNUNET_SYSERR;
1176   for (cnt = 0; cnt < 4; cnt++)
1177     if (temps[cnt] > 0xFF)
1178       return GNUNET_SYSERR;
1179   if (port > 65535)
1180     return GNUNET_SYSERR;
1181   r_buf->sin_family = AF_INET;
1182   r_buf->sin_port = htons (port);
1183   r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1184                                   (temps[2] << 8) + temps[3]);
1185 #if HAVE_SOCKADDR_IN_SIN_LEN
1186   r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1187 #endif
1188   return GNUNET_OK;
1189 }
1190
1191
1192 /**
1193  * Tries to convert 'addr' string to an IP (v4 or v6) address.
1194  * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1195  * 
1196  * @param addr a string, may not be 0-terminated.
1197  * @param addrlen number of bytes in addr (if addr is 0-terminated,
1198  *        0-terminator should not be counted towards addrlen).
1199  * @param r_buf a buffer to fill.
1200  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1201  *         case the contents of r_buf are undefined.
1202  */
1203 int
1204 GNUNET_STRINGS_to_address_ip (const char *addr, 
1205                               uint16_t addrlen,
1206                               struct sockaddr_storage *r_buf)
1207 {
1208   if (addr[0] == '[')
1209     return GNUNET_STRINGS_to_address_ipv6 (addr, addrlen, (struct sockaddr_in6 *) r_buf);
1210   return GNUNET_STRINGS_to_address_ipv4 (addr, addrlen, (struct sockaddr_in *) r_buf);
1211 }
1212
1213
1214 /**
1215  * Makes a copy of argv that consists of a single memory chunk that can be
1216  * freed with a single call to GNUNET_free ();
1217  */
1218 static char *const *
1219 _make_continuous_arg_copy (int argc, char *const *argv)
1220 {
1221   size_t argvsize = 0;
1222   int i;
1223   char **new_argv;
1224   char *p;
1225   for (i = 0; i < argc; i++)
1226     argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1227   new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1228   p = (char *) &new_argv[argc + 1];
1229   for (i = 0; i < argc; i++)
1230   {
1231     new_argv[i] = p;
1232     strcpy (p, argv[i]);
1233     p += strlen (argv[i]) + 1;
1234   }
1235   new_argv[argc] = NULL;
1236   return (char *const *) new_argv;
1237 }
1238
1239
1240 /**
1241  * Returns utf-8 encoded arguments.
1242  * Does nothing (returns a copy of argc and argv) on any platform
1243  * other than W32.
1244  * Returned argv has u8argv[u8argc] == NULL.
1245  * Returned argv is a single memory block, and can be freed with a single
1246  *   GNUNET_free () call.
1247  *
1248  * @param argc argc (as given by main())
1249  * @param argv argv (as given by main())
1250  * @param u8argc a location to store new argc in (though it's th same as argc)
1251  * @param u8argv a location to store new argv in
1252  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1253  */
1254 int
1255 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1256 {
1257 #if WINDOWS
1258   wchar_t *wcmd;
1259   wchar_t **wargv;
1260   int wargc;
1261   int i;
1262   char **split_u8argv;
1263
1264   wcmd = GetCommandLineW ();
1265   if (NULL == wcmd)
1266     return GNUNET_SYSERR;
1267   wargv = CommandLineToArgvW (wcmd, &wargc);
1268   if (NULL == wargv)
1269     return GNUNET_SYSERR;
1270
1271   split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1272
1273   for (i = 0; i < wargc; i++)
1274   {
1275     size_t strl;
1276     /* Hopefully it will allocate us NUL-terminated strings... */
1277     split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1278     if (split_u8argv == NULL)
1279     {
1280       int j;
1281       for (j = 0; j < i; j++)
1282         free (split_u8argv[j]);
1283       GNUNET_free (split_u8argv);
1284       LocalFree (wargv);
1285       return GNUNET_SYSERR;
1286     }
1287   }
1288
1289   *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1290   *u8argc = wargc;
1291
1292   for (i = 0; i < wargc; i++)
1293     free (split_u8argv[i]);
1294   free (split_u8argv);
1295   return GNUNET_OK;
1296 #else
1297   char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1298   *u8argv = new_argv;
1299   *u8argc = argc;
1300   return GNUNET_OK;
1301 #endif
1302 }
1303
1304 /* end of strings.c */