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 *);
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,
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 {
236 * Name of the unit (or NULL for end of table).
241 * Factor to apply for this unit.
243 unsigned long long value;
248 * Convert a string of the form "4 X 5 Y" into a numeric value
249 * by interpreting "X" and "Y" as units and then multiplying
250 * the numbers with the values associated with the respective
251 * unit from the conversion table.
253 * @param input input string to parse
254 * @param table table with the conversion of unit names to numbers
255 * @param output where to store the result
256 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
259 convert_with_table(const char *input,
260 const struct ConversionTable *table,
261 unsigned long long *output)
263 unsigned long long ret;
266 unsigned long long last;
271 in = GNUNET_strdup(input);
272 for (tok = strtok(in, " "); tok != NULL; tok = strtok(NULL, " "))
277 while ((table[i].name != NULL) && (0 != strcasecmp(table[i].name, tok)))
279 if (table[i].name != NULL)
281 last *= table[i].value;
282 break; /* next tok */
289 last = strtoull(tok, &endptr, 10);
290 if ((0 != errno) || (endptr == tok))
293 return GNUNET_SYSERR; /* expected number */
295 if ('\0' == endptr[0])
296 break; /* next tok */
298 tok = endptr; /* and re-check (handles times like "10s") */
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 },
326 { "MB", 1000 * 1000 },
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)
619 if (fil[0] == DIR_SEPARATOR)
620 /* absolute path, just copy */
621 return GNUNET_strdup(fil);
627 LOG(GNUNET_ERROR_TYPE_WARNING,
628 _("Failed to expand `$HOME': environment variable `HOME' not set"));
631 fm = GNUNET_strdup(fm);
632 /* do not copy '~' */
635 /* skip over dir seperator to be consistent */
636 if (fil_ptr[0] == DIR_SEPARATOR)
647 buffer = GNUNET_malloc(len);
648 if (getcwd(buffer, len) != NULL)
653 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
664 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "getcwd");
665 buffer = getenv("PWD"); /* alternative */
667 fm = GNUNET_strdup(buffer);
670 fm = GNUNET_strdup("./"); /* give up */
672 GNUNET_asprintf(&buffer,
675 (fm[strlen(fm) - 1] == DIR_SEPARATOR) ? ""
681 fn = GNUNET_malloc(MAX_PATH + 1);
683 if ((lRet = plibc_conv_to_win_path(fil, fn)) != ERROR_SUCCESS)
685 SetErrnoFromWinError(lRet);
686 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
689 /* is the path relative? */
690 if ((0 != strncmp(fn + 1, ":\\", 2)) && (0 != strncmp(fn, "\\\\", 2)))
692 char szCurDir[MAX_PATH + 1];
694 lRet = GetCurrentDirectory(MAX_PATH + 1, szCurDir);
695 if (lRet + strlen(fn) + 1 > (MAX_PATH + 1))
697 SetErrnoFromWinError(ERROR_BUFFER_OVERFLOW);
698 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
701 GNUNET_asprintf(&buffer, "%s\\%s", szCurDir, fn);
712 * Give relative time in human-readable fancy format.
713 * This is one of the very few calls in the entire API that is
716 * @param delta time in milli seconds
717 * @param do_round are we allowed to round a bit?
718 * @return time as human-readable string
721 GNUNET_STRINGS_relative_time_to_string(struct GNUNET_TIME_Relative delta,
724 static char buf[128];
725 const char *unit = _(/* time unit */ "µs");
726 uint64_t dval = delta.rel_value_us;
728 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
730 if (0 == delta.rel_value_us)
732 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
735 unit = _(/* time unit */ "ms");
736 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
739 unit = _(/* time unit */ "s");
740 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
743 unit = _(/* time unit */ "m");
744 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
747 unit = _(/* time unit */ "h");
748 if (((GNUNET_YES == do_round) && (dval > 5 * 24)) ||
753 unit = _(/* time unit */ "day");
755 unit = _(/* time unit */ "days");
761 GNUNET_snprintf(buf, sizeof(buf), "%llu %s", dval, unit);
767 * "asctime", except for GNUnet time. Converts a GNUnet internal
768 * absolute time (which is in UTC) to a string in local time.
769 * Note that the returned value will be overwritten if this function
772 * @param t the absolute time to convert
773 * @return timestamp in human-readable form in local time
776 GNUNET_STRINGS_absolute_time_to_string(struct GNUNET_TIME_Absolute t)
778 static char buf[255];
782 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
783 return _("end of time");
784 tt = t.abs_value_us / 1000LL / 1000LL;
786 /* This is hacky, but i don't know a way to detect libc character encoding.
787 * Just expect utf8 from glibc these days.
788 * As for msvcrt, use the wide variant, which always returns utf16
789 * (otherwise we'd have to detect current codepage or use W32API character
790 * set conversion routines to convert to UTF8).
793 strftime(buf, sizeof(buf), "%a %b %d %H:%M:%S %Y", tp);
796 static wchar_t wbuf[255];
801 sizeof(wbuf) / sizeof(wchar_t),
802 L"%a %b %d %H:%M:%S %Y",
806 conved = u16_to_u8(wbuf,
807 sizeof(wbuf) / sizeof(wchar_t),
810 if (conved != (uint8_t *)buf)
812 GNUNET_strlcpy(buf, (char *)conved, sizeof(buf));
823 * Returns a pointer to a part of filename (allocates nothing)!
825 * @param filename filename to extract basename from
826 * @return short (base) name of the file (that is, everything following the
827 * last directory separator in filename. If filename ends with a
828 * directory separator, the result will be a zero-length string.
829 * If filename has no directory separators, the result is filename
833 GNUNET_STRINGS_get_short_name(const char *filename)
835 const char *short_fn = filename;
838 while (NULL != (ss = strstr(short_fn, DIR_SEPARATOR_STR)) && (ss[1] != '\0'))
845 * Get the decoded value corresponding to a character according to Crockford
848 * @param a a character
849 * @return corresponding numeric value
852 getValue__(unsigned char a)
870 /* also consider U to be V */
879 if ((a >= '0') && (a <= '9'))
881 if ((a >= 'a') && (a <= 'z'))
883 /* return (a - 'a' + 10); */
885 if ((a >= 'A') && (a <= 'Z'))
895 return(a - 'A' + 10 - dec);
902 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
903 * Returns a pointer to the byte after the last byte in the string, that
904 * is where the 0-terminator was placed if there was room.
906 * @param data data to encode
907 * @param size size of data (in bytes)
908 * @param out buffer to fill
909 * @param out_size size of the buffer. Must be large enough to hold
910 * (size * 8 + 4) / 5 bytes
911 * @return pointer to the next byte in @a out or NULL on error.
914 GNUNET_STRINGS_data_to_string(const void *data,
920 * 32 characters for encoding
922 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
927 const unsigned char *udata;
930 if (out_size < (size * 8 + 4) / 5)
939 while ((rpos < size) || (vbit > 0))
941 if ((rpos < size) && (vbit < 5))
943 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
948 bits <<= (5 - vbit); /* zero-padding */
949 GNUNET_assert(vbit == ((size * 8) % 5));
952 if (wpos >= out_size)
957 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
960 GNUNET_assert(0 == vbit);
968 * Return the base32crockford encoding of the given buffer.
970 * The returned string will be freshly allocated, and must be free'd
971 * with GNUNET_free().
973 * @param buffer with data
974 * @param size size of the buffer
975 * @return freshly allocated, null-terminated string
978 GNUNET_STRINGS_data_to_string_alloc(const void *buf, size_t size)
981 size_t len = size * 8;
987 str_buf = GNUNET_malloc(len + 1);
988 end = GNUNET_STRINGS_data_to_string(buf, size, str_buf, len);
991 GNUNET_free(str_buf);
1000 * Convert Crockford Base32hex encoding back to data.
1001 * @a out_size must match exactly the size of the data before it was encoded.
1003 * @param enc the encoding
1004 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
1005 * @param out location where to store the decoded data
1006 * @param out_size size of the output buffer @a out
1007 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
1010 GNUNET_STRINGS_string_to_data(const char *enc,
1021 unsigned char *uout;
1022 unsigned int encoded_len = out_size * 8;
1028 return GNUNET_SYSERR;
1033 if ((encoded_len % 5) > 0)
1035 vbit = encoded_len % 5; /* padding! */
1037 bits = (ret = getValue__(enc[--rpos])) >> shift;
1043 bits = (ret = getValue__(enc[--rpos]));
1045 if ((encoded_len + shift) / 5 != enclen)
1046 return GNUNET_SYSERR;
1048 return GNUNET_SYSERR;
1054 return GNUNET_SYSERR;
1056 bits = ((ret = getValue__(enc[--rpos])) << vbit) | bits;
1058 return GNUNET_SYSERR;
1062 uout[--wpos] = (unsigned char)bits;
1067 if ((0 != rpos) || (0 != vbit))
1068 return GNUNET_SYSERR;
1074 * Parse a path that might be an URI.
1076 * @param path path to parse. Must be NULL-terminated.
1077 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1078 * represents the URI scheme will be stored. Can be NULL. The string is
1079 * allocated by the function, and should be freed by GNUNET_free() when
1080 * it is no longer needed.
1081 * @param path_part a pointer to 'const char *' where a pointer to the path
1082 * part of the URI will be stored. Can be NULL. Points to the same block
1083 * of memory as 'path', and thus must not be freed. Might point to '\0',
1084 * if path part is zero-length.
1085 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1086 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1087 * (if they weren't NULL).
1090 GNUNET_STRINGS_parse_uri(const char *path,
1092 const char **path_part)
1098 const char *post_scheme_part = NULL;
1101 for (end = 0, i = 0; !end && i < len; i++)
1106 if ((path[i] == ':') && (i > 0))
1111 if (!((path[i] >= 'A' && path[i] <= 'Z') ||
1112 (path[i] >= 'a' && path[i] <= 'z') ||
1113 (path[i] >= '0' && path[i] <= '9') || path[i] == '+' ||
1114 path[i] == '-' || (path[i] == '.')))
1129 post_scheme_part = &path[i];
1137 if (post_scheme_part == NULL)
1141 *scheme_part = GNUNET_malloc(post_scheme_part - path + 1);
1142 GNUNET_memcpy(*scheme_part, path, post_scheme_part - path);
1143 (*scheme_part)[post_scheme_part - path] = '\0';
1146 *path_part = post_scheme_part;
1152 * Check whether @a filename is absolute or not, and if it's an URI
1154 * @param filename filename to check
1155 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1156 * assume it's not URI
1157 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1158 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1159 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1160 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1161 * The string is allocated by the function, and should be freed with
1162 * GNUNET_free(). Can be NULL.
1163 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1166 GNUNET_STRINGS_path_is_absolute(const char *filename,
1169 char **r_uri_scheme)
1174 const char *post_scheme_path;
1177 /* consider POSIX paths to be absolute too, even on W32,
1178 * as plibc expansion will fix them for us.
1180 if (filename[0] == '/')
1184 is_uri = GNUNET_STRINGS_parse_uri(filename, &uri, &post_scheme_path);
1190 *r_uri_scheme = uri;
1192 GNUNET_free_non_null(uri);
1194 len = strlen(post_scheme_path);
1195 /* Special check for file:///c:/blah
1196 * We want to parse 'c:/', not '/c:/'
1198 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1199 post_scheme_path = &post_scheme_path[1];
1201 return GNUNET_STRINGS_path_is_absolute(post_scheme_path,
1210 *r_is_uri = GNUNET_NO;
1213 len = strlen(filename);
1215 ((filename[0] >= 'A' && filename[0] <= 'Z') ||
1216 (filename[0] >= 'a' && filename[0] <= 'z')) &&
1217 filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1224 #define _IFMT 0170000 /* type of file */
1225 #define _IFLNK 0120000 /* symbolic link */
1226 #define S_ISLNK(m) (((m) & _IFMT) == _IFLNK)
1231 * Perform @a checks on @a filename.
1233 * @param filename file to check
1234 * @param checks checks to perform
1235 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1236 * fails, #GNUNET_SYSERR when a check can't be performed
1239 GNUNET_STRINGS_check_filename(const char *filename,
1240 enum GNUNET_STRINGS_FilenameCheck checks)
1244 if ((NULL == filename) || (filename[0] == '\0'))
1245 return GNUNET_SYSERR;
1246 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1247 if (!GNUNET_STRINGS_path_is_absolute(filename, GNUNET_NO, NULL, NULL))
1250 (GNUNET_STRINGS_CHECK_EXISTS | GNUNET_STRINGS_CHECK_IS_DIRECTORY |
1251 GNUNET_STRINGS_CHECK_IS_LINK)))
1253 if (0 != stat(filename, &st))
1255 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1258 return GNUNET_SYSERR;
1261 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1262 if (!S_ISDIR(st.st_mode))
1264 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1265 if (!S_ISLNK(st.st_mode))
1272 * Tries to convert @a zt_addr string to an IPv6 address.
1273 * The string is expected to have the format "[ABCD::01]:80".
1275 * @param zt_addr 0-terminated string. May be mangled by the function.
1276 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1277 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1278 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1279 * @return #GNUNET_OK if conversion succeded.
1280 * #GNUNET_SYSERR otherwise, in which
1281 * case the contents of @a r_buf are undefined.
1284 GNUNET_STRINGS_to_address_ipv6(const char *zt_addr,
1286 struct sockaddr_in6 *r_buf)
1288 char zbuf[addrlen + 1];
1295 return GNUNET_SYSERR;
1296 GNUNET_memcpy(zbuf, zt_addr, addrlen);
1299 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1300 _("IPv6 address did not start with `['\n"));
1301 return GNUNET_SYSERR;
1303 zbuf[addrlen] = '\0';
1304 port_colon = strrchr(zbuf, ':');
1305 if (NULL == port_colon)
1307 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1308 _("IPv6 address did contain ':' to separate port number\n"));
1309 return GNUNET_SYSERR;
1311 if (']' != *(port_colon - 1))
1314 GNUNET_ERROR_TYPE_WARNING,
1315 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1316 return GNUNET_SYSERR;
1318 ret = sscanf(port_colon, ":%u%1s", &port, dummy);
1319 if ((1 != ret) || (port > 65535))
1322 GNUNET_ERROR_TYPE_WARNING,
1323 _("IPv6 address did contain a valid port number after the last ':'\n"));
1324 return GNUNET_SYSERR;
1326 *(port_colon - 1) = '\0';
1327 memset(r_buf, 0, sizeof(struct sockaddr_in6));
1328 ret = inet_pton(AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1331 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1332 _("Invalid IPv6 address `%s': %s\n"),
1335 return GNUNET_SYSERR;
1337 r_buf->sin6_port = htons(port);
1338 r_buf->sin6_family = AF_INET6;
1339 #if HAVE_SOCKADDR_IN_SIN_LEN
1340 r_buf->sin6_len = (u_char)sizeof(struct sockaddr_in6);
1347 * Tries to convert 'zt_addr' string to an IPv4 address.
1348 * The string is expected to have the format "1.2.3.4:80".
1350 * @param zt_addr 0-terminated string. May be mangled by the function.
1351 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1352 * @param r_buf a buffer to fill.
1353 * @return #GNUNET_OK if conversion succeded.
1354 * #GNUNET_SYSERR otherwise, in which case
1355 * the contents of @a r_buf are undefined.
1358 GNUNET_STRINGS_to_address_ipv4(const char *zt_addr,
1360 struct sockaddr_in *r_buf)
1362 unsigned int temps[4];
1368 return GNUNET_SYSERR;
1369 cnt = sscanf(zt_addr,
1370 "%u.%u.%u.%u:%u%1s",
1378 return GNUNET_SYSERR;
1379 for (cnt = 0; cnt < 4; cnt++)
1380 if (temps[cnt] > 0xFF)
1381 return GNUNET_SYSERR;
1383 return GNUNET_SYSERR;
1384 r_buf->sin_family = AF_INET;
1385 r_buf->sin_port = htons(port);
1386 r_buf->sin_addr.s_addr =
1387 htonl((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
1388 #if HAVE_SOCKADDR_IN_SIN_LEN
1389 r_buf->sin_len = (u_char)sizeof(struct sockaddr_in);
1396 * Tries to convert @a addr string to an IP (v4 or v6) address.
1397 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1399 * @param addr a string, may not be 0-terminated.
1400 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1401 * 0-terminator should not be counted towards addrlen).
1402 * @param r_buf a buffer to fill.
1403 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1404 * case the contents of @a r_buf are undefined.
1407 GNUNET_STRINGS_to_address_ip(const char *addr,
1409 struct sockaddr_storage *r_buf)
1412 return GNUNET_STRINGS_to_address_ipv6(addr,
1414 (struct sockaddr_in6 *)r_buf);
1415 return GNUNET_STRINGS_to_address_ipv4(addr,
1417 (struct sockaddr_in *)r_buf);
1422 * Parse an address given as a string into a
1423 * `struct sockaddr`.
1425 * @param addr the address
1426 * @param[out] af set to the parsed address family (i.e. AF_INET)
1427 * @param[out] sa set to the parsed address
1428 * @return 0 on error, otherwise number of bytes in @a sa
1431 GNUNET_STRINGS_parse_socket_addr(const char *addr,
1433 struct sockaddr **sa)
1435 char *cp = GNUNET_strdup(addr);
1441 *sa = GNUNET_malloc(sizeof(struct sockaddr_in6));
1443 GNUNET_STRINGS_to_address_ipv6(cp,
1445 (struct sockaddr_in6 *)*sa))
1454 return sizeof(struct sockaddr_in6);
1459 *sa = GNUNET_malloc(sizeof(struct sockaddr_in));
1461 GNUNET_STRINGS_to_address_ipv4(cp,
1463 (struct sockaddr_in *)*sa))
1472 return sizeof(struct sockaddr_in);
1478 * Makes a copy of argv that consists of a single memory chunk that can be
1479 * freed with a single call to GNUNET_free();
1481 static char *const *
1482 _make_continuous_arg_copy(int argc, char *const *argv)
1484 size_t argvsize = 0;
1489 for (i = 0; i < argc; i++)
1490 argvsize += strlen(argv[i]) + 1 + sizeof(char *);
1491 new_argv = GNUNET_malloc(argvsize + sizeof(char *));
1492 p = (char *)&new_argv[argc + 1];
1493 for (i = 0; i < argc; i++)
1497 p += strlen(argv[i]) + 1;
1499 new_argv[argc] = NULL;
1500 return (char *const *)new_argv;
1505 * Returns utf-8 encoded arguments.
1506 * Does nothing (returns a copy of argc and argv) on any platform
1508 * Returned argv has u8argv[u8argc] == NULL.
1509 * Returned argv is a single memory block, and can be freed with a single
1510 * GNUNET_free() call.
1512 * @param argc argc (as given by main())
1513 * @param argv argv (as given by main())
1514 * @param u8argc a location to store new argc in (though it's th same as argc)
1515 * @param u8argv a location to store new argv in
1516 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1519 GNUNET_STRINGS_get_utf8_args(int argc,
1522 char *const **u8argv)
1529 char **split_u8argv;
1531 wcmd = GetCommandLineW();
1533 return GNUNET_SYSERR;
1534 wargv = CommandLineToArgvW(wcmd, &wargc);
1536 return GNUNET_SYSERR;
1538 split_u8argv = GNUNET_malloc(argc * sizeof(char *));
1540 for (i = 0; i < wargc; i++)
1543 /* Hopefully it will allocate us NUL-terminated strings... */
1545 (char *)u16_to_u8(wargv[i], wcslen(wargv[i]) + 1, NULL, &strl);
1546 if (NULL == split_u8argv[i])
1549 for (j = 0; j < i; j++)
1550 free(split_u8argv[j]);
1551 GNUNET_free(split_u8argv);
1553 return GNUNET_SYSERR;
1557 *u8argv = _make_continuous_arg_copy(wargc, split_u8argv);
1560 for (i = 0; i < wargc; i++)
1561 free(split_u8argv[i]);
1565 char *const *new_argv =
1566 (char *const *)_make_continuous_arg_copy(argc, argv);
1575 * Parse the given port policy. The format is
1576 * "[!]SPORT[-DPORT]".
1578 * @param port_policy string to parse
1579 * @param pp policy to fill in
1580 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1581 * @a port_policy is malformed
1584 parse_port_policy(const char *port_policy,
1585 struct GNUNET_STRINGS_PortPolicy *pp)
1595 pp->negate_portrange = GNUNET_YES;
1598 if (2 == sscanf(pos, "%u-%u%1s", &s, &e, eol))
1600 if ((0 == s) || (s > 0xFFFF) || (e < s) || (e > 0xFFFF))
1602 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, _("Port not in range\n"));
1603 return GNUNET_SYSERR;
1605 pp->start_port = (uint16_t)s;
1606 pp->end_port = (uint16_t)e;
1609 if (1 == sscanf(pos, "%u%1s", &s, eol))
1611 if ((0 == s) || (s > 0xFFFF))
1613 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, _("Port not in range\n"));
1614 return GNUNET_SYSERR;
1617 pp->start_port = (uint16_t)s;
1618 pp->end_port = (uint16_t)s;
1621 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1622 _("Malformed port policy `%s'\n"),
1624 return GNUNET_SYSERR;
1629 * Parse an IPv4 network policy. The argument specifies a list of
1630 * subnets. The format is
1631 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1632 * be terminated with a semicolon). The network must be given in
1633 * dotted-decimal notation. The netmask can be given in CIDR notation
1634 * (/16) or in dotted-decimal (/255.255.0.0).
1636 * @param routeListX a string specifying the IPv4 subnets
1637 * @return the converted list, terminated with all zeros;
1638 * NULL if the synatx is flawed
1640 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1641 GNUNET_STRINGS_parse_ipv4_policy(const char *routeListX)
1649 unsigned int temps[8];
1651 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1657 if (NULL == routeListX)
1659 len = strlen(routeListX);
1662 routeList = GNUNET_strdup(routeListX);
1664 for (i = 0; i < len; i++)
1665 if (routeList[i] == ';')
1667 result = GNUNET_malloc(sizeof(struct GNUNET_STRINGS_IPv4NetworkPolicy) *
1673 for (colon = pos; ':' != routeList[colon]; colon++)
1674 if ((';' == routeList[colon]) || ('\0' == routeList[colon]))
1676 for (end = colon; ';' != routeList[end]; end++)
1677 if ('\0' == routeList[end])
1679 if ('\0' == routeList[end])
1681 routeList[end] = '\0';
1682 if (':' == routeList[colon])
1684 routeList[colon] = '\0';
1685 if (GNUNET_OK != parse_port_policy(&routeList[colon + 1], &result[i].pp))
1688 cnt = sscanf(&routeList[pos],
1689 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1701 for (j = 0; j < 8; j++)
1702 if (temps[j] > 0xFF)
1704 LOG(GNUNET_ERROR_TYPE_WARNING,
1705 _("Invalid format for IP: `%s'\n"),
1707 GNUNET_free(result);
1708 GNUNET_free(routeList);
1711 result[i].network.s_addr = htonl((temps[0] << 24) + (temps[1] << 16) +
1712 (temps[2] << 8) + temps[3]);
1713 result[i].netmask.s_addr = htonl((temps[4] << 24) + (temps[5] << 16) +
1714 (temps[6] << 8) + temps[7]);
1719 /* try second notation */
1720 cnt = sscanf(&routeList[pos],
1721 "%u.%u.%u.%u/%u%1s",
1730 for (j = 0; j < 4; j++)
1731 if (temps[j] > 0xFF)
1733 LOG(GNUNET_ERROR_TYPE_WARNING,
1734 _("Invalid format for IP: `%s'\n"),
1736 GNUNET_free(result);
1737 GNUNET_free(routeList);
1740 result[i].network.s_addr = htonl((temps[0] << 24) + (temps[1] << 16) +
1741 (temps[2] << 8) + temps[3]);
1742 if ((slash <= 32) && (slash >= 0))
1744 result[i].netmask.s_addr = 0;
1747 result[i].netmask.s_addr =
1748 (result[i].netmask.s_addr >> 1) + 0x80000000;
1751 result[i].netmask.s_addr = htonl(result[i].netmask.s_addr);
1758 LOG(GNUNET_ERROR_TYPE_WARNING,
1759 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1761 GNUNET_free(result);
1762 GNUNET_free(routeList);
1763 return NULL; /* error */
1766 /* try third notation */
1768 cnt = sscanf(&routeList[pos],
1777 for (j = 0; j < 4; j++)
1778 if (temps[j] > 0xFF)
1780 LOG(GNUNET_ERROR_TYPE_WARNING,
1781 _("Invalid format for IP: `%s'\n"),
1783 GNUNET_free(result);
1784 GNUNET_free(routeList);
1787 result[i].network.s_addr = htonl((temps[0] << 24) + (temps[1] << 16) +
1788 (temps[2] << 8) + temps[3]);
1789 result[i].netmask.s_addr = 0;
1792 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1795 result[i].netmask.s_addr = htonl(result[i].netmask.s_addr);
1800 LOG(GNUNET_ERROR_TYPE_WARNING,
1801 _("Invalid format for IP: `%s'\n"),
1803 GNUNET_free(result);
1804 GNUNET_free(routeList);
1805 return NULL; /* error */
1807 if (pos < strlen(routeList))
1809 LOG(GNUNET_ERROR_TYPE_WARNING,
1810 _("Invalid format: `%s'\n"),
1812 GNUNET_free(result);
1813 GNUNET_free(routeList);
1814 return NULL; /* oops */
1816 GNUNET_free(routeList);
1817 return result; /* ok */
1822 * Parse an IPv6 network policy. The argument specifies a list of
1823 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1824 * (no whitespace, must be terminated with a semicolon). The network
1825 * must be given in colon-hex notation. The netmask must be given in
1826 * CIDR notation (/16) or can be omitted to specify a single host.
1827 * Note that the netmask is mandatory if ports are specified.
1829 * @param routeListX a string specifying the policy
1830 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1832 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1833 GNUNET_STRINGS_parse_ipv6_policy(const char *routeListX)
1843 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1850 if (NULL == routeListX)
1852 len = strlen(routeListX);
1855 routeList = GNUNET_strdup(routeListX);
1857 for (i = 0; i < len; i++)
1858 if (';' == routeList[i])
1860 if (';' != routeList[len - 1])
1862 LOG(GNUNET_ERROR_TYPE_WARNING,
1863 _("Invalid network notation (does not end with ';': `%s')\n"),
1865 GNUNET_free(routeList);
1869 result = GNUNET_malloc(sizeof(struct GNUNET_STRINGS_IPv6NetworkPolicy) *
1876 while (';' != routeList[pos])
1879 while ((slash >= start) && (routeList[slash] != '/'))
1884 memset(&result[i].netmask, 0xFF, sizeof(struct in6_addr));
1889 routeList[pos] = '\0';
1890 for (colon = pos; ':' != routeList[colon]; colon--)
1891 if ('/' == routeList[colon])
1893 if (':' == routeList[colon])
1895 routeList[colon] = '\0';
1897 parse_port_policy(&routeList[colon + 1], &result[i].pp))
1899 GNUNET_free(result);
1900 GNUNET_free(routeList);
1904 ret = inet_pton(AF_INET6, &routeList[slash + 1], &result[i].netmask);
1908 if ((1 != sscanf(&routeList[slash + 1], "%u%1s", &bits, dummy)) ||
1912 LOG(GNUNET_ERROR_TYPE_WARNING,
1913 _("Wrong format `%s' for netmask\n"),
1914 &routeList[slash + 1]);
1918 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1920 GNUNET_free(result);
1921 GNUNET_free(routeList);
1927 result[i].netmask.s6_addr[off++] = 0xFF;
1932 result[i].netmask.s6_addr[off] =
1933 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1938 routeList[slash] = '\0';
1939 ret = inet_pton(AF_INET6, &routeList[start], &result[i].network);
1943 LOG(GNUNET_ERROR_TYPE_WARNING,
1944 _("Wrong format `%s' for network\n"),
1945 &routeList[slash + 1]);
1947 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "inet_pton");
1948 GNUNET_free(result);
1949 GNUNET_free(routeList);
1955 GNUNET_free(routeList);
1960 /** ******************** Base64 encoding ***********/
1962 #define FILLCHAR '='
1963 static char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1964 "abcdefghijklmnopqrstuvwxyz"
1969 * Encode into Base64.
1971 * @param in the data to encode
1972 * @param len the length of the input
1973 * @param output where to write the output (*output should be NULL,
1975 * @return the size of the output
1978 GNUNET_STRINGS_base64_encode(const void *in, size_t len, char **output)
1980 const char *data = in;
1985 opt = GNUNET_malloc(2 + (len * 4 / 3) + 8);
1986 for (size_t i = 0; i < len; ++i)
1990 c = (data[i] >> 2) & 0x3f;
1991 opt[ret++] = cvt[(int)c];
1992 c = (data[i] << 4) & 0x3f;
1994 c |= (data[i] >> 4) & 0x0f;
1995 opt[ret++] = cvt[(int)c];
1998 c = (data[i] << 2) & 0x3f;
2000 c |= (data[i] >> 6) & 0x03;
2001 opt[ret++] = cvt[(int)c];
2006 opt[ret++] = FILLCHAR;
2011 opt[ret++] = cvt[(int)c];
2015 opt[ret++] = FILLCHAR;
2022 #define cvtfind(a) \
2023 ((((a) >= 'A') && ((a) <= 'Z')) \
2025 : (((a) >= 'a') && ((a) <= 'z')) \
2027 : (((a) >= '0') && ((a) <= '9')) \
2029 : ((a) == '+') ? 62 : ((a) == '/') ? 63 : -1)
2033 * Decode from Base64.
2035 * @param data the data to encode
2036 * @param len the length of the input
2037 * @param output where to write the output (*output should be NULL,
2039 * @return the size of the output
2042 GNUNET_STRINGS_base64_decode(const char *data, size_t len, void **out)
2047 #define CHECK_CRLF \
2048 while (data[i] == '\r' || data[i] == '\n') \
2050 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, \
2051 "ignoring CR/LF\n"); \
2057 output = GNUNET_malloc((len * 3 / 4) + 8);
2058 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2059 "base64_decode decoding len=%d\n",
2061 for (size_t i = 0; i < len; ++i)
2067 if (FILLCHAR == data[i])
2069 c = (char)cvtfind(data[i]);
2072 c1 = (char)cvtfind(data[i]);
2073 c = (c << 2) | ((c1 >> 4) & 0x3);
2081 c = (char)cvtfind(c);
2082 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2092 c1 = (char)cvtfind(c1);
2093 c = ((c << 6) & 0xc0) | c1;
2103 /* end of strings.c */