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