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;
273 in = GNUNET_strdup (input);
274 for (tok = strtok_r (in, " ", &sptr);
276 tok = strtok_r (NULL, " ", &sptr))
281 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
283 if (table[i].name != NULL)
285 last *= table[i].value;
286 break; /* next tok */
293 last = strtoull (tok, &endptr, 10);
294 if ((0 != errno) || (endptr == tok))
297 return GNUNET_SYSERR; /* expected number */
299 if ('\0' == endptr[0])
300 break; /* next tok */
302 tok = endptr; /* and re-check (handles times like "10s") */
315 * Convert a given fancy human-readable size to bytes.
317 * @param fancy_size human readable string (i.e. 1 MB)
318 * @param size set to the size in bytes
319 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
322 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
323 unsigned long long *size)
325 static const struct ConversionTable table[] =
329 { "MiB", 1024 * 1024 },
330 { "MB", 1000 * 1000 },
331 { "GiB", 1024 * 1024 * 1024 },
332 { "GB", 1000 * 1000 * 1000 },
333 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL },
334 { "TB", 1000LL * 1000LL * 1000LL * 1024LL },
335 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
336 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL },
337 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
338 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL },
341 return convert_with_table (fancy_size, table, size);
346 * Convert a given fancy human-readable time to our internal
349 * @param fancy_time human readable string (i.e. 1 minute)
350 * @param rtime set to the relative time
351 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
354 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
355 struct GNUNET_TIME_Relative *rtime)
357 static const struct ConversionTable table[] =
360 { "s", 1000 * 1000LL },
361 { "second", 1000 * 1000LL },
362 { "seconds", 1000 * 1000LL },
363 { "\"", 1000 * 1000LL },
364 { "m", 60 * 1000 * 1000LL },
365 { "min", 60 * 1000 * 1000LL },
366 { "minute", 60 * 1000 * 1000LL },
367 { "minutes", 60 * 1000 * 1000LL },
368 { "'", 60 * 1000 * 1000LL },
369 { "h", 60 * 60 * 1000 * 1000LL },
370 { "hour", 60 * 60 * 1000 * 1000LL },
371 { "hours", 60 * 60 * 1000 * 1000LL },
372 { "d", 24 * 60 * 60 * 1000LL * 1000LL },
373 { "day", 24 * 60 * 60 * 1000LL * 1000LL },
374 { "days", 24 * 60 * 60 * 1000LL * 1000LL },
375 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL },
376 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL },
377 { "year", 31536000000000LL /* year */ },
378 { "years", 31536000000000LL /* year */ },
379 { "a", 31536000000000LL /* year */ },
382 unsigned long long val;
384 if (0 == strcasecmp ("forever", fancy_time))
386 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
389 ret = convert_with_table (fancy_time, table, &val);
390 rtime->rel_value_us = (uint64_t) val;
396 * Convert a given fancy human-readable time to our internal
397 * representation. The human-readable time is expected to be
398 * in local time, whereas the returned value will be in UTC.
400 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
401 * @param atime set to the absolute time
402 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
405 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
406 struct GNUNET_TIME_Absolute *atime)
412 if (0 == strcasecmp ("end of time", fancy_time))
414 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
417 eos = &fancy_time[strlen (fancy_time)];
418 memset (&tv, 0, sizeof(tv));
419 if ((eos != strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
420 (eos != strptime (fancy_time, "%c", &tv)) &&
421 (eos != strptime (fancy_time, "%Ec", &tv)) &&
422 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
423 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
424 (eos != strptime (fancy_time, "%x", &tv)) &&
425 (eos != strptime (fancy_time, "%Ex", &tv)) &&
426 (eos != strptime (fancy_time, "%Y-%m-%d", &tv)) &&
427 (eos != strptime (fancy_time, "%Y-%m", &tv)) &&
428 (eos != strptime (fancy_time, "%Y", &tv)))
429 return GNUNET_SYSERR;
431 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
437 * Convert the len characters long character sequence
438 * given in input that is in the given input charset
439 * to a string in given output charset.
441 * @param input input string
442 * @param len number of bytes in @a input
443 * @param input_charset character set used for @a input
444 * @param output_charset desired character set for the return value
445 * @return the converted string (0-terminated),
446 * if conversion fails, a copy of the orignal
447 * string is returned.
450 GNUNET_STRINGS_conv (const char *input,
452 const char *input_charset,
453 const char *output_charset)
457 char *encoded_string;
458 size_t u8_string_length;
459 size_t encoded_string_length;
461 u8_string = u8_conv_from_encoding (input_charset,
468 if (NULL == u8_string)
470 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
473 if (0 == strcmp (output_charset, "UTF-8"))
475 ret = GNUNET_malloc (u8_string_length + 1);
476 GNUNET_memcpy (ret, u8_string, u8_string_length);
477 ret[u8_string_length] = '\0';
481 encoded_string = u8_conv_to_encoding (output_charset,
487 &encoded_string_length);
489 if (NULL == encoded_string)
491 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
494 ret = GNUNET_malloc (encoded_string_length + 1);
495 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
496 ret[encoded_string_length] = '\0';
497 free (encoded_string);
500 LOG (GNUNET_ERROR_TYPE_WARNING,
501 _ ("Character sets requested were `%s'->`%s'\n"),
504 ret = GNUNET_malloc (len + 1);
505 GNUNET_memcpy (ret, input, len);
512 * Convert the len characters long character sequence
513 * given in input that is in the given charset
516 * @param input the input string (not necessarily 0-terminated)
517 * @param len the number of bytes in the @a input
518 * @param charset character set to convert from
519 * @return the converted string (0-terminated),
520 * if conversion fails, a copy of the orignal
521 * string is returned.
524 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
526 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
531 * Convert the len bytes-long UTF-8 string
532 * given in input to the given charset.
534 * @param input the input string (not necessarily 0-terminated)
535 * @param len the number of bytes in the @a input
536 * @param charset character set to convert to
537 * @return the converted string (0-terminated),
538 * if conversion fails, a copy of the orignal
539 * string is returned.
542 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
544 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
549 * Convert the utf-8 input string to lowercase.
550 * Output needs to be allocated appropriately.
552 * @param input input string
553 * @param output output buffer
556 GNUNET_STRINGS_utf8_tolower (const char *input, char *output)
561 tmp_in = u8_tolower ((uint8_t *) input,
562 strlen ((char *) input),
567 GNUNET_memcpy (output, tmp_in, len);
574 * Convert the utf-8 input string to uppercase.
575 * Output needs to be allocated appropriately.
577 * @param input input string
578 * @param output output buffer
581 GNUNET_STRINGS_utf8_toupper (const char *input, char *output)
586 tmp_in = u8_toupper ((uint8_t *) input,
587 strlen ((char *) input),
592 GNUNET_memcpy (output, tmp_in, len);
599 * Complete filename (a la shell) from abbrevition.
600 * @param fil the name of the file, may contain ~/ or
601 * be relative to the current directory
602 * @returns the full file name,
603 * NULL is returned on error
606 GNUNET_STRINGS_filename_expand (const char *fil)
616 if (fil[0] == DIR_SEPARATOR)
617 /* absolute path, just copy */
618 return GNUNET_strdup (fil);
621 fm = getenv ("HOME");
624 LOG (GNUNET_ERROR_TYPE_WARNING,
625 _ ("Failed to expand `$HOME': environment variable `HOME' not set"));
628 fm = GNUNET_strdup (fm);
629 /* do not copy '~' */
632 /* skip over dir seperator to be consistent */
633 if (fil_ptr[0] == DIR_SEPARATOR)
644 buffer = GNUNET_malloc (len);
645 if (getcwd (buffer, len) != NULL)
650 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
653 GNUNET_free (buffer);
656 GNUNET_free (buffer);
661 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
662 buffer = getenv ("PWD"); /* alternative */
664 fm = GNUNET_strdup (buffer);
667 fm = GNUNET_strdup ("./"); /* give up */
669 GNUNET_asprintf (&buffer,
672 (fm[strlen (fm) - 1] == DIR_SEPARATOR) ? ""
681 * Give relative time in human-readable fancy format.
682 * This is one of the very few calls in the entire API that is
685 * @param delta time in milli seconds
686 * @param do_round are we allowed to round a bit?
687 * @return time as human-readable string
690 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
693 static char buf[128];
694 const char *unit = _ (/* time unit */ "µs");
695 uint64_t dval = delta.rel_value_us;
697 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
698 return _ ("forever");
699 if (0 == delta.rel_value_us)
701 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
704 unit = _ (/* time unit */ "ms");
705 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
708 unit = _ (/* time unit */ "s");
709 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
712 unit = _ (/* time unit */ "m");
713 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
716 unit = _ (/* time unit */ "h");
717 if (((GNUNET_YES == do_round) && (dval > 5 * 24)) ||
722 unit = _ (/* time unit */ "day");
724 unit = _ (/* time unit */ "days");
730 GNUNET_snprintf (buf, sizeof(buf), "%llu %s", dval, unit);
736 * "asctime", except for GNUnet time. Converts a GNUnet internal
737 * absolute time (which is in UTC) to a string in local time.
738 * Note that the returned value will be overwritten if this function
741 * @param t the absolute time to convert
742 * @return timestamp in human-readable form in local time
745 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
747 static char buf[255];
751 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
752 return _ ("end of time");
753 tt = t.abs_value_us / 1000LL / 1000LL;
754 tp = localtime (&tt);
755 /* This is hacky, but i don't know a way to detect libc character encoding.
756 * Just expect utf8 from glibc these days.
757 * As for msvcrt, use the wide variant, which always returns utf16
758 * (otherwise we'd have to detect current codepage or use W32API character
759 * set conversion routines to convert to UTF8).
760 */strftime (buf, sizeof(buf), "%a %b %d %H:%M:%S %Y", tp);
768 * Returns a pointer to a part of filename (allocates nothing)!
770 * @param filename filename to extract basename from
771 * @return short (base) name of the file (that is, everything following the
772 * last directory separator in filename. If filename ends with a
773 * directory separator, the result will be a zero-length string.
774 * If filename has no directory separators, the result is filename
778 GNUNET_STRINGS_get_short_name (const char *filename)
780 const char *short_fn = filename;
783 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR)) && (ss[1] != '\0'))
790 * Get the decoded value corresponding to a character according to Crockford
793 * @param a a character
794 * @return corresponding numeric value
797 getValue__ (unsigned char a)
815 /* also consider U to be V */
824 if ((a >= '0') && (a <= '9'))
826 if ((a >= 'a') && (a <= 'z'))
828 /* return (a - 'a' + 10); */
830 if ((a >= 'A') && (a <= 'Z'))
840 return(a - 'A' + 10 - dec);
847 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
848 * Returns a pointer to the byte after the last byte in the string, that
849 * is where the 0-terminator was placed if there was room.
851 * @param data data to encode
852 * @param size size of data (in bytes)
853 * @param out buffer to fill
854 * @param out_size size of the buffer. Must be large enough to hold
855 * (size * 8 + 4) / 5 bytes
856 * @return pointer to the next byte in @a out or NULL on error.
859 GNUNET_STRINGS_data_to_string (const void *data,
865 * 32 characters for encoding
867 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
872 const unsigned char *udata;
875 if (out_size < (size * 8 + 4) / 5)
884 while ((rpos < size) || (vbit > 0))
886 if ((rpos < size) && (vbit < 5))
888 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
893 bits <<= (5 - vbit); /* zero-padding */
894 GNUNET_assert (vbit == ((size * 8) % 5));
897 if (wpos >= out_size)
902 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
905 GNUNET_assert (0 == vbit);
913 * Return the base32crockford encoding of the given buffer.
915 * The returned string will be freshly allocated, and must be free'd
916 * with GNUNET_free().
918 * @param buffer with data
919 * @param size size of the buffer
920 * @return freshly allocated, null-terminated string
923 GNUNET_STRINGS_data_to_string_alloc (const void *buf, size_t size)
926 size_t len = size * 8;
932 str_buf = GNUNET_malloc (len + 1);
933 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
936 GNUNET_free (str_buf);
945 * Convert Crockford Base32hex encoding back to data.
946 * @a out_size must match exactly the size of the data before it was encoded.
948 * @param enc the encoding
949 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
950 * @param out location where to store the decoded data
951 * @param out_size size of the output buffer @a out
952 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
955 GNUNET_STRINGS_string_to_data (const char *enc,
967 unsigned int encoded_len = out_size * 8;
973 return GNUNET_SYSERR;
978 if ((encoded_len % 5) > 0)
980 vbit = encoded_len % 5; /* padding! */
982 bits = (ret = getValue__ (enc[--rpos])) >> shift;
988 bits = (ret = getValue__ (enc[--rpos]));
990 if ((encoded_len + shift) / 5 != enclen)
991 return GNUNET_SYSERR;
993 return GNUNET_SYSERR;
999 return GNUNET_SYSERR;
1001 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1003 return GNUNET_SYSERR;
1007 uout[--wpos] = (unsigned char) bits;
1012 if ((0 != rpos) || (0 != vbit))
1013 return GNUNET_SYSERR;
1019 * Parse a path that might be an URI.
1021 * @param path path to parse. Must be NULL-terminated.
1022 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1023 * represents the URI scheme will be stored. Can be NULL. The string is
1024 * allocated by the function, and should be freed by GNUNET_free() when
1025 * it is no longer needed.
1026 * @param path_part a pointer to 'const char *' where a pointer to the path
1027 * part of the URI will be stored. Can be NULL. Points to the same block
1028 * of memory as 'path', and thus must not be freed. Might point to '\0',
1029 * if path part is zero-length.
1030 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1031 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1032 * (if they weren't NULL).
1035 GNUNET_STRINGS_parse_uri (const char *path,
1037 const char **path_part)
1043 const char *post_scheme_part = NULL;
1045 len = strlen (path);
1046 for (end = 0, i = 0; ! end && i < len; i++)
1051 if ((path[i] == ':') && (i > 0))
1056 if (! (((path[i] >= 'A') && (path[i] <= 'Z') ) ||
1057 ((path[i] >= 'a') && (path[i] <= 'z') ) ||
1058 ((path[i] >= '0') && (path[i] <= '9') ) || (path[i] == '+') ||
1059 (path[i] == '-') || (path[i] == '.')))
1074 post_scheme_part = &path[i];
1082 if (post_scheme_part == NULL)
1086 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1087 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1088 (*scheme_part)[post_scheme_part - path] = '\0';
1091 *path_part = post_scheme_part;
1097 * Check whether @a filename is absolute or not, and if it's an URI
1099 * @param filename filename to check
1100 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1101 * assume it's not URI
1102 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1103 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1104 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1105 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1106 * The string is allocated by the function, and should be freed with
1107 * GNUNET_free(). Can be NULL.
1108 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1111 GNUNET_STRINGS_path_is_absolute (const char *filename,
1114 char **r_uri_scheme)
1116 const char *post_scheme_path;
1119 /* consider POSIX paths to be absolute too, even on W32,
1120 * as plibc expansion will fix them for us.
1122 if (filename[0] == '/')
1126 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1132 *r_uri_scheme = uri;
1134 GNUNET_free_non_null (uri);
1136 return GNUNET_STRINGS_path_is_absolute (post_scheme_path,
1145 *r_is_uri = GNUNET_NO;
1153 * Perform @a checks on @a filename.
1155 * @param filename file to check
1156 * @param checks checks to perform
1157 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1158 * fails, #GNUNET_SYSERR when a check can't be performed
1161 GNUNET_STRINGS_check_filename (const char *filename,
1162 enum GNUNET_STRINGS_FilenameCheck checks)
1166 if ((NULL == filename) || (filename[0] == '\0'))
1167 return GNUNET_SYSERR;
1168 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1169 if (! GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1172 & (GNUNET_STRINGS_CHECK_EXISTS | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1173 | GNUNET_STRINGS_CHECK_IS_LINK)))
1175 if (0 != stat (filename, &st))
1177 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1180 return GNUNET_SYSERR;
1183 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1184 if (! S_ISDIR (st.st_mode))
1186 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1187 if (! S_ISLNK (st.st_mode))
1194 * Tries to convert @a zt_addr string to an IPv6 address.
1195 * The string is expected to have the format "[ABCD::01]:80".
1197 * @param zt_addr 0-terminated string. May be mangled by the function.
1198 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1199 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1200 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1201 * @return #GNUNET_OK if conversion succeded.
1202 * #GNUNET_SYSERR otherwise, in which
1203 * case the contents of @a r_buf are undefined.
1206 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1208 struct sockaddr_in6 *r_buf)
1210 char zbuf[addrlen + 1];
1217 return GNUNET_SYSERR;
1218 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1221 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1222 _ ("IPv6 address did not start with `['\n"));
1223 return GNUNET_SYSERR;
1225 zbuf[addrlen] = '\0';
1226 port_colon = strrchr (zbuf, ':');
1227 if (NULL == port_colon)
1229 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1230 _ ("IPv6 address did contain ':' to separate port number\n"));
1231 return GNUNET_SYSERR;
1233 if (']' != *(port_colon - 1))
1236 GNUNET_ERROR_TYPE_WARNING,
1237 _ ("IPv6 address did contain ']' before ':' to separate port number\n"));
1238 return GNUNET_SYSERR;
1240 ret = sscanf (port_colon, ":%u%1s", &port, dummy);
1241 if ((1 != ret) || (port > 65535))
1244 GNUNET_ERROR_TYPE_WARNING,
1245 _ ("IPv6 address did contain a valid port number after the last ':'\n"));
1246 return GNUNET_SYSERR;
1248 *(port_colon - 1) = '\0';
1249 memset (r_buf, 0, sizeof(struct sockaddr_in6));
1250 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1253 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1254 _ ("Invalid IPv6 address `%s': %s\n"),
1257 return GNUNET_SYSERR;
1259 r_buf->sin6_port = htons (port);
1260 r_buf->sin6_family = AF_INET6;
1261 #if HAVE_SOCKADDR_IN_SIN_LEN
1262 r_buf->sin6_len = (u_char) sizeof(struct sockaddr_in6);
1269 * Tries to convert 'zt_addr' string to an IPv4 address.
1270 * The string is expected to have the format "1.2.3.4:80".
1272 * @param zt_addr 0-terminated string. May be mangled by the function.
1273 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1274 * @param r_buf a buffer to fill.
1275 * @return #GNUNET_OK if conversion succeded.
1276 * #GNUNET_SYSERR otherwise, in which case
1277 * the contents of @a r_buf are undefined.
1280 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1282 struct sockaddr_in *r_buf)
1284 unsigned int temps[4];
1290 return GNUNET_SYSERR;
1291 cnt = sscanf (zt_addr,
1292 "%u.%u.%u.%u:%u%1s",
1300 return GNUNET_SYSERR;
1301 for (cnt = 0; cnt < 4; cnt++)
1302 if (temps[cnt] > 0xFF)
1303 return GNUNET_SYSERR;
1305 return GNUNET_SYSERR;
1306 r_buf->sin_family = AF_INET;
1307 r_buf->sin_port = htons (port);
1308 r_buf->sin_addr.s_addr =
1309 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
1310 #if HAVE_SOCKADDR_IN_SIN_LEN
1311 r_buf->sin_len = (u_char) sizeof(struct sockaddr_in);
1318 * Tries to convert @a addr string to an IP (v4 or v6) address.
1319 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1321 * @param addr a string, may not be 0-terminated.
1322 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1323 * 0-terminator should not be counted towards addrlen).
1324 * @param r_buf a buffer to fill.
1325 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1326 * case the contents of @a r_buf are undefined.
1329 GNUNET_STRINGS_to_address_ip (const char *addr,
1331 struct sockaddr_storage *r_buf)
1334 return GNUNET_STRINGS_to_address_ipv6 (addr,
1336 (struct sockaddr_in6 *) r_buf);
1337 return GNUNET_STRINGS_to_address_ipv4 (addr,
1339 (struct sockaddr_in *) r_buf);
1344 * Parse an address given as a string into a
1345 * `struct sockaddr`.
1347 * @param addr the address
1348 * @param[out] af set to the parsed address family (i.e. AF_INET)
1349 * @param[out] sa set to the parsed address
1350 * @return 0 on error, otherwise number of bytes in @a sa
1353 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1355 struct sockaddr **sa)
1357 char *cp = GNUNET_strdup (addr);
1363 *sa = GNUNET_malloc (sizeof(struct sockaddr_in6));
1365 GNUNET_STRINGS_to_address_ipv6 (cp,
1367 (struct sockaddr_in6 *) *sa))
1376 return sizeof(struct sockaddr_in6);
1381 *sa = GNUNET_malloc (sizeof(struct sockaddr_in));
1383 GNUNET_STRINGS_to_address_ipv4 (cp,
1385 (struct sockaddr_in *) *sa))
1394 return sizeof(struct sockaddr_in);
1400 * Makes a copy of argv that consists of a single memory chunk that can be
1401 * freed with a single call to GNUNET_free();
1403 static char *const *
1404 _make_continuous_arg_copy (int argc, char *const *argv)
1406 size_t argvsize = 0;
1411 for (i = 0; i < argc; i++)
1412 argvsize += strlen (argv[i]) + 1 + sizeof(char *);
1413 new_argv = GNUNET_malloc (argvsize + sizeof(char *));
1414 p = (char *) &new_argv[argc + 1];
1415 for (i = 0; i < argc; i++)
1418 strcpy (p, argv[i]);
1419 p += strlen (argv[i]) + 1;
1421 new_argv[argc] = NULL;
1422 return (char *const *) new_argv;
1427 * Returns utf-8 encoded arguments.
1428 * Does nothing (returns a copy of argc and argv) on any platform
1430 * Returned argv has u8argv[u8argc] == NULL.
1431 * Returned argv is a single memory block, and can be freed with a single
1432 * GNUNET_free() call.
1434 * @param argc argc (as given by main())
1435 * @param argv argv (as given by main())
1436 * @param u8argc a location to store new argc in (though it's th same as argc)
1437 * @param u8argv a location to store new argv in
1438 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1441 GNUNET_STRINGS_get_utf8_args (int argc,
1444 char *const **u8argv)
1446 char *const *new_argv =
1447 (char *const *) _make_continuous_arg_copy (argc, argv);
1455 * Parse the given port policy. The format is
1456 * "[!]SPORT[-DPORT]".
1458 * @param port_policy string to parse
1459 * @param pp policy to fill in
1460 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1461 * @a port_policy is malformed
1464 parse_port_policy (const char *port_policy,
1465 struct GNUNET_STRINGS_PortPolicy *pp)
1475 pp->negate_portrange = GNUNET_YES;
1478 if (2 == sscanf (pos, "%u-%u%1s", &s, &e, eol))
1480 if ((0 == s) || (s > 0xFFFF) || (e < s) || (e > 0xFFFF))
1482 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n"));
1483 return GNUNET_SYSERR;
1485 pp->start_port = (uint16_t) s;
1486 pp->end_port = (uint16_t) e;
1489 if (1 == sscanf (pos, "%u%1s", &s, eol))
1491 if ((0 == s) || (s > 0xFFFF))
1493 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n"));
1494 return GNUNET_SYSERR;
1497 pp->start_port = (uint16_t) s;
1498 pp->end_port = (uint16_t) s;
1501 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1502 _ ("Malformed port policy `%s'\n"),
1504 return GNUNET_SYSERR;
1509 * Parse an IPv4 network policy. The argument specifies a list of
1510 * subnets. The format is
1511 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1512 * be terminated with a semicolon). The network must be given in
1513 * dotted-decimal notation. The netmask can be given in CIDR notation
1514 * (/16) or in dotted-decimal (/255.255.0.0).
1516 * @param routeListX a string specifying the IPv4 subnets
1517 * @return the converted list, terminated with all zeros;
1518 * NULL if the synatx is flawed
1520 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1521 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1529 unsigned int temps[8];
1531 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1537 if (NULL == routeListX)
1539 len = strlen (routeListX);
1542 routeList = GNUNET_strdup (routeListX);
1544 for (i = 0; i < len; i++)
1545 if (routeList[i] == ';')
1547 result = GNUNET_malloc (sizeof(struct GNUNET_STRINGS_IPv4NetworkPolicy)
1553 for (colon = pos; ':' != routeList[colon]; colon++)
1554 if ((';' == routeList[colon]) || ('\0' == routeList[colon]))
1556 for (end = colon; ';' != routeList[end]; end++)
1557 if ('\0' == routeList[end])
1559 if ('\0' == routeList[end])
1561 routeList[end] = '\0';
1562 if (':' == routeList[colon])
1564 routeList[colon] = '\0';
1565 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1], &result[i].pp))
1568 cnt = sscanf (&routeList[pos],
1569 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1581 for (j = 0; j < 8; j++)
1582 if (temps[j] > 0xFF)
1584 LOG (GNUNET_ERROR_TYPE_WARNING,
1585 _ ("Invalid format for IP: `%s'\n"),
1587 GNUNET_free (result);
1588 GNUNET_free (routeList);
1591 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16)
1592 + (temps[2] << 8) + temps[3]);
1593 result[i].netmask.s_addr = htonl ((temps[4] << 24) + (temps[5] << 16)
1594 + (temps[6] << 8) + temps[7]);
1599 /* try second notation */
1600 cnt = sscanf (&routeList[pos],
1601 "%u.%u.%u.%u/%u%1s",
1610 for (j = 0; j < 4; j++)
1611 if (temps[j] > 0xFF)
1613 LOG (GNUNET_ERROR_TYPE_WARNING,
1614 _ ("Invalid format for IP: `%s'\n"),
1616 GNUNET_free (result);
1617 GNUNET_free (routeList);
1620 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16)
1621 + (temps[2] << 8) + temps[3]);
1622 if ((slash <= 32) && (slash >= 0))
1624 result[i].netmask.s_addr = 0;
1627 result[i].netmask.s_addr =
1628 (result[i].netmask.s_addr >> 1) + 0x80000000;
1631 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1638 LOG (GNUNET_ERROR_TYPE_WARNING,
1639 _ ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1641 GNUNET_free (result);
1642 GNUNET_free (routeList);
1643 return NULL; /* error */
1646 /* try third notation */
1648 cnt = sscanf (&routeList[pos],
1657 for (j = 0; j < 4; j++)
1658 if (temps[j] > 0xFF)
1660 LOG (GNUNET_ERROR_TYPE_WARNING,
1661 _ ("Invalid format for IP: `%s'\n"),
1663 GNUNET_free (result);
1664 GNUNET_free (routeList);
1667 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16)
1668 + (temps[2] << 8) + temps[3]);
1669 result[i].netmask.s_addr = 0;
1672 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1675 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1680 LOG (GNUNET_ERROR_TYPE_WARNING,
1681 _ ("Invalid format for IP: `%s'\n"),
1683 GNUNET_free (result);
1684 GNUNET_free (routeList);
1685 return NULL; /* error */
1687 if (pos < strlen (routeList))
1689 LOG (GNUNET_ERROR_TYPE_WARNING,
1690 _ ("Invalid format: `%s'\n"),
1692 GNUNET_free (result);
1693 GNUNET_free (routeList);
1694 return NULL; /* oops */
1696 GNUNET_free (routeList);
1697 return result; /* ok */
1702 * Parse an IPv6 network policy. The argument specifies a list of
1703 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1704 * (no whitespace, must be terminated with a semicolon). The network
1705 * must be given in colon-hex notation. The netmask must be given in
1706 * CIDR notation (/16) or can be omitted to specify a single host.
1707 * Note that the netmask is mandatory if ports are specified.
1709 * @param routeListX a string specifying the policy
1710 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1712 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1713 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1723 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1730 if (NULL == routeListX)
1732 len = strlen (routeListX);
1735 routeList = GNUNET_strdup (routeListX);
1737 for (i = 0; i < len; i++)
1738 if (';' == routeList[i])
1740 if (';' != routeList[len - 1])
1742 LOG (GNUNET_ERROR_TYPE_WARNING,
1743 _ ("Invalid network notation (does not end with ';': `%s')\n"),
1745 GNUNET_free (routeList);
1749 result = GNUNET_malloc (sizeof(struct GNUNET_STRINGS_IPv6NetworkPolicy)
1756 while (';' != routeList[pos])
1759 while ((slash >= start) && (routeList[slash] != '/'))
1764 memset (&result[i].netmask, 0xFF, sizeof(struct in6_addr));
1769 routeList[pos] = '\0';
1770 for (colon = pos; ':' != routeList[colon]; colon--)
1771 if ('/' == routeList[colon])
1773 if (':' == routeList[colon])
1775 routeList[colon] = '\0';
1777 parse_port_policy (&routeList[colon + 1], &result[i].pp))
1779 GNUNET_free (result);
1780 GNUNET_free (routeList);
1784 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1788 if ((1 != sscanf (&routeList[slash + 1], "%u%1s", &bits, dummy)) ||
1792 LOG (GNUNET_ERROR_TYPE_WARNING,
1793 _ ("Wrong format `%s' for netmask\n"),
1794 &routeList[slash + 1]);
1798 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1800 GNUNET_free (result);
1801 GNUNET_free (routeList);
1807 result[i].netmask.s6_addr[off++] = 0xFF;
1812 result[i].netmask.s6_addr[off] =
1813 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1818 routeList[slash] = '\0';
1819 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1823 LOG (GNUNET_ERROR_TYPE_WARNING,
1824 _ ("Wrong format `%s' for network\n"),
1825 &routeList[slash + 1]);
1827 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
1828 GNUNET_free (result);
1829 GNUNET_free (routeList);
1835 GNUNET_free (routeList);
1840 /** ******************** Base64 encoding ***********/
1842 #define FILLCHAR '='
1843 static char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1844 "abcdefghijklmnopqrstuvwxyz"
1849 * Encode into Base64.
1851 * @param in the data to encode
1852 * @param len the length of the input
1853 * @param output where to write the output (*output should be NULL,
1855 * @return the size of the output
1858 GNUNET_STRINGS_base64_encode (const void *in, size_t len, char **output)
1860 const char *data = in;
1865 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1866 for (size_t i = 0; i < len; ++i)
1870 c = (data[i] >> 2) & 0x3f;
1871 opt[ret++] = cvt[(int) c];
1872 c = (data[i] << 4) & 0x3f;
1874 c |= (data[i] >> 4) & 0x0f;
1875 opt[ret++] = cvt[(int) c];
1878 c = (data[i] << 2) & 0x3f;
1880 c |= (data[i] >> 6) & 0x03;
1881 opt[ret++] = cvt[(int) c];
1886 opt[ret++] = FILLCHAR;
1891 opt[ret++] = cvt[(int) c];
1895 opt[ret++] = FILLCHAR;
1904 * Encode into Base64url. RFC7515
1906 * @param in the data to encode
1907 * @param len the length of the input
1908 * @param output where to write the output (*output should be NULL,
1910 * @return the size of the output
1913 GNUNET_STRINGS_base64url_encode (const void *in, size_t len, char **output)
1918 GNUNET_STRINGS_base64_encode (in, len, output);
1920 /* Replace with correct characters for base64url */
1922 while ('\0' != enc[pos])
1924 if ('+' == enc[pos])
1926 if ('/' == enc[pos])
1928 if ('=' == enc[pos])
1935 return strlen (enc);
1939 #define cvtfind(a) \
1940 ((((a) >= 'A') && ((a) <= 'Z')) \
1942 : (((a) >= 'a') && ((a) <= 'z')) \
1944 : (((a) >= '0') && ((a) <= '9')) \
1946 : ((a) == '+') ? 62 : ((a) == '/') ? 63 : -1)
1950 * Decode from Base64.
1952 * @param data the data to encode
1953 * @param len the length of the input
1954 * @param output where to write the output (*output should be NULL,
1956 * @return the size of the output
1959 GNUNET_STRINGS_base64_decode (const char *data, size_t len, void **out)
1964 #define CHECK_CRLF \
1965 while (data[i] == '\r' || data[i] == '\n') \
1967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, \
1968 "ignoring CR/LF\n"); \
1974 output = GNUNET_malloc ((len * 3 / 4) + 8);
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "base64_decode decoding len=%d\n",
1978 for (size_t i = 0; i < len; ++i)
1984 if (FILLCHAR == data[i])
1986 c = (char) cvtfind (data[i]);
1989 c1 = (char) cvtfind (data[i]);
1990 c = (c << 2) | ((c1 >> 4) & 0x3);
1998 c = (char) cvtfind (c);
1999 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2009 c1 = (char) cvtfind (c1);
2010 c = ((c << 6) & 0xc0) | c1;
2021 * Decode from Base64url. RFC7515
2023 * @param data the data to decode
2024 * @param len the length of the input
2025 * @param output where to write the output (*output should be NULL,
2027 * @return the size of the output
2030 GNUNET_STRINGS_base64url_decode (const char *data, size_t len, void **out)
2036 /* make enough space for padding */
2037 s = GNUNET_malloc (len + 3);
2038 memcpy (s, data, len);
2040 for (int i = 0; i < strlen (s); i++)
2048 switch (padding) // Pad with trailing '='s
2051 break; // No pad chars in this case
2057 break; // Two pad chars
2061 break; // One pad char
2066 ret = GNUNET_STRINGS_base64_decode (s, len, out);
2072 /* end of strings.c */