-doxygen, coding conventions
[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.
336  *
337  * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
338  * @param atime set to the absolute time
339  * @return GNUNET_OK on success, GNUNET_SYSERR on error
340  */
341 int
342 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
343                                        struct GNUNET_TIME_Absolute *atime)
344 {
345   struct tm tv;
346   time_t t;
347
348   if (0 == strcasecmp ("end of time", fancy_time))
349   {
350     *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
351     return GNUNET_OK;
352   }
353   memset (&tv, 0, sizeof (tv));
354   if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
355        (NULL == strptime (fancy_time, "%c", &tv)) &&
356        (NULL == strptime (fancy_time, "%Ec", &tv)) &&
357        (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
358        (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
359        (NULL == strptime (fancy_time, "%x", &tv)) &&
360        (NULL == strptime (fancy_time, "%Ex", &tv)) &&
361        (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
362        (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
363        (NULL == strptime (fancy_time, "%Y", &tv)) )
364     return GNUNET_SYSERR;
365   t = mktime (&tv);
366   atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
367 #if LINUX
368   atime->abs_value_us -= 1000LL * 1000LL * timezone;
369 #endif
370   return GNUNET_OK;
371 }
372
373
374 /**
375  * Convert the len characters long character sequence
376  * given in input that is in the given input charset
377  * to a string in given output charset.
378  * @return the converted string (0-terminated),
379  *  if conversion fails, a copy of the orignal
380  *  string is returned.
381  */
382 char *
383 GNUNET_STRINGS_conv (const char *input,
384                      size_t len, 
385                      const char *input_charset, 
386                      const char *output_charset)
387 {
388   char *ret;
389   uint8_t *u8_string;
390   char *encoded_string;
391   size_t u8_string_length;
392   size_t encoded_string_length;
393
394   u8_string = u8_conv_from_encoding (input_charset, 
395                                      iconveh_error, 
396                                      input, len, 
397                                      NULL, NULL, 
398                                      &u8_string_length);
399   if (NULL == u8_string)
400   {
401     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
402     goto fail;
403   }
404   if (0 == strcmp (output_charset, "UTF-8"))
405   {
406     ret = GNUNET_malloc (u8_string_length + 1);
407     memcpy (ret, u8_string, u8_string_length);
408     ret[u8_string_length] = '\0';
409     free (u8_string);
410     return ret;
411   }
412   encoded_string = u8_conv_to_encoding (output_charset, iconveh_error, 
413                                         u8_string, u8_string_length, 
414                                         NULL, NULL, 
415                                         &encoded_string_length);
416   free (u8_string);
417   if (NULL == encoded_string)
418   {
419     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
420     goto fail;
421   }
422   ret = GNUNET_malloc (encoded_string_length + 1);
423   memcpy (ret, encoded_string, encoded_string_length);
424   ret[encoded_string_length] = '\0';
425   free (encoded_string);
426   return ret;
427  fail:
428   LOG (GNUNET_ERROR_TYPE_WARNING, _("Character sets requested were `%s'->`%s'\n"),
429        "UTF-8", output_charset);
430   ret = GNUNET_malloc (len + 1);
431   memcpy (ret, input, len);
432   ret[len] = '\0';
433   return ret;
434 }
435
436
437 /**
438  * Convert the len characters long character sequence
439  * given in input that is in the given charset
440  * to UTF-8.
441  * @return the converted string (0-terminated),
442  *  if conversion fails, a copy of the orignal
443  *  string is returned.
444  */
445 char *
446 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
447 {
448   return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
449 }
450
451
452 /**
453  * Convert the len bytes-long UTF-8 string
454  * given in input to the given charset.
455  *
456  * @return the converted string (0-terminated),
457  *  if conversion fails, a copy of the orignal
458  *  string is returned.
459  */
460 char *
461 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
462 {
463   return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
464 }
465
466
467 /**
468  * Convert the utf-8 input string to lowercase
469  * Output needs to be allocated appropriately
470  *
471  * @param input input string
472  * @param output output buffer
473  */
474 void
475 GNUNET_STRINGS_utf8_tolower(const char* input, char** output)
476 {
477   uint8_t *tmp_in;
478   size_t len;
479
480   tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
481                        NULL, UNINORM_NFD, NULL, &len);
482   memcpy(*output, tmp_in, len);
483   (*output)[len] = '\0';
484   free(tmp_in);
485 }
486
487
488 /**
489  * Convert the utf-8 input string to uppercase
490  * Output needs to be allocated appropriately
491  *
492  * @param input input string
493  * @param output output buffer
494  */
495 void
496 GNUNET_STRINGS_utf8_toupper(const char* input, char** output)
497 {
498   uint8_t *tmp_in;
499   size_t len;
500
501   tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
502                        NULL, UNINORM_NFD, NULL, &len);
503   memcpy(*output, tmp_in, len);
504   (*output)[len] = '\0';
505   free(tmp_in);
506 }
507
508
509 /**
510  * Complete filename (a la shell) from abbrevition.
511  * @param fil the name of the file, may contain ~/ or
512  *        be relative to the current directory
513  * @returns the full file name,
514  *          NULL is returned on error
515  */
516 char *
517 GNUNET_STRINGS_filename_expand (const char *fil)
518 {
519   char *buffer;
520 #ifndef MINGW
521   size_t len;
522   size_t n;
523   char *fm;
524   const char *fil_ptr;
525 #else
526   char *fn;
527   long lRet;
528 #endif
529
530   if (fil == NULL)
531     return NULL;
532
533 #ifndef MINGW
534   if (fil[0] == DIR_SEPARATOR)
535     /* absolute path, just copy */
536     return GNUNET_strdup (fil);
537   if (fil[0] == '~')
538   {
539     fm = getenv ("HOME");
540     if (fm == NULL)
541     {
542       LOG (GNUNET_ERROR_TYPE_WARNING,
543            _("Failed to expand `$HOME': environment variable `HOME' not set"));
544       return NULL;
545     }
546     fm = GNUNET_strdup (fm);
547     /* do not copy '~' */
548     fil_ptr = fil + 1;
549
550     /* skip over dir seperator to be consistent */
551     if (fil_ptr[0] == DIR_SEPARATOR)
552       fil_ptr++;
553   }
554   else
555   {
556     /* relative path */
557     fil_ptr = fil;
558     len = 512;
559     fm = NULL;
560     while (1)
561     {
562       buffer = GNUNET_malloc (len);
563       if (getcwd (buffer, len) != NULL)
564       {
565         fm = buffer;
566         break;
567       }
568       if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
569       {
570         len *= 2;
571         GNUNET_free (buffer);
572         continue;
573       }
574       GNUNET_free (buffer);
575       break;
576     }
577     if (fm == NULL)
578     {
579       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
580       buffer = getenv ("PWD");  /* alternative */
581       if (buffer != NULL)
582         fm = GNUNET_strdup (buffer);
583     }
584     if (fm == NULL)
585       fm = GNUNET_strdup ("./");        /* give up */
586   }
587   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
588   buffer = GNUNET_malloc (n);
589   GNUNET_snprintf (buffer, n, "%s%s%s", fm,
590                    (fm[strlen (fm) - 1] ==
591                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
592   GNUNET_free (fm);
593   return buffer;
594 #else
595   fn = GNUNET_malloc (MAX_PATH + 1);
596
597   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
598   {
599     SetErrnoFromWinError (lRet);
600     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
601     return NULL;
602   }
603   /* is the path relative? */
604   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
605   {
606     char szCurDir[MAX_PATH + 1];
607
608     lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
609     if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
610     {
611       SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
612       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
613       return NULL;
614     }
615     buffer = GNUNET_malloc (MAX_PATH + 1);
616     GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
617     GNUNET_free (fn);
618     fn = buffer;
619   }
620
621   return fn;
622 #endif
623 }
624
625
626 /**
627  * Give relative time in human-readable fancy format.
628  * This is one of the very few calls in the entire API that is
629  * NOT reentrant!
630  *
631  * @param delta time in milli seconds
632  * @param do_round are we allowed to round a bit?
633  * @return time as human-readable string
634  */
635 const char *
636 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
637                                         int do_round)
638 {
639   static char buf[128];
640   const char *unit = _( /* time unit */ "µs");
641   uint64_t dval = delta.rel_value_us;
642
643   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
644     return _("forever");
645   if (0 == delta.rel_value_us)
646     return _("0 ms");
647   if ( ( (GNUNET_YES == do_round) && 
648          (dval > 5 * 1000) ) || 
649        (0 == (dval % 1000) ))
650   {
651     dval = dval / 1000;
652     unit = _( /* time unit */ "ms");
653     if ( ( (GNUNET_YES == do_round) && 
654            (dval > 5 * 1000) ) || 
655          (0 == (dval % 1000) ))
656     {
657       dval = dval / 1000;
658       unit = _( /* time unit */ "s");
659       if ( ( (GNUNET_YES == do_round) &&
660              (dval > 5 * 60) ) ||
661            (0 == (dval % 60) ) )
662       {
663         dval = dval / 60;
664         unit = _( /* time unit */ "m");
665         if ( ( (GNUNET_YES == do_round) &&
666                (dval > 5 * 60) ) || 
667              (0 == (dval % 60) ))
668         {
669           dval = dval / 60;
670           unit = _( /* time unit */ "h");
671           if ( ( (GNUNET_YES == do_round) &&
672                  (dval > 5 * 24) ) ||
673                (0 == (dval % 24)) )
674           {
675             dval = dval / 24;
676             if (1 == dval)
677               unit = _( /* time unit */ "day");
678             else
679               unit = _( /* time unit */ "days");
680           }
681         }
682       }
683     }
684   }
685   GNUNET_snprintf (buf, sizeof (buf),
686                    "%llu %s", dval, unit);
687   return buf;
688 }
689
690
691 /**
692  * "asctime", except for GNUnet time.
693  * This is one of the very few calls in the entire API that is
694  * NOT reentrant!
695  *
696  * @param t time to convert
697  * @return absolute time in human-readable format
698  */
699 const char *
700 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
701 {
702   static char buf[255];
703   time_t tt;
704   struct tm *tp;
705
706   if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
707     return _("end of time");
708   tt = t.abs_value_us / 1000LL / 1000LL;
709   tp = gmtime (&tt);
710   strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
711   return buf;
712 }
713
714
715 /**
716  * "man basename"
717  * Returns a pointer to a part of filename (allocates nothing)!
718  *
719  * @param filename filename to extract basename from
720  * @return short (base) name of the file (that is, everything following the
721  *         last directory separator in filename. If filename ends with a
722  *         directory separator, the result will be a zero-length string.
723  *         If filename has no directory separators, the result is filename
724  *         itself.
725  */
726 const char *
727 GNUNET_STRINGS_get_short_name (const char *filename)
728 {
729   const char *short_fn = filename;
730   const char *ss;
731   while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
732       && (ss[1] != '\0'))
733     short_fn = 1 + ss;
734   return short_fn;
735 }
736
737
738 /**
739  * Get the numeric value corresponding to a character.
740  *
741  * @param a a character
742  * @return corresponding numeric value
743  */
744 static unsigned int
745 getValue__ (unsigned char a)
746 {
747   if ((a >= '0') && (a <= '9'))
748     return a - '0';
749   if ((a >= 'A') && (a <= 'V'))
750     return (a - 'A' + 10);
751   return -1;
752 }
753
754
755 /**
756  * Convert binary data to ASCII encoding.  The ASCII encoding is rather
757  * GNUnet specific.  It was chosen such that it only uses characters
758  * in [0-9A-V], can be produced without complex arithmetics and uses a
759  * small number of characters.  
760  * Does not append 0-terminator, but returns a pointer to the place where
761  * it should be placed, if needed.
762  *
763  * @param data data to encode
764  * @param size size of data (in bytes)
765  * @param out buffer to fill
766  * @param out_size size of the buffer. Must be large enough to hold
767  * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
768  * @return pointer to the next byte in 'out' or NULL on error.
769  */
770 char *
771 GNUNET_STRINGS_data_to_string (const void *data, size_t size, char *out, size_t out_size)
772 {
773   /**
774    * 32 characters for encoding 
775    */
776   static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
777   unsigned int wpos;
778   unsigned int rpos;
779   unsigned int bits;
780   unsigned int vbit;
781   const unsigned char *udata;
782
783   GNUNET_assert (data != NULL);
784   GNUNET_assert (out != NULL);
785   udata = data;
786   if (out_size < (((size*8) + ((size*8) % 5)) % 5))
787   {
788     GNUNET_break (0);
789     return NULL;
790   }
791   vbit = 0;
792   wpos = 0;
793   rpos = 0;
794   bits = 0;
795   while ((rpos < size) || (vbit > 0))
796   {
797     if ((rpos < size) && (vbit < 5))
798     {
799       bits = (bits << 8) | udata[rpos++];   /* eat 8 more bits */
800       vbit += 8;
801     }
802     if (vbit < 5)
803     {
804       bits <<= (5 - vbit);      /* zero-padding */
805       GNUNET_assert (vbit == ((size * 8) % 5));
806       vbit = 5;
807     }
808     if (wpos >= out_size)
809     {
810       GNUNET_break (0);
811       return NULL;
812     }
813     out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
814     vbit -= 5;
815   }
816   GNUNET_assert (vbit == 0);
817   if (wpos < out_size)
818     out[wpos] = '\0';
819   return &out[wpos];
820 }
821
822
823 /**
824  * Convert ASCII encoding back to data
825  * out_size must match exactly the size of the data before it was encoded.
826  *
827  * @param enc the encoding
828  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
829  * @param out location where to store the decoded data
830  * @param out_size size of the output buffer
831  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
832  */
833 int
834 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
835                                void *out, size_t out_size)
836 {
837   unsigned int rpos;
838   unsigned int wpos;
839   unsigned int bits;
840   unsigned int vbit;
841   int ret;
842   int shift;
843   unsigned char *uout;
844   unsigned int encoded_len = out_size * 8;
845
846   if (0 == enclen)
847   {
848     if (0 == out_size)
849       return GNUNET_OK;
850     return GNUNET_SYSERR;
851   }
852   uout = out;
853   wpos = out_size;
854   rpos = enclen;
855   if ((encoded_len % 5) > 0)
856   {
857     vbit = encoded_len % 5; /* padding! */
858     shift = 5 - vbit;
859     bits = (ret = getValue__ (enc[--rpos])) >> (5 - (encoded_len % 5));
860   }
861   else
862   {
863     vbit = 5;
864     shift = 0;
865     bits = (ret = getValue__ (enc[--rpos]));
866   }
867   if ((encoded_len + shift) / 5 != enclen)
868     return GNUNET_SYSERR;
869   if (-1 == ret)
870     return GNUNET_SYSERR;
871   while (wpos > 0)
872   {
873     if (0 == rpos)
874     {
875       GNUNET_break (0);
876       return GNUNET_SYSERR;
877     }
878     bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
879     if (-1 == ret)
880       return GNUNET_SYSERR;
881     vbit += 5;
882     if (vbit >= 8)
883     {
884       uout[--wpos] = (unsigned char) bits;
885       bits >>= 8;
886       vbit -= 8;
887     }
888   }
889   if ( (0 != rpos) ||
890        (0 != vbit) )
891     return GNUNET_SYSERR;
892   return GNUNET_OK;
893 }
894
895
896 /**
897  * Parse a path that might be an URI.
898  *
899  * @param path path to parse. Must be NULL-terminated.
900  * @param scheme_part a pointer to 'char *' where a pointer to a string that
901  *        represents the URI scheme will be stored. Can be NULL. The string is
902  *        allocated by the function, and should be freed by GNUNET_free() when
903  *        it is no longer needed.
904  * @param path_part a pointer to 'const char *' where a pointer to the path
905  *        part of the URI will be stored. Can be NULL. Points to the same block
906  *        of memory as 'path', and thus must not be freed. Might point to '\0',
907  *        if path part is zero-length.
908  * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
909  *         an URI, '* scheme_part' and '*path_part' will remain unchanged
910  *         (if they weren't NULL).
911  */
912 int
913 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
914     const char **path_part)
915 {
916   size_t len;
917   int i, end;
918   int pp_state = 0;
919   const char *post_scheme_part = NULL;
920   len = strlen (path);
921   for (end = 0, i = 0; !end && i < len; i++)
922   {
923     switch (pp_state)
924     {
925     case 0:
926       if (path[i] == ':' && i > 0)
927       {
928         pp_state += 1;
929         continue;
930       }
931       if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
932           || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
933           || (path[i] == '.')))
934         end = 1;
935       break;
936     case 1:
937     case 2:
938       if (path[i] == '/')
939       {
940         pp_state += 1;
941         continue;
942       }
943       end = 1;
944       break;
945     case 3:
946       post_scheme_part = &path[i];
947       end = 1;
948       break;
949     default:
950       end = 1;
951     }
952   }
953   if (post_scheme_part == NULL)
954     return GNUNET_NO;
955   if (scheme_part)
956   {
957     *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
958     memcpy (*scheme_part, path, post_scheme_part - path);
959     (*scheme_part)[post_scheme_part - path] = '\0';
960   }
961   if (path_part)
962     *path_part = post_scheme_part;
963   return GNUNET_YES;
964 }
965
966
967 /**
968  * Check whether 'filename' is absolute or not, and if it's an URI
969  *
970  * @param filename filename to check
971  * @param can_be_uri GNUNET_YES to check for being URI, GNUNET_NO - to
972  *        assume it's not URI
973  * @param r_is_uri a pointer to an int that is set to GNUNET_YES if 'filename'
974  *        is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
975  *        not GNUNET_YES, *r_is_uri is set to GNUNET_NO.
976  * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
977  *        The string is allocated by the function, and should be freed with
978  *        GNUNET_free (). Can be NULL.
979  * @return GNUNET_YES if 'filename' is absolute, GNUNET_NO otherwise.
980  */
981 int
982 GNUNET_STRINGS_path_is_absolute (const char *filename, int can_be_uri,
983     int *r_is_uri, char **r_uri_scheme)
984 {
985 #if WINDOWS
986   size_t len;
987 #endif
988   const char *post_scheme_path;
989   int is_uri;
990   char * uri;
991   /* consider POSIX paths to be absolute too, even on W32,
992    * as plibc expansion will fix them for us.
993    */
994   if (filename[0] == '/')
995     return GNUNET_YES;
996   if (can_be_uri)
997   {
998     is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
999     if (r_is_uri)
1000       *r_is_uri = is_uri;
1001     if (is_uri)
1002     {
1003       if (r_uri_scheme)
1004         *r_uri_scheme = uri;
1005       else
1006         GNUNET_free_non_null (uri);
1007 #if WINDOWS
1008       len = strlen(post_scheme_path);
1009       /* Special check for file:///c:/blah
1010        * We want to parse 'c:/', not '/c:/'
1011        */
1012       if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1013         post_scheme_path = &post_scheme_path[1];
1014 #endif
1015       return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1016     }
1017   }
1018   else
1019   {
1020     if (r_is_uri)
1021       *r_is_uri = GNUNET_NO;
1022   }
1023 #if WINDOWS
1024   len = strlen (filename);
1025   if (len >= 3 &&
1026       ((filename[0] >= 'A' && filename[0] <= 'Z')
1027       || (filename[0] >= 'a' && filename[0] <= 'z'))
1028       && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1029     return GNUNET_YES;
1030 #endif
1031   return GNUNET_NO;
1032 }
1033
1034 #if MINGW
1035 #define         _IFMT           0170000 /* type of file */
1036 #define         _IFLNK          0120000 /* symbolic link */
1037 #define  S_ISLNK(m)     (((m)&_IFMT) == _IFLNK)
1038 #endif
1039
1040
1041 /**
1042  * Perform 'checks' on 'filename'
1043  * 
1044  * @param filename file to check
1045  * @param checks checks to perform
1046  * @return GNUNET_YES if all checks pass, GNUNET_NO if at least one of them
1047  *         fails, GNUNET_SYSERR when a check can't be performed
1048  */
1049 int
1050 GNUNET_STRINGS_check_filename (const char *filename,
1051                                enum GNUNET_STRINGS_FilenameCheck checks)
1052 {
1053   struct stat st;
1054   if ( (NULL == filename) || (filename[0] == '\0') )
1055     return GNUNET_SYSERR;
1056   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1057     if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1058       return GNUNET_NO;
1059   if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1060                       | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1061                       | GNUNET_STRINGS_CHECK_IS_LINK)))
1062   {
1063     if (0 != STAT (filename, &st))
1064     {
1065       if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1066         return GNUNET_NO;
1067       else
1068         return GNUNET_SYSERR;
1069     }
1070   }
1071   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1072     if (!S_ISDIR (st.st_mode))
1073       return GNUNET_NO;
1074   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1075     if (!S_ISLNK (st.st_mode))
1076       return GNUNET_NO;
1077   return GNUNET_YES;
1078 }
1079
1080
1081 /**
1082  * Tries to convert 'zt_addr' string to an IPv6 address.
1083  * The string is expected to have the format "[ABCD::01]:80".
1084  * 
1085  * @param zt_addr 0-terminated string. May be mangled by the function.
1086  * @param addrlen length of zt_addr (not counting 0-terminator).
1087  * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1088  *        then its sin6_port, sin6_family and sin6_addr are set appropriately.
1089  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1090  *         case the contents of r_buf are undefined.
1091  */
1092 int
1093 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr, 
1094                                 uint16_t addrlen,
1095                                 struct sockaddr_in6 *r_buf)
1096 {
1097   char zbuf[addrlen + 1];
1098   int ret;
1099   char *port_colon;
1100   unsigned int port;
1101
1102   if (addrlen < 6)
1103     return GNUNET_SYSERR;  
1104   memcpy (zbuf, zt_addr, addrlen);
1105   if ('[' != zbuf[0])
1106   {
1107     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1108                 _("IPv6 address did not start with `['\n"));
1109     return GNUNET_SYSERR;
1110   }
1111   zbuf[addrlen] = '\0';
1112   port_colon = strrchr (zbuf, ':');
1113   if (NULL == port_colon)
1114   {
1115     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1116                 _("IPv6 address did contain ':' to separate port number\n"));
1117     return GNUNET_SYSERR;
1118   }
1119   if (']' != *(port_colon - 1))
1120   {
1121     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1122                 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1123     return GNUNET_SYSERR;
1124   }
1125   ret = SSCANF (port_colon, ":%u", &port);
1126   if ( (1 != ret) || (port > 65535) )
1127   {
1128     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1129                 _("IPv6 address did contain a valid port number after the last ':'\n"));
1130     return GNUNET_SYSERR;
1131   }
1132   *(port_colon-1) = '\0';
1133   memset (r_buf, 0, sizeof (struct sockaddr_in6));
1134   ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1135   if (ret <= 0)
1136   {
1137     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1138                 _("Invalid IPv6 address `%s': %s\n"),
1139                 &zbuf[1],
1140                 STRERROR (errno));
1141     return GNUNET_SYSERR;
1142   }
1143   r_buf->sin6_port = htons (port);
1144   r_buf->sin6_family = AF_INET6;
1145 #if HAVE_SOCKADDR_IN_SIN_LEN
1146   r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1147 #endif
1148   return GNUNET_OK;
1149 }
1150
1151
1152 /**
1153  * Tries to convert 'zt_addr' string to an IPv4 address.
1154  * The string is expected to have the format "1.2.3.4:80".
1155  * 
1156  * @param zt_addr 0-terminated string. May be mangled by the function.
1157  * @param addrlen length of zt_addr (not counting 0-terminator).
1158  * @param r_buf a buffer to fill.
1159  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which case
1160  *         the contents of r_buf are undefined.
1161  */
1162 int
1163 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1164                                 struct sockaddr_in *r_buf)
1165 {
1166   unsigned int temps[4];
1167   unsigned int port;
1168   unsigned int cnt;
1169
1170   if (addrlen < 9)
1171     return GNUNET_SYSERR;
1172   cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1173   if (5 != cnt)
1174     return GNUNET_SYSERR;
1175   for (cnt = 0; cnt < 4; cnt++)
1176     if (temps[cnt] > 0xFF)
1177       return GNUNET_SYSERR;
1178   if (port > 65535)
1179     return GNUNET_SYSERR;
1180   r_buf->sin_family = AF_INET;
1181   r_buf->sin_port = htons (port);
1182   r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1183                                   (temps[2] << 8) + temps[3]);
1184 #if HAVE_SOCKADDR_IN_SIN_LEN
1185   r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1186 #endif
1187   return GNUNET_OK;
1188 }
1189
1190
1191 /**
1192  * Tries to convert 'addr' string to an IP (v4 or v6) address.
1193  * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1194  * 
1195  * @param addr a string, may not be 0-terminated.
1196  * @param addrlen number of bytes in addr (if addr is 0-terminated,
1197  *        0-terminator should not be counted towards addrlen).
1198  * @param r_buf a buffer to fill.
1199  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1200  *         case the contents of r_buf are undefined.
1201  */
1202 int
1203 GNUNET_STRINGS_to_address_ip (const char *addr, 
1204                               uint16_t addrlen,
1205                               struct sockaddr_storage *r_buf)
1206 {
1207   if (addr[0] == '[')
1208     return GNUNET_STRINGS_to_address_ipv6 (addr, addrlen, (struct sockaddr_in6 *) r_buf);
1209   return GNUNET_STRINGS_to_address_ipv4 (addr, addrlen, (struct sockaddr_in *) r_buf);
1210 }
1211
1212
1213 /**
1214  * Makes a copy of argv that consists of a single memory chunk that can be
1215  * freed with a single call to GNUNET_free ();
1216  */
1217 static char *const *
1218 _make_continuous_arg_copy (int argc, char *const *argv)
1219 {
1220   size_t argvsize = 0;
1221   int i;
1222   char **new_argv;
1223   char *p;
1224   for (i = 0; i < argc; i++)
1225     argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1226   new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1227   p = (char *) &new_argv[argc + 1];
1228   for (i = 0; i < argc; i++)
1229   {
1230     new_argv[i] = p;
1231     strcpy (p, argv[i]);
1232     p += strlen (argv[i]) + 1;
1233   }
1234   new_argv[argc] = NULL;
1235   return (char *const *) new_argv;
1236 }
1237
1238
1239 /**
1240  * Returns utf-8 encoded arguments.
1241  * Does nothing (returns a copy of argc and argv) on any platform
1242  * other than W32.
1243  * Returned argv has u8argv[u8argc] == NULL.
1244  * Returned argv is a single memory block, and can be freed with a single
1245  *   GNUNET_free () call.
1246  *
1247  * @param argc argc (as given by main())
1248  * @param argv argv (as given by main())
1249  * @param u8argc a location to store new argc in (though it's th same as argc)
1250  * @param u8argv a location to store new argv in
1251  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1252  */
1253 int
1254 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1255 {
1256 #if WINDOWS
1257   wchar_t *wcmd;
1258   wchar_t **wargv;
1259   int wargc;
1260   int i;
1261   char **split_u8argv;
1262
1263   wcmd = GetCommandLineW ();
1264   if (NULL == wcmd)
1265     return GNUNET_SYSERR;
1266   wargv = CommandLineToArgvW (wcmd, &wargc);
1267   if (NULL == wargv)
1268     return GNUNET_SYSERR;
1269
1270   split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1271
1272   for (i = 0; i < wargc; i++)
1273   {
1274     size_t strl;
1275     /* Hopefully it will allocate us NUL-terminated strings... */
1276     split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1277     if (NULL == split_u8argv[i])
1278     {
1279       int j;
1280       for (j = 0; j < i; j++)
1281         free (split_u8argv[j]);
1282       GNUNET_free (split_u8argv);
1283       LocalFree (wargv);
1284       return GNUNET_SYSERR;
1285     }
1286   }
1287
1288   *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1289   *u8argc = wargc;
1290
1291   for (i = 0; i < wargc; i++)
1292     free (split_u8argv[i]);
1293   free (split_u8argv);
1294   return GNUNET_OK;
1295 #else
1296   char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1297   *u8argv = new_argv;
1298   *u8argc = argc;
1299   return GNUNET_OK;
1300 #endif
1301 }
1302
1303 /* end of strings.c */