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") */
312 * Convert a given fancy human-readable size to bytes.
314 * @param fancy_size human readable string (i.e. 1 MB)
315 * @param size set to the size in bytes
316 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
319 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
320 unsigned long long *size)
322 static const struct ConversionTable table[] =
326 { "MiB", 1024 * 1024 },
327 { "MB", 1000 * 1000 },
328 { "GiB", 1024 * 1024 * 1024 },
329 { "GB", 1000 * 1000 * 1000 },
330 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL },
331 { "TB", 1000LL * 1000LL * 1000LL * 1024LL },
332 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
333 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL },
334 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
335 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL },
338 return convert_with_table (fancy_size, table, size);
343 * Convert a given fancy human-readable time to our internal
346 * @param fancy_time human readable string (i.e. 1 minute)
347 * @param rtime set to the relative time
348 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
351 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
352 struct GNUNET_TIME_Relative *rtime)
354 static const struct ConversionTable table[] =
357 { "s", 1000 * 1000LL },
358 { "second", 1000 * 1000LL },
359 { "seconds", 1000 * 1000LL },
360 { "\"", 1000 * 1000LL },
361 { "m", 60 * 1000 * 1000LL },
362 { "min", 60 * 1000 * 1000LL },
363 { "minute", 60 * 1000 * 1000LL },
364 { "minutes", 60 * 1000 * 1000LL },
365 { "'", 60 * 1000 * 1000LL },
366 { "h", 60 * 60 * 1000 * 1000LL },
367 { "hour", 60 * 60 * 1000 * 1000LL },
368 { "hours", 60 * 60 * 1000 * 1000LL },
369 { "d", 24 * 60 * 60 * 1000LL * 1000LL },
370 { "day", 24 * 60 * 60 * 1000LL * 1000LL },
371 { "days", 24 * 60 * 60 * 1000LL * 1000LL },
372 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL },
373 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL },
374 { "year", 31536000000000LL /* year */ },
375 { "years", 31536000000000LL /* year */ },
376 { "a", 31536000000000LL /* year */ },
379 unsigned long long val;
381 if (0 == strcasecmp ("forever", fancy_time))
383 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
386 ret = convert_with_table (fancy_time, table, &val);
387 rtime->rel_value_us = (uint64_t) val;
393 * Convert a given fancy human-readable time to our internal
394 * representation. The human-readable time is expected to be
395 * in local time, whereas the returned value will be in UTC.
397 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
398 * @param atime set to the absolute time
399 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
402 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
403 struct GNUNET_TIME_Absolute *atime)
409 if (0 == strcasecmp ("end of time", fancy_time))
411 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
414 eos = &fancy_time[strlen (fancy_time)];
415 memset (&tv, 0, sizeof(tv));
416 if ((eos != strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
417 (eos != strptime (fancy_time, "%c", &tv)) &&
418 (eos != strptime (fancy_time, "%Ec", &tv)) &&
419 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
420 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
421 (eos != strptime (fancy_time, "%x", &tv)) &&
422 (eos != strptime (fancy_time, "%Ex", &tv)) &&
423 (eos != strptime (fancy_time, "%Y-%m-%d", &tv)) &&
424 (eos != strptime (fancy_time, "%Y-%m", &tv)) &&
425 (eos != strptime (fancy_time, "%Y", &tv)))
426 return GNUNET_SYSERR;
428 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
434 * Convert the len characters long character sequence
435 * given in input that is in the given input charset
436 * to a string in given output charset.
438 * @param input input string
439 * @param len number of bytes in @a input
440 * @param input_charset character set used for @a input
441 * @param output_charset desired character set for the return value
442 * @return the converted string (0-terminated),
443 * if conversion fails, a copy of the orignal
444 * string is returned.
447 GNUNET_STRINGS_conv (const char *input,
449 const char *input_charset,
450 const char *output_charset)
454 char *encoded_string;
455 size_t u8_string_length;
456 size_t encoded_string_length;
458 u8_string = u8_conv_from_encoding (input_charset,
465 if (NULL == u8_string)
467 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
470 if (0 == strcmp (output_charset, "UTF-8"))
472 ret = GNUNET_malloc (u8_string_length + 1);
473 GNUNET_memcpy (ret, u8_string, u8_string_length);
474 ret[u8_string_length] = '\0';
478 encoded_string = u8_conv_to_encoding (output_charset,
484 &encoded_string_length);
486 if (NULL == encoded_string)
488 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
491 ret = GNUNET_malloc (encoded_string_length + 1);
492 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
493 ret[encoded_string_length] = '\0';
494 free (encoded_string);
497 LOG (GNUNET_ERROR_TYPE_WARNING,
498 _ ("Character sets requested were `%s'->`%s'\n"),
501 ret = GNUNET_malloc (len + 1);
502 GNUNET_memcpy (ret, input, len);
509 * Convert the len characters long character sequence
510 * given in input that is in the given charset
513 * @param input the input string (not necessarily 0-terminated)
514 * @param len the number of bytes in the @a input
515 * @param charset character set to convert from
516 * @return the converted string (0-terminated),
517 * if conversion fails, a copy of the orignal
518 * string is returned.
521 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
523 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
528 * Convert the len bytes-long UTF-8 string
529 * given in input to the given charset.
531 * @param input the input string (not necessarily 0-terminated)
532 * @param len the number of bytes in the @a input
533 * @param charset character set to convert to
534 * @return the converted string (0-terminated),
535 * if conversion fails, a copy of the orignal
536 * string is returned.
539 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
541 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
546 * Convert the utf-8 input string to lowercase.
547 * Output needs to be allocated appropriately.
549 * @param input input string
550 * @param output output buffer
553 GNUNET_STRINGS_utf8_tolower (const char *input, char *output)
558 tmp_in = u8_tolower ((uint8_t *) input,
559 strlen ((char *) input),
564 GNUNET_memcpy (output, tmp_in, len);
571 * Convert the utf-8 input string to uppercase.
572 * Output needs to be allocated appropriately.
574 * @param input input string
575 * @param output output buffer
578 GNUNET_STRINGS_utf8_toupper (const char *input, char *output)
583 tmp_in = u8_toupper ((uint8_t *) input,
584 strlen ((char *) input),
589 GNUNET_memcpy (output, tmp_in, len);
596 * Complete filename (a la shell) from abbrevition.
597 * @param fil the name of the file, may contain ~/ or
598 * be relative to the current directory
599 * @returns the full file name,
600 * NULL is returned on error
603 GNUNET_STRINGS_filename_expand (const char *fil)
613 if (fil[0] == DIR_SEPARATOR)
614 /* absolute path, just copy */
615 return GNUNET_strdup (fil);
618 fm = getenv ("HOME");
621 LOG (GNUNET_ERROR_TYPE_WARNING,
622 _ ("Failed to expand `$HOME': environment variable `HOME' not set"));
625 fm = GNUNET_strdup (fm);
626 /* do not copy '~' */
629 /* skip over dir seperator to be consistent */
630 if (fil_ptr[0] == DIR_SEPARATOR)
641 buffer = GNUNET_malloc (len);
642 if (getcwd (buffer, len) != NULL)
647 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
650 GNUNET_free (buffer);
653 GNUNET_free (buffer);
658 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
659 buffer = getenv ("PWD"); /* alternative */
661 fm = GNUNET_strdup (buffer);
664 fm = GNUNET_strdup ("./"); /* give up */
666 GNUNET_asprintf (&buffer,
669 (fm[strlen (fm) - 1] == DIR_SEPARATOR) ? ""
678 * Give relative time in human-readable fancy format.
679 * This is one of the very few calls in the entire API that is
682 * @param delta time in milli seconds
683 * @param do_round are we allowed to round a bit?
684 * @return time as human-readable string
687 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
690 static char buf[128];
691 const char *unit = _ (/* time unit */ "µs");
692 uint64_t dval = delta.rel_value_us;
694 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
695 return _ ("forever");
696 if (0 == delta.rel_value_us)
698 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
701 unit = _ (/* time unit */ "ms");
702 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
705 unit = _ (/* time unit */ "s");
706 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
709 unit = _ (/* time unit */ "m");
710 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
713 unit = _ (/* time unit */ "h");
714 if (((GNUNET_YES == do_round) && (dval > 5 * 24)) ||
719 unit = _ (/* time unit */ "day");
721 unit = _ (/* time unit */ "days");
727 GNUNET_snprintf (buf, sizeof(buf), "%llu %s", dval, unit);
733 * "asctime", except for GNUnet time. Converts a GNUnet internal
734 * absolute time (which is in UTC) to a string in local time.
735 * Note that the returned value will be overwritten if this function
738 * @param t the absolute time to convert
739 * @return timestamp in human-readable form in local time
742 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
744 static char buf[255];
748 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
749 return _ ("end of time");
750 tt = t.abs_value_us / 1000LL / 1000LL;
751 tp = localtime (&tt);
752 /* This is hacky, but i don't know a way to detect libc character encoding.
753 * Just expect utf8 from glibc these days.
754 * As for msvcrt, use the wide variant, which always returns utf16
755 * (otherwise we'd have to detect current codepage or use W32API character
756 * set conversion routines to convert to UTF8).
757 */strftime (buf, sizeof(buf), "%a %b %d %H:%M:%S %Y", tp);
765 * Returns a pointer to a part of filename (allocates nothing)!
767 * @param filename filename to extract basename from
768 * @return short (base) name of the file (that is, everything following the
769 * last directory separator in filename. If filename ends with a
770 * directory separator, the result will be a zero-length string.
771 * If filename has no directory separators, the result is filename
775 GNUNET_STRINGS_get_short_name (const char *filename)
777 const char *short_fn = filename;
780 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR)) && (ss[1] != '\0'))
787 * Get the decoded value corresponding to a character according to Crockford
790 * @param a a character
791 * @return corresponding numeric value
794 getValue__ (unsigned char a)
812 /* also consider U to be V */
821 if ((a >= '0') && (a <= '9'))
823 if ((a >= 'a') && (a <= 'z'))
825 /* return (a - 'a' + 10); */
827 if ((a >= 'A') && (a <= 'Z'))
837 return(a - 'A' + 10 - dec);
844 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
845 * Returns a pointer to the byte after the last byte in the string, that
846 * is where the 0-terminator was placed if there was room.
848 * @param data data to encode
849 * @param size size of data (in bytes)
850 * @param out buffer to fill
851 * @param out_size size of the buffer. Must be large enough to hold
852 * (size * 8 + 4) / 5 bytes
853 * @return pointer to the next byte in @a out or NULL on error.
856 GNUNET_STRINGS_data_to_string (const void *data,
862 * 32 characters for encoding
864 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
869 const unsigned char *udata;
872 if (out_size < (size * 8 + 4) / 5)
881 while ((rpos < size) || (vbit > 0))
883 if ((rpos < size) && (vbit < 5))
885 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
890 bits <<= (5 - vbit); /* zero-padding */
891 GNUNET_assert (vbit == ((size * 8) % 5));
894 if (wpos >= out_size)
899 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
902 GNUNET_assert (0 == vbit);
910 * Return the base32crockford encoding of the given buffer.
912 * The returned string will be freshly allocated, and must be free'd
913 * with GNUNET_free().
915 * @param buffer with data
916 * @param size size of the buffer
917 * @return freshly allocated, null-terminated string
920 GNUNET_STRINGS_data_to_string_alloc (const void *buf, size_t size)
923 size_t len = size * 8;
929 str_buf = GNUNET_malloc (len + 1);
930 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
933 GNUNET_free (str_buf);
942 * Convert Crockford Base32hex encoding back to data.
943 * @a out_size must match exactly the size of the data before it was encoded.
945 * @param enc the encoding
946 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
947 * @param out location where to store the decoded data
948 * @param out_size size of the output buffer @a out
949 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
952 GNUNET_STRINGS_string_to_data (const char *enc,
964 unsigned int encoded_len = out_size * 8;
970 return GNUNET_SYSERR;
975 if ((encoded_len % 5) > 0)
977 vbit = encoded_len % 5; /* padding! */
979 bits = (ret = getValue__ (enc[--rpos])) >> shift;
985 bits = (ret = getValue__ (enc[--rpos]));
987 if ((encoded_len + shift) / 5 != enclen)
988 return GNUNET_SYSERR;
990 return GNUNET_SYSERR;
996 return GNUNET_SYSERR;
998 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1000 return GNUNET_SYSERR;
1004 uout[--wpos] = (unsigned char) bits;
1009 if ((0 != rpos) || (0 != vbit))
1010 return GNUNET_SYSERR;
1016 * Parse a path that might be an URI.
1018 * @param path path to parse. Must be NULL-terminated.
1019 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1020 * represents the URI scheme will be stored. Can be NULL. The string is
1021 * allocated by the function, and should be freed by GNUNET_free() when
1022 * it is no longer needed.
1023 * @param path_part a pointer to 'const char *' where a pointer to the path
1024 * part of the URI will be stored. Can be NULL. Points to the same block
1025 * of memory as 'path', and thus must not be freed. Might point to '\0',
1026 * if path part is zero-length.
1027 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1028 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1029 * (if they weren't NULL).
1032 GNUNET_STRINGS_parse_uri (const char *path,
1034 const char **path_part)
1040 const char *post_scheme_part = NULL;
1042 len = strlen (path);
1043 for (end = 0, i = 0; ! end && i < len; i++)
1048 if ((path[i] == ':') && (i > 0))
1053 if (! (((path[i] >= 'A') && (path[i] <= 'Z') ) ||
1054 ((path[i] >= 'a') && (path[i] <= 'z') ) ||
1055 ((path[i] >= '0') && (path[i] <= '9') ) || (path[i] == '+') ||
1056 (path[i] == '-') || (path[i] == '.')))
1071 post_scheme_part = &path[i];
1079 if (post_scheme_part == NULL)
1083 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1084 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1085 (*scheme_part)[post_scheme_part - path] = '\0';
1088 *path_part = post_scheme_part;
1094 * Check whether @a filename is absolute or not, and if it's an URI
1096 * @param filename filename to check
1097 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1098 * assume it's not URI
1099 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1100 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1101 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1102 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1103 * The string is allocated by the function, and should be freed with
1104 * GNUNET_free(). Can be NULL.
1105 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1108 GNUNET_STRINGS_path_is_absolute (const char *filename,
1111 char **r_uri_scheme)
1113 const char *post_scheme_path;
1116 /* consider POSIX paths to be absolute too, even on W32,
1117 * as plibc expansion will fix them for us.
1119 if (filename[0] == '/')
1123 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1129 *r_uri_scheme = uri;
1131 GNUNET_free_non_null (uri);
1133 return GNUNET_STRINGS_path_is_absolute (post_scheme_path,
1142 *r_is_uri = GNUNET_NO;
1150 * Perform @a checks on @a filename.
1152 * @param filename file to check
1153 * @param checks checks to perform
1154 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1155 * fails, #GNUNET_SYSERR when a check can't be performed
1158 GNUNET_STRINGS_check_filename (const char *filename,
1159 enum GNUNET_STRINGS_FilenameCheck checks)
1163 if ((NULL == filename) || (filename[0] == '\0'))
1164 return GNUNET_SYSERR;
1165 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1166 if (! GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1169 & (GNUNET_STRINGS_CHECK_EXISTS | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1170 | GNUNET_STRINGS_CHECK_IS_LINK)))
1172 if (0 != stat (filename, &st))
1174 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1177 return GNUNET_SYSERR;
1180 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1181 if (! S_ISDIR (st.st_mode))
1183 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1184 if (! S_ISLNK (st.st_mode))
1191 * Tries to convert @a zt_addr string to an IPv6 address.
1192 * The string is expected to have the format "[ABCD::01]:80".
1194 * @param zt_addr 0-terminated string. May be mangled by the function.
1195 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1196 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1197 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1198 * @return #GNUNET_OK if conversion succeded.
1199 * #GNUNET_SYSERR otherwise, in which
1200 * case the contents of @a r_buf are undefined.
1203 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1205 struct sockaddr_in6 *r_buf)
1207 char zbuf[addrlen + 1];
1214 return GNUNET_SYSERR;
1215 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1219 _ ("IPv6 address did not start with `['\n"));
1220 return GNUNET_SYSERR;
1222 zbuf[addrlen] = '\0';
1223 port_colon = strrchr (zbuf, ':');
1224 if (NULL == port_colon)
1226 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1227 _ ("IPv6 address did contain ':' to separate port number\n"));
1228 return GNUNET_SYSERR;
1230 if (']' != *(port_colon - 1))
1233 GNUNET_ERROR_TYPE_WARNING,
1234 _ ("IPv6 address did contain ']' before ':' to separate port number\n"));
1235 return GNUNET_SYSERR;
1237 ret = sscanf (port_colon, ":%u%1s", &port, dummy);
1238 if ((1 != ret) || (port > 65535))
1241 GNUNET_ERROR_TYPE_WARNING,
1242 _ ("IPv6 address did contain a valid port number after the last ':'\n"));
1243 return GNUNET_SYSERR;
1245 *(port_colon - 1) = '\0';
1246 memset (r_buf, 0, sizeof(struct sockaddr_in6));
1247 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1250 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1251 _ ("Invalid IPv6 address `%s': %s\n"),
1254 return GNUNET_SYSERR;
1256 r_buf->sin6_port = htons (port);
1257 r_buf->sin6_family = AF_INET6;
1258 #if HAVE_SOCKADDR_IN_SIN_LEN
1259 r_buf->sin6_len = (u_char) sizeof(struct sockaddr_in6);
1266 * Tries to convert 'zt_addr' string to an IPv4 address.
1267 * The string is expected to have the format "1.2.3.4:80".
1269 * @param zt_addr 0-terminated string. May be mangled by the function.
1270 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1271 * @param r_buf a buffer to fill.
1272 * @return #GNUNET_OK if conversion succeded.
1273 * #GNUNET_SYSERR otherwise, in which case
1274 * the contents of @a r_buf are undefined.
1277 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1279 struct sockaddr_in *r_buf)
1281 unsigned int temps[4];
1287 return GNUNET_SYSERR;
1288 cnt = sscanf (zt_addr,
1289 "%u.%u.%u.%u:%u%1s",
1297 return GNUNET_SYSERR;
1298 for (cnt = 0; cnt < 4; cnt++)
1299 if (temps[cnt] > 0xFF)
1300 return GNUNET_SYSERR;
1302 return GNUNET_SYSERR;
1303 r_buf->sin_family = AF_INET;
1304 r_buf->sin_port = htons (port);
1305 r_buf->sin_addr.s_addr =
1306 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
1307 #if HAVE_SOCKADDR_IN_SIN_LEN
1308 r_buf->sin_len = (u_char) sizeof(struct sockaddr_in);
1315 * Tries to convert @a addr string to an IP (v4 or v6) address.
1316 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1318 * @param addr a string, may not be 0-terminated.
1319 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1320 * 0-terminator should not be counted towards addrlen).
1321 * @param r_buf a buffer to fill.
1322 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1323 * case the contents of @a r_buf are undefined.
1326 GNUNET_STRINGS_to_address_ip (const char *addr,
1328 struct sockaddr_storage *r_buf)
1331 return GNUNET_STRINGS_to_address_ipv6 (addr,
1333 (struct sockaddr_in6 *) r_buf);
1334 return GNUNET_STRINGS_to_address_ipv4 (addr,
1336 (struct sockaddr_in *) r_buf);
1341 * Parse an address given as a string into a
1342 * `struct sockaddr`.
1344 * @param addr the address
1345 * @param[out] af set to the parsed address family (i.e. AF_INET)
1346 * @param[out] sa set to the parsed address
1347 * @return 0 on error, otherwise number of bytes in @a sa
1350 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1352 struct sockaddr **sa)
1354 char *cp = GNUNET_strdup (addr);
1360 *sa = GNUNET_malloc (sizeof(struct sockaddr_in6));
1362 GNUNET_STRINGS_to_address_ipv6 (cp,
1364 (struct sockaddr_in6 *) *sa))
1373 return sizeof(struct sockaddr_in6);
1378 *sa = GNUNET_malloc (sizeof(struct sockaddr_in));
1380 GNUNET_STRINGS_to_address_ipv4 (cp,
1382 (struct sockaddr_in *) *sa))
1391 return sizeof(struct sockaddr_in);
1397 * Makes a copy of argv that consists of a single memory chunk that can be
1398 * freed with a single call to GNUNET_free();
1400 static char *const *
1401 _make_continuous_arg_copy (int argc, char *const *argv)
1403 size_t argvsize = 0;
1408 for (i = 0; i < argc; i++)
1409 argvsize += strlen (argv[i]) + 1 + sizeof(char *);
1410 new_argv = GNUNET_malloc (argvsize + sizeof(char *));
1411 p = (char *) &new_argv[argc + 1];
1412 for (i = 0; i < argc; i++)
1415 strcpy (p, argv[i]);
1416 p += strlen (argv[i]) + 1;
1418 new_argv[argc] = NULL;
1419 return (char *const *) new_argv;
1424 * Returns utf-8 encoded arguments.
1425 * Does nothing (returns a copy of argc and argv) on any platform
1427 * Returned argv has u8argv[u8argc] == NULL.
1428 * Returned argv is a single memory block, and can be freed with a single
1429 * GNUNET_free() call.
1431 * @param argc argc (as given by main())
1432 * @param argv argv (as given by main())
1433 * @param u8argc a location to store new argc in (though it's th same as argc)
1434 * @param u8argv a location to store new argv in
1435 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1438 GNUNET_STRINGS_get_utf8_args (int argc,
1441 char *const **u8argv)
1443 char *const *new_argv =
1444 (char *const *) _make_continuous_arg_copy (argc, argv);
1452 * Parse the given port policy. The format is
1453 * "[!]SPORT[-DPORT]".
1455 * @param port_policy string to parse
1456 * @param pp policy to fill in
1457 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1458 * @a port_policy is malformed
1461 parse_port_policy (const char *port_policy,
1462 struct GNUNET_STRINGS_PortPolicy *pp)
1472 pp->negate_portrange = GNUNET_YES;
1475 if (2 == sscanf (pos, "%u-%u%1s", &s, &e, eol))
1477 if ((0 == s) || (s > 0xFFFF) || (e < s) || (e > 0xFFFF))
1479 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n"));
1480 return GNUNET_SYSERR;
1482 pp->start_port = (uint16_t) s;
1483 pp->end_port = (uint16_t) e;
1486 if (1 == sscanf (pos, "%u%1s", &s, eol))
1488 if ((0 == s) || (s > 0xFFFF))
1490 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n"));
1491 return GNUNET_SYSERR;
1494 pp->start_port = (uint16_t) s;
1495 pp->end_port = (uint16_t) s;
1498 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1499 _ ("Malformed port policy `%s'\n"),
1501 return GNUNET_SYSERR;
1506 * Parse an IPv4 network policy. The argument specifies a list of
1507 * subnets. The format is
1508 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1509 * be terminated with a semicolon). The network must be given in
1510 * dotted-decimal notation. The netmask can be given in CIDR notation
1511 * (/16) or in dotted-decimal (/255.255.0.0).
1513 * @param routeListX a string specifying the IPv4 subnets
1514 * @return the converted list, terminated with all zeros;
1515 * NULL if the synatx is flawed
1517 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1518 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1526 unsigned int temps[8];
1528 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1534 if (NULL == routeListX)
1536 len = strlen (routeListX);
1539 routeList = GNUNET_strdup (routeListX);
1541 for (i = 0; i < len; i++)
1542 if (routeList[i] == ';')
1544 result = GNUNET_malloc (sizeof(struct GNUNET_STRINGS_IPv4NetworkPolicy)
1550 for (colon = pos; ':' != routeList[colon]; colon++)
1551 if ((';' == routeList[colon]) || ('\0' == routeList[colon]))
1553 for (end = colon; ';' != routeList[end]; end++)
1554 if ('\0' == routeList[end])
1556 if ('\0' == routeList[end])
1558 routeList[end] = '\0';
1559 if (':' == routeList[colon])
1561 routeList[colon] = '\0';
1562 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1], &result[i].pp))
1565 cnt = sscanf (&routeList[pos],
1566 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1578 for (j = 0; j < 8; j++)
1579 if (temps[j] > 0xFF)
1581 LOG (GNUNET_ERROR_TYPE_WARNING,
1582 _ ("Invalid format for IP: `%s'\n"),
1584 GNUNET_free (result);
1585 GNUNET_free (routeList);
1588 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16)
1589 + (temps[2] << 8) + temps[3]);
1590 result[i].netmask.s_addr = htonl ((temps[4] << 24) + (temps[5] << 16)
1591 + (temps[6] << 8) + temps[7]);
1596 /* try second notation */
1597 cnt = sscanf (&routeList[pos],
1598 "%u.%u.%u.%u/%u%1s",
1607 for (j = 0; j < 4; j++)
1608 if (temps[j] > 0xFF)
1610 LOG (GNUNET_ERROR_TYPE_WARNING,
1611 _ ("Invalid format for IP: `%s'\n"),
1613 GNUNET_free (result);
1614 GNUNET_free (routeList);
1617 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16)
1618 + (temps[2] << 8) + temps[3]);
1619 if ((slash <= 32) && (slash >= 0))
1621 result[i].netmask.s_addr = 0;
1624 result[i].netmask.s_addr =
1625 (result[i].netmask.s_addr >> 1) + 0x80000000;
1628 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1635 LOG (GNUNET_ERROR_TYPE_WARNING,
1636 _ ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1638 GNUNET_free (result);
1639 GNUNET_free (routeList);
1640 return NULL; /* error */
1643 /* try third notation */
1645 cnt = sscanf (&routeList[pos],
1654 for (j = 0; j < 4; j++)
1655 if (temps[j] > 0xFF)
1657 LOG (GNUNET_ERROR_TYPE_WARNING,
1658 _ ("Invalid format for IP: `%s'\n"),
1660 GNUNET_free (result);
1661 GNUNET_free (routeList);
1664 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16)
1665 + (temps[2] << 8) + temps[3]);
1666 result[i].netmask.s_addr = 0;
1669 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1672 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1677 LOG (GNUNET_ERROR_TYPE_WARNING,
1678 _ ("Invalid format for IP: `%s'\n"),
1680 GNUNET_free (result);
1681 GNUNET_free (routeList);
1682 return NULL; /* error */
1684 if (pos < strlen (routeList))
1686 LOG (GNUNET_ERROR_TYPE_WARNING,
1687 _ ("Invalid format: `%s'\n"),
1689 GNUNET_free (result);
1690 GNUNET_free (routeList);
1691 return NULL; /* oops */
1693 GNUNET_free (routeList);
1694 return result; /* ok */
1699 * Parse an IPv6 network policy. The argument specifies a list of
1700 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1701 * (no whitespace, must be terminated with a semicolon). The network
1702 * must be given in colon-hex notation. The netmask must be given in
1703 * CIDR notation (/16) or can be omitted to specify a single host.
1704 * Note that the netmask is mandatory if ports are specified.
1706 * @param routeListX a string specifying the policy
1707 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1709 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1710 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1720 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1727 if (NULL == routeListX)
1729 len = strlen (routeListX);
1732 routeList = GNUNET_strdup (routeListX);
1734 for (i = 0; i < len; i++)
1735 if (';' == routeList[i])
1737 if (';' != routeList[len - 1])
1739 LOG (GNUNET_ERROR_TYPE_WARNING,
1740 _ ("Invalid network notation (does not end with ';': `%s')\n"),
1742 GNUNET_free (routeList);
1746 result = GNUNET_malloc (sizeof(struct GNUNET_STRINGS_IPv6NetworkPolicy)
1753 while (';' != routeList[pos])
1756 while ((slash >= start) && (routeList[slash] != '/'))
1761 memset (&result[i].netmask, 0xFF, sizeof(struct in6_addr));
1766 routeList[pos] = '\0';
1767 for (colon = pos; ':' != routeList[colon]; colon--)
1768 if ('/' == routeList[colon])
1770 if (':' == routeList[colon])
1772 routeList[colon] = '\0';
1774 parse_port_policy (&routeList[colon + 1], &result[i].pp))
1776 GNUNET_free (result);
1777 GNUNET_free (routeList);
1781 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1785 if ((1 != sscanf (&routeList[slash + 1], "%u%1s", &bits, dummy)) ||
1789 LOG (GNUNET_ERROR_TYPE_WARNING,
1790 _ ("Wrong format `%s' for netmask\n"),
1791 &routeList[slash + 1]);
1795 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1797 GNUNET_free (result);
1798 GNUNET_free (routeList);
1804 result[i].netmask.s6_addr[off++] = 0xFF;
1809 result[i].netmask.s6_addr[off] =
1810 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1815 routeList[slash] = '\0';
1816 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1820 LOG (GNUNET_ERROR_TYPE_WARNING,
1821 _ ("Wrong format `%s' for network\n"),
1822 &routeList[slash + 1]);
1824 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
1825 GNUNET_free (result);
1826 GNUNET_free (routeList);
1832 GNUNET_free (routeList);
1837 /** ******************** Base64 encoding ***********/
1839 #define FILLCHAR '='
1840 static char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1841 "abcdefghijklmnopqrstuvwxyz"
1846 * Encode into Base64.
1848 * @param in the data to encode
1849 * @param len the length of the input
1850 * @param output where to write the output (*output should be NULL,
1852 * @return the size of the output
1855 GNUNET_STRINGS_base64_encode (const void *in, size_t len, char **output)
1857 const char *data = in;
1862 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1863 for (size_t i = 0; i < len; ++i)
1867 c = (data[i] >> 2) & 0x3f;
1868 opt[ret++] = cvt[(int) c];
1869 c = (data[i] << 4) & 0x3f;
1871 c |= (data[i] >> 4) & 0x0f;
1872 opt[ret++] = cvt[(int) c];
1875 c = (data[i] << 2) & 0x3f;
1877 c |= (data[i] >> 6) & 0x03;
1878 opt[ret++] = cvt[(int) c];
1883 opt[ret++] = FILLCHAR;
1888 opt[ret++] = cvt[(int) c];
1892 opt[ret++] = FILLCHAR;
1900 #define cvtfind(a) \
1901 ((((a) >= 'A') && ((a) <= 'Z')) \
1903 : (((a) >= 'a') && ((a) <= 'z')) \
1905 : (((a) >= '0') && ((a) <= '9')) \
1907 : ((a) == '+') ? 62 : ((a) == '/') ? 63 : -1)
1911 * Decode from Base64.
1913 * @param data the data to encode
1914 * @param len the length of the input
1915 * @param output where to write the output (*output should be NULL,
1917 * @return the size of the output
1920 GNUNET_STRINGS_base64_decode (const char *data, size_t len, void **out)
1925 #define CHECK_CRLF \
1926 while (data[i] == '\r' || data[i] == '\n') \
1928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, \
1929 "ignoring CR/LF\n"); \
1935 output = GNUNET_malloc ((len * 3 / 4) + 8);
1936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1937 "base64_decode decoding len=%d\n",
1939 for (size_t i = 0; i < len; ++i)
1945 if (FILLCHAR == data[i])
1947 c = (char) cvtfind (data[i]);
1950 c1 = (char) cvtfind (data[i]);
1951 c = (c << 2) | ((c1 >> 4) & 0x3);
1959 c = (char) cvtfind (c);
1960 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
1970 c1 = (char) cvtfind (c1);
1971 c = ((c << 6) & 0xc0) | c1;
1981 /* end of strings.c */