2 This file is part of GNUnet.
3 Copyright (C) 2005-2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @file util/strings.c
23 * @brief string functions
25 * @author Christian Grothoff
32 #include "gnunet_crypto_lib.h"
33 #include "gnunet_strings_lib.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 * Fill a buffer of the given size with
45 * count 0-terminated strings (given as varargs).
46 * If "buffer" is NULL, only compute the amount of
47 * space required (sum of "strlen(arg)+1").
49 * Unlike using "snprintf" with "%s", this function
50 * will add 0-terminators after each string. The
51 * #GNUNET_string_buffer_tokenize() function can be
52 * used to parse the buffer back into individual
55 * @param buffer the buffer to fill with strings, can
56 * be NULL in which case only the necessary
57 * amount of space will be calculated
58 * @param size number of bytes available in buffer
59 * @param count number of strings that follow
60 * @param ... count 0-terminated strings to copy to buffer
61 * @return number of bytes written to the buffer
62 * (or number of bytes that would have been written)
65 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
76 s = va_arg (ap, const char *);
78 slen = strlen (s) + 1;
81 GNUNET_assert (needed + slen <= size);
82 GNUNET_memcpy (&buffer[needed], s, slen);
93 * Given a buffer of a given size, find "count"
94 * 0-terminated strings in the buffer and assign
95 * the count (varargs) of type "const char**" to the
96 * locations of the respective strings in the
99 * @param buffer the buffer to parse
100 * @param size size of the buffer
101 * @param count number of strings to locate
102 * @return offset of the character after the last 0-termination
103 * in the buffer, or 0 on error.
106 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
107 unsigned int count, ...)
115 va_start (ap, count);
118 r = va_arg (ap, const char **);
121 while ((needed < size) && (buffer[needed] != '\0'))
126 return 0; /* error */
129 needed++; /* skip 0-termination */
138 * Convert a given filesize into a fancy human-readable format.
140 * @param size number of bytes
141 * @return fancy representation of the size (possibly rounded) for humans
144 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
146 const char *unit = _( /* size unit */ "b");
169 ret = GNUNET_malloc (32);
170 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
176 * Unit conversion table entry for 'convert_with_table'.
178 struct ConversionTable
181 * Name of the unit (or NULL for end of table).
186 * Factor to apply for this unit.
188 unsigned long long value;
193 * Convert a string of the form "4 X 5 Y" into a numeric value
194 * by interpreting "X" and "Y" as units and then multiplying
195 * the numbers with the values associated with the respective
196 * unit from the conversion table.
198 * @param input input string to parse
199 * @param table table with the conversion of unit names to numbers
200 * @param output where to store the result
201 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
204 convert_with_table (const char *input,
205 const struct ConversionTable *table,
206 unsigned long long *output)
208 unsigned long long ret;
211 unsigned long long last;
216 in = GNUNET_strdup (input);
217 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
222 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
224 if (table[i].name != NULL)
226 last *= table[i].value;
227 break; /* next tok */
234 last = strtoull (tok, &endptr, 10);
235 if ((0 != errno) || (endptr == tok))
238 return GNUNET_SYSERR; /* expected number */
240 if ('\0' == endptr[0])
241 break; /* next tok */
243 tok = endptr; /* and re-check (handles times like "10s") */
245 } while (GNUNET_YES);
255 * Convert a given fancy human-readable size to bytes.
257 * @param fancy_size human readable string (i.e. 1 MB)
258 * @param size set to the size in bytes
259 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
262 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
263 unsigned long long *size)
265 static const struct ConversionTable table[] =
270 { "MiB", 1024 * 1024},
271 { "MB", 1000 * 1000},
272 { "GiB", 1024 * 1024 * 1024},
273 { "GB", 1000 * 1000 * 1000},
274 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
275 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
276 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
277 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
278 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
279 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
283 return convert_with_table (fancy_size,
290 * Convert a given fancy human-readable time to our internal
293 * @param fancy_time human readable string (i.e. 1 minute)
294 * @param rtime set to the relative time
295 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
298 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
299 struct GNUNET_TIME_Relative *rtime)
301 static const struct ConversionTable table[] =
305 { "s", 1000 * 1000LL },
306 { "\"", 1000 * 1000LL },
307 { "m", 60 * 1000 * 1000LL},
308 { "min", 60 * 1000 * 1000LL},
309 { "minute", 60 * 1000 * 1000LL},
310 { "minutes", 60 * 1000 * 1000LL},
311 { "'", 60 * 1000 * 1000LL},
312 { "h", 60 * 60 * 1000 * 1000LL},
313 { "hour", 60 * 60 * 1000 * 1000LL},
314 { "hours", 60 * 60 * 1000 * 1000LL},
315 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
316 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
317 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
318 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
319 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
320 { "year", 31536000000000LL /* year */ },
321 { "years", 31536000000000LL /* year */ },
322 { "a", 31536000000000LL /* year */ },
326 unsigned long long val;
328 if (0 == strcasecmp ("forever", fancy_time))
330 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
333 ret = convert_with_table (fancy_time,
336 rtime->rel_value_us = (uint64_t) val;
342 * Convert a given fancy human-readable time to our internal
343 * representation. The human-readable time is expected to be
344 * in local time, whereas the returned value will be in UTC.
346 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
347 * @param atime set to the absolute time
348 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
351 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
352 struct GNUNET_TIME_Absolute *atime)
357 if (0 == strcasecmp ("end of time",
360 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
363 memset (&tv, 0, sizeof (tv));
364 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
365 (NULL == strptime (fancy_time, "%c", &tv)) &&
366 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
367 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
368 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
369 (NULL == strptime (fancy_time, "%x", &tv)) &&
370 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
371 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
372 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
373 (NULL == strptime (fancy_time, "%Y", &tv)) )
374 return GNUNET_SYSERR;
376 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
382 * Convert the len characters long character sequence
383 * given in input that is in the given input charset
384 * to a string in given output charset.
386 * @param input input string
387 * @param len number of bytes in @a input
388 * @param input_charset character set used for @a input
389 * @param output_charset desired character set for the return value
390 * @return the converted string (0-terminated),
391 * if conversion fails, a copy of the orignal
392 * string is returned.
395 GNUNET_STRINGS_conv (const char *input,
397 const char *input_charset,
398 const char *output_charset)
402 char *encoded_string;
403 size_t u8_string_length;
404 size_t encoded_string_length;
406 u8_string = u8_conv_from_encoding (input_charset,
411 if (NULL == u8_string)
413 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
416 if (0 == strcmp (output_charset, "UTF-8"))
418 ret = GNUNET_malloc (u8_string_length + 1);
419 GNUNET_memcpy (ret, u8_string, u8_string_length);
420 ret[u8_string_length] = '\0';
424 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
425 u8_string, u8_string_length,
427 &encoded_string_length);
429 if (NULL == encoded_string)
431 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
434 ret = GNUNET_malloc (encoded_string_length + 1);
435 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
436 ret[encoded_string_length] = '\0';
437 free (encoded_string);
440 LOG (GNUNET_ERROR_TYPE_WARNING,
441 _("Character sets requested were `%s'->`%s'\n"),
442 "UTF-8", output_charset);
443 ret = GNUNET_malloc (len + 1);
444 GNUNET_memcpy (ret, input, len);
451 * Convert the len characters long character sequence
452 * given in input that is in the given charset
455 * @param input the input string (not necessarily 0-terminated)
456 * @param len the number of bytes in the @a input
457 * @param charset character set to convert from
458 * @return the converted string (0-terminated),
459 * if conversion fails, a copy of the orignal
460 * string is returned.
463 GNUNET_STRINGS_to_utf8 (const char *input,
467 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
472 * Convert the len bytes-long UTF-8 string
473 * given in input to the given charset.
475 * @param input the input string (not necessarily 0-terminated)
476 * @param len the number of bytes in the @a input
477 * @param charset character set to convert to
478 * @return the converted string (0-terminated),
479 * if conversion fails, a copy of the orignal
480 * string is returned.
483 GNUNET_STRINGS_from_utf8 (const char *input,
487 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
492 * Convert the utf-8 input string to lowercase.
493 * Output needs to be allocated appropriately.
495 * @param input input string
496 * @param output output buffer
499 GNUNET_STRINGS_utf8_tolower (const char *input,
505 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
506 NULL, UNINORM_NFD, NULL, &len);
507 GNUNET_memcpy(output, tmp_in, len);
514 * Convert the utf-8 input string to uppercase.
515 * Output needs to be allocated appropriately.
517 * @param input input string
518 * @param output output buffer
521 GNUNET_STRINGS_utf8_toupper(const char *input,
527 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
528 NULL, UNINORM_NFD, NULL, &len);
529 GNUNET_memcpy (output, tmp_in, len);
536 * Complete filename (a la shell) from abbrevition.
537 * @param fil the name of the file, may contain ~/ or
538 * be relative to the current directory
539 * @returns the full file name,
540 * NULL is returned on error
543 GNUNET_STRINGS_filename_expand (const char *fil)
559 if (fil[0] == DIR_SEPARATOR)
560 /* absolute path, just copy */
561 return GNUNET_strdup (fil);
564 fm = getenv ("HOME");
567 LOG (GNUNET_ERROR_TYPE_WARNING,
568 _("Failed to expand `$HOME': environment variable `HOME' not set"));
571 fm = GNUNET_strdup (fm);
572 /* do not copy '~' */
575 /* skip over dir seperator to be consistent */
576 if (fil_ptr[0] == DIR_SEPARATOR)
587 buffer = GNUNET_malloc (len);
588 if (getcwd (buffer, len) != NULL)
593 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
596 GNUNET_free (buffer);
599 GNUNET_free (buffer);
604 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
606 buffer = getenv ("PWD"); /* alternative */
608 fm = GNUNET_strdup (buffer);
611 fm = GNUNET_strdup ("./"); /* give up */
613 GNUNET_asprintf (&buffer,
616 (fm[strlen (fm) - 1] ==
617 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
621 fn = GNUNET_malloc (MAX_PATH + 1);
623 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
625 SetErrnoFromWinError (lRet);
626 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
627 "plibc_conv_to_win_path");
630 /* is the path relative? */
631 if ( (0 != strncmp (fn + 1, ":\\", 2)) &&
632 (0 != strncmp (fn, "\\\\", 2)) )
634 char szCurDir[MAX_PATH + 1];
636 lRet = GetCurrentDirectory (MAX_PATH + 1,
638 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
640 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
641 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
642 "GetCurrentDirectory");
645 GNUNET_asprintf (&buffer,
659 * Give relative time in human-readable fancy format.
660 * This is one of the very few calls in the entire API that is
663 * @param delta time in milli seconds
664 * @param do_round are we allowed to round a bit?
665 * @return time as human-readable string
668 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
671 static char buf[128];
672 const char *unit = _( /* time unit */ "µs");
673 uint64_t dval = delta.rel_value_us;
675 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
677 if (0 == delta.rel_value_us)
679 if ( ( (GNUNET_YES == do_round) &&
680 (dval > 5 * 1000) ) ||
681 (0 == (dval % 1000) ))
684 unit = _( /* time unit */ "ms");
685 if ( ( (GNUNET_YES == do_round) &&
686 (dval > 5 * 1000) ) ||
687 (0 == (dval % 1000) ))
690 unit = _( /* time unit */ "s");
691 if ( ( (GNUNET_YES == do_round) &&
693 (0 == (dval % 60) ) )
696 unit = _( /* time unit */ "m");
697 if ( ( (GNUNET_YES == do_round) &&
702 unit = _( /* time unit */ "h");
703 if ( ( (GNUNET_YES == do_round) &&
709 unit = _( /* time unit */ "day");
711 unit = _( /* time unit */ "days");
717 GNUNET_snprintf (buf, sizeof (buf),
718 "%llu %s", dval, unit);
724 * "asctime", except for GNUnet time. Converts a GNUnet internal
725 * absolute time (which is in UTC) to a string in local time.
726 * Note that the returned value will be overwritten if this function
729 * @param t the absolute time to convert
730 * @return timestamp in human-readable form in local time
733 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
735 static char buf[255];
739 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
740 return _("end of time");
741 tt = t.abs_value_us / 1000LL / 1000LL;
742 tp = localtime (&tt);
743 /* This is hacky, but i don't know a way to detect libc character encoding.
744 * Just expect utf8 from glibc these days.
745 * As for msvcrt, use the wide variant, which always returns utf16
746 * (otherwise we'd have to detect current codepage or use W32API character
747 * set conversion routines to convert to UTF8).
750 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
753 static wchar_t wbuf[255];
757 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
758 L"%a %b %d %H:%M:%S %Y", tp);
760 ssize = sizeof (buf);
761 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
762 (uint8_t *) buf, &ssize);
763 if (conved != (uint8_t *) buf)
765 strncpy (buf, (char *) conved, sizeof (buf));
777 * Returns a pointer to a part of filename (allocates nothing)!
779 * @param filename filename to extract basename from
780 * @return short (base) name of the file (that is, everything following the
781 * last directory separator in filename. If filename ends with a
782 * directory separator, the result will be a zero-length string.
783 * If filename has no directory separators, the result is filename
787 GNUNET_STRINGS_get_short_name (const char *filename)
789 const char *short_fn = filename;
791 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
799 * Get the decoded value corresponding to a character according to Crockford
802 * @param a a character
803 * @return corresponding numeric value
806 getValue__ (unsigned char a)
822 /* also consider U to be V */
830 if ((a >= '0') && (a <= '9'))
832 if ((a >= 'a') && (a <= 'z'))
834 /* return (a - 'a' + 10); */
836 if ((a >= 'A') && (a <= 'Z'))
846 return (a - 'A' + 10 - dec);
853 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
854 * Returns a pointer to the byte after the last byte in the string, that
855 * is where the 0-terminator was placed if there was room.
857 * @param data data to encode
858 * @param size size of data (in bytes)
859 * @param out buffer to fill
860 * @param out_size size of the buffer. Must be large enough to hold
861 * (size * 8 + 4) / 5 bytes
862 * @return pointer to the next byte in @a out or NULL on error.
865 GNUNET_STRINGS_data_to_string (const void *data,
871 * 32 characters for encoding
873 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
878 const unsigned char *udata;
881 if (out_size < (size * 8 + 4) / 5)
890 while ((rpos < size) || (vbit > 0))
892 if ((rpos < size) && (vbit < 5))
894 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
899 bits <<= (5 - vbit); /* zero-padding */
900 GNUNET_assert (vbit == ((size * 8) % 5));
903 if (wpos >= out_size)
908 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
911 GNUNET_assert (0 == vbit);
919 * Return the base32crockford encoding of the given buffer.
921 * The returned string will be freshly allocated, and must be free'd
922 * with GNUNET_free().
924 * @param buffer with data
925 * @param size size of the buffer
926 * @return freshly allocated, null-terminated string
929 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
933 size_t len = size * 8;
939 str_buf = GNUNET_malloc (len + 1);
940 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
943 GNUNET_free (str_buf);
952 * Convert Crockford Base32hex encoding back to data.
953 * @a out_size must match exactly the size of the data before it was encoded.
955 * @param enc the encoding
956 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
957 * @param out location where to store the decoded data
958 * @param out_size size of the output buffer @a out
959 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
962 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
963 void *out, size_t out_size)
972 unsigned int encoded_len = out_size * 8;
978 return GNUNET_SYSERR;
983 if ((encoded_len % 5) > 0)
985 vbit = encoded_len % 5; /* padding! */
987 bits = (ret = getValue__ (enc[--rpos])) >> shift;
993 bits = (ret = getValue__ (enc[--rpos]));
995 if ((encoded_len + shift) / 5 != enclen)
996 return GNUNET_SYSERR;
998 return GNUNET_SYSERR;
1004 return GNUNET_SYSERR;
1006 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1008 return GNUNET_SYSERR;
1012 uout[--wpos] = (unsigned char) bits;
1019 return GNUNET_SYSERR;
1025 * Parse a path that might be an URI.
1027 * @param path path to parse. Must be NULL-terminated.
1028 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1029 * represents the URI scheme will be stored. Can be NULL. The string is
1030 * allocated by the function, and should be freed by GNUNET_free() when
1031 * it is no longer needed.
1032 * @param path_part a pointer to 'const char *' where a pointer to the path
1033 * part of the URI will be stored. Can be NULL. Points to the same block
1034 * of memory as 'path', and thus must not be freed. Might point to '\0',
1035 * if path part is zero-length.
1036 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1037 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1038 * (if they weren't NULL).
1041 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
1042 const char **path_part)
1047 const char *post_scheme_part = NULL;
1048 len = strlen (path);
1049 for (end = 0, i = 0; !end && i < len; i++)
1054 if (path[i] == ':' && i > 0)
1059 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1060 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1061 || (path[i] == '.')))
1074 post_scheme_part = &path[i];
1081 if (post_scheme_part == NULL)
1085 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1086 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1087 (*scheme_part)[post_scheme_part - path] = '\0';
1090 *path_part = post_scheme_part;
1096 * Check whether @a filename is absolute or not, and if it's an URI
1098 * @param filename filename to check
1099 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1100 * assume it's not URI
1101 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1102 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1103 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1104 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1105 * The string is allocated by the function, and should be freed with
1106 * GNUNET_free(). Can be NULL.
1107 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1110 GNUNET_STRINGS_path_is_absolute (const char *filename,
1113 char **r_uri_scheme)
1118 const char *post_scheme_path;
1121 /* consider POSIX paths to be absolute too, even on W32,
1122 * as plibc expansion will fix them for us.
1124 if (filename[0] == '/')
1128 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1134 *r_uri_scheme = uri;
1136 GNUNET_free_non_null (uri);
1138 len = strlen(post_scheme_path);
1139 /* Special check for file:///c:/blah
1140 * We want to parse 'c:/', not '/c:/'
1142 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1143 post_scheme_path = &post_scheme_path[1];
1145 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1151 *r_is_uri = GNUNET_NO;
1154 len = strlen (filename);
1156 ((filename[0] >= 'A' && filename[0] <= 'Z')
1157 || (filename[0] >= 'a' && filename[0] <= 'z'))
1158 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1165 #define _IFMT 0170000 /* type of file */
1166 #define _IFLNK 0120000 /* symbolic link */
1167 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1172 * Perform @a checks on @a filename.
1174 * @param filename file to check
1175 * @param checks checks to perform
1176 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1177 * fails, #GNUNET_SYSERR when a check can't be performed
1180 GNUNET_STRINGS_check_filename (const char *filename,
1181 enum GNUNET_STRINGS_FilenameCheck checks)
1184 if ( (NULL == filename) || (filename[0] == '\0') )
1185 return GNUNET_SYSERR;
1186 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1187 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1189 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1190 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1191 | GNUNET_STRINGS_CHECK_IS_LINK)))
1193 if (0 != STAT (filename, &st))
1195 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1198 return GNUNET_SYSERR;
1201 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1202 if (!S_ISDIR (st.st_mode))
1204 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1205 if (!S_ISLNK (st.st_mode))
1212 * Tries to convert @a zt_addr string to an IPv6 address.
1213 * The string is expected to have the format "[ABCD::01]:80".
1215 * @param zt_addr 0-terminated string. May be mangled by the function.
1216 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1217 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1218 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1219 * @return #GNUNET_OK if conversion succeded.
1220 * #GNUNET_SYSERR otherwise, in which
1221 * case the contents of @a r_buf are undefined.
1224 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1226 struct sockaddr_in6 *r_buf)
1228 char zbuf[addrlen + 1];
1234 return GNUNET_SYSERR;
1235 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1238 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1239 _("IPv6 address did not start with `['\n"));
1240 return GNUNET_SYSERR;
1242 zbuf[addrlen] = '\0';
1243 port_colon = strrchr (zbuf, ':');
1244 if (NULL == port_colon)
1246 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1247 _("IPv6 address did contain ':' to separate port number\n"));
1248 return GNUNET_SYSERR;
1250 if (']' != *(port_colon - 1))
1252 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1253 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1254 return GNUNET_SYSERR;
1256 ret = SSCANF (port_colon, ":%u", &port);
1257 if ( (1 != ret) || (port > 65535) )
1259 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1260 _("IPv6 address did contain a valid port number after the last ':'\n"));
1261 return GNUNET_SYSERR;
1263 *(port_colon-1) = '\0';
1264 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1265 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1268 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1269 _("Invalid IPv6 address `%s': %s\n"),
1272 return GNUNET_SYSERR;
1274 r_buf->sin6_port = htons (port);
1275 r_buf->sin6_family = AF_INET6;
1276 #if HAVE_SOCKADDR_IN_SIN_LEN
1277 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1284 * Tries to convert 'zt_addr' string to an IPv4 address.
1285 * The string is expected to have the format "1.2.3.4:80".
1287 * @param zt_addr 0-terminated string. May be mangled by the function.
1288 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1289 * @param r_buf a buffer to fill.
1290 * @return #GNUNET_OK if conversion succeded.
1291 * #GNUNET_SYSERR otherwise, in which case
1292 * the contents of @a r_buf are undefined.
1295 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1297 struct sockaddr_in *r_buf)
1299 unsigned int temps[4];
1304 return GNUNET_SYSERR;
1305 cnt = SSCANF (zt_addr,
1313 return GNUNET_SYSERR;
1314 for (cnt = 0; cnt < 4; cnt++)
1315 if (temps[cnt] > 0xFF)
1316 return GNUNET_SYSERR;
1318 return GNUNET_SYSERR;
1319 r_buf->sin_family = AF_INET;
1320 r_buf->sin_port = htons (port);
1321 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1322 (temps[2] << 8) + temps[3]);
1323 #if HAVE_SOCKADDR_IN_SIN_LEN
1324 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1331 * Tries to convert @a addr string to an IP (v4 or v6) address.
1332 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1334 * @param addr a string, may not be 0-terminated.
1335 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1336 * 0-terminator should not be counted towards addrlen).
1337 * @param r_buf a buffer to fill.
1338 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1339 * case the contents of @a r_buf are undefined.
1342 GNUNET_STRINGS_to_address_ip (const char *addr,
1344 struct sockaddr_storage *r_buf)
1347 return GNUNET_STRINGS_to_address_ipv6 (addr,
1349 (struct sockaddr_in6 *) r_buf);
1350 return GNUNET_STRINGS_to_address_ipv4 (addr,
1352 (struct sockaddr_in *) r_buf);
1357 * Parse an address given as a string into a
1358 * `struct sockaddr`.
1360 * @param addr the address
1361 * @param[out] af set to the parsed address family (i.e. AF_INET)
1362 * @param[out] sa set to the parsed address
1363 * @return 0 on error, otherwise number of bytes in @a sa
1366 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1368 struct sockaddr **sa)
1370 char *cp = GNUNET_strdup (addr);
1376 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1378 GNUNET_STRINGS_to_address_ipv6 (cp,
1380 (struct sockaddr_in6 *) *sa))
1389 return sizeof (struct sockaddr_in6);
1394 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1396 GNUNET_STRINGS_to_address_ipv4 (cp,
1398 (struct sockaddr_in *) *sa))
1407 return sizeof (struct sockaddr_in);
1413 * Makes a copy of argv that consists of a single memory chunk that can be
1414 * freed with a single call to GNUNET_free();
1416 static char *const *
1417 _make_continuous_arg_copy (int argc,
1420 size_t argvsize = 0;
1424 for (i = 0; i < argc; i++)
1425 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1426 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1427 p = (char *) &new_argv[argc + 1];
1428 for (i = 0; i < argc; i++)
1431 strcpy (p, argv[i]);
1432 p += strlen (argv[i]) + 1;
1434 new_argv[argc] = NULL;
1435 return (char *const *) new_argv;
1440 * Returns utf-8 encoded arguments.
1441 * Does nothing (returns a copy of argc and argv) on any platform
1443 * Returned argv has u8argv[u8argc] == NULL.
1444 * Returned argv is a single memory block, and can be freed with a single
1445 * GNUNET_free() call.
1447 * @param argc argc (as given by main())
1448 * @param argv argv (as given by main())
1449 * @param u8argc a location to store new argc in (though it's th same as argc)
1450 * @param u8argv a location to store new argv in
1451 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1454 GNUNET_STRINGS_get_utf8_args (int argc,
1457 char *const **u8argv)
1464 char **split_u8argv;
1466 wcmd = GetCommandLineW ();
1468 return GNUNET_SYSERR;
1469 wargv = CommandLineToArgvW (wcmd, &wargc);
1471 return GNUNET_SYSERR;
1473 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1475 for (i = 0; i < wargc; i++)
1478 /* Hopefully it will allocate us NUL-terminated strings... */
1479 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1480 if (NULL == split_u8argv[i])
1483 for (j = 0; j < i; j++)
1484 free (split_u8argv[j]);
1485 GNUNET_free (split_u8argv);
1487 return GNUNET_SYSERR;
1491 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1494 for (i = 0; i < wargc; i++)
1495 free (split_u8argv[i]);
1496 free (split_u8argv);
1499 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1508 * Parse the given port policy. The format is
1509 * "[!]SPORT[-DPORT]".
1511 * @param port_policy string to parse
1512 * @param pp policy to fill in
1513 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1514 * @a port_policy is malformed
1517 parse_port_policy (const char *port_policy,
1518 struct GNUNET_STRINGS_PortPolicy *pp)
1528 pp->negate_portrange = GNUNET_YES;
1531 if (2 == sscanf (pos,
1540 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1541 _("Port not in range\n"));
1542 return GNUNET_SYSERR;
1544 pp->start_port = (uint16_t) s;
1545 pp->end_port = (uint16_t) e;
1548 if (1 == sscanf (pos,
1556 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1557 _("Port not in range\n"));
1558 return GNUNET_SYSERR;
1561 pp->start_port = (uint16_t) s;
1562 pp->end_port = (uint16_t) s;
1565 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1566 _("Malformed port policy `%s'\n"),
1568 return GNUNET_SYSERR;
1573 * Parse an IPv4 network policy. The argument specifies a list of
1574 * subnets. The format is
1575 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1576 * be terminated with a semicolon). The network must be given in
1577 * dotted-decimal notation. The netmask can be given in CIDR notation
1578 * (/16) or in dotted-decimal (/255.255.0.0).
1580 * @param routeListX a string specifying the IPv4 subnets
1581 * @return the converted list, terminated with all zeros;
1582 * NULL if the synatx is flawed
1584 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1585 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1593 unsigned int temps[8];
1595 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1600 if (NULL == routeListX)
1602 len = strlen (routeListX);
1605 routeList = GNUNET_strdup (routeListX);
1607 for (i = 0; i < len; i++)
1608 if (routeList[i] == ';')
1610 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1615 for (colon = pos; ':' != routeList[colon]; colon++)
1616 if ( (';' == routeList[colon]) ||
1617 ('\0' == routeList[colon]) )
1619 for (end = colon; ';' != routeList[end]; end++)
1620 if ('\0' == routeList[end])
1622 if ('\0' == routeList[end])
1624 routeList[end] = '\0';
1625 if (':' == routeList[colon])
1627 routeList[colon] = '\0';
1628 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1633 SSCANF (&routeList[pos],
1634 "%u.%u.%u.%u/%u.%u.%u.%u",
1645 for (j = 0; j < 8; 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 =
1659 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1665 /* try second notation */
1667 SSCANF (&routeList[pos],
1676 for (j = 0; j < 4; j++)
1677 if (temps[j] > 0xFF)
1679 LOG (GNUNET_ERROR_TYPE_WARNING,
1680 _("Invalid format for IP: `%s'\n"),
1682 GNUNET_free (result);
1683 GNUNET_free (routeList);
1686 result[i].network.s_addr =
1687 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1689 if ((slash <= 32) && (slash >= 0))
1691 result[i].netmask.s_addr = 0;
1694 result[i].netmask.s_addr =
1695 (result[i].netmask.s_addr >> 1) + 0x80000000;
1698 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1705 LOG (GNUNET_ERROR_TYPE_WARNING,
1706 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1708 GNUNET_free (result);
1709 GNUNET_free (routeList);
1710 return NULL; /* error */
1713 /* try third notation */
1716 SSCANF (&routeList[pos],
1724 for (j = 0; j < 4; j++)
1725 if (temps[j] > 0xFF)
1727 LOG (GNUNET_ERROR_TYPE_WARNING,
1728 _("Invalid format for IP: `%s'\n"),
1730 GNUNET_free (result);
1731 GNUNET_free (routeList);
1734 result[i].network.s_addr =
1735 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1737 result[i].netmask.s_addr = 0;
1740 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1743 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1748 LOG (GNUNET_ERROR_TYPE_WARNING,
1749 _("Invalid format for IP: `%s'\n"),
1751 GNUNET_free (result);
1752 GNUNET_free (routeList);
1753 return NULL; /* error */
1755 if (pos < strlen (routeList))
1757 LOG (GNUNET_ERROR_TYPE_WARNING,
1758 _("Invalid format: `%s'\n"),
1760 GNUNET_free (result);
1761 GNUNET_free (routeList);
1762 return NULL; /* oops */
1764 GNUNET_free (routeList);
1765 return result; /* ok */
1770 * Parse an IPv6 network policy. The argument specifies a list of
1771 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1772 * (no whitespace, must be terminated with a semicolon). The network
1773 * must be given in colon-hex notation. The netmask must be given in
1774 * CIDR notation (/16) or can be omitted to specify a single host.
1775 * Note that the netmask is mandatory if ports are specified.
1777 * @param routeListX a string specifying the policy
1778 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1780 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1781 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1791 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1797 if (NULL == routeListX)
1799 len = strlen (routeListX);
1802 routeList = GNUNET_strdup (routeListX);
1804 for (i = 0; i < len; i++)
1805 if (';' == routeList[i])
1807 if (';' != routeList[len - 1])
1809 LOG (GNUNET_ERROR_TYPE_WARNING,
1810 _("Invalid network notation (does not end with ';': `%s')\n"),
1812 GNUNET_free (routeList);
1816 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1822 while (';' != routeList[pos])
1825 while ((slash >= start) && (routeList[slash] != '/'))
1830 memset (&result[i].netmask,
1832 sizeof (struct in6_addr));
1837 routeList[pos] = '\0';
1838 for (colon = pos; ':' != routeList[colon]; colon--)
1839 if ('/' == routeList[colon])
1841 if (':' == routeList[colon])
1843 routeList[colon] = '\0';
1844 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1847 GNUNET_free (result);
1848 GNUNET_free (routeList);
1852 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1856 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1859 LOG (GNUNET_ERROR_TYPE_WARNING,
1860 _("Wrong format `%s' for netmask\n"),
1861 &routeList[slash + 1]);
1865 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1867 GNUNET_free (result);
1868 GNUNET_free (routeList);
1874 result[i].netmask.s6_addr[off++] = 0xFF;
1879 result[i].netmask.s6_addr[off] =
1880 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1885 routeList[slash] = '\0';
1886 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1890 LOG (GNUNET_ERROR_TYPE_WARNING,
1891 _("Wrong format `%s' for network\n"),
1892 &routeList[slash + 1]);
1894 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1896 GNUNET_free (result);
1897 GNUNET_free (routeList);
1903 GNUNET_free (routeList);
1909 /** ******************** Base64 encoding ***********/
1911 #define FILLCHAR '='
1913 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1917 * Encode into Base64.
1919 * @param data the data to encode
1920 * @param len the length of the input
1921 * @param output where to write the output (*output should be NULL,
1923 * @return the size of the output
1926 GNUNET_STRINGS_base64_encode (const char *data,
1936 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1938 for (i = 0; i < len; ++i)
1940 c = (data[i] >> 2) & 0x3f;
1941 opt[ret++] = cvt[(int) c];
1942 c = (data[i] << 4) & 0x3f;
1944 c |= (data[i] >> 4) & 0x0f;
1945 opt[ret++] = cvt[(int) c];
1948 c = (data[i] << 2) & 0x3f;
1950 c |= (data[i] >> 6) & 0x03;
1951 opt[ret++] = cvt[(int) c];
1956 opt[ret++] = FILLCHAR;
1961 opt[ret++] = cvt[(int) c];
1965 opt[ret++] = FILLCHAR;
1968 opt[ret++] = FILLCHAR;
1972 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
1973 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
1974 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
1976 :((a) == '/') ? 63 : -1)
1980 * Decode from Base64.
1982 * @param data the data to encode
1983 * @param len the length of the input
1984 * @param output where to write the output (*output should be NULL,
1986 * @return the size of the output
1989 GNUNET_STRINGS_base64_decode (const char *data,
1990 size_t len, char **output)
1997 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
1998 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
2000 if (i >= len) goto END; \
2003 *output = GNUNET_malloc ((len * 3 / 4) + 8);
2004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2005 "base64_decode decoding len=%d\n",
2007 for (i = 0; i < len; ++i)
2010 if (FILLCHAR == data[i])
2012 c = (char) cvtfind (data[i]);
2015 c1 = (char) cvtfind (data[i]);
2016 c = (c << 2) | ((c1 >> 4) & 0x3);
2017 (*output)[ret++] = c;
2024 c = (char) cvtfind (c);
2025 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2026 (*output)[ret++] = c1;
2035 c1 = (char) cvtfind (c1);
2036 c = ((c << 6) & 0xc0) | c1;
2037 (*output)[ret++] = c;
2048 /* end of strings.c */