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