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) GNUNET_log_from_strerror (kind, "util-strings", syscall)
43 * Fill a buffer of the given size with
44 * count 0-terminated strings (given as varargs).
45 * If "buffer" is NULL, only compute the amount of
46 * space required (sum of "strlen(arg)+1").
48 * Unlike using "snprintf" with "%s", this function
49 * will add 0-terminators after each string. The
50 * #GNUNET_string_buffer_tokenize() function can be
51 * used to parse the buffer back into individual
54 * @param buffer the buffer to fill with strings, can
55 * be NULL in which case only the necessary
56 * amount of space will be calculated
57 * @param size number of bytes available in buffer
58 * @param count number of strings that follow
59 * @param ... count 0-terminated strings to copy to buffer
60 * @return number of bytes written to the buffer
61 * (or number of bytes that would have been written)
64 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
75 s = va_arg (ap, const char *);
77 slen = strlen (s) + 1;
80 GNUNET_assert (needed + slen <= size);
81 GNUNET_memcpy (&buffer[needed], s, slen);
92 * Convert a peer path to a human-readable string.
94 * @param pids array of PIDs to convert to a string
95 * @param num_pids length of the @a pids array
96 * @return string representing the array of @a pids
99 GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids,
100 unsigned int num_pids)
104 size_t plen = num_pids * 5 + 1;
107 buf = GNUNET_malloc (plen);
108 for (unsigned int i = 0;
112 off += GNUNET_snprintf (&buf[off],
115 GNUNET_i2s (&pids[i]),
116 (i == num_pids -1) ? "" : "-");
123 * Given a buffer of a given size, find "count"
124 * 0-terminated strings in the buffer and assign
125 * the count (varargs) of type "const char**" to the
126 * locations of the respective strings in the
129 * @param buffer the buffer to parse
130 * @param size size of the buffer
131 * @param count number of strings to locate
132 * @return offset of the character after the last 0-termination
133 * in the buffer, or 0 on error.
136 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
137 unsigned int count, ...)
145 va_start (ap, count);
148 r = va_arg (ap, const char **);
151 while ((needed < size) && (buffer[needed] != '\0'))
156 return 0; /* error */
159 needed++; /* skip 0-termination */
168 * Convert a given filesize into a fancy human-readable format.
170 * @param size number of bytes
171 * @return fancy representation of the size (possibly rounded) for humans
174 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
176 const char *unit = _( /* size unit */ "b");
199 ret = GNUNET_malloc (32);
200 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
206 * Unit conversion table entry for 'convert_with_table'.
208 struct ConversionTable
211 * Name of the unit (or NULL for end of table).
216 * Factor to apply for this unit.
218 unsigned long long value;
223 * Convert a string of the form "4 X 5 Y" into a numeric value
224 * by interpreting "X" and "Y" as units and then multiplying
225 * the numbers with the values associated with the respective
226 * unit from the conversion table.
228 * @param input input string to parse
229 * @param table table with the conversion of unit names to numbers
230 * @param output where to store the result
231 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
234 convert_with_table (const char *input,
235 const struct ConversionTable *table,
236 unsigned long long *output)
238 unsigned long long ret;
241 unsigned long long last;
246 in = GNUNET_strdup (input);
247 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
252 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
254 if (table[i].name != NULL)
256 last *= table[i].value;
257 break; /* next tok */
264 last = strtoull (tok, &endptr, 10);
265 if ((0 != errno) || (endptr == tok))
268 return GNUNET_SYSERR; /* expected number */
270 if ('\0' == endptr[0])
271 break; /* next tok */
273 tok = endptr; /* and re-check (handles times like "10s") */
275 } while (GNUNET_YES);
285 * Convert a given fancy human-readable size to bytes.
287 * @param fancy_size human readable string (i.e. 1 MB)
288 * @param size set to the size in bytes
289 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
292 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
293 unsigned long long *size)
295 static const struct ConversionTable table[] =
300 { "MiB", 1024 * 1024},
301 { "MB", 1000 * 1000},
302 { "GiB", 1024 * 1024 * 1024},
303 { "GB", 1000 * 1000 * 1000},
304 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
305 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
306 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
307 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
308 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
309 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
313 return convert_with_table (fancy_size,
320 * Convert a given fancy human-readable time to our internal
323 * @param fancy_time human readable string (i.e. 1 minute)
324 * @param rtime set to the relative time
325 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
328 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
329 struct GNUNET_TIME_Relative *rtime)
331 static const struct ConversionTable table[] =
335 { "s", 1000 * 1000LL },
336 { "second", 1000 * 1000LL },
337 { "seconds", 1000 * 1000LL },
338 { "\"", 1000 * 1000LL },
339 { "m", 60 * 1000 * 1000LL},
340 { "min", 60 * 1000 * 1000LL},
341 { "minute", 60 * 1000 * 1000LL},
342 { "minutes", 60 * 1000 * 1000LL},
343 { "'", 60 * 1000 * 1000LL},
344 { "h", 60 * 60 * 1000 * 1000LL},
345 { "hour", 60 * 60 * 1000 * 1000LL},
346 { "hours", 60 * 60 * 1000 * 1000LL},
347 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
348 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
349 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
350 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
351 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
352 { "year", 31536000000000LL /* year */ },
353 { "years", 31536000000000LL /* year */ },
354 { "a", 31536000000000LL /* year */ },
358 unsigned long long val;
360 if (0 == strcasecmp ("forever", fancy_time))
362 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
365 ret = convert_with_table (fancy_time,
368 rtime->rel_value_us = (uint64_t) val;
374 * Convert a given fancy human-readable time to our internal
375 * representation. The human-readable time is expected to be
376 * in local time, whereas the returned value will be in UTC.
378 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
379 * @param atime set to the absolute time
380 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
383 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
384 struct GNUNET_TIME_Absolute *atime)
390 if (0 == strcasecmp ("end of time",
393 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
396 eos = &fancy_time[strlen (fancy_time)];
397 memset (&tv, 0, sizeof (tv));
398 if ( (eos != strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
399 (eos != strptime (fancy_time, "%c", &tv)) &&
400 (eos != strptime (fancy_time, "%Ec", &tv)) &&
401 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
402 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
403 (eos != strptime (fancy_time, "%x", &tv)) &&
404 (eos != strptime (fancy_time, "%Ex", &tv)) &&
405 (eos != strptime (fancy_time, "%Y-%m-%d", &tv)) &&
406 (eos != strptime (fancy_time, "%Y-%m", &tv)) &&
407 (eos != strptime (fancy_time, "%Y", &tv)) )
408 return GNUNET_SYSERR;
410 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
416 * Convert the len characters long character sequence
417 * given in input that is in the given input charset
418 * to a string in given output charset.
420 * @param input input string
421 * @param len number of bytes in @a input
422 * @param input_charset character set used for @a input
423 * @param output_charset desired character set for the return value
424 * @return the converted string (0-terminated),
425 * if conversion fails, a copy of the orignal
426 * string is returned.
429 GNUNET_STRINGS_conv (const char *input,
431 const char *input_charset,
432 const char *output_charset)
436 char *encoded_string;
437 size_t u8_string_length;
438 size_t encoded_string_length;
440 u8_string = u8_conv_from_encoding (input_charset,
445 if (NULL == u8_string)
447 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
450 if (0 == strcmp (output_charset, "UTF-8"))
452 ret = GNUNET_malloc (u8_string_length + 1);
453 GNUNET_memcpy (ret, u8_string, u8_string_length);
454 ret[u8_string_length] = '\0';
458 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
459 u8_string, u8_string_length,
461 &encoded_string_length);
463 if (NULL == encoded_string)
465 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
468 ret = GNUNET_malloc (encoded_string_length + 1);
469 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
470 ret[encoded_string_length] = '\0';
471 free (encoded_string);
474 LOG (GNUNET_ERROR_TYPE_WARNING,
475 _("Character sets requested were `%s'->`%s'\n"),
476 "UTF-8", output_charset);
477 ret = GNUNET_malloc (len + 1);
478 GNUNET_memcpy (ret, input, len);
485 * Convert the len characters long character sequence
486 * given in input that is in the given charset
489 * @param input the input string (not necessarily 0-terminated)
490 * @param len the number of bytes in the @a input
491 * @param charset character set to convert from
492 * @return the converted string (0-terminated),
493 * if conversion fails, a copy of the orignal
494 * string is returned.
497 GNUNET_STRINGS_to_utf8 (const char *input,
501 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
506 * Convert the len bytes-long UTF-8 string
507 * given in input to the given charset.
509 * @param input the input string (not necessarily 0-terminated)
510 * @param len the number of bytes in the @a input
511 * @param charset character set to convert to
512 * @return the converted string (0-terminated),
513 * if conversion fails, a copy of the orignal
514 * string is returned.
517 GNUNET_STRINGS_from_utf8 (const char *input,
521 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
526 * Convert the utf-8 input string to lowercase.
527 * Output needs to be allocated appropriately.
529 * @param input input string
530 * @param output output buffer
533 GNUNET_STRINGS_utf8_tolower (const char *input,
539 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
540 NULL, UNINORM_NFD, NULL, &len);
541 GNUNET_memcpy(output, tmp_in, len);
548 * Convert the utf-8 input string to uppercase.
549 * Output needs to be allocated appropriately.
551 * @param input input string
552 * @param output output buffer
555 GNUNET_STRINGS_utf8_toupper(const char *input,
561 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
562 NULL, UNINORM_NFD, NULL, &len);
563 GNUNET_memcpy (output, tmp_in, len);
570 * Complete filename (a la shell) from abbrevition.
571 * @param fil the name of the file, may contain ~/ or
572 * be relative to the current directory
573 * @returns the full file name,
574 * NULL is returned on error
577 GNUNET_STRINGS_filename_expand (const char *fil)
593 if (fil[0] == DIR_SEPARATOR)
594 /* absolute path, just copy */
595 return GNUNET_strdup (fil);
598 fm = getenv ("HOME");
601 LOG (GNUNET_ERROR_TYPE_WARNING,
602 _("Failed to expand `$HOME': environment variable `HOME' not set"));
605 fm = GNUNET_strdup (fm);
606 /* do not copy '~' */
609 /* skip over dir seperator to be consistent */
610 if (fil_ptr[0] == DIR_SEPARATOR)
621 buffer = GNUNET_malloc (len);
622 if (getcwd (buffer, len) != NULL)
627 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
630 GNUNET_free (buffer);
633 GNUNET_free (buffer);
638 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
640 buffer = getenv ("PWD"); /* alternative */
642 fm = GNUNET_strdup (buffer);
645 fm = GNUNET_strdup ("./"); /* give up */
647 GNUNET_asprintf (&buffer,
650 (fm[strlen (fm) - 1] ==
651 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
655 fn = GNUNET_malloc (MAX_PATH + 1);
657 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
659 SetErrnoFromWinError (lRet);
660 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
661 "plibc_conv_to_win_path");
664 /* is the path relative? */
665 if ( (0 != strncmp (fn + 1, ":\\", 2)) &&
666 (0 != strncmp (fn, "\\\\", 2)) )
668 char szCurDir[MAX_PATH + 1];
670 lRet = GetCurrentDirectory (MAX_PATH + 1,
672 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
674 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
675 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
676 "GetCurrentDirectory");
679 GNUNET_asprintf (&buffer,
693 * Give relative time in human-readable fancy format.
694 * This is one of the very few calls in the entire API that is
697 * @param delta time in milli seconds
698 * @param do_round are we allowed to round a bit?
699 * @return time as human-readable string
702 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
705 static char buf[128];
706 const char *unit = _( /* time unit */ "µs");
707 uint64_t dval = delta.rel_value_us;
709 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
711 if (0 == delta.rel_value_us)
713 if ( ( (GNUNET_YES == do_round) &&
714 (dval > 5 * 1000) ) ||
715 (0 == (dval % 1000) ))
718 unit = _( /* time unit */ "ms");
719 if ( ( (GNUNET_YES == do_round) &&
720 (dval > 5 * 1000) ) ||
721 (0 == (dval % 1000) ))
724 unit = _( /* time unit */ "s");
725 if ( ( (GNUNET_YES == do_round) &&
727 (0 == (dval % 60) ) )
730 unit = _( /* time unit */ "m");
731 if ( ( (GNUNET_YES == do_round) &&
736 unit = _( /* time unit */ "h");
737 if ( ( (GNUNET_YES == do_round) &&
743 unit = _( /* time unit */ "day");
745 unit = _( /* time unit */ "days");
751 GNUNET_snprintf (buf, sizeof (buf),
752 "%llu %s", dval, unit);
758 * "asctime", except for GNUnet time. Converts a GNUnet internal
759 * absolute time (which is in UTC) to a string in local time.
760 * Note that the returned value will be overwritten if this function
763 * @param t the absolute time to convert
764 * @return timestamp in human-readable form in local time
767 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
769 static char buf[255];
773 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
774 return _("end of time");
775 tt = t.abs_value_us / 1000LL / 1000LL;
776 tp = localtime (&tt);
777 /* This is hacky, but i don't know a way to detect libc character encoding.
778 * Just expect utf8 from glibc these days.
779 * As for msvcrt, use the wide variant, which always returns utf16
780 * (otherwise we'd have to detect current codepage or use W32API character
781 * set conversion routines to convert to UTF8).
784 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
787 static wchar_t wbuf[255];
791 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
792 L"%a %b %d %H:%M:%S %Y", tp);
794 ssize = sizeof (buf);
795 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
796 (uint8_t *) buf, &ssize);
797 if (conved != (uint8_t *) buf)
799 strncpy (buf, (char *) conved, sizeof (buf));
811 * Returns a pointer to a part of filename (allocates nothing)!
813 * @param filename filename to extract basename from
814 * @return short (base) name of the file (that is, everything following the
815 * last directory separator in filename. If filename ends with a
816 * directory separator, the result will be a zero-length string.
817 * If filename has no directory separators, the result is filename
821 GNUNET_STRINGS_get_short_name (const char *filename)
823 const char *short_fn = filename;
826 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
834 * Get the decoded value corresponding to a character according to Crockford
837 * @param a a character
838 * @return corresponding numeric value
841 getValue__ (unsigned char a)
857 /* also consider U to be V */
865 if ((a >= '0') && (a <= '9'))
867 if ((a >= 'a') && (a <= 'z'))
869 /* return (a - 'a' + 10); */
871 if ((a >= 'A') && (a <= 'Z'))
881 return (a - 'A' + 10 - dec);
888 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
889 * Returns a pointer to the byte after the last byte in the string, that
890 * is where the 0-terminator was placed if there was room.
892 * @param data data to encode
893 * @param size size of data (in bytes)
894 * @param out buffer to fill
895 * @param out_size size of the buffer. Must be large enough to hold
896 * (size * 8 + 4) / 5 bytes
897 * @return pointer to the next byte in @a out or NULL on error.
900 GNUNET_STRINGS_data_to_string (const void *data,
906 * 32 characters for encoding
908 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
913 const unsigned char *udata;
916 if (out_size < (size * 8 + 4) / 5)
925 while ((rpos < size) || (vbit > 0))
927 if ((rpos < size) && (vbit < 5))
929 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
934 bits <<= (5 - vbit); /* zero-padding */
935 GNUNET_assert (vbit == ((size * 8) % 5));
938 if (wpos >= out_size)
943 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
946 GNUNET_assert (0 == vbit);
954 * Return the base32crockford encoding of the given buffer.
956 * The returned string will be freshly allocated, and must be free'd
957 * with GNUNET_free().
959 * @param buffer with data
960 * @param size size of the buffer
961 * @return freshly allocated, null-terminated string
964 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
968 size_t len = size * 8;
974 str_buf = GNUNET_malloc (len + 1);
975 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
978 GNUNET_free (str_buf);
987 * Convert Crockford Base32hex encoding back to data.
988 * @a out_size must match exactly the size of the data before it was encoded.
990 * @param enc the encoding
991 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
992 * @param out location where to store the decoded data
993 * @param out_size size of the output buffer @a out
994 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
997 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
998 void *out, size_t out_size)
1006 unsigned char *uout;
1007 unsigned int encoded_len = out_size * 8;
1013 return GNUNET_SYSERR;
1018 if ((encoded_len % 5) > 0)
1020 vbit = encoded_len % 5; /* padding! */
1022 bits = (ret = getValue__ (enc[--rpos])) >> shift;
1028 bits = (ret = getValue__ (enc[--rpos]));
1030 if ((encoded_len + shift) / 5 != enclen)
1031 return GNUNET_SYSERR;
1033 return GNUNET_SYSERR;
1039 return GNUNET_SYSERR;
1041 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1043 return GNUNET_SYSERR;
1047 uout[--wpos] = (unsigned char) bits;
1054 return GNUNET_SYSERR;
1060 * Parse a path that might be an URI.
1062 * @param path path to parse. Must be NULL-terminated.
1063 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1064 * represents the URI scheme will be stored. Can be NULL. The string is
1065 * allocated by the function, and should be freed by GNUNET_free() when
1066 * it is no longer needed.
1067 * @param path_part a pointer to 'const char *' where a pointer to the path
1068 * part of the URI will be stored. Can be NULL. Points to the same block
1069 * of memory as 'path', and thus must not be freed. Might point to '\0',
1070 * if path part is zero-length.
1071 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1072 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1073 * (if they weren't NULL).
1076 GNUNET_STRINGS_parse_uri (const char *path,
1078 const char **path_part)
1084 const char *post_scheme_part = NULL;
1085 len = strlen (path);
1086 for (end = 0, i = 0; !end && i < len; i++)
1091 if ( (path[i] == ':') && (i > 0) )
1096 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1097 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1098 || (path[i] == '.')))
1111 post_scheme_part = &path[i];
1118 if (post_scheme_part == NULL)
1122 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1123 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1124 (*scheme_part)[post_scheme_part - path] = '\0';
1127 *path_part = post_scheme_part;
1133 * Check whether @a filename is absolute or not, and if it's an URI
1135 * @param filename filename to check
1136 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1137 * assume it's not URI
1138 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1139 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1140 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1141 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1142 * The string is allocated by the function, and should be freed with
1143 * GNUNET_free(). Can be NULL.
1144 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1147 GNUNET_STRINGS_path_is_absolute (const char *filename,
1150 char **r_uri_scheme)
1155 const char *post_scheme_path;
1158 /* consider POSIX paths to be absolute too, even on W32,
1159 * as plibc expansion will fix them for us.
1161 if (filename[0] == '/')
1165 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1171 *r_uri_scheme = uri;
1173 GNUNET_free_non_null (uri);
1175 len = strlen(post_scheme_path);
1176 /* Special check for file:///c:/blah
1177 * We want to parse 'c:/', not '/c:/'
1179 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1180 post_scheme_path = &post_scheme_path[1];
1182 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1188 *r_is_uri = GNUNET_NO;
1191 len = strlen (filename);
1193 ((filename[0] >= 'A' && filename[0] <= 'Z')
1194 || (filename[0] >= 'a' && filename[0] <= 'z'))
1195 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1202 #define _IFMT 0170000 /* type of file */
1203 #define _IFLNK 0120000 /* symbolic link */
1204 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1209 * Perform @a checks on @a filename.
1211 * @param filename file to check
1212 * @param checks checks to perform
1213 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1214 * fails, #GNUNET_SYSERR when a check can't be performed
1217 GNUNET_STRINGS_check_filename (const char *filename,
1218 enum GNUNET_STRINGS_FilenameCheck checks)
1221 if ( (NULL == filename) || (filename[0] == '\0') )
1222 return GNUNET_SYSERR;
1223 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1224 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1226 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1227 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1228 | GNUNET_STRINGS_CHECK_IS_LINK)))
1230 if (0 != STAT (filename, &st))
1232 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1235 return GNUNET_SYSERR;
1238 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1239 if (!S_ISDIR (st.st_mode))
1241 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1242 if (!S_ISLNK (st.st_mode))
1249 * Tries to convert @a zt_addr string to an IPv6 address.
1250 * The string is expected to have the format "[ABCD::01]:80".
1252 * @param zt_addr 0-terminated string. May be mangled by the function.
1253 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1254 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1255 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1256 * @return #GNUNET_OK if conversion succeded.
1257 * #GNUNET_SYSERR otherwise, in which
1258 * case the contents of @a r_buf are undefined.
1261 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1263 struct sockaddr_in6 *r_buf)
1265 char zbuf[addrlen + 1];
1272 return GNUNET_SYSERR;
1273 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1276 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1277 _("IPv6 address did not start with `['\n"));
1278 return GNUNET_SYSERR;
1280 zbuf[addrlen] = '\0';
1281 port_colon = strrchr (zbuf, ':');
1282 if (NULL == port_colon)
1284 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1285 _("IPv6 address did contain ':' to separate port number\n"));
1286 return GNUNET_SYSERR;
1288 if (']' != *(port_colon - 1))
1290 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1291 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1292 return GNUNET_SYSERR;
1294 ret = SSCANF (port_colon,
1298 if ( (1 != ret) || (port > 65535) )
1300 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1301 _("IPv6 address did contain a valid port number after the last ':'\n"));
1302 return GNUNET_SYSERR;
1304 *(port_colon-1) = '\0';
1305 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1306 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1309 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1310 _("Invalid IPv6 address `%s': %s\n"),
1313 return GNUNET_SYSERR;
1315 r_buf->sin6_port = htons (port);
1316 r_buf->sin6_family = AF_INET6;
1317 #if HAVE_SOCKADDR_IN_SIN_LEN
1318 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1325 * Tries to convert 'zt_addr' string to an IPv4 address.
1326 * The string is expected to have the format "1.2.3.4:80".
1328 * @param zt_addr 0-terminated string. May be mangled by the function.
1329 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1330 * @param r_buf a buffer to fill.
1331 * @return #GNUNET_OK if conversion succeded.
1332 * #GNUNET_SYSERR otherwise, in which case
1333 * the contents of @a r_buf are undefined.
1336 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1338 struct sockaddr_in *r_buf)
1340 unsigned int temps[4];
1346 return GNUNET_SYSERR;
1347 cnt = SSCANF (zt_addr,
1348 "%u.%u.%u.%u:%u%1s",
1356 return GNUNET_SYSERR;
1357 for (cnt = 0; cnt < 4; cnt++)
1358 if (temps[cnt] > 0xFF)
1359 return GNUNET_SYSERR;
1361 return GNUNET_SYSERR;
1362 r_buf->sin_family = AF_INET;
1363 r_buf->sin_port = htons (port);
1364 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1365 (temps[2] << 8) + temps[3]);
1366 #if HAVE_SOCKADDR_IN_SIN_LEN
1367 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1374 * Tries to convert @a addr string to an IP (v4 or v6) address.
1375 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1377 * @param addr a string, may not be 0-terminated.
1378 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1379 * 0-terminator should not be counted towards addrlen).
1380 * @param r_buf a buffer to fill.
1381 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1382 * case the contents of @a r_buf are undefined.
1385 GNUNET_STRINGS_to_address_ip (const char *addr,
1387 struct sockaddr_storage *r_buf)
1390 return GNUNET_STRINGS_to_address_ipv6 (addr,
1392 (struct sockaddr_in6 *) r_buf);
1393 return GNUNET_STRINGS_to_address_ipv4 (addr,
1395 (struct sockaddr_in *) r_buf);
1400 * Parse an address given as a string into a
1401 * `struct sockaddr`.
1403 * @param addr the address
1404 * @param[out] af set to the parsed address family (i.e. AF_INET)
1405 * @param[out] sa set to the parsed address
1406 * @return 0 on error, otherwise number of bytes in @a sa
1409 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1411 struct sockaddr **sa)
1413 char *cp = GNUNET_strdup (addr);
1419 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1421 GNUNET_STRINGS_to_address_ipv6 (cp,
1423 (struct sockaddr_in6 *) *sa))
1432 return sizeof (struct sockaddr_in6);
1437 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1439 GNUNET_STRINGS_to_address_ipv4 (cp,
1441 (struct sockaddr_in *) *sa))
1450 return sizeof (struct sockaddr_in);
1456 * Makes a copy of argv that consists of a single memory chunk that can be
1457 * freed with a single call to GNUNET_free();
1459 static char *const *
1460 _make_continuous_arg_copy (int argc,
1463 size_t argvsize = 0;
1467 for (i = 0; i < argc; i++)
1468 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1469 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1470 p = (char *) &new_argv[argc + 1];
1471 for (i = 0; i < argc; i++)
1474 strcpy (p, argv[i]);
1475 p += strlen (argv[i]) + 1;
1477 new_argv[argc] = NULL;
1478 return (char *const *) new_argv;
1483 * Returns utf-8 encoded arguments.
1484 * Does nothing (returns a copy of argc and argv) on any platform
1486 * Returned argv has u8argv[u8argc] == NULL.
1487 * Returned argv is a single memory block, and can be freed with a single
1488 * GNUNET_free() call.
1490 * @param argc argc (as given by main())
1491 * @param argv argv (as given by main())
1492 * @param u8argc a location to store new argc in (though it's th same as argc)
1493 * @param u8argv a location to store new argv in
1494 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1497 GNUNET_STRINGS_get_utf8_args (int argc,
1500 char *const **u8argv)
1507 char **split_u8argv;
1509 wcmd = GetCommandLineW ();
1511 return GNUNET_SYSERR;
1512 wargv = CommandLineToArgvW (wcmd, &wargc);
1514 return GNUNET_SYSERR;
1516 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1518 for (i = 0; i < wargc; i++)
1521 /* Hopefully it will allocate us NUL-terminated strings... */
1522 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1523 if (NULL == split_u8argv[i])
1526 for (j = 0; j < i; j++)
1527 free (split_u8argv[j]);
1528 GNUNET_free (split_u8argv);
1530 return GNUNET_SYSERR;
1534 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1537 for (i = 0; i < wargc; i++)
1538 free (split_u8argv[i]);
1539 free (split_u8argv);
1542 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1551 * Parse the given port policy. The format is
1552 * "[!]SPORT[-DPORT]".
1554 * @param port_policy string to parse
1555 * @param pp policy to fill in
1556 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1557 * @a port_policy is malformed
1560 parse_port_policy (const char *port_policy,
1561 struct GNUNET_STRINGS_PortPolicy *pp)
1571 pp->negate_portrange = GNUNET_YES;
1574 if (2 == sscanf (pos,
1585 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1586 _("Port not in range\n"));
1587 return GNUNET_SYSERR;
1589 pp->start_port = (uint16_t) s;
1590 pp->end_port = (uint16_t) e;
1593 if (1 == sscanf (pos,
1601 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1602 _("Port not in range\n"));
1603 return GNUNET_SYSERR;
1606 pp->start_port = (uint16_t) s;
1607 pp->end_port = (uint16_t) s;
1610 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1611 _("Malformed port policy `%s'\n"),
1613 return GNUNET_SYSERR;
1618 * Parse an IPv4 network policy. The argument specifies a list of
1619 * subnets. The format is
1620 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1621 * be terminated with a semicolon). The network must be given in
1622 * dotted-decimal notation. The netmask can be given in CIDR notation
1623 * (/16) or in dotted-decimal (/255.255.0.0).
1625 * @param routeListX a string specifying the IPv4 subnets
1626 * @return the converted list, terminated with all zeros;
1627 * NULL if the synatx is flawed
1629 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1630 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1638 unsigned int temps[8];
1640 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1646 if (NULL == routeListX)
1648 len = strlen (routeListX);
1651 routeList = GNUNET_strdup (routeListX);
1653 for (i = 0; i < len; i++)
1654 if (routeList[i] == ';')
1656 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1661 for (colon = pos; ':' != routeList[colon]; colon++)
1662 if ( (';' == routeList[colon]) ||
1663 ('\0' == routeList[colon]) )
1665 for (end = colon; ';' != routeList[end]; end++)
1666 if ('\0' == routeList[end])
1668 if ('\0' == routeList[end])
1670 routeList[end] = '\0';
1671 if (':' == routeList[colon])
1673 routeList[colon] = '\0';
1674 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1679 SSCANF (&routeList[pos],
1680 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1692 for (j = 0; j < 8; j++)
1693 if (temps[j] > 0xFF)
1695 LOG (GNUNET_ERROR_TYPE_WARNING,
1696 _("Invalid format for IP: `%s'\n"),
1698 GNUNET_free (result);
1699 GNUNET_free (routeList);
1702 result[i].network.s_addr =
1703 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1705 result[i].netmask.s_addr =
1706 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1712 /* try second notation */
1714 SSCANF (&routeList[pos],
1715 "%u.%u.%u.%u/%u%1s",
1724 for (j = 0; j < 4; j++)
1725 if (temps[j] > 0xFF)
1727 LOG (GNUNET_ERROR_TYPE_WARNING,
1728 _("Invalid format for IP: `%s'\n"),
1730 GNUNET_free (result);
1731 GNUNET_free (routeList);
1734 result[i].network.s_addr =
1735 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1737 if ((slash <= 32) && (slash >= 0))
1739 result[i].netmask.s_addr = 0;
1742 result[i].netmask.s_addr =
1743 (result[i].netmask.s_addr >> 1) + 0x80000000;
1746 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1753 LOG (GNUNET_ERROR_TYPE_WARNING,
1754 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1756 GNUNET_free (result);
1757 GNUNET_free (routeList);
1758 return NULL; /* error */
1761 /* try third notation */
1764 SSCANF (&routeList[pos],
1773 for (j = 0; j < 4; j++)
1774 if (temps[j] > 0xFF)
1776 LOG (GNUNET_ERROR_TYPE_WARNING,
1777 _("Invalid format for IP: `%s'\n"),
1779 GNUNET_free (result);
1780 GNUNET_free (routeList);
1783 result[i].network.s_addr =
1784 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1786 result[i].netmask.s_addr = 0;
1789 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1792 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1797 LOG (GNUNET_ERROR_TYPE_WARNING,
1798 _("Invalid format for IP: `%s'\n"),
1800 GNUNET_free (result);
1801 GNUNET_free (routeList);
1802 return NULL; /* error */
1804 if (pos < strlen (routeList))
1806 LOG (GNUNET_ERROR_TYPE_WARNING,
1807 _("Invalid format: `%s'\n"),
1809 GNUNET_free (result);
1810 GNUNET_free (routeList);
1811 return NULL; /* oops */
1813 GNUNET_free (routeList);
1814 return result; /* ok */
1819 * Parse an IPv6 network policy. The argument specifies a list of
1820 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1821 * (no whitespace, must be terminated with a semicolon). The network
1822 * must be given in colon-hex notation. The netmask must be given in
1823 * CIDR notation (/16) or can be omitted to specify a single host.
1824 * Note that the netmask is mandatory if ports are specified.
1826 * @param routeListX a string specifying the policy
1827 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1829 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1830 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1840 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1847 if (NULL == routeListX)
1849 len = strlen (routeListX);
1852 routeList = GNUNET_strdup (routeListX);
1854 for (i = 0; i < len; i++)
1855 if (';' == routeList[i])
1857 if (';' != routeList[len - 1])
1859 LOG (GNUNET_ERROR_TYPE_WARNING,
1860 _("Invalid network notation (does not end with ';': `%s')\n"),
1862 GNUNET_free (routeList);
1866 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1872 while (';' != routeList[pos])
1875 while ((slash >= start) && (routeList[slash] != '/'))
1880 memset (&result[i].netmask,
1882 sizeof (struct in6_addr));
1887 routeList[pos] = '\0';
1888 for (colon = pos; ':' != routeList[colon]; colon--)
1889 if ('/' == routeList[colon])
1891 if (':' == routeList[colon])
1893 routeList[colon] = '\0';
1894 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1897 GNUNET_free (result);
1898 GNUNET_free (routeList);
1902 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1906 if ( (1 != SSCANF (&routeList[slash + 1],
1913 LOG (GNUNET_ERROR_TYPE_WARNING,
1914 _("Wrong format `%s' for netmask\n"),
1915 &routeList[slash + 1]);
1919 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1921 GNUNET_free (result);
1922 GNUNET_free (routeList);
1928 result[i].netmask.s6_addr[off++] = 0xFF;
1933 result[i].netmask.s6_addr[off] =
1934 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1939 routeList[slash] = '\0';
1940 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1944 LOG (GNUNET_ERROR_TYPE_WARNING,
1945 _("Wrong format `%s' for network\n"),
1946 &routeList[slash + 1]);
1948 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1950 GNUNET_free (result);
1951 GNUNET_free (routeList);
1957 GNUNET_free (routeList);
1963 /** ******************** Base64 encoding ***********/
1965 #define FILLCHAR '='
1967 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1971 * Encode into Base64.
1973 * @param in the data to encode
1974 * @param len the length of the input
1975 * @param output where to write the output (*output should be NULL,
1977 * @return the size of the output
1980 GNUNET_STRINGS_base64_encode (const void *in,
1984 const char *data = in;
1989 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1990 for (size_t i = 0; i < len; ++i)
1994 c = (data[i] >> 2) & 0x3f;
1995 opt[ret++] = cvt[(int) c];
1996 c = (data[i] << 4) & 0x3f;
1998 c |= (data[i] >> 4) & 0x0f;
1999 opt[ret++] = cvt[(int) c];
2002 c = (data[i] << 2) & 0x3f;
2004 c |= (data[i] >> 6) & 0x03;
2005 opt[ret++] = cvt[(int) c];
2010 opt[ret++] = FILLCHAR;
2015 opt[ret++] = cvt[(int) c];
2019 opt[ret++] = FILLCHAR;
2026 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
2027 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
2028 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
2030 :((a) == '/') ? 63 : -1)
2034 * Decode from Base64.
2036 * @param data the data to encode
2037 * @param len the length of the input
2038 * @param output where to write the output (*output should be NULL,
2040 * @return the size of the output
2043 GNUNET_STRINGS_base64_decode (const char *data,
2050 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
2051 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
2053 if (i >= len) goto END; \
2056 output = GNUNET_malloc ((len * 3 / 4) + 8);
2057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2058 "base64_decode decoding len=%d\n",
2060 for (size_t i = 0; i < len; ++i)
2066 if (FILLCHAR == data[i])
2068 c = (char) cvtfind (data[i]);
2071 c1 = (char) cvtfind (data[i]);
2072 c = (c << 2) | ((c1 >> 4) & 0x3);
2080 c = (char) cvtfind (c);
2081 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2091 c1 = (char) cvtfind (c1);
2092 c = ((c << 6) & 0xc0) | c1;
2102 /* end of strings.c */