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
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
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 { "\"", 1000 * 1000LL },
337 { "m", 60 * 1000 * 1000LL},
338 { "min", 60 * 1000 * 1000LL},
339 { "minute", 60 * 1000 * 1000LL},
340 { "minutes", 60 * 1000 * 1000LL},
341 { "'", 60 * 1000 * 1000LL},
342 { "h", 60 * 60 * 1000 * 1000LL},
343 { "hour", 60 * 60 * 1000 * 1000LL},
344 { "hours", 60 * 60 * 1000 * 1000LL},
345 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
346 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
347 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
348 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
349 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
350 { "year", 31536000000000LL /* year */ },
351 { "years", 31536000000000LL /* year */ },
352 { "a", 31536000000000LL /* year */ },
356 unsigned long long val;
358 if (0 == strcasecmp ("forever", fancy_time))
360 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
363 ret = convert_with_table (fancy_time,
366 rtime->rel_value_us = (uint64_t) val;
372 * Convert a given fancy human-readable time to our internal
373 * representation. The human-readable time is expected to be
374 * in local time, whereas the returned value will be in UTC.
376 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
377 * @param atime set to the absolute time
378 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
381 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
382 struct GNUNET_TIME_Absolute *atime)
387 if (0 == strcasecmp ("end of time",
390 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
393 memset (&tv, 0, sizeof (tv));
394 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
395 (NULL == strptime (fancy_time, "%c", &tv)) &&
396 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
397 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
398 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
399 (NULL == strptime (fancy_time, "%x", &tv)) &&
400 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
401 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
402 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
403 (NULL == strptime (fancy_time, "%Y", &tv)) )
404 return GNUNET_SYSERR;
406 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
412 * Convert the len characters long character sequence
413 * given in input that is in the given input charset
414 * to a string in given output charset.
416 * @param input input string
417 * @param len number of bytes in @a input
418 * @param input_charset character set used for @a input
419 * @param output_charset desired character set for the return value
420 * @return the converted string (0-terminated),
421 * if conversion fails, a copy of the orignal
422 * string is returned.
425 GNUNET_STRINGS_conv (const char *input,
427 const char *input_charset,
428 const char *output_charset)
432 char *encoded_string;
433 size_t u8_string_length;
434 size_t encoded_string_length;
436 u8_string = u8_conv_from_encoding (input_charset,
441 if (NULL == u8_string)
443 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
446 if (0 == strcmp (output_charset, "UTF-8"))
448 ret = GNUNET_malloc (u8_string_length + 1);
449 GNUNET_memcpy (ret, u8_string, u8_string_length);
450 ret[u8_string_length] = '\0';
454 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
455 u8_string, u8_string_length,
457 &encoded_string_length);
459 if (NULL == encoded_string)
461 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
464 ret = GNUNET_malloc (encoded_string_length + 1);
465 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
466 ret[encoded_string_length] = '\0';
467 free (encoded_string);
470 LOG (GNUNET_ERROR_TYPE_WARNING,
471 _("Character sets requested were `%s'->`%s'\n"),
472 "UTF-8", output_charset);
473 ret = GNUNET_malloc (len + 1);
474 GNUNET_memcpy (ret, input, len);
481 * Convert the len characters long character sequence
482 * given in input that is in the given charset
485 * @param input the input string (not necessarily 0-terminated)
486 * @param len the number of bytes in the @a input
487 * @param charset character set to convert from
488 * @return the converted string (0-terminated),
489 * if conversion fails, a copy of the orignal
490 * string is returned.
493 GNUNET_STRINGS_to_utf8 (const char *input,
497 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
502 * Convert the len bytes-long UTF-8 string
503 * given in input to the given charset.
505 * @param input the input string (not necessarily 0-terminated)
506 * @param len the number of bytes in the @a input
507 * @param charset character set to convert to
508 * @return the converted string (0-terminated),
509 * if conversion fails, a copy of the orignal
510 * string is returned.
513 GNUNET_STRINGS_from_utf8 (const char *input,
517 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
522 * Convert the utf-8 input string to lowercase.
523 * Output needs to be allocated appropriately.
525 * @param input input string
526 * @param output output buffer
529 GNUNET_STRINGS_utf8_tolower (const char *input,
535 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
536 NULL, UNINORM_NFD, NULL, &len);
537 GNUNET_memcpy(output, tmp_in, len);
544 * Convert the utf-8 input string to uppercase.
545 * Output needs to be allocated appropriately.
547 * @param input input string
548 * @param output output buffer
551 GNUNET_STRINGS_utf8_toupper(const char *input,
557 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
558 NULL, UNINORM_NFD, NULL, &len);
559 GNUNET_memcpy (output, tmp_in, len);
566 * Complete filename (a la shell) from abbrevition.
567 * @param fil the name of the file, may contain ~/ or
568 * be relative to the current directory
569 * @returns the full file name,
570 * NULL is returned on error
573 GNUNET_STRINGS_filename_expand (const char *fil)
589 if (fil[0] == DIR_SEPARATOR)
590 /* absolute path, just copy */
591 return GNUNET_strdup (fil);
594 fm = getenv ("HOME");
597 LOG (GNUNET_ERROR_TYPE_WARNING,
598 _("Failed to expand `$HOME': environment variable `HOME' not set"));
601 fm = GNUNET_strdup (fm);
602 /* do not copy '~' */
605 /* skip over dir seperator to be consistent */
606 if (fil_ptr[0] == DIR_SEPARATOR)
617 buffer = GNUNET_malloc (len);
618 if (getcwd (buffer, len) != NULL)
623 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
626 GNUNET_free (buffer);
629 GNUNET_free (buffer);
634 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
636 buffer = getenv ("PWD"); /* alternative */
638 fm = GNUNET_strdup (buffer);
641 fm = GNUNET_strdup ("./"); /* give up */
643 GNUNET_asprintf (&buffer,
646 (fm[strlen (fm) - 1] ==
647 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
651 fn = GNUNET_malloc (MAX_PATH + 1);
653 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
655 SetErrnoFromWinError (lRet);
656 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
657 "plibc_conv_to_win_path");
660 /* is the path relative? */
661 if ( (0 != strncmp (fn + 1, ":\\", 2)) &&
662 (0 != strncmp (fn, "\\\\", 2)) )
664 char szCurDir[MAX_PATH + 1];
666 lRet = GetCurrentDirectory (MAX_PATH + 1,
668 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
670 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
671 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
672 "GetCurrentDirectory");
675 GNUNET_asprintf (&buffer,
689 * Give relative time in human-readable fancy format.
690 * This is one of the very few calls in the entire API that is
693 * @param delta time in milli seconds
694 * @param do_round are we allowed to round a bit?
695 * @return time as human-readable string
698 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
701 static char buf[128];
702 const char *unit = _( /* time unit */ "µs");
703 uint64_t dval = delta.rel_value_us;
705 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
707 if (0 == delta.rel_value_us)
709 if ( ( (GNUNET_YES == do_round) &&
710 (dval > 5 * 1000) ) ||
711 (0 == (dval % 1000) ))
714 unit = _( /* time unit */ "ms");
715 if ( ( (GNUNET_YES == do_round) &&
716 (dval > 5 * 1000) ) ||
717 (0 == (dval % 1000) ))
720 unit = _( /* time unit */ "s");
721 if ( ( (GNUNET_YES == do_round) &&
723 (0 == (dval % 60) ) )
726 unit = _( /* time unit */ "m");
727 if ( ( (GNUNET_YES == do_round) &&
732 unit = _( /* time unit */ "h");
733 if ( ( (GNUNET_YES == do_round) &&
739 unit = _( /* time unit */ "day");
741 unit = _( /* time unit */ "days");
747 GNUNET_snprintf (buf, sizeof (buf),
748 "%llu %s", dval, unit);
754 * "asctime", except for GNUnet time. Converts a GNUnet internal
755 * absolute time (which is in UTC) to a string in local time.
756 * Note that the returned value will be overwritten if this function
759 * @param t the absolute time to convert
760 * @return timestamp in human-readable form in local time
763 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
765 static char buf[255];
769 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
770 return _("end of time");
771 tt = t.abs_value_us / 1000LL / 1000LL;
772 tp = localtime (&tt);
773 /* This is hacky, but i don't know a way to detect libc character encoding.
774 * Just expect utf8 from glibc these days.
775 * As for msvcrt, use the wide variant, which always returns utf16
776 * (otherwise we'd have to detect current codepage or use W32API character
777 * set conversion routines to convert to UTF8).
780 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
783 static wchar_t wbuf[255];
787 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
788 L"%a %b %d %H:%M:%S %Y", tp);
790 ssize = sizeof (buf);
791 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
792 (uint8_t *) buf, &ssize);
793 if (conved != (uint8_t *) buf)
795 strncpy (buf, (char *) conved, sizeof (buf));
807 * Returns a pointer to a part of filename (allocates nothing)!
809 * @param filename filename to extract basename from
810 * @return short (base) name of the file (that is, everything following the
811 * last directory separator in filename. If filename ends with a
812 * directory separator, the result will be a zero-length string.
813 * If filename has no directory separators, the result is filename
817 GNUNET_STRINGS_get_short_name (const char *filename)
819 const char *short_fn = filename;
821 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
829 * Get the decoded value corresponding to a character according to Crockford
832 * @param a a character
833 * @return corresponding numeric value
836 getValue__ (unsigned char a)
852 /* also consider U to be V */
860 if ((a >= '0') && (a <= '9'))
862 if ((a >= 'a') && (a <= 'z'))
864 /* return (a - 'a' + 10); */
866 if ((a >= 'A') && (a <= 'Z'))
876 return (a - 'A' + 10 - dec);
883 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
884 * Returns a pointer to the byte after the last byte in the string, that
885 * is where the 0-terminator was placed if there was room.
887 * @param data data to encode
888 * @param size size of data (in bytes)
889 * @param out buffer to fill
890 * @param out_size size of the buffer. Must be large enough to hold
891 * (size * 8 + 4) / 5 bytes
892 * @return pointer to the next byte in @a out or NULL on error.
895 GNUNET_STRINGS_data_to_string (const void *data,
901 * 32 characters for encoding
903 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
908 const unsigned char *udata;
911 if (out_size < (size * 8 + 4) / 5)
920 while ((rpos < size) || (vbit > 0))
922 if ((rpos < size) && (vbit < 5))
924 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
929 bits <<= (5 - vbit); /* zero-padding */
930 GNUNET_assert (vbit == ((size * 8) % 5));
933 if (wpos >= out_size)
938 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
941 GNUNET_assert (0 == vbit);
949 * Return the base32crockford encoding of the given buffer.
951 * The returned string will be freshly allocated, and must be free'd
952 * with GNUNET_free().
954 * @param buffer with data
955 * @param size size of the buffer
956 * @return freshly allocated, null-terminated string
959 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
963 size_t len = size * 8;
969 str_buf = GNUNET_malloc (len + 1);
970 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
973 GNUNET_free (str_buf);
982 * Convert Crockford Base32hex encoding back to data.
983 * @a out_size must match exactly the size of the data before it was encoded.
985 * @param enc the encoding
986 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
987 * @param out location where to store the decoded data
988 * @param out_size size of the output buffer @a out
989 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
992 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
993 void *out, size_t out_size)
1001 unsigned char *uout;
1002 unsigned int encoded_len = out_size * 8;
1008 return GNUNET_SYSERR;
1013 if ((encoded_len % 5) > 0)
1015 vbit = encoded_len % 5; /* padding! */
1017 bits = (ret = getValue__ (enc[--rpos])) >> shift;
1023 bits = (ret = getValue__ (enc[--rpos]));
1025 if ((encoded_len + shift) / 5 != enclen)
1026 return GNUNET_SYSERR;
1028 return GNUNET_SYSERR;
1034 return GNUNET_SYSERR;
1036 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1038 return GNUNET_SYSERR;
1042 uout[--wpos] = (unsigned char) bits;
1049 return GNUNET_SYSERR;
1055 * Parse a path that might be an URI.
1057 * @param path path to parse. Must be NULL-terminated.
1058 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1059 * represents the URI scheme will be stored. Can be NULL. The string is
1060 * allocated by the function, and should be freed by GNUNET_free() when
1061 * it is no longer needed.
1062 * @param path_part a pointer to 'const char *' where a pointer to the path
1063 * part of the URI will be stored. Can be NULL. Points to the same block
1064 * of memory as 'path', and thus must not be freed. Might point to '\0',
1065 * if path part is zero-length.
1066 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1067 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1068 * (if they weren't NULL).
1071 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
1072 const char **path_part)
1077 const char *post_scheme_part = NULL;
1078 len = strlen (path);
1079 for (end = 0, i = 0; !end && i < len; i++)
1084 if (path[i] == ':' && i > 0)
1089 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1090 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1091 || (path[i] == '.')))
1104 post_scheme_part = &path[i];
1111 if (post_scheme_part == NULL)
1115 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1116 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1117 (*scheme_part)[post_scheme_part - path] = '\0';
1120 *path_part = post_scheme_part;
1126 * Check whether @a filename is absolute or not, and if it's an URI
1128 * @param filename filename to check
1129 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1130 * assume it's not URI
1131 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1132 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1133 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1134 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1135 * The string is allocated by the function, and should be freed with
1136 * GNUNET_free(). Can be NULL.
1137 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1140 GNUNET_STRINGS_path_is_absolute (const char *filename,
1143 char **r_uri_scheme)
1148 const char *post_scheme_path;
1151 /* consider POSIX paths to be absolute too, even on W32,
1152 * as plibc expansion will fix them for us.
1154 if (filename[0] == '/')
1158 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1164 *r_uri_scheme = uri;
1166 GNUNET_free_non_null (uri);
1168 len = strlen(post_scheme_path);
1169 /* Special check for file:///c:/blah
1170 * We want to parse 'c:/', not '/c:/'
1172 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1173 post_scheme_path = &post_scheme_path[1];
1175 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1181 *r_is_uri = GNUNET_NO;
1184 len = strlen (filename);
1186 ((filename[0] >= 'A' && filename[0] <= 'Z')
1187 || (filename[0] >= 'a' && filename[0] <= 'z'))
1188 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1195 #define _IFMT 0170000 /* type of file */
1196 #define _IFLNK 0120000 /* symbolic link */
1197 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1202 * Perform @a checks on @a filename.
1204 * @param filename file to check
1205 * @param checks checks to perform
1206 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1207 * fails, #GNUNET_SYSERR when a check can't be performed
1210 GNUNET_STRINGS_check_filename (const char *filename,
1211 enum GNUNET_STRINGS_FilenameCheck checks)
1214 if ( (NULL == filename) || (filename[0] == '\0') )
1215 return GNUNET_SYSERR;
1216 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1217 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1219 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1220 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1221 | GNUNET_STRINGS_CHECK_IS_LINK)))
1223 if (0 != STAT (filename, &st))
1225 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1228 return GNUNET_SYSERR;
1231 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1232 if (!S_ISDIR (st.st_mode))
1234 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1235 if (!S_ISLNK (st.st_mode))
1242 * Tries to convert @a zt_addr string to an IPv6 address.
1243 * The string is expected to have the format "[ABCD::01]:80".
1245 * @param zt_addr 0-terminated string. May be mangled by the function.
1246 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1247 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1248 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1249 * @return #GNUNET_OK if conversion succeded.
1250 * #GNUNET_SYSERR otherwise, in which
1251 * case the contents of @a r_buf are undefined.
1254 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1256 struct sockaddr_in6 *r_buf)
1258 char zbuf[addrlen + 1];
1264 return GNUNET_SYSERR;
1265 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1268 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1269 _("IPv6 address did not start with `['\n"));
1270 return GNUNET_SYSERR;
1272 zbuf[addrlen] = '\0';
1273 port_colon = strrchr (zbuf, ':');
1274 if (NULL == port_colon)
1276 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1277 _("IPv6 address did contain ':' to separate port number\n"));
1278 return GNUNET_SYSERR;
1280 if (']' != *(port_colon - 1))
1282 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1283 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1284 return GNUNET_SYSERR;
1286 ret = SSCANF (port_colon, ":%u", &port);
1287 if ( (1 != ret) || (port > 65535) )
1289 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1290 _("IPv6 address did contain a valid port number after the last ':'\n"));
1291 return GNUNET_SYSERR;
1293 *(port_colon-1) = '\0';
1294 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1295 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1298 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1299 _("Invalid IPv6 address `%s': %s\n"),
1302 return GNUNET_SYSERR;
1304 r_buf->sin6_port = htons (port);
1305 r_buf->sin6_family = AF_INET6;
1306 #if HAVE_SOCKADDR_IN_SIN_LEN
1307 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1314 * Tries to convert 'zt_addr' string to an IPv4 address.
1315 * The string is expected to have the format "1.2.3.4:80".
1317 * @param zt_addr 0-terminated string. May be mangled by the function.
1318 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1319 * @param r_buf a buffer to fill.
1320 * @return #GNUNET_OK if conversion succeded.
1321 * #GNUNET_SYSERR otherwise, in which case
1322 * the contents of @a r_buf are undefined.
1325 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1327 struct sockaddr_in *r_buf)
1329 unsigned int temps[4];
1334 return GNUNET_SYSERR;
1335 cnt = SSCANF (zt_addr,
1343 return GNUNET_SYSERR;
1344 for (cnt = 0; cnt < 4; cnt++)
1345 if (temps[cnt] > 0xFF)
1346 return GNUNET_SYSERR;
1348 return GNUNET_SYSERR;
1349 r_buf->sin_family = AF_INET;
1350 r_buf->sin_port = htons (port);
1351 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1352 (temps[2] << 8) + temps[3]);
1353 #if HAVE_SOCKADDR_IN_SIN_LEN
1354 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1361 * Tries to convert @a addr string to an IP (v4 or v6) address.
1362 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1364 * @param addr a string, may not be 0-terminated.
1365 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1366 * 0-terminator should not be counted towards addrlen).
1367 * @param r_buf a buffer to fill.
1368 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1369 * case the contents of @a r_buf are undefined.
1372 GNUNET_STRINGS_to_address_ip (const char *addr,
1374 struct sockaddr_storage *r_buf)
1377 return GNUNET_STRINGS_to_address_ipv6 (addr,
1379 (struct sockaddr_in6 *) r_buf);
1380 return GNUNET_STRINGS_to_address_ipv4 (addr,
1382 (struct sockaddr_in *) r_buf);
1387 * Parse an address given as a string into a
1388 * `struct sockaddr`.
1390 * @param addr the address
1391 * @param[out] af set to the parsed address family (i.e. AF_INET)
1392 * @param[out] sa set to the parsed address
1393 * @return 0 on error, otherwise number of bytes in @a sa
1396 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1398 struct sockaddr **sa)
1400 char *cp = GNUNET_strdup (addr);
1406 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1408 GNUNET_STRINGS_to_address_ipv6 (cp,
1410 (struct sockaddr_in6 *) *sa))
1419 return sizeof (struct sockaddr_in6);
1424 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1426 GNUNET_STRINGS_to_address_ipv4 (cp,
1428 (struct sockaddr_in *) *sa))
1437 return sizeof (struct sockaddr_in);
1443 * Makes a copy of argv that consists of a single memory chunk that can be
1444 * freed with a single call to GNUNET_free();
1446 static char *const *
1447 _make_continuous_arg_copy (int argc,
1450 size_t argvsize = 0;
1454 for (i = 0; i < argc; i++)
1455 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1456 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1457 p = (char *) &new_argv[argc + 1];
1458 for (i = 0; i < argc; i++)
1461 strcpy (p, argv[i]);
1462 p += strlen (argv[i]) + 1;
1464 new_argv[argc] = NULL;
1465 return (char *const *) new_argv;
1470 * Returns utf-8 encoded arguments.
1471 * Does nothing (returns a copy of argc and argv) on any platform
1473 * Returned argv has u8argv[u8argc] == NULL.
1474 * Returned argv is a single memory block, and can be freed with a single
1475 * GNUNET_free() call.
1477 * @param argc argc (as given by main())
1478 * @param argv argv (as given by main())
1479 * @param u8argc a location to store new argc in (though it's th same as argc)
1480 * @param u8argv a location to store new argv in
1481 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1484 GNUNET_STRINGS_get_utf8_args (int argc,
1487 char *const **u8argv)
1494 char **split_u8argv;
1496 wcmd = GetCommandLineW ();
1498 return GNUNET_SYSERR;
1499 wargv = CommandLineToArgvW (wcmd, &wargc);
1501 return GNUNET_SYSERR;
1503 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1505 for (i = 0; i < wargc; i++)
1508 /* Hopefully it will allocate us NUL-terminated strings... */
1509 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1510 if (NULL == split_u8argv[i])
1513 for (j = 0; j < i; j++)
1514 free (split_u8argv[j]);
1515 GNUNET_free (split_u8argv);
1517 return GNUNET_SYSERR;
1521 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1524 for (i = 0; i < wargc; i++)
1525 free (split_u8argv[i]);
1526 free (split_u8argv);
1529 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1538 * Parse the given port policy. The format is
1539 * "[!]SPORT[-DPORT]".
1541 * @param port_policy string to parse
1542 * @param pp policy to fill in
1543 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1544 * @a port_policy is malformed
1547 parse_port_policy (const char *port_policy,
1548 struct GNUNET_STRINGS_PortPolicy *pp)
1558 pp->negate_portrange = GNUNET_YES;
1561 if (2 == sscanf (pos,
1570 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1571 _("Port not in range\n"));
1572 return GNUNET_SYSERR;
1574 pp->start_port = (uint16_t) s;
1575 pp->end_port = (uint16_t) e;
1578 if (1 == sscanf (pos,
1586 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1587 _("Port not in range\n"));
1588 return GNUNET_SYSERR;
1591 pp->start_port = (uint16_t) s;
1592 pp->end_port = (uint16_t) s;
1595 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1596 _("Malformed port policy `%s'\n"),
1598 return GNUNET_SYSERR;
1603 * Parse an IPv4 network policy. The argument specifies a list of
1604 * subnets. The format is
1605 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1606 * be terminated with a semicolon). The network must be given in
1607 * dotted-decimal notation. The netmask can be given in CIDR notation
1608 * (/16) or in dotted-decimal (/255.255.0.0).
1610 * @param routeListX a string specifying the IPv4 subnets
1611 * @return the converted list, terminated with all zeros;
1612 * NULL if the synatx is flawed
1614 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1615 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1623 unsigned int temps[8];
1625 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1630 if (NULL == routeListX)
1632 len = strlen (routeListX);
1635 routeList = GNUNET_strdup (routeListX);
1637 for (i = 0; i < len; i++)
1638 if (routeList[i] == ';')
1640 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1645 for (colon = pos; ':' != routeList[colon]; colon++)
1646 if ( (';' == routeList[colon]) ||
1647 ('\0' == routeList[colon]) )
1649 for (end = colon; ';' != routeList[end]; end++)
1650 if ('\0' == routeList[end])
1652 if ('\0' == routeList[end])
1654 routeList[end] = '\0';
1655 if (':' == routeList[colon])
1657 routeList[colon] = '\0';
1658 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1663 SSCANF (&routeList[pos],
1664 "%u.%u.%u.%u/%u.%u.%u.%u",
1675 for (j = 0; j < 8; j++)
1676 if (temps[j] > 0xFF)
1678 LOG (GNUNET_ERROR_TYPE_WARNING,
1679 _("Invalid format for IP: `%s'\n"),
1681 GNUNET_free (result);
1682 GNUNET_free (routeList);
1685 result[i].network.s_addr =
1686 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1688 result[i].netmask.s_addr =
1689 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1695 /* try second notation */
1697 SSCANF (&routeList[pos],
1706 for (j = 0; j < 4; j++)
1707 if (temps[j] > 0xFF)
1709 LOG (GNUNET_ERROR_TYPE_WARNING,
1710 _("Invalid format for IP: `%s'\n"),
1712 GNUNET_free (result);
1713 GNUNET_free (routeList);
1716 result[i].network.s_addr =
1717 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1719 if ((slash <= 32) && (slash >= 0))
1721 result[i].netmask.s_addr = 0;
1724 result[i].netmask.s_addr =
1725 (result[i].netmask.s_addr >> 1) + 0x80000000;
1728 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1735 LOG (GNUNET_ERROR_TYPE_WARNING,
1736 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1738 GNUNET_free (result);
1739 GNUNET_free (routeList);
1740 return NULL; /* error */
1743 /* try third notation */
1746 SSCANF (&routeList[pos],
1754 for (j = 0; j < 4; j++)
1755 if (temps[j] > 0xFF)
1757 LOG (GNUNET_ERROR_TYPE_WARNING,
1758 _("Invalid format for IP: `%s'\n"),
1760 GNUNET_free (result);
1761 GNUNET_free (routeList);
1764 result[i].network.s_addr =
1765 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1767 result[i].netmask.s_addr = 0;
1770 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1773 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1778 LOG (GNUNET_ERROR_TYPE_WARNING,
1779 _("Invalid format for IP: `%s'\n"),
1781 GNUNET_free (result);
1782 GNUNET_free (routeList);
1783 return NULL; /* error */
1785 if (pos < strlen (routeList))
1787 LOG (GNUNET_ERROR_TYPE_WARNING,
1788 _("Invalid format: `%s'\n"),
1790 GNUNET_free (result);
1791 GNUNET_free (routeList);
1792 return NULL; /* oops */
1794 GNUNET_free (routeList);
1795 return result; /* ok */
1800 * Parse an IPv6 network policy. The argument specifies a list of
1801 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1802 * (no whitespace, must be terminated with a semicolon). The network
1803 * must be given in colon-hex notation. The netmask must be given in
1804 * CIDR notation (/16) or can be omitted to specify a single host.
1805 * Note that the netmask is mandatory if ports are specified.
1807 * @param routeListX a string specifying the policy
1808 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1810 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1811 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1821 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1827 if (NULL == routeListX)
1829 len = strlen (routeListX);
1832 routeList = GNUNET_strdup (routeListX);
1834 for (i = 0; i < len; i++)
1835 if (';' == routeList[i])
1837 if (';' != routeList[len - 1])
1839 LOG (GNUNET_ERROR_TYPE_WARNING,
1840 _("Invalid network notation (does not end with ';': `%s')\n"),
1842 GNUNET_free (routeList);
1846 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1852 while (';' != routeList[pos])
1855 while ((slash >= start) && (routeList[slash] != '/'))
1860 memset (&result[i].netmask,
1862 sizeof (struct in6_addr));
1867 routeList[pos] = '\0';
1868 for (colon = pos; ':' != routeList[colon]; colon--)
1869 if ('/' == routeList[colon])
1871 if (':' == routeList[colon])
1873 routeList[colon] = '\0';
1874 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1877 GNUNET_free (result);
1878 GNUNET_free (routeList);
1882 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1886 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1889 LOG (GNUNET_ERROR_TYPE_WARNING,
1890 _("Wrong format `%s' for netmask\n"),
1891 &routeList[slash + 1]);
1895 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1897 GNUNET_free (result);
1898 GNUNET_free (routeList);
1904 result[i].netmask.s6_addr[off++] = 0xFF;
1909 result[i].netmask.s6_addr[off] =
1910 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1915 routeList[slash] = '\0';
1916 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1920 LOG (GNUNET_ERROR_TYPE_WARNING,
1921 _("Wrong format `%s' for network\n"),
1922 &routeList[slash + 1]);
1924 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1926 GNUNET_free (result);
1927 GNUNET_free (routeList);
1933 GNUNET_free (routeList);
1939 /** ******************** Base64 encoding ***********/
1941 #define FILLCHAR '='
1943 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1947 * Encode into Base64.
1949 * @param data the data to encode
1950 * @param len the length of the input
1951 * @param output where to write the output (*output should be NULL,
1953 * @return the size of the output
1956 GNUNET_STRINGS_base64_encode (const char *data,
1966 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1968 for (i = 0; i < len; ++i)
1970 c = (data[i] >> 2) & 0x3f;
1971 opt[ret++] = cvt[(int) c];
1972 c = (data[i] << 4) & 0x3f;
1974 c |= (data[i] >> 4) & 0x0f;
1975 opt[ret++] = cvt[(int) c];
1978 c = (data[i] << 2) & 0x3f;
1980 c |= (data[i] >> 6) & 0x03;
1981 opt[ret++] = cvt[(int) c];
1986 opt[ret++] = FILLCHAR;
1991 opt[ret++] = cvt[(int) c];
1995 opt[ret++] = FILLCHAR;
1998 opt[ret++] = FILLCHAR;
2002 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
2003 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
2004 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
2006 :((a) == '/') ? 63 : -1)
2010 * Decode from Base64.
2012 * @param data the data to encode
2013 * @param len the length of the input
2014 * @param output where to write the output (*output should be NULL,
2016 * @return the size of the output
2019 GNUNET_STRINGS_base64_decode (const char *data,
2020 size_t len, char **output)
2027 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
2028 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
2030 if (i >= len) goto END; \
2033 *output = GNUNET_malloc ((len * 3 / 4) + 8);
2034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2035 "base64_decode decoding len=%d\n",
2037 for (i = 0; i < len; ++i)
2040 if (FILLCHAR == data[i])
2042 c = (char) cvtfind (data[i]);
2045 c1 = (char) cvtfind (data[i]);
2046 c = (c << 2) | ((c1 >> 4) & 0x3);
2047 (*output)[ret++] = c;
2054 c = (char) cvtfind (c);
2055 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2056 (*output)[ret++] = c1;
2065 c1 = (char) cvtfind (c1);
2066 c = ((c << 6) & 0xc0) | c1;
2067 (*output)[ret++] = c;
2078 /* end of strings.c */