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