2 This file is part of GNUnet.
3 Copyright (C) 2005-2017 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
21 * @file util/strings.c
22 * @brief string functions
24 * @author Christian Grothoff
31 #include "gnunet_crypto_lib.h"
32 #include "gnunet_strings_lib.h"
37 #define LOG(kind, ...) GNUNET_log_from (kind, "util-strings", __VA_ARGS__)
39 #define LOG_STRERROR(kind, syscall) \
40 GNUNET_log_from_strerror (kind, "util-strings", 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 * Convert a peer path to a human-readable string.
95 * @param pids array of PIDs to convert to a string
96 * @param num_pids length of the @a pids array
97 * @return string representing the array of @a pids
100 GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids,
101 unsigned int num_pids)
105 size_t plen = num_pids * 5 + 1;
108 buf = GNUNET_malloc (plen);
109 for (unsigned int i = 0; i < num_pids; i++)
111 off += GNUNET_snprintf (&buf[off],
114 GNUNET_i2s (&pids[i]),
115 (i == num_pids - 1) ? "" : "-");
122 * Given a buffer of a given size, find "count"
123 * 0-terminated strings in the buffer and assign
124 * the count (varargs) of type "const char**" to the
125 * locations of the respective strings in the
128 * @param buffer the buffer to parse
129 * @param size size of the buffer
130 * @param count number of strings to locate
131 * @return offset of the character after the last 0-termination
132 * in the buffer, or 0 on error.
135 GNUNET_STRINGS_buffer_tokenize (const char *buffer,
146 va_start (ap, count);
149 r = va_arg (ap, const char **);
152 while ((needed < size) && (buffer[needed] != '\0'))
157 return 0; /* error */
160 needed++; /* skip 0-termination */
169 * Convert a given filesize into a fancy human-readable format.
171 * @param size number of bytes
172 * @return fancy representation of the size (possibly rounded) for humans
175 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
177 const char *unit = _ (/* size unit */ "b");
200 ret = GNUNET_malloc (32);
201 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
207 * Like strlcpy but portable. The given string @a src is copied until its null
208 * byte or until @a n - 1 bytes have been read. The destination buffer is
209 * guaranteed to be null-terminated.
211 * @param dst destination of the copy (must be @a n bytes long)
212 * @param src source of the copy (at most @a n - 1 bytes will be read)
213 * @param n the length of the string to copy, including its terminating null
215 * @return the length of the string that was copied, excluding the terminating
219 GNUNET_strlcpy (char *dst, const char *src, size_t n)
223 GNUNET_assert (0 != n);
224 slen = strnlen (src, n - 1);
225 memcpy (dst, src, slen);
232 * Unit conversion table entry for 'convert_with_table'.
234 struct ConversionTable
237 * Name of the unit (or NULL for end of table).
242 * Factor to apply for this unit.
244 unsigned long long value;
249 * Convert a string of the form "4 X 5 Y" into a numeric value
250 * by interpreting "X" and "Y" as units and then multiplying
251 * the numbers with the values associated with the respective
252 * unit from the conversion table.
254 * @param input input string to parse
255 * @param table table with the conversion of unit names to numbers
256 * @param output where to store the result
257 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
260 convert_with_table (const char *input,
261 const struct ConversionTable *table,
262 unsigned long long *output)
264 unsigned long long ret;
267 unsigned long long last;
272 in = GNUNET_strdup (input);
273 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
278 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
280 if (table[i].name != NULL)
282 last *= table[i].value;
283 break; /* next tok */
290 last = strtoull (tok, &endptr, 10);
291 if ((0 != errno) || (endptr == tok))
294 return GNUNET_SYSERR; /* expected number */
296 if ('\0' == endptr[0])
297 break; /* next tok */
299 tok = endptr; /* and re-check (handles times like "10s") */
301 } while (GNUNET_YES);
311 * Convert a given fancy human-readable size to bytes.
313 * @param fancy_size human readable string (i.e. 1 MB)
314 * @param size set to the size in bytes
315 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
318 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
319 unsigned long long *size)
321 static const struct ConversionTable table[] =
325 {"MiB", 1024 * 1024},
327 {"GiB", 1024 * 1024 * 1024},
328 {"GB", 1000 * 1000 * 1000},
329 {"TiB", 1024LL * 1024LL * 1024LL * 1024LL},
330 {"TB", 1000LL * 1000LL * 1000LL * 1024LL},
331 {"PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
332 {"PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
333 {"EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
334 {"EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
337 return convert_with_table (fancy_size, table, size);
342 * Convert a given fancy human-readable time to our internal
345 * @param fancy_time human readable string (i.e. 1 minute)
346 * @param rtime set to the relative time
347 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
350 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
351 struct GNUNET_TIME_Relative *rtime)
353 static const struct ConversionTable table[] =
356 {"s", 1000 * 1000LL},
357 {"second", 1000 * 1000LL},
358 {"seconds", 1000 * 1000LL},
359 {"\"", 1000 * 1000LL},
360 {"m", 60 * 1000 * 1000LL},
361 {"min", 60 * 1000 * 1000LL},
362 {"minute", 60 * 1000 * 1000LL},
363 {"minutes", 60 * 1000 * 1000LL},
364 {"'", 60 * 1000 * 1000LL},
365 {"h", 60 * 60 * 1000 * 1000LL},
366 {"hour", 60 * 60 * 1000 * 1000LL},
367 {"hours", 60 * 60 * 1000 * 1000LL},
368 {"d", 24 * 60 * 60 * 1000LL * 1000LL},
369 {"day", 24 * 60 * 60 * 1000LL * 1000LL},
370 {"days", 24 * 60 * 60 * 1000LL * 1000LL},
371 {"week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
372 {"weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
373 {"year", 31536000000000LL /* year */},
374 {"years", 31536000000000LL /* year */},
375 {"a", 31536000000000LL /* year */},
378 unsigned long long val;
380 if (0 == strcasecmp ("forever", fancy_time))
382 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
385 ret = convert_with_table (fancy_time, table, &val);
386 rtime->rel_value_us = (uint64_t) val;
392 * Convert a given fancy human-readable time to our internal
393 * representation. The human-readable time is expected to be
394 * in local time, whereas the returned value will be in UTC.
396 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
397 * @param atime set to the absolute time
398 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
401 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
402 struct GNUNET_TIME_Absolute *atime)
408 if (0 == strcasecmp ("end of time", fancy_time))
410 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
413 eos = &fancy_time[strlen (fancy_time)];
414 memset (&tv, 0, sizeof (tv));
415 if ((eos != strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
416 (eos != strptime (fancy_time, "%c", &tv)) &&
417 (eos != strptime (fancy_time, "%Ec", &tv)) &&
418 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
419 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
420 (eos != strptime (fancy_time, "%x", &tv)) &&
421 (eos != strptime (fancy_time, "%Ex", &tv)) &&
422 (eos != strptime (fancy_time, "%Y-%m-%d", &tv)) &&
423 (eos != strptime (fancy_time, "%Y-%m", &tv)) &&
424 (eos != strptime (fancy_time, "%Y", &tv)))
425 return GNUNET_SYSERR;
427 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
433 * Convert the len characters long character sequence
434 * given in input that is in the given input charset
435 * to a string in given output charset.
437 * @param input input string
438 * @param len number of bytes in @a input
439 * @param input_charset character set used for @a input
440 * @param output_charset desired character set for the return value
441 * @return the converted string (0-terminated),
442 * if conversion fails, a copy of the orignal
443 * string is returned.
446 GNUNET_STRINGS_conv (const char *input,
448 const char *input_charset,
449 const char *output_charset)
453 char *encoded_string;
454 size_t u8_string_length;
455 size_t encoded_string_length;
457 u8_string = u8_conv_from_encoding (input_charset,
464 if (NULL == u8_string)
466 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
469 if (0 == strcmp (output_charset, "UTF-8"))
471 ret = GNUNET_malloc (u8_string_length + 1);
472 GNUNET_memcpy (ret, u8_string, u8_string_length);
473 ret[u8_string_length] = '\0';
477 encoded_string = u8_conv_to_encoding (output_charset,
483 &encoded_string_length);
485 if (NULL == encoded_string)
487 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
490 ret = GNUNET_malloc (encoded_string_length + 1);
491 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
492 ret[encoded_string_length] = '\0';
493 free (encoded_string);
496 LOG (GNUNET_ERROR_TYPE_WARNING,
497 _ ("Character sets requested were `%s'->`%s'\n"),
500 ret = GNUNET_malloc (len + 1);
501 GNUNET_memcpy (ret, input, len);
508 * Convert the len characters long character sequence
509 * given in input that is in the given charset
512 * @param input the input string (not necessarily 0-terminated)
513 * @param len the number of bytes in the @a input
514 * @param charset character set to convert from
515 * @return the converted string (0-terminated),
516 * if conversion fails, a copy of the orignal
517 * string is returned.
520 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
522 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
527 * Convert the len bytes-long UTF-8 string
528 * given in input to the given charset.
530 * @param input the input string (not necessarily 0-terminated)
531 * @param len the number of bytes in the @a input
532 * @param charset character set to convert to
533 * @return the converted string (0-terminated),
534 * if conversion fails, a copy of the orignal
535 * string is returned.
538 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
540 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
545 * Convert the utf-8 input string to lowercase.
546 * Output needs to be allocated appropriately.
548 * @param input input string
549 * @param output output buffer
552 GNUNET_STRINGS_utf8_tolower (const char *input, char *output)
557 tmp_in = u8_tolower ((uint8_t *) input,
558 strlen ((char *) input),
563 GNUNET_memcpy (output, tmp_in, len);
570 * Convert the utf-8 input string to uppercase.
571 * Output needs to be allocated appropriately.
573 * @param input input string
574 * @param output output buffer
577 GNUNET_STRINGS_utf8_toupper (const char *input, char *output)
582 tmp_in = u8_toupper ((uint8_t *) input,
583 strlen ((char *) input),
588 GNUNET_memcpy (output, tmp_in, len);
595 * Complete filename (a la shell) from abbrevition.
596 * @param fil the name of the file, may contain ~/ or
597 * be relative to the current directory
598 * @returns the full file name,
599 * NULL is returned on error
602 GNUNET_STRINGS_filename_expand (const char *fil)
618 if (fil[0] == DIR_SEPARATOR)
619 /* absolute path, just copy */
620 return GNUNET_strdup (fil);
623 fm = getenv ("HOME");
626 LOG (GNUNET_ERROR_TYPE_WARNING,
627 _ ("Failed to expand `$HOME': environment variable `HOME' not set"));
630 fm = GNUNET_strdup (fm);
631 /* do not copy '~' */
634 /* skip over dir seperator to be consistent */
635 if (fil_ptr[0] == DIR_SEPARATOR)
646 buffer = GNUNET_malloc (len);
647 if (getcwd (buffer, len) != NULL)
652 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
655 GNUNET_free (buffer);
658 GNUNET_free (buffer);
663 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
664 buffer = getenv ("PWD"); /* alternative */
666 fm = GNUNET_strdup (buffer);
669 fm = GNUNET_strdup ("./"); /* give up */
671 GNUNET_asprintf (&buffer,
674 (fm[strlen (fm) - 1] == DIR_SEPARATOR) ? ""
680 fn = GNUNET_malloc (MAX_PATH + 1);
682 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
684 SetErrnoFromWinError (lRet);
685 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
688 /* is the path relative? */
689 if ((0 != strncmp (fn + 1, ":\\", 2)) && (0 != strncmp (fn, "\\\\", 2)))
691 char szCurDir[MAX_PATH + 1];
693 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
694 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
696 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
697 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
700 GNUNET_asprintf (&buffer, "%s\\%s", szCurDir, fn);
711 * Give relative time in human-readable fancy format.
712 * This is one of the very few calls in the entire API that is
715 * @param delta time in milli seconds
716 * @param do_round are we allowed to round a bit?
717 * @return time as human-readable string
720 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
723 static char buf[128];
724 const char *unit = _ (/* time unit */ "µs");
725 uint64_t dval = delta.rel_value_us;
727 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
728 return _ ("forever");
729 if (0 == delta.rel_value_us)
731 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
734 unit = _ (/* time unit */ "ms");
735 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
738 unit = _ (/* time unit */ "s");
739 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
742 unit = _ (/* time unit */ "m");
743 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
746 unit = _ (/* time unit */ "h");
747 if (((GNUNET_YES == do_round) && (dval > 5 * 24)) ||
752 unit = _ (/* time unit */ "day");
754 unit = _ (/* time unit */ "days");
760 GNUNET_snprintf (buf, sizeof (buf), "%llu %s", dval, unit);
766 * "asctime", except for GNUnet time. Converts a GNUnet internal
767 * absolute time (which is in UTC) to a string in local time.
768 * Note that the returned value will be overwritten if this function
771 * @param t the absolute time to convert
772 * @return timestamp in human-readable form in local time
775 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
777 static char buf[255];
781 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
782 return _ ("end of time");
783 tt = t.abs_value_us / 1000LL / 1000LL;
784 tp = localtime (&tt);
785 /* This is hacky, but i don't know a way to detect libc character encoding.
786 * Just expect utf8 from glibc these days.
787 * As for msvcrt, use the wide variant, which always returns utf16
788 * (otherwise we'd have to detect current codepage or use W32API character
789 * set conversion routines to convert to UTF8).
792 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
795 static wchar_t wbuf[255];
800 sizeof (wbuf) / sizeof (wchar_t),
801 L"%a %b %d %H:%M:%S %Y",
804 ssize = sizeof (buf);
805 conved = u16_to_u8 (wbuf,
806 sizeof (wbuf) / sizeof (wchar_t),
809 if (conved != (uint8_t *) buf)
811 GNUNET_strlcpy (buf, (char *) conved, sizeof (buf));
822 * Returns a pointer to a part of filename (allocates nothing)!
824 * @param filename filename to extract basename from
825 * @return short (base) name of the file (that is, everything following the
826 * last directory separator in filename. If filename ends with a
827 * directory separator, the result will be a zero-length string.
828 * If filename has no directory separators, the result is filename
832 GNUNET_STRINGS_get_short_name (const char *filename)
834 const char *short_fn = filename;
837 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR)) && (ss[1] != '\0'))
844 * Get the decoded value corresponding to a character according to Crockford
847 * @param a a character
848 * @return corresponding numeric value
851 getValue__ (unsigned char a)
867 /* also consider U to be V */
875 if ((a >= '0') && (a <= '9'))
877 if ((a >= 'a') && (a <= 'z'))
879 /* return (a - 'a' + 10); */
881 if ((a >= 'A') && (a <= 'Z'))
891 return (a - 'A' + 10 - dec);
898 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
899 * Returns a pointer to the byte after the last byte in the string, that
900 * is where the 0-terminator was placed if there was room.
902 * @param data data to encode
903 * @param size size of data (in bytes)
904 * @param out buffer to fill
905 * @param out_size size of the buffer. Must be large enough to hold
906 * (size * 8 + 4) / 5 bytes
907 * @return pointer to the next byte in @a out or NULL on error.
910 GNUNET_STRINGS_data_to_string (const void *data,
916 * 32 characters for encoding
918 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
923 const unsigned char *udata;
926 if (out_size < (size * 8 + 4) / 5)
935 while ((rpos < size) || (vbit > 0))
937 if ((rpos < size) && (vbit < 5))
939 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
944 bits <<= (5 - vbit); /* zero-padding */
945 GNUNET_assert (vbit == ((size * 8) % 5));
948 if (wpos >= out_size)
953 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
956 GNUNET_assert (0 == vbit);
964 * Return the base32crockford encoding of the given buffer.
966 * The returned string will be freshly allocated, and must be free'd
967 * with GNUNET_free().
969 * @param buffer with data
970 * @param size size of the buffer
971 * @return freshly allocated, null-terminated string
974 GNUNET_STRINGS_data_to_string_alloc (const void *buf, size_t size)
977 size_t len = size * 8;
983 str_buf = GNUNET_malloc (len + 1);
984 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
987 GNUNET_free (str_buf);
996 * Convert Crockford Base32hex encoding back to data.
997 * @a out_size must match exactly the size of the data before it was encoded.
999 * @param enc the encoding
1000 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
1001 * @param out location where to store the decoded data
1002 * @param out_size size of the output buffer @a out
1003 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
1006 GNUNET_STRINGS_string_to_data (const char *enc,
1017 unsigned char *uout;
1018 unsigned int encoded_len = out_size * 8;
1024 return GNUNET_SYSERR;
1029 if ((encoded_len % 5) > 0)
1031 vbit = encoded_len % 5; /* padding! */
1033 bits = (ret = getValue__ (enc[--rpos])) >> shift;
1039 bits = (ret = getValue__ (enc[--rpos]));
1041 if ((encoded_len + shift) / 5 != enclen)
1042 return GNUNET_SYSERR;
1044 return GNUNET_SYSERR;
1050 return GNUNET_SYSERR;
1052 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1054 return GNUNET_SYSERR;
1058 uout[--wpos] = (unsigned char) bits;
1063 if ((0 != rpos) || (0 != vbit))
1064 return GNUNET_SYSERR;
1070 * Parse a path that might be an URI.
1072 * @param path path to parse. Must be NULL-terminated.
1073 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1074 * represents the URI scheme will be stored. Can be NULL. The string is
1075 * allocated by the function, and should be freed by GNUNET_free() when
1076 * it is no longer needed.
1077 * @param path_part a pointer to 'const char *' where a pointer to the path
1078 * part of the URI will be stored. Can be NULL. Points to the same block
1079 * of memory as 'path', and thus must not be freed. Might point to '\0',
1080 * if path part is zero-length.
1081 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1082 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1083 * (if they weren't NULL).
1086 GNUNET_STRINGS_parse_uri (const char *path,
1088 const char **path_part)
1094 const char *post_scheme_part = NULL;
1095 len = strlen (path);
1096 for (end = 0, i = 0; ! end && i < len; i++)
1101 if ((path[i] == ':') && (i > 0))
1106 if (! ((path[i] >= 'A' && path[i] <= 'Z') ||
1107 (path[i] >= 'a' && path[i] <= 'z') ||
1108 (path[i] >= '0' && path[i] <= '9') || path[i] == '+' ||
1109 path[i] == '-' || (path[i] == '.')))
1122 post_scheme_part = &path[i];
1129 if (post_scheme_part == NULL)
1133 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1134 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1135 (*scheme_part)[post_scheme_part - path] = '\0';
1138 *path_part = post_scheme_part;
1144 * Check whether @a filename is absolute or not, and if it's an URI
1146 * @param filename filename to check
1147 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1148 * assume it's not URI
1149 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1150 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1151 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1152 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1153 * The string is allocated by the function, and should be freed with
1154 * GNUNET_free(). Can be NULL.
1155 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1158 GNUNET_STRINGS_path_is_absolute (const char *filename,
1161 char **r_uri_scheme)
1166 const char *post_scheme_path;
1169 /* consider POSIX paths to be absolute too, even on W32,
1170 * as plibc expansion will fix them for us.
1172 if (filename[0] == '/')
1176 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1182 *r_uri_scheme = uri;
1184 GNUNET_free_non_null (uri);
1186 len = strlen (post_scheme_path);
1187 /* Special check for file:///c:/blah
1188 * We want to parse 'c:/', not '/c:/'
1190 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1191 post_scheme_path = &post_scheme_path[1];
1193 return GNUNET_STRINGS_path_is_absolute (post_scheme_path,
1202 *r_is_uri = GNUNET_NO;
1205 len = strlen (filename);
1207 ((filename[0] >= 'A' && filename[0] <= 'Z') ||
1208 (filename[0] >= 'a' && filename[0] <= 'z')) &&
1209 filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1216 #define _IFMT 0170000 /* type of file */
1217 #define _IFLNK 0120000 /* symbolic link */
1218 #define S_ISLNK(m) (((m) &_IFMT) == _IFLNK)
1223 * Perform @a checks on @a filename.
1225 * @param filename file to check
1226 * @param checks checks to perform
1227 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1228 * fails, #GNUNET_SYSERR when a check can't be performed
1231 GNUNET_STRINGS_check_filename (const char *filename,
1232 enum GNUNET_STRINGS_FilenameCheck checks)
1235 if ((NULL == filename) || (filename[0] == '\0'))
1236 return GNUNET_SYSERR;
1237 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1238 if (! GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1241 (GNUNET_STRINGS_CHECK_EXISTS | GNUNET_STRINGS_CHECK_IS_DIRECTORY |
1242 GNUNET_STRINGS_CHECK_IS_LINK)))
1244 if (0 != stat (filename, &st))
1246 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1249 return GNUNET_SYSERR;
1252 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1253 if (! S_ISDIR (st.st_mode))
1255 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1256 if (! S_ISLNK (st.st_mode))
1263 * Tries to convert @a zt_addr string to an IPv6 address.
1264 * The string is expected to have the format "[ABCD::01]:80".
1266 * @param zt_addr 0-terminated string. May be mangled by the function.
1267 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1268 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1269 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1270 * @return #GNUNET_OK if conversion succeded.
1271 * #GNUNET_SYSERR otherwise, in which
1272 * case the contents of @a r_buf are undefined.
1275 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1277 struct sockaddr_in6 *r_buf)
1279 char zbuf[addrlen + 1];
1286 return GNUNET_SYSERR;
1287 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1290 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1291 _ ("IPv6 address did not start with `['\n"));
1292 return GNUNET_SYSERR;
1294 zbuf[addrlen] = '\0';
1295 port_colon = strrchr (zbuf, ':');
1296 if (NULL == port_colon)
1298 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1299 _ ("IPv6 address did contain ':' to separate port number\n"));
1300 return GNUNET_SYSERR;
1302 if (']' != *(port_colon - 1))
1305 GNUNET_ERROR_TYPE_WARNING,
1306 _ ("IPv6 address did contain ']' before ':' to separate port number\n"));
1307 return GNUNET_SYSERR;
1309 ret = sscanf (port_colon, ":%u%1s", &port, dummy);
1310 if ((1 != ret) || (port > 65535))
1313 GNUNET_ERROR_TYPE_WARNING,
1314 _ ("IPv6 address did contain a valid port number after the last ':'\n"));
1315 return GNUNET_SYSERR;
1317 *(port_colon - 1) = '\0';
1318 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1319 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1322 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1323 _ ("Invalid IPv6 address `%s': %s\n"),
1326 return GNUNET_SYSERR;
1328 r_buf->sin6_port = htons (port);
1329 r_buf->sin6_family = AF_INET6;
1330 #if HAVE_SOCKADDR_IN_SIN_LEN
1331 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1338 * Tries to convert 'zt_addr' string to an IPv4 address.
1339 * The string is expected to have the format "1.2.3.4:80".
1341 * @param zt_addr 0-terminated string. May be mangled by the function.
1342 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1343 * @param r_buf a buffer to fill.
1344 * @return #GNUNET_OK if conversion succeded.
1345 * #GNUNET_SYSERR otherwise, in which case
1346 * the contents of @a r_buf are undefined.
1349 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1351 struct sockaddr_in *r_buf)
1353 unsigned int temps[4];
1359 return GNUNET_SYSERR;
1360 cnt = sscanf (zt_addr,
1361 "%u.%u.%u.%u:%u%1s",
1369 return GNUNET_SYSERR;
1370 for (cnt = 0; cnt < 4; cnt++)
1371 if (temps[cnt] > 0xFF)
1372 return GNUNET_SYSERR;
1374 return GNUNET_SYSERR;
1375 r_buf->sin_family = AF_INET;
1376 r_buf->sin_port = htons (port);
1377 r_buf->sin_addr.s_addr =
1378 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
1379 #if HAVE_SOCKADDR_IN_SIN_LEN
1380 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1387 * Tries to convert @a addr string to an IP (v4 or v6) address.
1388 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1390 * @param addr a string, may not be 0-terminated.
1391 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1392 * 0-terminator should not be counted towards addrlen).
1393 * @param r_buf a buffer to fill.
1394 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1395 * case the contents of @a r_buf are undefined.
1398 GNUNET_STRINGS_to_address_ip (const char *addr,
1400 struct sockaddr_storage *r_buf)
1403 return GNUNET_STRINGS_to_address_ipv6 (addr,
1405 (struct sockaddr_in6 *) r_buf);
1406 return GNUNET_STRINGS_to_address_ipv4 (addr,
1408 (struct sockaddr_in *) r_buf);
1413 * Parse an address given as a string into a
1414 * `struct sockaddr`.
1416 * @param addr the address
1417 * @param[out] af set to the parsed address family (i.e. AF_INET)
1418 * @param[out] sa set to the parsed address
1419 * @return 0 on error, otherwise number of bytes in @a sa
1422 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1424 struct sockaddr **sa)
1426 char *cp = GNUNET_strdup (addr);
1432 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1434 GNUNET_STRINGS_to_address_ipv6 (cp,
1436 (struct sockaddr_in6 *) *sa))
1445 return sizeof (struct sockaddr_in6);
1450 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1452 GNUNET_STRINGS_to_address_ipv4 (cp,
1454 (struct sockaddr_in *) *sa))
1463 return sizeof (struct sockaddr_in);
1469 * Makes a copy of argv that consists of a single memory chunk that can be
1470 * freed with a single call to GNUNET_free();
1472 static char *const *
1473 _make_continuous_arg_copy (int argc, char *const *argv)
1475 size_t argvsize = 0;
1479 for (i = 0; i < argc; i++)
1480 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1481 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1482 p = (char *) &new_argv[argc + 1];
1483 for (i = 0; i < argc; i++)
1486 strcpy (p, argv[i]);
1487 p += strlen (argv[i]) + 1;
1489 new_argv[argc] = NULL;
1490 return (char *const *) new_argv;
1495 * Returns utf-8 encoded arguments.
1496 * Does nothing (returns a copy of argc and argv) on any platform
1498 * Returned argv has u8argv[u8argc] == NULL.
1499 * Returned argv is a single memory block, and can be freed with a single
1500 * GNUNET_free() call.
1502 * @param argc argc (as given by main())
1503 * @param argv argv (as given by main())
1504 * @param u8argc a location to store new argc in (though it's th same as argc)
1505 * @param u8argv a location to store new argv in
1506 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1509 GNUNET_STRINGS_get_utf8_args (int argc,
1512 char *const **u8argv)
1519 char **split_u8argv;
1521 wcmd = GetCommandLineW ();
1523 return GNUNET_SYSERR;
1524 wargv = CommandLineToArgvW (wcmd, &wargc);
1526 return GNUNET_SYSERR;
1528 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1530 for (i = 0; i < wargc; i++)
1533 /* Hopefully it will allocate us NUL-terminated strings... */
1535 (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1536 if (NULL == split_u8argv[i])
1539 for (j = 0; j < i; j++)
1540 free (split_u8argv[j]);
1541 GNUNET_free (split_u8argv);
1543 return GNUNET_SYSERR;
1547 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1550 for (i = 0; i < wargc; i++)
1551 free (split_u8argv[i]);
1552 free (split_u8argv);
1555 char *const *new_argv =
1556 (char *const *) _make_continuous_arg_copy (argc, argv);
1565 * Parse the given port policy. The format is
1566 * "[!]SPORT[-DPORT]".
1568 * @param port_policy string to parse
1569 * @param pp policy to fill in
1570 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1571 * @a port_policy is malformed
1574 parse_port_policy (const char *port_policy,
1575 struct GNUNET_STRINGS_PortPolicy *pp)
1585 pp->negate_portrange = GNUNET_YES;
1588 if (2 == sscanf (pos, "%u-%u%1s", &s, &e, eol))
1590 if ((0 == s) || (s > 0xFFFF) || (e < s) || (e > 0xFFFF))
1592 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n"));
1593 return GNUNET_SYSERR;
1595 pp->start_port = (uint16_t) s;
1596 pp->end_port = (uint16_t) e;
1599 if (1 == sscanf (pos, "%u%1s", &s, eol))
1601 if ((0 == s) || (s > 0xFFFF))
1603 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n"));
1604 return GNUNET_SYSERR;
1607 pp->start_port = (uint16_t) s;
1608 pp->end_port = (uint16_t) s;
1611 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1612 _ ("Malformed port policy `%s'\n"),
1614 return GNUNET_SYSERR;
1619 * Parse an IPv4 network policy. The argument specifies a list of
1620 * subnets. The format is
1621 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1622 * be terminated with a semicolon). The network must be given in
1623 * dotted-decimal notation. The netmask can be given in CIDR notation
1624 * (/16) or in dotted-decimal (/255.255.0.0).
1626 * @param routeListX a string specifying the IPv4 subnets
1627 * @return the converted list, terminated with all zeros;
1628 * NULL if the synatx is flawed
1630 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1631 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1639 unsigned int temps[8];
1641 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1647 if (NULL == routeListX)
1649 len = strlen (routeListX);
1652 routeList = GNUNET_strdup (routeListX);
1654 for (i = 0; i < len; i++)
1655 if (routeList[i] == ';')
1657 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) *
1663 for (colon = pos; ':' != routeList[colon]; colon++)
1664 if ((';' == routeList[colon]) || ('\0' == routeList[colon]))
1666 for (end = colon; ';' != routeList[end]; end++)
1667 if ('\0' == routeList[end])
1669 if ('\0' == routeList[end])
1671 routeList[end] = '\0';
1672 if (':' == routeList[colon])
1674 routeList[colon] = '\0';
1675 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1], &result[i].pp))
1678 cnt = sscanf (&routeList[pos],
1679 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1691 for (j = 0; j < 8; j++)
1692 if (temps[j] > 0xFF)
1694 LOG (GNUNET_ERROR_TYPE_WARNING,
1695 _ ("Invalid format for IP: `%s'\n"),
1697 GNUNET_free (result);
1698 GNUNET_free (routeList);
1701 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1702 (temps[2] << 8) + temps[3]);
1703 result[i].netmask.s_addr = htonl ((temps[4] << 24) + (temps[5] << 16) +
1704 (temps[6] << 8) + temps[7]);
1709 /* try second notation */
1710 cnt = sscanf (&routeList[pos],
1711 "%u.%u.%u.%u/%u%1s",
1720 for (j = 0; j < 4; j++)
1721 if (temps[j] > 0xFF)
1723 LOG (GNUNET_ERROR_TYPE_WARNING,
1724 _ ("Invalid format for IP: `%s'\n"),
1726 GNUNET_free (result);
1727 GNUNET_free (routeList);
1730 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1731 (temps[2] << 8) + temps[3]);
1732 if ((slash <= 32) && (slash >= 0))
1734 result[i].netmask.s_addr = 0;
1737 result[i].netmask.s_addr =
1738 (result[i].netmask.s_addr >> 1) + 0x80000000;
1741 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1748 LOG (GNUNET_ERROR_TYPE_WARNING,
1749 _ ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1751 GNUNET_free (result);
1752 GNUNET_free (routeList);
1753 return NULL; /* error */
1756 /* try third notation */
1758 cnt = sscanf (&routeList[pos],
1767 for (j = 0; j < 4; j++)
1768 if (temps[j] > 0xFF)
1770 LOG (GNUNET_ERROR_TYPE_WARNING,
1771 _ ("Invalid format for IP: `%s'\n"),
1773 GNUNET_free (result);
1774 GNUNET_free (routeList);
1777 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1778 (temps[2] << 8) + temps[3]);
1779 result[i].netmask.s_addr = 0;
1782 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1785 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1790 LOG (GNUNET_ERROR_TYPE_WARNING,
1791 _ ("Invalid format for IP: `%s'\n"),
1793 GNUNET_free (result);
1794 GNUNET_free (routeList);
1795 return NULL; /* error */
1797 if (pos < strlen (routeList))
1799 LOG (GNUNET_ERROR_TYPE_WARNING,
1800 _ ("Invalid format: `%s'\n"),
1802 GNUNET_free (result);
1803 GNUNET_free (routeList);
1804 return NULL; /* oops */
1806 GNUNET_free (routeList);
1807 return result; /* ok */
1812 * Parse an IPv6 network policy. The argument specifies a list of
1813 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1814 * (no whitespace, must be terminated with a semicolon). The network
1815 * must be given in colon-hex notation. The netmask must be given in
1816 * CIDR notation (/16) or can be omitted to specify a single host.
1817 * Note that the netmask is mandatory if ports are specified.
1819 * @param routeListX a string specifying the policy
1820 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1822 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1823 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1833 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1840 if (NULL == routeListX)
1842 len = strlen (routeListX);
1845 routeList = GNUNET_strdup (routeListX);
1847 for (i = 0; i < len; i++)
1848 if (';' == routeList[i])
1850 if (';' != routeList[len - 1])
1852 LOG (GNUNET_ERROR_TYPE_WARNING,
1853 _ ("Invalid network notation (does not end with ';': `%s')\n"),
1855 GNUNET_free (routeList);
1859 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) *
1866 while (';' != routeList[pos])
1869 while ((slash >= start) && (routeList[slash] != '/'))
1874 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
1879 routeList[pos] = '\0';
1880 for (colon = pos; ':' != routeList[colon]; colon--)
1881 if ('/' == routeList[colon])
1883 if (':' == routeList[colon])
1885 routeList[colon] = '\0';
1887 parse_port_policy (&routeList[colon + 1], &result[i].pp))
1889 GNUNET_free (result);
1890 GNUNET_free (routeList);
1894 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1898 if ((1 != sscanf (&routeList[slash + 1], "%u%1s", &bits, dummy)) ||
1902 LOG (GNUNET_ERROR_TYPE_WARNING,
1903 _ ("Wrong format `%s' for netmask\n"),
1904 &routeList[slash + 1]);
1908 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1910 GNUNET_free (result);
1911 GNUNET_free (routeList);
1917 result[i].netmask.s6_addr[off++] = 0xFF;
1922 result[i].netmask.s6_addr[off] =
1923 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1928 routeList[slash] = '\0';
1929 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1933 LOG (GNUNET_ERROR_TYPE_WARNING,
1934 _ ("Wrong format `%s' for network\n"),
1935 &routeList[slash + 1]);
1937 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
1938 GNUNET_free (result);
1939 GNUNET_free (routeList);
1945 GNUNET_free (routeList);
1950 /** ******************** Base64 encoding ***********/
1952 #define FILLCHAR '='
1953 static char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1954 "abcdefghijklmnopqrstuvwxyz"
1959 * Encode into Base64.
1961 * @param in the data to encode
1962 * @param len the length of the input
1963 * @param output where to write the output (*output should be NULL,
1965 * @return the size of the output
1968 GNUNET_STRINGS_base64_encode (const void *in, size_t len, char **output)
1970 const char *data = in;
1975 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1976 for (size_t i = 0; i < len; ++i)
1980 c = (data[i] >> 2) & 0x3f;
1981 opt[ret++] = cvt[(int) c];
1982 c = (data[i] << 4) & 0x3f;
1984 c |= (data[i] >> 4) & 0x0f;
1985 opt[ret++] = cvt[(int) c];
1988 c = (data[i] << 2) & 0x3f;
1990 c |= (data[i] >> 6) & 0x03;
1991 opt[ret++] = cvt[(int) c];
1996 opt[ret++] = FILLCHAR;
2001 opt[ret++] = cvt[(int) c];
2005 opt[ret++] = FILLCHAR;
2012 #define cvtfind(a) \
2013 ((((a) >= 'A') && ((a) <= 'Z')) \
2015 : (((a) >= 'a') && ((a) <= 'z')) \
2017 : (((a) >= '0') && ((a) <= '9')) \
2019 : ((a) == '+') ? 62 : ((a) == '/') ? 63 : -1)
2023 * Decode from Base64.
2025 * @param data the data to encode
2026 * @param len the length of the input
2027 * @param output where to write the output (*output should be NULL,
2029 * @return the size of the output
2032 GNUNET_STRINGS_base64_decode (const char *data, size_t len, void **out)
2037 #define CHECK_CRLF \
2038 while (data[i] == '\r' || data[i] == '\n') \
2040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, \
2041 "ignoring CR/LF\n"); \
2047 output = GNUNET_malloc ((len * 3 / 4) + 8);
2048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2049 "base64_decode decoding len=%d\n",
2051 for (size_t i = 0; i < len; ++i)
2057 if (FILLCHAR == data[i])
2059 c = (char) cvtfind (data[i]);
2062 c1 = (char) cvtfind (data[i]);
2063 c = (c << 2) | ((c1 >> 4) & 0x3);
2071 c = (char) cvtfind (c);
2072 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2082 c1 = (char) cvtfind (c1);
2083 c = ((c << 6) & 0xc0) | c1;
2093 /* end of strings.c */