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