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)
389 if (0 == strcasecmp ("end of time",
392 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
395 memset (&tv, 0, sizeof (tv));
396 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
397 (NULL == strptime (fancy_time, "%c", &tv)) &&
398 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
399 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
400 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
401 (NULL == strptime (fancy_time, "%x", &tv)) &&
402 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
403 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
404 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
405 (NULL == strptime (fancy_time, "%Y", &tv)) )
406 return GNUNET_SYSERR;
408 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
414 * Convert the len characters long character sequence
415 * given in input that is in the given input charset
416 * to a string in given output charset.
418 * @param input input string
419 * @param len number of bytes in @a input
420 * @param input_charset character set used for @a input
421 * @param output_charset desired character set for the return value
422 * @return the converted string (0-terminated),
423 * if conversion fails, a copy of the orignal
424 * string is returned.
427 GNUNET_STRINGS_conv (const char *input,
429 const char *input_charset,
430 const char *output_charset)
434 char *encoded_string;
435 size_t u8_string_length;
436 size_t encoded_string_length;
438 u8_string = u8_conv_from_encoding (input_charset,
443 if (NULL == u8_string)
445 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
448 if (0 == strcmp (output_charset, "UTF-8"))
450 ret = GNUNET_malloc (u8_string_length + 1);
451 GNUNET_memcpy (ret, u8_string, u8_string_length);
452 ret[u8_string_length] = '\0';
456 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
457 u8_string, u8_string_length,
459 &encoded_string_length);
461 if (NULL == encoded_string)
463 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
466 ret = GNUNET_malloc (encoded_string_length + 1);
467 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
468 ret[encoded_string_length] = '\0';
469 free (encoded_string);
472 LOG (GNUNET_ERROR_TYPE_WARNING,
473 _("Character sets requested were `%s'->`%s'\n"),
474 "UTF-8", output_charset);
475 ret = GNUNET_malloc (len + 1);
476 GNUNET_memcpy (ret, input, len);
483 * Convert the len characters long character sequence
484 * given in input that is in the given charset
487 * @param input the input string (not necessarily 0-terminated)
488 * @param len the number of bytes in the @a input
489 * @param charset character set to convert from
490 * @return the converted string (0-terminated),
491 * if conversion fails, a copy of the orignal
492 * string is returned.
495 GNUNET_STRINGS_to_utf8 (const char *input,
499 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
504 * Convert the len bytes-long UTF-8 string
505 * given in input to the given charset.
507 * @param input the input string (not necessarily 0-terminated)
508 * @param len the number of bytes in the @a input
509 * @param charset character set to convert to
510 * @return the converted string (0-terminated),
511 * if conversion fails, a copy of the orignal
512 * string is returned.
515 GNUNET_STRINGS_from_utf8 (const char *input,
519 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
524 * Convert the utf-8 input string to lowercase.
525 * Output needs to be allocated appropriately.
527 * @param input input string
528 * @param output output buffer
531 GNUNET_STRINGS_utf8_tolower (const char *input,
537 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
538 NULL, UNINORM_NFD, NULL, &len);
539 GNUNET_memcpy(output, tmp_in, len);
546 * Convert the utf-8 input string to uppercase.
547 * Output needs to be allocated appropriately.
549 * @param input input string
550 * @param output output buffer
553 GNUNET_STRINGS_utf8_toupper(const char *input,
559 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
560 NULL, UNINORM_NFD, NULL, &len);
561 GNUNET_memcpy (output, tmp_in, len);
568 * Complete filename (a la shell) from abbrevition.
569 * @param fil the name of the file, may contain ~/ or
570 * be relative to the current directory
571 * @returns the full file name,
572 * NULL is returned on error
575 GNUNET_STRINGS_filename_expand (const char *fil)
591 if (fil[0] == DIR_SEPARATOR)
592 /* absolute path, just copy */
593 return GNUNET_strdup (fil);
596 fm = getenv ("HOME");
599 LOG (GNUNET_ERROR_TYPE_WARNING,
600 _("Failed to expand `$HOME': environment variable `HOME' not set"));
603 fm = GNUNET_strdup (fm);
604 /* do not copy '~' */
607 /* skip over dir seperator to be consistent */
608 if (fil_ptr[0] == DIR_SEPARATOR)
619 buffer = GNUNET_malloc (len);
620 if (getcwd (buffer, len) != NULL)
625 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
628 GNUNET_free (buffer);
631 GNUNET_free (buffer);
636 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
638 buffer = getenv ("PWD"); /* alternative */
640 fm = GNUNET_strdup (buffer);
643 fm = GNUNET_strdup ("./"); /* give up */
645 GNUNET_asprintf (&buffer,
648 (fm[strlen (fm) - 1] ==
649 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
653 fn = GNUNET_malloc (MAX_PATH + 1);
655 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
657 SetErrnoFromWinError (lRet);
658 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
659 "plibc_conv_to_win_path");
662 /* is the path relative? */
663 if ( (0 != strncmp (fn + 1, ":\\", 2)) &&
664 (0 != strncmp (fn, "\\\\", 2)) )
666 char szCurDir[MAX_PATH + 1];
668 lRet = GetCurrentDirectory (MAX_PATH + 1,
670 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
672 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
673 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
674 "GetCurrentDirectory");
677 GNUNET_asprintf (&buffer,
691 * Give relative time in human-readable fancy format.
692 * This is one of the very few calls in the entire API that is
695 * @param delta time in milli seconds
696 * @param do_round are we allowed to round a bit?
697 * @return time as human-readable string
700 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
703 static char buf[128];
704 const char *unit = _( /* time unit */ "µs");
705 uint64_t dval = delta.rel_value_us;
707 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
709 if (0 == delta.rel_value_us)
711 if ( ( (GNUNET_YES == do_round) &&
712 (dval > 5 * 1000) ) ||
713 (0 == (dval % 1000) ))
716 unit = _( /* time unit */ "ms");
717 if ( ( (GNUNET_YES == do_round) &&
718 (dval > 5 * 1000) ) ||
719 (0 == (dval % 1000) ))
722 unit = _( /* time unit */ "s");
723 if ( ( (GNUNET_YES == do_round) &&
725 (0 == (dval % 60) ) )
728 unit = _( /* time unit */ "m");
729 if ( ( (GNUNET_YES == do_round) &&
734 unit = _( /* time unit */ "h");
735 if ( ( (GNUNET_YES == do_round) &&
741 unit = _( /* time unit */ "day");
743 unit = _( /* time unit */ "days");
749 GNUNET_snprintf (buf, sizeof (buf),
750 "%llu %s", dval, unit);
756 * "asctime", except for GNUnet time. Converts a GNUnet internal
757 * absolute time (which is in UTC) to a string in local time.
758 * Note that the returned value will be overwritten if this function
761 * @param t the absolute time to convert
762 * @return timestamp in human-readable form in local time
765 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
767 static char buf[255];
771 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
772 return _("end of time");
773 tt = t.abs_value_us / 1000LL / 1000LL;
774 tp = localtime (&tt);
775 /* This is hacky, but i don't know a way to detect libc character encoding.
776 * Just expect utf8 from glibc these days.
777 * As for msvcrt, use the wide variant, which always returns utf16
778 * (otherwise we'd have to detect current codepage or use W32API character
779 * set conversion routines to convert to UTF8).
782 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
785 static wchar_t wbuf[255];
789 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
790 L"%a %b %d %H:%M:%S %Y", tp);
792 ssize = sizeof (buf);
793 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
794 (uint8_t *) buf, &ssize);
795 if (conved != (uint8_t *) buf)
797 strncpy (buf, (char *) conved, sizeof (buf));
809 * Returns a pointer to a part of filename (allocates nothing)!
811 * @param filename filename to extract basename from
812 * @return short (base) name of the file (that is, everything following the
813 * last directory separator in filename. If filename ends with a
814 * directory separator, the result will be a zero-length string.
815 * If filename has no directory separators, the result is filename
819 GNUNET_STRINGS_get_short_name (const char *filename)
821 const char *short_fn = filename;
824 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
832 * Get the decoded value corresponding to a character according to Crockford
835 * @param a a character
836 * @return corresponding numeric value
839 getValue__ (unsigned char a)
855 /* also consider U to be V */
863 if ((a >= '0') && (a <= '9'))
865 if ((a >= 'a') && (a <= 'z'))
867 /* return (a - 'a' + 10); */
869 if ((a >= 'A') && (a <= 'Z'))
879 return (a - 'A' + 10 - dec);
886 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
887 * Returns a pointer to the byte after the last byte in the string, that
888 * is where the 0-terminator was placed if there was room.
890 * @param data data to encode
891 * @param size size of data (in bytes)
892 * @param out buffer to fill
893 * @param out_size size of the buffer. Must be large enough to hold
894 * (size * 8 + 4) / 5 bytes
895 * @return pointer to the next byte in @a out or NULL on error.
898 GNUNET_STRINGS_data_to_string (const void *data,
904 * 32 characters for encoding
906 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
911 const unsigned char *udata;
914 if (out_size < (size * 8 + 4) / 5)
923 while ((rpos < size) || (vbit > 0))
925 if ((rpos < size) && (vbit < 5))
927 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
932 bits <<= (5 - vbit); /* zero-padding */
933 GNUNET_assert (vbit == ((size * 8) % 5));
936 if (wpos >= out_size)
941 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
944 GNUNET_assert (0 == vbit);
952 * Return the base32crockford encoding of the given buffer.
954 * The returned string will be freshly allocated, and must be free'd
955 * with GNUNET_free().
957 * @param buffer with data
958 * @param size size of the buffer
959 * @return freshly allocated, null-terminated string
962 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
966 size_t len = size * 8;
972 str_buf = GNUNET_malloc (len + 1);
973 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
976 GNUNET_free (str_buf);
985 * Convert Crockford Base32hex encoding back to data.
986 * @a out_size must match exactly the size of the data before it was encoded.
988 * @param enc the encoding
989 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
990 * @param out location where to store the decoded data
991 * @param out_size size of the output buffer @a out
992 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
995 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
996 void *out, size_t out_size)
1004 unsigned char *uout;
1005 unsigned int encoded_len = out_size * 8;
1011 return GNUNET_SYSERR;
1016 if ((encoded_len % 5) > 0)
1018 vbit = encoded_len % 5; /* padding! */
1020 bits = (ret = getValue__ (enc[--rpos])) >> shift;
1026 bits = (ret = getValue__ (enc[--rpos]));
1028 if ((encoded_len + shift) / 5 != enclen)
1029 return GNUNET_SYSERR;
1031 return GNUNET_SYSERR;
1037 return GNUNET_SYSERR;
1039 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1041 return GNUNET_SYSERR;
1045 uout[--wpos] = (unsigned char) bits;
1052 return GNUNET_SYSERR;
1058 * Parse a path that might be an URI.
1060 * @param path path to parse. Must be NULL-terminated.
1061 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1062 * represents the URI scheme will be stored. Can be NULL. The string is
1063 * allocated by the function, and should be freed by GNUNET_free() when
1064 * it is no longer needed.
1065 * @param path_part a pointer to 'const char *' where a pointer to the path
1066 * part of the URI will be stored. Can be NULL. Points to the same block
1067 * of memory as 'path', and thus must not be freed. Might point to '\0',
1068 * if path part is zero-length.
1069 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1070 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1071 * (if they weren't NULL).
1074 GNUNET_STRINGS_parse_uri (const char *path,
1076 const char **path_part)
1082 const char *post_scheme_part = NULL;
1083 len = strlen (path);
1084 for (end = 0, i = 0; !end && i < len; i++)
1089 if ( (path[i] == ':') && (i > 0) )
1094 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1095 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1096 || (path[i] == '.')))
1109 post_scheme_part = &path[i];
1116 if (post_scheme_part == NULL)
1120 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1121 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1122 (*scheme_part)[post_scheme_part - path] = '\0';
1125 *path_part = post_scheme_part;
1131 * Check whether @a filename is absolute or not, and if it's an URI
1133 * @param filename filename to check
1134 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1135 * assume it's not URI
1136 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1137 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1138 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1139 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1140 * The string is allocated by the function, and should be freed with
1141 * GNUNET_free(). Can be NULL.
1142 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1145 GNUNET_STRINGS_path_is_absolute (const char *filename,
1148 char **r_uri_scheme)
1153 const char *post_scheme_path;
1156 /* consider POSIX paths to be absolute too, even on W32,
1157 * as plibc expansion will fix them for us.
1159 if (filename[0] == '/')
1163 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1169 *r_uri_scheme = uri;
1171 GNUNET_free_non_null (uri);
1173 len = strlen(post_scheme_path);
1174 /* Special check for file:///c:/blah
1175 * We want to parse 'c:/', not '/c:/'
1177 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1178 post_scheme_path = &post_scheme_path[1];
1180 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1186 *r_is_uri = GNUNET_NO;
1189 len = strlen (filename);
1191 ((filename[0] >= 'A' && filename[0] <= 'Z')
1192 || (filename[0] >= 'a' && filename[0] <= 'z'))
1193 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1200 #define _IFMT 0170000 /* type of file */
1201 #define _IFLNK 0120000 /* symbolic link */
1202 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1207 * Perform @a checks on @a filename.
1209 * @param filename file to check
1210 * @param checks checks to perform
1211 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1212 * fails, #GNUNET_SYSERR when a check can't be performed
1215 GNUNET_STRINGS_check_filename (const char *filename,
1216 enum GNUNET_STRINGS_FilenameCheck checks)
1219 if ( (NULL == filename) || (filename[0] == '\0') )
1220 return GNUNET_SYSERR;
1221 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1222 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1224 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1225 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1226 | GNUNET_STRINGS_CHECK_IS_LINK)))
1228 if (0 != STAT (filename, &st))
1230 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1233 return GNUNET_SYSERR;
1236 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1237 if (!S_ISDIR (st.st_mode))
1239 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1240 if (!S_ISLNK (st.st_mode))
1247 * Tries to convert @a zt_addr string to an IPv6 address.
1248 * The string is expected to have the format "[ABCD::01]:80".
1250 * @param zt_addr 0-terminated string. May be mangled by the function.
1251 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1252 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1253 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1254 * @return #GNUNET_OK if conversion succeded.
1255 * #GNUNET_SYSERR otherwise, in which
1256 * case the contents of @a r_buf are undefined.
1259 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1261 struct sockaddr_in6 *r_buf)
1263 char zbuf[addrlen + 1];
1270 return GNUNET_SYSERR;
1271 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1274 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1275 _("IPv6 address did not start with `['\n"));
1276 return GNUNET_SYSERR;
1278 zbuf[addrlen] = '\0';
1279 port_colon = strrchr (zbuf, ':');
1280 if (NULL == port_colon)
1282 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1283 _("IPv6 address did contain ':' to separate port number\n"));
1284 return GNUNET_SYSERR;
1286 if (']' != *(port_colon - 1))
1288 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1289 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1290 return GNUNET_SYSERR;
1292 ret = SSCANF (port_colon,
1296 if ( (1 != ret) || (port > 65535) )
1298 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1299 _("IPv6 address did contain a valid port number after the last ':'\n"));
1300 return GNUNET_SYSERR;
1302 *(port_colon-1) = '\0';
1303 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1304 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1307 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1308 _("Invalid IPv6 address `%s': %s\n"),
1311 return GNUNET_SYSERR;
1313 r_buf->sin6_port = htons (port);
1314 r_buf->sin6_family = AF_INET6;
1315 #if HAVE_SOCKADDR_IN_SIN_LEN
1316 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1323 * Tries to convert 'zt_addr' string to an IPv4 address.
1324 * The string is expected to have the format "1.2.3.4:80".
1326 * @param zt_addr 0-terminated string. May be mangled by the function.
1327 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1328 * @param r_buf a buffer to fill.
1329 * @return #GNUNET_OK if conversion succeded.
1330 * #GNUNET_SYSERR otherwise, in which case
1331 * the contents of @a r_buf are undefined.
1334 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1336 struct sockaddr_in *r_buf)
1338 unsigned int temps[4];
1344 return GNUNET_SYSERR;
1345 cnt = SSCANF (zt_addr,
1346 "%u.%u.%u.%u:%u%1s",
1354 return GNUNET_SYSERR;
1355 for (cnt = 0; cnt < 4; cnt++)
1356 if (temps[cnt] > 0xFF)
1357 return GNUNET_SYSERR;
1359 return GNUNET_SYSERR;
1360 r_buf->sin_family = AF_INET;
1361 r_buf->sin_port = htons (port);
1362 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1363 (temps[2] << 8) + temps[3]);
1364 #if HAVE_SOCKADDR_IN_SIN_LEN
1365 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1372 * Tries to convert @a addr string to an IP (v4 or v6) address.
1373 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1375 * @param addr a string, may not be 0-terminated.
1376 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1377 * 0-terminator should not be counted towards addrlen).
1378 * @param r_buf a buffer to fill.
1379 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1380 * case the contents of @a r_buf are undefined.
1383 GNUNET_STRINGS_to_address_ip (const char *addr,
1385 struct sockaddr_storage *r_buf)
1388 return GNUNET_STRINGS_to_address_ipv6 (addr,
1390 (struct sockaddr_in6 *) r_buf);
1391 return GNUNET_STRINGS_to_address_ipv4 (addr,
1393 (struct sockaddr_in *) r_buf);
1398 * Parse an address given as a string into a
1399 * `struct sockaddr`.
1401 * @param addr the address
1402 * @param[out] af set to the parsed address family (i.e. AF_INET)
1403 * @param[out] sa set to the parsed address
1404 * @return 0 on error, otherwise number of bytes in @a sa
1407 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1409 struct sockaddr **sa)
1411 char *cp = GNUNET_strdup (addr);
1417 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1419 GNUNET_STRINGS_to_address_ipv6 (cp,
1421 (struct sockaddr_in6 *) *sa))
1430 return sizeof (struct sockaddr_in6);
1435 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1437 GNUNET_STRINGS_to_address_ipv4 (cp,
1439 (struct sockaddr_in *) *sa))
1448 return sizeof (struct sockaddr_in);
1454 * Makes a copy of argv that consists of a single memory chunk that can be
1455 * freed with a single call to GNUNET_free();
1457 static char *const *
1458 _make_continuous_arg_copy (int argc,
1461 size_t argvsize = 0;
1465 for (i = 0; i < argc; i++)
1466 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1467 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1468 p = (char *) &new_argv[argc + 1];
1469 for (i = 0; i < argc; i++)
1472 strcpy (p, argv[i]);
1473 p += strlen (argv[i]) + 1;
1475 new_argv[argc] = NULL;
1476 return (char *const *) new_argv;
1481 * Returns utf-8 encoded arguments.
1482 * Does nothing (returns a copy of argc and argv) on any platform
1484 * Returned argv has u8argv[u8argc] == NULL.
1485 * Returned argv is a single memory block, and can be freed with a single
1486 * GNUNET_free() call.
1488 * @param argc argc (as given by main())
1489 * @param argv argv (as given by main())
1490 * @param u8argc a location to store new argc in (though it's th same as argc)
1491 * @param u8argv a location to store new argv in
1492 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1495 GNUNET_STRINGS_get_utf8_args (int argc,
1498 char *const **u8argv)
1505 char **split_u8argv;
1507 wcmd = GetCommandLineW ();
1509 return GNUNET_SYSERR;
1510 wargv = CommandLineToArgvW (wcmd, &wargc);
1512 return GNUNET_SYSERR;
1514 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1516 for (i = 0; i < wargc; i++)
1519 /* Hopefully it will allocate us NUL-terminated strings... */
1520 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1521 if (NULL == split_u8argv[i])
1524 for (j = 0; j < i; j++)
1525 free (split_u8argv[j]);
1526 GNUNET_free (split_u8argv);
1528 return GNUNET_SYSERR;
1532 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1535 for (i = 0; i < wargc; i++)
1536 free (split_u8argv[i]);
1537 free (split_u8argv);
1540 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1549 * Parse the given port policy. The format is
1550 * "[!]SPORT[-DPORT]".
1552 * @param port_policy string to parse
1553 * @param pp policy to fill in
1554 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1555 * @a port_policy is malformed
1558 parse_port_policy (const char *port_policy,
1559 struct GNUNET_STRINGS_PortPolicy *pp)
1569 pp->negate_portrange = GNUNET_YES;
1572 if (2 == sscanf (pos,
1583 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1584 _("Port not in range\n"));
1585 return GNUNET_SYSERR;
1587 pp->start_port = (uint16_t) s;
1588 pp->end_port = (uint16_t) e;
1591 if (1 == sscanf (pos,
1599 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1600 _("Port not in range\n"));
1601 return GNUNET_SYSERR;
1604 pp->start_port = (uint16_t) s;
1605 pp->end_port = (uint16_t) s;
1608 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1609 _("Malformed port policy `%s'\n"),
1611 return GNUNET_SYSERR;
1616 * Parse an IPv4 network policy. The argument specifies a list of
1617 * subnets. The format is
1618 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1619 * be terminated with a semicolon). The network must be given in
1620 * dotted-decimal notation. The netmask can be given in CIDR notation
1621 * (/16) or in dotted-decimal (/255.255.0.0).
1623 * @param routeListX a string specifying the IPv4 subnets
1624 * @return the converted list, terminated with all zeros;
1625 * NULL if the synatx is flawed
1627 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1628 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1636 unsigned int temps[8];
1638 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1644 if (NULL == routeListX)
1646 len = strlen (routeListX);
1649 routeList = GNUNET_strdup (routeListX);
1651 for (i = 0; i < len; i++)
1652 if (routeList[i] == ';')
1654 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1659 for (colon = pos; ':' != routeList[colon]; colon++)
1660 if ( (';' == routeList[colon]) ||
1661 ('\0' == routeList[colon]) )
1663 for (end = colon; ';' != routeList[end]; end++)
1664 if ('\0' == routeList[end])
1666 if ('\0' == routeList[end])
1668 routeList[end] = '\0';
1669 if (':' == routeList[colon])
1671 routeList[colon] = '\0';
1672 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1677 SSCANF (&routeList[pos],
1678 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1690 for (j = 0; j < 8; j++)
1691 if (temps[j] > 0xFF)
1693 LOG (GNUNET_ERROR_TYPE_WARNING,
1694 _("Invalid format for IP: `%s'\n"),
1696 GNUNET_free (result);
1697 GNUNET_free (routeList);
1700 result[i].network.s_addr =
1701 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1703 result[i].netmask.s_addr =
1704 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1710 /* try second notation */
1712 SSCANF (&routeList[pos],
1713 "%u.%u.%u.%u/%u%1s",
1722 for (j = 0; j < 4; j++)
1723 if (temps[j] > 0xFF)
1725 LOG (GNUNET_ERROR_TYPE_WARNING,
1726 _("Invalid format for IP: `%s'\n"),
1728 GNUNET_free (result);
1729 GNUNET_free (routeList);
1732 result[i].network.s_addr =
1733 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1735 if ((slash <= 32) && (slash >= 0))
1737 result[i].netmask.s_addr = 0;
1740 result[i].netmask.s_addr =
1741 (result[i].netmask.s_addr >> 1) + 0x80000000;
1744 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1751 LOG (GNUNET_ERROR_TYPE_WARNING,
1752 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1754 GNUNET_free (result);
1755 GNUNET_free (routeList);
1756 return NULL; /* error */
1759 /* try third notation */
1762 SSCANF (&routeList[pos],
1771 for (j = 0; j < 4; j++)
1772 if (temps[j] > 0xFF)
1774 LOG (GNUNET_ERROR_TYPE_WARNING,
1775 _("Invalid format for IP: `%s'\n"),
1777 GNUNET_free (result);
1778 GNUNET_free (routeList);
1781 result[i].network.s_addr =
1782 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1784 result[i].netmask.s_addr = 0;
1787 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1790 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1795 LOG (GNUNET_ERROR_TYPE_WARNING,
1796 _("Invalid format for IP: `%s'\n"),
1798 GNUNET_free (result);
1799 GNUNET_free (routeList);
1800 return NULL; /* error */
1802 if (pos < strlen (routeList))
1804 LOG (GNUNET_ERROR_TYPE_WARNING,
1805 _("Invalid format: `%s'\n"),
1807 GNUNET_free (result);
1808 GNUNET_free (routeList);
1809 return NULL; /* oops */
1811 GNUNET_free (routeList);
1812 return result; /* ok */
1817 * Parse an IPv6 network policy. The argument specifies a list of
1818 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1819 * (no whitespace, must be terminated with a semicolon). The network
1820 * must be given in colon-hex notation. The netmask must be given in
1821 * CIDR notation (/16) or can be omitted to specify a single host.
1822 * Note that the netmask is mandatory if ports are specified.
1824 * @param routeListX a string specifying the policy
1825 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1827 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1828 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1838 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1845 if (NULL == routeListX)
1847 len = strlen (routeListX);
1850 routeList = GNUNET_strdup (routeListX);
1852 for (i = 0; i < len; i++)
1853 if (';' == routeList[i])
1855 if (';' != routeList[len - 1])
1857 LOG (GNUNET_ERROR_TYPE_WARNING,
1858 _("Invalid network notation (does not end with ';': `%s')\n"),
1860 GNUNET_free (routeList);
1864 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1870 while (';' != routeList[pos])
1873 while ((slash >= start) && (routeList[slash] != '/'))
1878 memset (&result[i].netmask,
1880 sizeof (struct in6_addr));
1885 routeList[pos] = '\0';
1886 for (colon = pos; ':' != routeList[colon]; colon--)
1887 if ('/' == routeList[colon])
1889 if (':' == routeList[colon])
1891 routeList[colon] = '\0';
1892 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1895 GNUNET_free (result);
1896 GNUNET_free (routeList);
1900 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1904 if ( (1 != SSCANF (&routeList[slash + 1],
1911 LOG (GNUNET_ERROR_TYPE_WARNING,
1912 _("Wrong format `%s' for netmask\n"),
1913 &routeList[slash + 1]);
1917 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1919 GNUNET_free (result);
1920 GNUNET_free (routeList);
1926 result[i].netmask.s6_addr[off++] = 0xFF;
1931 result[i].netmask.s6_addr[off] =
1932 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1937 routeList[slash] = '\0';
1938 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1942 LOG (GNUNET_ERROR_TYPE_WARNING,
1943 _("Wrong format `%s' for network\n"),
1944 &routeList[slash + 1]);
1946 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1948 GNUNET_free (result);
1949 GNUNET_free (routeList);
1955 GNUNET_free (routeList);
1961 /** ******************** Base64 encoding ***********/
1963 #define FILLCHAR '='
1965 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1969 * Encode into Base64.
1971 * @param in the data to encode
1972 * @param len the length of the input
1973 * @param output where to write the output (*output should be NULL,
1975 * @return the size of the output
1978 GNUNET_STRINGS_base64_encode (const void *in,
1982 const char *data = in;
1987 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1988 for (size_t i = 0; i < len; ++i)
1992 c = (data[i] >> 2) & 0x3f;
1993 opt[ret++] = cvt[(int) c];
1994 c = (data[i] << 4) & 0x3f;
1996 c |= (data[i] >> 4) & 0x0f;
1997 opt[ret++] = cvt[(int) c];
2000 c = (data[i] << 2) & 0x3f;
2002 c |= (data[i] >> 6) & 0x03;
2003 opt[ret++] = cvt[(int) c];
2008 opt[ret++] = FILLCHAR;
2013 opt[ret++] = cvt[(int) c];
2017 opt[ret++] = FILLCHAR;
2024 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
2025 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
2026 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
2028 :((a) == '/') ? 63 : -1)
2032 * Decode from Base64.
2034 * @param data the data to encode
2035 * @param len the length of the input
2036 * @param output where to write the output (*output should be NULL,
2038 * @return the size of the output
2041 GNUNET_STRINGS_base64_decode (const char *data,
2048 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
2049 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
2051 if (i >= len) goto END; \
2054 output = GNUNET_malloc ((len * 3 / 4) + 8);
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "base64_decode decoding len=%d\n",
2058 for (size_t i = 0; i < len; ++i)
2064 if (FILLCHAR == data[i])
2066 c = (char) cvtfind (data[i]);
2069 c1 = (char) cvtfind (data[i]);
2070 c = (c << 2) | ((c1 >> 4) & 0x3);
2078 c = (char) cvtfind (c);
2079 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2089 c1 = (char) cvtfind (c1);
2090 c = ((c << 6) & 0xc0) | c1;
2100 /* end of strings.c */