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