2 This file is part of GNUnet.
3 Copyright (C) 2005-2013 Christian Grothoff (and other contributing authors)
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 3, or (at your
8 option) any later version.
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.
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.
22 * @file util/strings.c
23 * @brief string functions
25 * @author Christian Grothoff
32 #include "gnunet_util_lib.h"
37 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
39 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
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").
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
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)
64 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
75 s = va_arg (ap, const char *);
77 slen = strlen (s) + 1;
80 GNUNET_assert (needed + slen <= size);
81 memcpy (&buffer[needed], s, slen);
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
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.
105 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
106 unsigned int count, ...)
114 va_start (ap, count);
117 r = va_arg (ap, const char **);
120 while ((needed < size) && (buffer[needed] != '\0'))
125 return 0; /* error */
128 needed++; /* skip 0-termination */
137 * Convert a given filesize into a fancy human-readable format.
139 * @param size number of bytes
140 * @return fancy representation of the size (possibly rounded) for humans
143 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
145 const char *unit = _( /* size unit */ "b");
168 ret = GNUNET_malloc (32);
169 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
175 * Unit conversion table entry for 'convert_with_table'.
177 struct ConversionTable
180 * Name of the unit (or NULL for end of table).
185 * Factor to apply for this unit.
187 unsigned long long value;
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.
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
203 convert_with_table (const char *input,
204 const struct ConversionTable *table,
205 unsigned long long *output)
207 unsigned long long ret;
210 unsigned long long last;
215 in = GNUNET_strdup (input);
216 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
221 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
223 if (table[i].name != NULL)
225 last *= table[i].value;
226 break; /* next tok */
233 last = strtoull (tok, &endptr, 10);
234 if ((0 != errno) || (endptr == tok))
237 return GNUNET_SYSERR; /* expected number */
239 if ('\0' == endptr[0])
240 break; /* next tok */
242 tok = endptr; /* and re-check (handles times like "10s") */
244 } while (GNUNET_YES);
254 * Convert a given fancy human-readable size to bytes.
256 * @param fancy_size human readable string (i.e. 1 MB)
257 * @param size set to the size in bytes
258 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
261 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
262 unsigned long long *size)
264 static const struct ConversionTable table[] =
269 { "MiB", 1024 * 1024},
270 { "MB", 1000 * 1000},
271 { "GiB", 1024 * 1024 * 1024},
272 { "GB", 1000 * 1000 * 1000},
273 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
274 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
275 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
276 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
277 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
278 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
282 return convert_with_table (fancy_size,
289 * Convert a given fancy human-readable time to our internal
292 * @param fancy_time human readable string (i.e. 1 minute)
293 * @param rtime set to the relative time
294 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
297 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
298 struct GNUNET_TIME_Relative *rtime)
300 static const struct ConversionTable table[] =
304 { "s", 1000 * 1000LL },
305 { "\"", 1000 * 1000LL },
306 { "m", 60 * 1000 * 1000LL},
307 { "min", 60 * 1000 * 1000LL},
308 { "minutes", 60 * 1000 * 1000LL},
309 { "'", 60 * 1000 * 1000LL},
310 { "h", 60 * 60 * 1000 * 1000LL},
311 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
312 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
313 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
314 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
315 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
316 { "a", 31536000000000LL /* year */ },
320 unsigned long long val;
322 if (0 == strcasecmp ("forever", fancy_time))
324 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
327 ret = convert_with_table (fancy_time,
330 rtime->rel_value_us = (uint64_t) val;
336 * Convert a given fancy human-readable time to our internal
337 * representation. The human-readable time is expected to be
338 * in local time, whereas the returned value will be in UTC.
340 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
341 * @param atime set to the absolute time
342 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
345 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
346 struct GNUNET_TIME_Absolute *atime)
351 if (0 == strcasecmp ("end of time", fancy_time))
353 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
356 memset (&tv, 0, sizeof (tv));
357 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
358 (NULL == strptime (fancy_time, "%c", &tv)) &&
359 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
360 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
361 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
362 (NULL == strptime (fancy_time, "%x", &tv)) &&
363 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
364 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
365 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
366 (NULL == strptime (fancy_time, "%Y", &tv)) )
367 return GNUNET_SYSERR;
369 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
375 * Convert the len characters long character sequence
376 * given in input that is in the given input charset
377 * to a string in given output charset.
379 * @param input input string
380 * @param len number of bytes in @a input
381 * @param input_charset character set used for @a input
382 * @param output_charset desired character set for the return value
383 * @return the converted string (0-terminated),
384 * if conversion fails, a copy of the orignal
385 * string is returned.
388 GNUNET_STRINGS_conv (const char *input,
390 const char *input_charset,
391 const char *output_charset)
395 char *encoded_string;
396 size_t u8_string_length;
397 size_t encoded_string_length;
399 u8_string = u8_conv_from_encoding (input_charset,
404 if (NULL == u8_string)
406 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
409 if (0 == strcmp (output_charset, "UTF-8"))
411 ret = GNUNET_malloc (u8_string_length + 1);
412 memcpy (ret, u8_string, u8_string_length);
413 ret[u8_string_length] = '\0';
417 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
418 u8_string, u8_string_length,
420 &encoded_string_length);
422 if (NULL == encoded_string)
424 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
427 ret = GNUNET_malloc (encoded_string_length + 1);
428 memcpy (ret, encoded_string, encoded_string_length);
429 ret[encoded_string_length] = '\0';
430 free (encoded_string);
433 LOG (GNUNET_ERROR_TYPE_WARNING,
434 _("Character sets requested were `%s'->`%s'\n"),
435 "UTF-8", output_charset);
436 ret = GNUNET_malloc (len + 1);
437 memcpy (ret, input, len);
444 * Convert the len characters long character sequence
445 * given in input that is in the given charset
448 * @param input the input string (not necessarily 0-terminated)
449 * @param len the number of bytes in the @a input
450 * @param charset character set to convert from
451 * @return the converted string (0-terminated),
452 * if conversion fails, a copy of the orignal
453 * string is returned.
456 GNUNET_STRINGS_to_utf8 (const char *input,
460 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
465 * Convert the len bytes-long UTF-8 string
466 * given in input to the given charset.
468 * @param input the input string (not necessarily 0-terminated)
469 * @param len the number of bytes in the @a input
470 * @param charset character set to convert to
471 * @return the converted string (0-terminated),
472 * if conversion fails, a copy of the orignal
473 * string is returned.
476 GNUNET_STRINGS_from_utf8 (const char *input,
480 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
485 * Convert the utf-8 input string to lowercase.
486 * Output needs to be allocated appropriately.
488 * @param input input string
489 * @param output output buffer
492 GNUNET_STRINGS_utf8_tolower (const char *input,
498 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
499 NULL, UNINORM_NFD, NULL, &len);
500 memcpy(output, tmp_in, len);
507 * Convert the utf-8 input string to uppercase.
508 * Output needs to be allocated appropriately.
510 * @param input input string
511 * @param output output buffer
514 GNUNET_STRINGS_utf8_toupper(const char *input,
520 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
521 NULL, UNINORM_NFD, NULL, &len);
522 memcpy (output, tmp_in, len);
529 * Complete filename (a la shell) from abbrevition.
530 * @param fil the name of the file, may contain ~/ or
531 * be relative to the current directory
532 * @returns the full file name,
533 * NULL is returned on error
536 GNUNET_STRINGS_filename_expand (const char *fil)
553 if (fil[0] == DIR_SEPARATOR)
554 /* absolute path, just copy */
555 return GNUNET_strdup (fil);
558 fm = getenv ("HOME");
561 LOG (GNUNET_ERROR_TYPE_WARNING,
562 _("Failed to expand `$HOME': environment variable `HOME' not set"));
565 fm = GNUNET_strdup (fm);
566 /* do not copy '~' */
569 /* skip over dir seperator to be consistent */
570 if (fil_ptr[0] == DIR_SEPARATOR)
581 buffer = GNUNET_malloc (len);
582 if (getcwd (buffer, len) != NULL)
587 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
590 GNUNET_free (buffer);
593 GNUNET_free (buffer);
598 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
599 buffer = getenv ("PWD"); /* alternative */
601 fm = GNUNET_strdup (buffer);
604 fm = GNUNET_strdup ("./"); /* give up */
606 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
607 buffer = GNUNET_malloc (n);
608 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
609 (fm[strlen (fm) - 1] ==
610 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
614 fn = GNUNET_malloc (MAX_PATH + 1);
616 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
618 SetErrnoFromWinError (lRet);
619 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
622 /* is the path relative? */
623 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
625 char szCurDir[MAX_PATH + 1];
627 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
628 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
630 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
631 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
634 buffer = GNUNET_malloc (MAX_PATH + 1);
635 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
646 * Give relative time in human-readable fancy format.
647 * This is one of the very few calls in the entire API that is
650 * @param delta time in milli seconds
651 * @param do_round are we allowed to round a bit?
652 * @return time as human-readable string
655 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
658 static char buf[128];
659 const char *unit = _( /* time unit */ "µs");
660 uint64_t dval = delta.rel_value_us;
662 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
664 if (0 == delta.rel_value_us)
666 if ( ( (GNUNET_YES == do_round) &&
667 (dval > 5 * 1000) ) ||
668 (0 == (dval % 1000) ))
671 unit = _( /* time unit */ "ms");
672 if ( ( (GNUNET_YES == do_round) &&
673 (dval > 5 * 1000) ) ||
674 (0 == (dval % 1000) ))
677 unit = _( /* time unit */ "s");
678 if ( ( (GNUNET_YES == do_round) &&
680 (0 == (dval % 60) ) )
683 unit = _( /* time unit */ "m");
684 if ( ( (GNUNET_YES == do_round) &&
689 unit = _( /* time unit */ "h");
690 if ( ( (GNUNET_YES == do_round) &&
696 unit = _( /* time unit */ "day");
698 unit = _( /* time unit */ "days");
704 GNUNET_snprintf (buf, sizeof (buf),
705 "%llu %s", dval, unit);
711 * "asctime", except for GNUnet time. Converts a GNUnet internal
712 * absolute time (which is in UTC) to a string in local time.
713 * Note that the returned value will be overwritten if this function
716 * @param t the absolute time to convert
717 * @return timestamp in human-readable form in local time
720 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
722 static char buf[255];
726 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
727 return _("end of time");
728 tt = t.abs_value_us / 1000LL / 1000LL;
729 tp = localtime (&tt);
730 /* This is hacky, but i don't know a way to detect libc character encoding.
731 * Just expect utf8 from glibc these days.
732 * As for msvcrt, use the wide variant, which always returns utf16
733 * (otherwise we'd have to detect current codepage or use W32API character
734 * set conversion routines to convert to UTF8).
737 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
740 static wchar_t wbuf[255];
744 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
745 L"%a %b %d %H:%M:%S %Y", tp);
747 ssize = sizeof (buf);
748 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
749 (uint8_t *) buf, &ssize);
750 if (conved != (uint8_t *) buf)
752 strncpy (buf, (char *) conved, sizeof (buf));
764 * Returns a pointer to a part of filename (allocates nothing)!
766 * @param filename filename to extract basename from
767 * @return short (base) name of the file (that is, everything following the
768 * last directory separator in filename. If filename ends with a
769 * directory separator, the result will be a zero-length string.
770 * If filename has no directory separators, the result is filename
774 GNUNET_STRINGS_get_short_name (const char *filename)
776 const char *short_fn = filename;
778 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
786 * Get the decoded value corresponding to a character according to Crockford
789 * @param a a character
790 * @return corresponding numeric value
793 getValue__ (unsigned char a)
809 /* also consider U to be V */
817 if ((a >= '0') && (a <= '9'))
819 if ((a >= 'a') && (a <= 'z'))
821 /* return (a - 'a' + 10); */
823 if ((a >= 'A') && (a <= 'Z'))
833 return (a - 'A' + 10 - dec);
840 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
841 * Returns a pointer to the byte after the last byte in the string, that
842 * is where the 0-terminator was placed if there was room.
844 * @param data data to encode
845 * @param size size of data (in bytes)
846 * @param out buffer to fill
847 * @param out_size size of the buffer. Must be large enough to hold
848 * (size * 8 + 4) / 5 bytes
849 * @return pointer to the next byte in @a out or NULL on error.
852 GNUNET_STRINGS_data_to_string (const void *data,
858 * 32 characters for encoding
860 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
865 const unsigned char *udata;
868 if (out_size < (size * 8 + 4) / 5)
877 while ((rpos < size) || (vbit > 0))
879 if ((rpos < size) && (vbit < 5))
881 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
886 bits <<= (5 - vbit); /* zero-padding */
887 GNUNET_assert (vbit == ((size * 8) % 5));
890 if (wpos >= out_size)
895 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
898 GNUNET_assert (0 == vbit);
906 * Return the base32crockford encoding of the given buffer.
908 * The returned string will be freshly allocated, and must be free'd
909 * with GNUNET_free().
911 * @param buffer with data
912 * @param size size of the buffer
913 * @return freshly allocated, null-terminated string
916 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
920 size_t len = size * 8;
926 str_buf = GNUNET_malloc (len + 1);
927 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
930 GNUNET_free (str_buf);
939 * Convert Crockford Base32hex encoding back to data.
940 * @a out_size must match exactly the size of the data before it was encoded.
942 * @param enc the encoding
943 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
944 * @param out location where to store the decoded data
945 * @param out_size size of the output buffer @a out
946 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
949 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
950 void *out, size_t out_size)
959 unsigned int encoded_len = out_size * 8;
965 return GNUNET_SYSERR;
970 if ((encoded_len % 5) > 0)
972 vbit = encoded_len % 5; /* padding! */
974 bits = (ret = getValue__ (enc[--rpos])) >> shift;
980 bits = (ret = getValue__ (enc[--rpos]));
982 if ((encoded_len + shift) / 5 != enclen)
983 return GNUNET_SYSERR;
985 return GNUNET_SYSERR;
991 return GNUNET_SYSERR;
993 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
995 return GNUNET_SYSERR;
999 uout[--wpos] = (unsigned char) bits;
1006 return GNUNET_SYSERR;
1012 * Parse a path that might be an URI.
1014 * @param path path to parse. Must be NULL-terminated.
1015 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1016 * represents the URI scheme will be stored. Can be NULL. The string is
1017 * allocated by the function, and should be freed by GNUNET_free() when
1018 * it is no longer needed.
1019 * @param path_part a pointer to 'const char *' where a pointer to the path
1020 * part of the URI will be stored. Can be NULL. Points to the same block
1021 * of memory as 'path', and thus must not be freed. Might point to '\0',
1022 * if path part is zero-length.
1023 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1024 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1025 * (if they weren't NULL).
1028 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
1029 const char **path_part)
1034 const char *post_scheme_part = NULL;
1035 len = strlen (path);
1036 for (end = 0, i = 0; !end && i < len; i++)
1041 if (path[i] == ':' && i > 0)
1046 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1047 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1048 || (path[i] == '.')))
1061 post_scheme_part = &path[i];
1068 if (post_scheme_part == NULL)
1072 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1073 memcpy (*scheme_part, path, post_scheme_part - path);
1074 (*scheme_part)[post_scheme_part - path] = '\0';
1077 *path_part = post_scheme_part;
1083 * Check whether @a filename is absolute or not, and if it's an URI
1085 * @param filename filename to check
1086 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1087 * assume it's not URI
1088 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1089 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1090 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1091 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1092 * The string is allocated by the function, and should be freed with
1093 * GNUNET_free(). Can be NULL.
1094 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1097 GNUNET_STRINGS_path_is_absolute (const char *filename,
1100 char **r_uri_scheme)
1105 const char *post_scheme_path;
1108 /* consider POSIX paths to be absolute too, even on W32,
1109 * as plibc expansion will fix them for us.
1111 if (filename[0] == '/')
1115 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1121 *r_uri_scheme = uri;
1123 GNUNET_free_non_null (uri);
1125 len = strlen(post_scheme_path);
1126 /* Special check for file:///c:/blah
1127 * We want to parse 'c:/', not '/c:/'
1129 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1130 post_scheme_path = &post_scheme_path[1];
1132 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1138 *r_is_uri = GNUNET_NO;
1141 len = strlen (filename);
1143 ((filename[0] >= 'A' && filename[0] <= 'Z')
1144 || (filename[0] >= 'a' && filename[0] <= 'z'))
1145 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1152 #define _IFMT 0170000 /* type of file */
1153 #define _IFLNK 0120000 /* symbolic link */
1154 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1159 * Perform @a checks on @a filename.
1161 * @param filename file to check
1162 * @param checks checks to perform
1163 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1164 * fails, #GNUNET_SYSERR when a check can't be performed
1167 GNUNET_STRINGS_check_filename (const char *filename,
1168 enum GNUNET_STRINGS_FilenameCheck checks)
1171 if ( (NULL == filename) || (filename[0] == '\0') )
1172 return GNUNET_SYSERR;
1173 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1174 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1176 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1177 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1178 | GNUNET_STRINGS_CHECK_IS_LINK)))
1180 if (0 != STAT (filename, &st))
1182 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1185 return GNUNET_SYSERR;
1188 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1189 if (!S_ISDIR (st.st_mode))
1191 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1192 if (!S_ISLNK (st.st_mode))
1199 * Tries to convert 'zt_addr' string to an IPv6 address.
1200 * The string is expected to have the format "[ABCD::01]:80".
1202 * @param zt_addr 0-terminated string. May be mangled by the function.
1203 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1204 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1205 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1206 * @return #GNUNET_OK if conversion succeded.
1207 * #GNUNET_SYSERR otherwise, in which
1208 * case the contents of @a r_buf are undefined.
1211 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1213 struct sockaddr_in6 *r_buf)
1215 char zbuf[addrlen + 1];
1221 return GNUNET_SYSERR;
1222 memcpy (zbuf, zt_addr, addrlen);
1225 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1226 _("IPv6 address did not start with `['\n"));
1227 return GNUNET_SYSERR;
1229 zbuf[addrlen] = '\0';
1230 port_colon = strrchr (zbuf, ':');
1231 if (NULL == port_colon)
1233 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1234 _("IPv6 address did contain ':' to separate port number\n"));
1235 return GNUNET_SYSERR;
1237 if (']' != *(port_colon - 1))
1239 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1240 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1241 return GNUNET_SYSERR;
1243 ret = SSCANF (port_colon, ":%u", &port);
1244 if ( (1 != ret) || (port > 65535) )
1246 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1247 _("IPv6 address did contain a valid port number after the last ':'\n"));
1248 return GNUNET_SYSERR;
1250 *(port_colon-1) = '\0';
1251 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1252 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1255 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1256 _("Invalid IPv6 address `%s': %s\n"),
1259 return GNUNET_SYSERR;
1261 r_buf->sin6_port = htons (port);
1262 r_buf->sin6_family = AF_INET6;
1263 #if HAVE_SOCKADDR_IN_SIN_LEN
1264 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1271 * Tries to convert 'zt_addr' string to an IPv4 address.
1272 * The string is expected to have the format "1.2.3.4:80".
1274 * @param zt_addr 0-terminated string. May be mangled by the function.
1275 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1276 * @param r_buf a buffer to fill.
1277 * @return #GNUNET_OK if conversion succeded.
1278 * #GNUNET_SYSERR otherwise, in which case
1279 * the contents of @a r_buf are undefined.
1282 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1283 struct sockaddr_in *r_buf)
1285 unsigned int temps[4];
1290 return GNUNET_SYSERR;
1291 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1293 return GNUNET_SYSERR;
1294 for (cnt = 0; cnt < 4; cnt++)
1295 if (temps[cnt] > 0xFF)
1296 return GNUNET_SYSERR;
1298 return GNUNET_SYSERR;
1299 r_buf->sin_family = AF_INET;
1300 r_buf->sin_port = htons (port);
1301 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1302 (temps[2] << 8) + temps[3]);
1303 #if HAVE_SOCKADDR_IN_SIN_LEN
1304 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1311 * Tries to convert @a addr string to an IP (v4 or v6) address.
1312 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1314 * @param addr a string, may not be 0-terminated.
1315 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1316 * 0-terminator should not be counted towards addrlen).
1317 * @param r_buf a buffer to fill.
1318 * @return #GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1319 * case the contents of r_buf are undefined.
1322 GNUNET_STRINGS_to_address_ip (const char *addr,
1324 struct sockaddr_storage *r_buf)
1327 return GNUNET_STRINGS_to_address_ipv6 (addr,
1329 (struct sockaddr_in6 *) r_buf);
1330 return GNUNET_STRINGS_to_address_ipv4 (addr,
1332 (struct sockaddr_in *) r_buf);
1337 * Makes a copy of argv that consists of a single memory chunk that can be
1338 * freed with a single call to GNUNET_free();
1340 static char *const *
1341 _make_continuous_arg_copy (int argc,
1344 size_t argvsize = 0;
1348 for (i = 0; i < argc; i++)
1349 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1350 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1351 p = (char *) &new_argv[argc + 1];
1352 for (i = 0; i < argc; i++)
1355 strcpy (p, argv[i]);
1356 p += strlen (argv[i]) + 1;
1358 new_argv[argc] = NULL;
1359 return (char *const *) new_argv;
1364 * Returns utf-8 encoded arguments.
1365 * Does nothing (returns a copy of argc and argv) on any platform
1367 * Returned argv has u8argv[u8argc] == NULL.
1368 * Returned argv is a single memory block, and can be freed with a single
1369 * GNUNET_free() call.
1371 * @param argc argc (as given by main())
1372 * @param argv argv (as given by main())
1373 * @param u8argc a location to store new argc in (though it's th same as argc)
1374 * @param u8argv a location to store new argv in
1375 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1378 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1385 char **split_u8argv;
1387 wcmd = GetCommandLineW ();
1389 return GNUNET_SYSERR;
1390 wargv = CommandLineToArgvW (wcmd, &wargc);
1392 return GNUNET_SYSERR;
1394 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1396 for (i = 0; i < wargc; i++)
1399 /* Hopefully it will allocate us NUL-terminated strings... */
1400 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1401 if (NULL == split_u8argv[i])
1404 for (j = 0; j < i; j++)
1405 free (split_u8argv[j]);
1406 GNUNET_free (split_u8argv);
1408 return GNUNET_SYSERR;
1412 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1415 for (i = 0; i < wargc; i++)
1416 free (split_u8argv[i]);
1417 free (split_u8argv);
1420 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1429 * Parse the given port policy. The format is
1430 * "[!]SPORT[-DPORT]".
1432 * @param port_policy string to parse
1433 * @param pp policy to fill in
1434 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1435 * @a port_policy is malformed
1438 parse_port_policy (const char *port_policy,
1439 struct GNUNET_STRINGS_PortPolicy *pp)
1449 pp->negate_portrange = GNUNET_YES;
1452 if (2 == sscanf (pos,
1461 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1462 _("Port not in range\n"));
1463 return GNUNET_SYSERR;
1465 pp->start_port = (uint16_t) s;
1466 pp->end_port = (uint16_t) e;
1469 if (1 == sscanf (pos,
1477 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1478 _("Port not in range\n"));
1479 return GNUNET_SYSERR;
1482 pp->start_port = (uint16_t) s;
1483 pp->end_port = (uint16_t) s;
1486 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1487 _("Malformed port policy `%s'\n"),
1489 return GNUNET_SYSERR;
1494 * Parse an IPv4 network policy. The argument specifies a list of
1495 * subnets. The format is
1496 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1497 * be terminated with a semicolon). The network must be given in
1498 * dotted-decimal notation. The netmask can be given in CIDR notation
1499 * (/16) or in dotted-decimal (/255.255.0.0).
1501 * @param routeListX a string specifying the IPv4 subnets
1502 * @return the converted list, terminated with all zeros;
1503 * NULL if the synatx is flawed
1505 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1506 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1514 unsigned int temps[8];
1516 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1521 if (NULL == routeListX)
1523 len = strlen (routeListX);
1526 routeList = GNUNET_strdup (routeListX);
1528 for (i = 0; i < len; i++)
1529 if (routeList[i] == ';')
1531 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1536 for (colon = pos; ':' != routeList[colon]; colon++)
1537 if ( (';' == routeList[colon]) ||
1538 ('\0' == routeList[colon]) )
1540 for (end = colon; ';' != routeList[end]; end++)
1541 if ('\0' == routeList[end])
1543 if ('\0' == routeList[end])
1545 routeList[end] = '\0';
1546 if (':' == routeList[colon])
1548 routeList[colon] = '\0';
1549 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1554 SSCANF (&routeList[pos],
1555 "%u.%u.%u.%u/%u.%u.%u.%u",
1566 for (j = 0; j < 8; j++)
1567 if (temps[j] > 0xFF)
1569 LOG (GNUNET_ERROR_TYPE_WARNING,
1570 _("Invalid format for IP: `%s'\n"),
1572 GNUNET_free (result);
1573 GNUNET_free (routeList);
1576 result[i].network.s_addr =
1577 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1579 result[i].netmask.s_addr =
1580 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1586 /* try second notation */
1588 SSCANF (&routeList[pos],
1597 for (j = 0; j < 4; j++)
1598 if (temps[j] > 0xFF)
1600 LOG (GNUNET_ERROR_TYPE_WARNING,
1601 _("Invalid format for IP: `%s'\n"),
1603 GNUNET_free (result);
1604 GNUNET_free (routeList);
1607 result[i].network.s_addr =
1608 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1610 if ((slash <= 32) && (slash >= 0))
1612 result[i].netmask.s_addr = 0;
1615 result[i].netmask.s_addr =
1616 (result[i].netmask.s_addr >> 1) + 0x80000000;
1619 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1626 LOG (GNUNET_ERROR_TYPE_WARNING,
1627 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1629 GNUNET_free (result);
1630 GNUNET_free (routeList);
1631 return NULL; /* error */
1634 /* try third notation */
1637 SSCANF (&routeList[pos],
1645 for (j = 0; j < 4; j++)
1646 if (temps[j] > 0xFF)
1648 LOG (GNUNET_ERROR_TYPE_WARNING,
1649 _("Invalid format for IP: `%s'\n"),
1651 GNUNET_free (result);
1652 GNUNET_free (routeList);
1655 result[i].network.s_addr =
1656 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1658 result[i].netmask.s_addr = 0;
1661 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1664 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1669 LOG (GNUNET_ERROR_TYPE_WARNING,
1670 _("Invalid format for IP: `%s'\n"),
1672 GNUNET_free (result);
1673 GNUNET_free (routeList);
1674 return NULL; /* error */
1676 if (pos < strlen (routeList))
1678 LOG (GNUNET_ERROR_TYPE_WARNING,
1679 _("Invalid format: `%s'\n"),
1681 GNUNET_free (result);
1682 GNUNET_free (routeList);
1683 return NULL; /* oops */
1685 GNUNET_free (routeList);
1686 return result; /* ok */
1691 * Parse an IPv6 network policy. The argument specifies a list of
1692 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1693 * (no whitespace, must be terminated with a semicolon). The network
1694 * must be given in colon-hex notation. The netmask must be given in
1695 * CIDR notation (/16) or can be omitted to specify a single host.
1696 * Note that the netmask is mandatory if ports are specified.
1698 * @param routeListX a string specifying the policy
1699 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1701 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1702 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1712 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1718 if (NULL == routeListX)
1720 len = strlen (routeListX);
1723 routeList = GNUNET_strdup (routeListX);
1725 for (i = 0; i < len; i++)
1726 if (';' == routeList[i])
1728 if (';' != routeList[len - 1])
1730 LOG (GNUNET_ERROR_TYPE_WARNING,
1731 _("Invalid network notation (does not end with ';': `%s')\n"),
1733 GNUNET_free (routeList);
1737 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1743 while (';' != routeList[pos])
1746 while ((slash >= start) && (routeList[slash] != '/'))
1751 memset (&result[i].netmask,
1753 sizeof (struct in6_addr));
1758 routeList[pos] = '\0';
1759 for (colon = pos; ':' != routeList[colon]; colon--)
1760 if ('/' == routeList[colon])
1762 if (':' == routeList[colon])
1764 routeList[colon] = '\0';
1765 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1768 GNUNET_free (result);
1769 GNUNET_free (routeList);
1773 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1777 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1780 LOG (GNUNET_ERROR_TYPE_WARNING,
1781 _("Wrong format `%s' for netmask\n"),
1782 &routeList[slash + 1]);
1786 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1788 GNUNET_free (result);
1789 GNUNET_free (routeList);
1795 result[i].netmask.s6_addr[off++] = 0xFF;
1800 result[i].netmask.s6_addr[off] =
1801 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1806 routeList[slash] = '\0';
1807 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1811 LOG (GNUNET_ERROR_TYPE_WARNING,
1812 _("Wrong format `%s' for network\n"),
1813 &routeList[slash + 1]);
1815 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1817 GNUNET_free (result);
1818 GNUNET_free (routeList);
1824 GNUNET_free (routeList);
1830 /** ******************** Base64 encoding ***********/
1832 #define FILLCHAR '='
1834 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1838 * Encode into Base64.
1840 * @param data the data to encode
1841 * @param len the length of the input
1842 * @param output where to write the output (*output should be NULL,
1844 * @return the size of the output
1847 GNUNET_STRINGS_base64_encode (const char *data,
1857 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1859 for (i = 0; i < len; ++i)
1861 c = (data[i] >> 2) & 0x3f;
1862 opt[ret++] = cvt[(int) c];
1863 c = (data[i] << 4) & 0x3f;
1865 c |= (data[i] >> 4) & 0x0f;
1866 opt[ret++] = cvt[(int) c];
1869 c = (data[i] << 2) & 0x3f;
1871 c |= (data[i] >> 6) & 0x03;
1872 opt[ret++] = cvt[(int) c];
1877 opt[ret++] = FILLCHAR;
1882 opt[ret++] = cvt[(int) c];
1886 opt[ret++] = FILLCHAR;
1889 opt[ret++] = FILLCHAR;
1893 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
1894 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
1895 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
1897 :((a) == '/') ? 63 : -1)
1901 * Decode from Base64.
1903 * @param data the data to encode
1904 * @param len the length of the input
1905 * @param output where to write the output (*output should be NULL,
1907 * @return the size of the output
1910 GNUNET_STRINGS_base64_decode (const char *data,
1911 size_t len, char **output)
1918 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
1919 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
1921 if (i >= len) goto END; \
1924 *output = GNUNET_malloc ((len * 3 / 4) + 8);
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "base64_decode decoding len=%d\n",
1928 for (i = 0; i < len; ++i)
1931 if (FILLCHAR == data[i])
1933 c = (char) cvtfind (data[i]);
1936 c1 = (char) cvtfind (data[i]);
1937 c = (c << 2) | ((c1 >> 4) & 0x3);
1938 (*output)[ret++] = c;
1945 c = (char) cvtfind (c);
1946 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
1947 (*output)[ret++] = c1;
1956 c1 = (char) cvtfind (c1);
1957 c = ((c << 6) & 0xc0) | c1;
1958 (*output)[ret++] = c;
1969 /* end of strings.c */