- fix
[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     GNUNET_assert (rpos > 0);
856     bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
857     if (-1 == ret)
858       return GNUNET_SYSERR;
859     vbit += 5;
860     if (vbit >= 8)
861     {
862       uout[--wpos] = (unsigned char) bits;
863       bits >>= 8;
864       vbit -= 8;
865     }
866   }
867   GNUNET_assert (rpos == 0);
868   GNUNET_assert (vbit == 0);
869
870   return GNUNET_OK;
871 }
872
873
874 /**
875  * Parse a path that might be an URI.
876  *
877  * @param path path to parse. Must be NULL-terminated.
878  * @param scheme_part a pointer to 'char *' where a pointer to a string that
879  *        represents the URI scheme will be stored. Can be NULL. The string is
880  *        allocated by the function, and should be freed by GNUNET_free() when
881  *        it is no longer needed.
882  * @param path_part a pointer to 'const char *' where a pointer to the path
883  *        part of the URI will be stored. Can be NULL. Points to the same block
884  *        of memory as 'path', and thus must not be freed. Might point to '\0',
885  *        if path part is zero-length.
886  * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
887  *         an URI, '* scheme_part' and '*path_part' will remain unchanged
888  *         (if they weren't NULL).
889  */
890 int
891 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
892     const char **path_part)
893 {
894   size_t len;
895   int i, end;
896   int pp_state = 0;
897   const char *post_scheme_part = NULL;
898   len = strlen (path);
899   for (end = 0, i = 0; !end && i < len; i++)
900   {
901     switch (pp_state)
902     {
903     case 0:
904       if (path[i] == ':' && i > 0)
905       {
906         pp_state += 1;
907         continue;
908       }
909       if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
910           || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
911           || (path[i] == '.')))
912         end = 1;
913       break;
914     case 1:
915     case 2:
916       if (path[i] == '/')
917       {
918         pp_state += 1;
919         continue;
920       }
921       end = 1;
922       break;
923     case 3:
924       post_scheme_part = &path[i];
925       end = 1;
926       break;
927     default:
928       end = 1;
929     }
930   }
931   if (post_scheme_part == NULL)
932     return GNUNET_NO;
933   if (scheme_part)
934   {
935     *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
936     memcpy (*scheme_part, path, post_scheme_part - path);
937     (*scheme_part)[post_scheme_part - path] = '\0';
938   }
939   if (path_part)
940     *path_part = post_scheme_part;
941   return GNUNET_YES;
942 }
943
944
945 /**
946  * Check whether 'filename' is absolute or not, and if it's an URI
947  *
948  * @param filename filename to check
949  * @param can_be_uri GNUNET_YES to check for being URI, GNUNET_NO - to
950  *        assume it's not URI
951  * @param r_is_uri a pointer to an int that is set to GNUNET_YES if 'filename'
952  *        is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
953  *        not GNUNET_YES, *r_is_uri is set to GNUNET_NO.
954  * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
955  *        The string is allocated by the function, and should be freed with
956  *        GNUNET_free (). Can be NULL.
957  * @return GNUNET_YES if 'filename' is absolute, GNUNET_NO otherwise.
958  */
959 int
960 GNUNET_STRINGS_path_is_absolute (const char *filename, int can_be_uri,
961     int *r_is_uri, char **r_uri_scheme)
962 {
963 #if WINDOWS
964   size_t len;
965 #endif
966   const char *post_scheme_path;
967   int is_uri;
968   char * uri;
969   /* consider POSIX paths to be absolute too, even on W32,
970    * as plibc expansion will fix them for us.
971    */
972   if (filename[0] == '/')
973     return GNUNET_YES;
974   if (can_be_uri)
975   {
976     is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
977     if (r_is_uri)
978       *r_is_uri = is_uri;
979     if (is_uri)
980     {
981       if (r_uri_scheme)
982         *r_uri_scheme = uri;
983       else
984         GNUNET_free_non_null (uri);
985 #if WINDOWS
986       len = strlen(post_scheme_path);
987       /* Special check for file:///c:/blah
988        * We want to parse 'c:/', not '/c:/'
989        */
990       if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
991         post_scheme_path = &post_scheme_path[1];
992 #endif
993       return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
994     }
995   }
996   else
997   {
998     if (r_is_uri)
999       *r_is_uri = GNUNET_NO;
1000   }
1001 #if WINDOWS
1002   len = strlen (filename);
1003   if (len >= 3 &&
1004       ((filename[0] >= 'A' && filename[0] <= 'Z')
1005       || (filename[0] >= 'a' && filename[0] <= 'z'))
1006       && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1007     return GNUNET_YES;
1008 #endif
1009   return GNUNET_NO;
1010 }
1011
1012 #if MINGW
1013 #define         _IFMT           0170000 /* type of file */
1014 #define         _IFLNK          0120000 /* symbolic link */
1015 #define  S_ISLNK(m)     (((m)&_IFMT) == _IFLNK)
1016 #endif
1017
1018
1019 /**
1020  * Perform 'checks' on 'filename'
1021  * 
1022  * @param filename file to check
1023  * @param checks checks to perform
1024  * @return GNUNET_YES if all checks pass, GNUNET_NO if at least one of them
1025  *         fails, GNUNET_SYSERR when a check can't be performed
1026  */
1027 int
1028 GNUNET_STRINGS_check_filename (const char *filename,
1029                                enum GNUNET_STRINGS_FilenameCheck checks)
1030 {
1031   struct stat st;
1032   if ( (NULL == filename) || (filename[0] == '\0') )
1033     return GNUNET_SYSERR;
1034   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1035     if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1036       return GNUNET_NO;
1037   if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1038                       | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1039                       | GNUNET_STRINGS_CHECK_IS_LINK)))
1040   {
1041     if (0 != STAT (filename, &st))
1042     {
1043       if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1044         return GNUNET_NO;
1045       else
1046         return GNUNET_SYSERR;
1047     }
1048   }
1049   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1050     if (!S_ISDIR (st.st_mode))
1051       return GNUNET_NO;
1052   if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1053     if (!S_ISLNK (st.st_mode))
1054       return GNUNET_NO;
1055   return GNUNET_YES;
1056 }
1057
1058
1059 /**
1060  * Tries to convert 'zt_addr' string to an IPv6 address.
1061  * The string is expected to have the format "[ABCD::01]:80".
1062  * 
1063  * @param zt_addr 0-terminated string. May be mangled by the function.
1064  * @param addrlen length of zt_addr (not counting 0-terminator).
1065  * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1066  *        then its sin6_port, sin6_family and sin6_addr are set appropriately.
1067  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1068  *         case the contents of r_buf are undefined.
1069  */
1070 int
1071 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr, 
1072                                 uint16_t addrlen,
1073                                 struct sockaddr_in6 *r_buf)
1074 {
1075   char zbuf[addrlen + 1];
1076   int ret;
1077   char *port_colon;
1078   unsigned int port;
1079
1080   if (addrlen < 6)
1081     return GNUNET_SYSERR;  
1082   memcpy (zbuf, zt_addr, addrlen);
1083   if ('[' != zbuf[0])
1084   {
1085     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1086                 _("IPv6 address did not start with `['\n"));
1087     return GNUNET_SYSERR;
1088   }
1089   zbuf[addrlen] = '\0';
1090   port_colon = strrchr (zbuf, ':');
1091   if (NULL == port_colon)
1092   {
1093     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1094                 _("IPv6 address did contain ':' to separate port number\n"));
1095     return GNUNET_SYSERR;
1096   }
1097   if (']' != *(port_colon - 1))
1098   {
1099     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1100                 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1101     return GNUNET_SYSERR;
1102   }
1103   ret = SSCANF (port_colon, ":%u", &port);
1104   if ( (1 != ret) || (port > 65535) )
1105   {
1106     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1107                 _("IPv6 address did contain a valid port number after the last ':'\n"));
1108     return GNUNET_SYSERR;
1109   }
1110   *(port_colon-1) = '\0';
1111   memset (r_buf, 0, sizeof (struct sockaddr_in6));
1112   ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1113   if (ret <= 0)
1114   {
1115     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1116                 _("Invalid IPv6 address `%s': %s\n"),
1117                 &zbuf[1],
1118                 STRERROR (errno));
1119     return GNUNET_SYSERR;
1120   }
1121   r_buf->sin6_port = htons (port);
1122   r_buf->sin6_family = AF_INET6;
1123 #if HAVE_SOCKADDR_IN_SIN_LEN
1124   r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1125 #endif
1126   return GNUNET_OK;
1127 }
1128
1129
1130 /**
1131  * Tries to convert 'zt_addr' string to an IPv4 address.
1132  * The string is expected to have the format "1.2.3.4:80".
1133  * 
1134  * @param zt_addr 0-terminated string. May be mangled by the function.
1135  * @param addrlen length of zt_addr (not counting 0-terminator).
1136  * @param r_buf a buffer to fill.
1137  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which case
1138  *         the contents of r_buf are undefined.
1139  */
1140 int
1141 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1142                                 struct sockaddr_in *r_buf)
1143 {
1144   unsigned int temps[4];
1145   unsigned int port;
1146   unsigned int cnt;
1147
1148   if (addrlen < 9)
1149     return GNUNET_SYSERR;
1150   cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1151   if (5 != cnt)
1152     return GNUNET_SYSERR;
1153   for (cnt = 0; cnt < 4; cnt++)
1154     if (temps[cnt] > 0xFF)
1155       return GNUNET_SYSERR;
1156   if (port > 65535)
1157     return GNUNET_SYSERR;
1158   r_buf->sin_family = AF_INET;
1159   r_buf->sin_port = htons (port);
1160   r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1161                                   (temps[2] << 8) + temps[3]);
1162 #if HAVE_SOCKADDR_IN_SIN_LEN
1163   r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1164 #endif
1165   return GNUNET_OK;
1166 }
1167
1168
1169 /**
1170  * Tries to convert 'addr' string to an IP (v4 or v6) address.
1171  * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1172  * 
1173  * @param addr a string, may not be 0-terminated.
1174  * @param addrlen number of bytes in addr (if addr is 0-terminated,
1175  *        0-terminator should not be counted towards addrlen).
1176  * @param r_buf a buffer to fill.
1177  * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1178  *         case the contents of r_buf are undefined.
1179  */
1180 int
1181 GNUNET_STRINGS_to_address_ip (const char *addr, 
1182                               uint16_t addrlen,
1183                               struct sockaddr_storage *r_buf)
1184 {
1185   if (addr[0] == '[')
1186     return GNUNET_STRINGS_to_address_ipv6 (addr, addrlen, (struct sockaddr_in6 *) r_buf);
1187   return GNUNET_STRINGS_to_address_ipv4 (addr, addrlen, (struct sockaddr_in *) r_buf);
1188 }
1189
1190
1191 /**
1192  * Makes a copy of argv that consists of a single memory chunk that can be
1193  * freed with a single call to GNUNET_free ();
1194  */
1195 static char *const *
1196 _make_continuous_arg_copy (int argc, char *const *argv)
1197 {
1198   size_t argvsize = 0;
1199   int i;
1200   char **new_argv;
1201   char *p;
1202   for (i = 0; i < argc; i++)
1203     argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1204   new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1205   p = (char *) &new_argv[argc + 1];
1206   for (i = 0; i < argc; i++)
1207   {
1208     new_argv[i] = p;
1209     strcpy (p, argv[i]);
1210     p += strlen (argv[i]) + 1;
1211   }
1212   new_argv[argc] = NULL;
1213   return (char *const *) new_argv;
1214 }
1215
1216
1217 /**
1218  * Returns utf-8 encoded arguments.
1219  * Does nothing (returns a copy of argc and argv) on any platform
1220  * other than W32.
1221  * Returned argv has u8argv[u8argc] == NULL.
1222  * Returned argv is a single memory block, and can be freed with a single
1223  *   GNUNET_free () call.
1224  *
1225  * @param argc argc (as given by main())
1226  * @param argv argv (as given by main())
1227  * @param u8argc a location to store new argc in (though it's th same as argc)
1228  * @param u8argv a location to store new argv in
1229  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1230  */
1231 int
1232 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1233 {
1234 #if WINDOWS
1235   wchar_t *wcmd;
1236   wchar_t **wargv;
1237   int wargc;
1238   int i;
1239   char **split_u8argv;
1240
1241   wcmd = GetCommandLineW ();
1242   if (NULL == wcmd)
1243     return GNUNET_SYSERR;
1244   wargv = CommandLineToArgvW (wcmd, &wargc);
1245   if (NULL == wargv)
1246     return GNUNET_SYSERR;
1247
1248   split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1249
1250   for (i = 0; i < wargc; i++)
1251   {
1252     size_t strl;
1253     /* Hopefully it will allocate us NUL-terminated strings... */
1254     split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1255     if (split_u8argv == NULL)
1256     {
1257       int j;
1258       for (j = 0; j < i; j++)
1259         free (split_u8argv[j]);
1260       GNUNET_free (split_u8argv);
1261       LocalFree (wargv);
1262       return GNUNET_SYSERR;
1263     }
1264   }
1265
1266   *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1267   *u8argc = wargc;
1268
1269   for (i = 0; i < wargc; i++)
1270     free (split_u8argv[i]);
1271   free (split_u8argv);
1272   return GNUNET_OK;
1273 #else
1274   char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1275   *u8argv = new_argv;
1276   *u8argc = argc;
1277   return GNUNET_OK;
1278 #endif
1279 }
1280
1281 /* end of strings.c */