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