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