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/>.
19 * @file util/strings.c
20 * @brief string functions
22 * @author Christian Grothoff
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_strings_lib.h"
35 #define LOG(kind,...) GNUNET_log_from (kind, "util-strings", __VA_ARGS__)
37 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-strings", syscall)
41 * Fill a buffer of the given size with
42 * count 0-terminated strings (given as varargs).
43 * If "buffer" is NULL, only compute the amount of
44 * space required (sum of "strlen(arg)+1").
46 * Unlike using "snprintf" with "%s", this function
47 * will add 0-terminators after each string. The
48 * #GNUNET_string_buffer_tokenize() function can be
49 * used to parse the buffer back into individual
52 * @param buffer the buffer to fill with strings, can
53 * be NULL in which case only the necessary
54 * amount of space will be calculated
55 * @param size number of bytes available in buffer
56 * @param count number of strings that follow
57 * @param ... count 0-terminated strings to copy to buffer
58 * @return number of bytes written to the buffer
59 * (or number of bytes that would have been written)
62 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
73 s = va_arg (ap, const char *);
75 slen = strlen (s) + 1;
78 GNUNET_assert (needed + slen <= size);
79 GNUNET_memcpy (&buffer[needed], s, slen);
90 * Convert a peer path to a human-readable string.
92 * @param pids array of PIDs to convert to a string
93 * @param num_pids length of the @a pids array
94 * @return string representing the array of @a pids
97 GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids,
98 unsigned int num_pids)
102 size_t plen = num_pids * 5 + 1;
105 buf = GNUNET_malloc (plen);
106 for (unsigned int i = 0;
110 off += GNUNET_snprintf (&buf[off],
113 GNUNET_i2s (&pids[i]),
114 (i == num_pids -1) ? "" : "-");
121 * Given a buffer of a given size, find "count"
122 * 0-terminated strings in the buffer and assign
123 * the count (varargs) of type "const char**" to the
124 * locations of the respective strings in the
127 * @param buffer the buffer to parse
128 * @param size size of the buffer
129 * @param count number of strings to locate
130 * @return offset of the character after the last 0-termination
131 * in the buffer, or 0 on error.
134 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
135 unsigned int count, ...)
143 va_start (ap, count);
146 r = va_arg (ap, const char **);
149 while ((needed < size) && (buffer[needed] != '\0'))
154 return 0; /* error */
157 needed++; /* skip 0-termination */
166 * Convert a given filesize into a fancy human-readable format.
168 * @param size number of bytes
169 * @return fancy representation of the size (possibly rounded) for humans
172 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
174 const char *unit = _( /* size unit */ "b");
197 ret = GNUNET_malloc (32);
198 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
204 * Unit conversion table entry for 'convert_with_table'.
206 struct ConversionTable
209 * Name of the unit (or NULL for end of table).
214 * Factor to apply for this unit.
216 unsigned long long value;
221 * Convert a string of the form "4 X 5 Y" into a numeric value
222 * by interpreting "X" and "Y" as units and then multiplying
223 * the numbers with the values associated with the respective
224 * unit from the conversion table.
226 * @param input input string to parse
227 * @param table table with the conversion of unit names to numbers
228 * @param output where to store the result
229 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
232 convert_with_table (const char *input,
233 const struct ConversionTable *table,
234 unsigned long long *output)
236 unsigned long long ret;
239 unsigned long long last;
244 in = GNUNET_strdup (input);
245 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
250 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
252 if (table[i].name != NULL)
254 last *= table[i].value;
255 break; /* next tok */
262 last = strtoull (tok, &endptr, 10);
263 if ((0 != errno) || (endptr == tok))
266 return GNUNET_SYSERR; /* expected number */
268 if ('\0' == endptr[0])
269 break; /* next tok */
271 tok = endptr; /* and re-check (handles times like "10s") */
273 } while (GNUNET_YES);
283 * Convert a given fancy human-readable size to bytes.
285 * @param fancy_size human readable string (i.e. 1 MB)
286 * @param size set to the size in bytes
287 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
290 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
291 unsigned long long *size)
293 static const struct ConversionTable table[] =
298 { "MiB", 1024 * 1024},
299 { "MB", 1000 * 1000},
300 { "GiB", 1024 * 1024 * 1024},
301 { "GB", 1000 * 1000 * 1000},
302 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
303 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
304 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
305 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
306 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
307 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
311 return convert_with_table (fancy_size,
318 * Convert a given fancy human-readable time to our internal
321 * @param fancy_time human readable string (i.e. 1 minute)
322 * @param rtime set to the relative time
323 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
326 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
327 struct GNUNET_TIME_Relative *rtime)
329 static const struct ConversionTable table[] =
333 { "s", 1000 * 1000LL },
334 { "second", 1000 * 1000LL },
335 { "seconds", 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;
822 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
830 * Get the decoded value corresponding to a character according to Crockford
833 * @param a a character
834 * @return corresponding numeric value
837 getValue__ (unsigned char a)
853 /* also consider U to be V */
861 if ((a >= '0') && (a <= '9'))
863 if ((a >= 'a') && (a <= 'z'))
865 /* return (a - 'a' + 10); */
867 if ((a >= 'A') && (a <= 'Z'))
877 return (a - 'A' + 10 - dec);
884 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
885 * Returns a pointer to the byte after the last byte in the string, that
886 * is where the 0-terminator was placed if there was room.
888 * @param data data to encode
889 * @param size size of data (in bytes)
890 * @param out buffer to fill
891 * @param out_size size of the buffer. Must be large enough to hold
892 * (size * 8 + 4) / 5 bytes
893 * @return pointer to the next byte in @a out or NULL on error.
896 GNUNET_STRINGS_data_to_string (const void *data,
902 * 32 characters for encoding
904 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
909 const unsigned char *udata;
912 if (out_size < (size * 8 + 4) / 5)
921 while ((rpos < size) || (vbit > 0))
923 if ((rpos < size) && (vbit < 5))
925 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
930 bits <<= (5 - vbit); /* zero-padding */
931 GNUNET_assert (vbit == ((size * 8) % 5));
934 if (wpos >= out_size)
939 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
942 GNUNET_assert (0 == vbit);
950 * Return the base32crockford encoding of the given buffer.
952 * The returned string will be freshly allocated, and must be free'd
953 * with GNUNET_free().
955 * @param buffer with data
956 * @param size size of the buffer
957 * @return freshly allocated, null-terminated string
960 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
964 size_t len = size * 8;
970 str_buf = GNUNET_malloc (len + 1);
971 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
974 GNUNET_free (str_buf);
983 * Convert Crockford Base32hex encoding back to data.
984 * @a out_size must match exactly the size of the data before it was encoded.
986 * @param enc the encoding
987 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
988 * @param out location where to store the decoded data
989 * @param out_size size of the output buffer @a out
990 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
993 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
994 void *out, size_t out_size)
1002 unsigned char *uout;
1003 unsigned int encoded_len = out_size * 8;
1009 return GNUNET_SYSERR;
1014 if ((encoded_len % 5) > 0)
1016 vbit = encoded_len % 5; /* padding! */
1018 bits = (ret = getValue__ (enc[--rpos])) >> shift;
1024 bits = (ret = getValue__ (enc[--rpos]));
1026 if ((encoded_len + shift) / 5 != enclen)
1027 return GNUNET_SYSERR;
1029 return GNUNET_SYSERR;
1035 return GNUNET_SYSERR;
1037 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1039 return GNUNET_SYSERR;
1043 uout[--wpos] = (unsigned char) bits;
1050 return GNUNET_SYSERR;
1056 * Parse a path that might be an URI.
1058 * @param path path to parse. Must be NULL-terminated.
1059 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1060 * represents the URI scheme will be stored. Can be NULL. The string is
1061 * allocated by the function, and should be freed by GNUNET_free() when
1062 * it is no longer needed.
1063 * @param path_part a pointer to 'const char *' where a pointer to the path
1064 * part of the URI will be stored. Can be NULL. Points to the same block
1065 * of memory as 'path', and thus must not be freed. Might point to '\0',
1066 * if path part is zero-length.
1067 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1068 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1069 * (if they weren't NULL).
1072 GNUNET_STRINGS_parse_uri (const char *path,
1074 const char **path_part)
1080 const char *post_scheme_part = NULL;
1081 len = strlen (path);
1082 for (end = 0, i = 0; !end && i < len; i++)
1087 if ( (path[i] == ':') && (i > 0) )
1092 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1093 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1094 || (path[i] == '.')))
1107 post_scheme_part = &path[i];
1114 if (post_scheme_part == NULL)
1118 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1119 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1120 (*scheme_part)[post_scheme_part - path] = '\0';
1123 *path_part = post_scheme_part;
1129 * Check whether @a filename is absolute or not, and if it's an URI
1131 * @param filename filename to check
1132 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1133 * assume it's not URI
1134 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1135 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1136 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1137 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1138 * The string is allocated by the function, and should be freed with
1139 * GNUNET_free(). Can be NULL.
1140 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1143 GNUNET_STRINGS_path_is_absolute (const char *filename,
1146 char **r_uri_scheme)
1151 const char *post_scheme_path;
1154 /* consider POSIX paths to be absolute too, even on W32,
1155 * as plibc expansion will fix them for us.
1157 if (filename[0] == '/')
1161 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1167 *r_uri_scheme = uri;
1169 GNUNET_free_non_null (uri);
1171 len = strlen(post_scheme_path);
1172 /* Special check for file:///c:/blah
1173 * We want to parse 'c:/', not '/c:/'
1175 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1176 post_scheme_path = &post_scheme_path[1];
1178 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1184 *r_is_uri = GNUNET_NO;
1187 len = strlen (filename);
1189 ((filename[0] >= 'A' && filename[0] <= 'Z')
1190 || (filename[0] >= 'a' && filename[0] <= 'z'))
1191 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1198 #define _IFMT 0170000 /* type of file */
1199 #define _IFLNK 0120000 /* symbolic link */
1200 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1205 * Perform @a checks on @a filename.
1207 * @param filename file to check
1208 * @param checks checks to perform
1209 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1210 * fails, #GNUNET_SYSERR when a check can't be performed
1213 GNUNET_STRINGS_check_filename (const char *filename,
1214 enum GNUNET_STRINGS_FilenameCheck checks)
1217 if ( (NULL == filename) || (filename[0] == '\0') )
1218 return GNUNET_SYSERR;
1219 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1220 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1222 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1223 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1224 | GNUNET_STRINGS_CHECK_IS_LINK)))
1226 if (0 != STAT (filename, &st))
1228 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1231 return GNUNET_SYSERR;
1234 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1235 if (!S_ISDIR (st.st_mode))
1237 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1238 if (!S_ISLNK (st.st_mode))
1245 * Tries to convert @a zt_addr string to an IPv6 address.
1246 * The string is expected to have the format "[ABCD::01]:80".
1248 * @param zt_addr 0-terminated string. May be mangled by the function.
1249 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1250 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1251 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1252 * @return #GNUNET_OK if conversion succeded.
1253 * #GNUNET_SYSERR otherwise, in which
1254 * case the contents of @a r_buf are undefined.
1257 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1259 struct sockaddr_in6 *r_buf)
1261 char zbuf[addrlen + 1];
1268 return GNUNET_SYSERR;
1269 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1272 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1273 _("IPv6 address did not start with `['\n"));
1274 return GNUNET_SYSERR;
1276 zbuf[addrlen] = '\0';
1277 port_colon = strrchr (zbuf, ':');
1278 if (NULL == port_colon)
1280 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1281 _("IPv6 address did contain ':' to separate port number\n"));
1282 return GNUNET_SYSERR;
1284 if (']' != *(port_colon - 1))
1286 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1287 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1288 return GNUNET_SYSERR;
1290 ret = SSCANF (port_colon,
1294 if ( (1 != ret) || (port > 65535) )
1296 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1297 _("IPv6 address did contain a valid port number after the last ':'\n"));
1298 return GNUNET_SYSERR;
1300 *(port_colon-1) = '\0';
1301 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1302 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1305 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1306 _("Invalid IPv6 address `%s': %s\n"),
1309 return GNUNET_SYSERR;
1311 r_buf->sin6_port = htons (port);
1312 r_buf->sin6_family = AF_INET6;
1313 #if HAVE_SOCKADDR_IN_SIN_LEN
1314 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1321 * Tries to convert 'zt_addr' string to an IPv4 address.
1322 * The string is expected to have the format "1.2.3.4:80".
1324 * @param zt_addr 0-terminated string. May be mangled by the function.
1325 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1326 * @param r_buf a buffer to fill.
1327 * @return #GNUNET_OK if conversion succeded.
1328 * #GNUNET_SYSERR otherwise, in which case
1329 * the contents of @a r_buf are undefined.
1332 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1334 struct sockaddr_in *r_buf)
1336 unsigned int temps[4];
1342 return GNUNET_SYSERR;
1343 cnt = SSCANF (zt_addr,
1344 "%u.%u.%u.%u:%u%1s",
1352 return GNUNET_SYSERR;
1353 for (cnt = 0; cnt < 4; cnt++)
1354 if (temps[cnt] > 0xFF)
1355 return GNUNET_SYSERR;
1357 return GNUNET_SYSERR;
1358 r_buf->sin_family = AF_INET;
1359 r_buf->sin_port = htons (port);
1360 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1361 (temps[2] << 8) + temps[3]);
1362 #if HAVE_SOCKADDR_IN_SIN_LEN
1363 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1370 * Tries to convert @a addr string to an IP (v4 or v6) address.
1371 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1373 * @param addr a string, may not be 0-terminated.
1374 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1375 * 0-terminator should not be counted towards addrlen).
1376 * @param r_buf a buffer to fill.
1377 * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
1378 * case the contents of @a r_buf are undefined.
1381 GNUNET_STRINGS_to_address_ip (const char *addr,
1383 struct sockaddr_storage *r_buf)
1386 return GNUNET_STRINGS_to_address_ipv6 (addr,
1388 (struct sockaddr_in6 *) r_buf);
1389 return GNUNET_STRINGS_to_address_ipv4 (addr,
1391 (struct sockaddr_in *) r_buf);
1396 * Parse an address given as a string into a
1397 * `struct sockaddr`.
1399 * @param addr the address
1400 * @param[out] af set to the parsed address family (i.e. AF_INET)
1401 * @param[out] sa set to the parsed address
1402 * @return 0 on error, otherwise number of bytes in @a sa
1405 GNUNET_STRINGS_parse_socket_addr (const char *addr,
1407 struct sockaddr **sa)
1409 char *cp = GNUNET_strdup (addr);
1415 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1417 GNUNET_STRINGS_to_address_ipv6 (cp,
1419 (struct sockaddr_in6 *) *sa))
1428 return sizeof (struct sockaddr_in6);
1433 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1435 GNUNET_STRINGS_to_address_ipv4 (cp,
1437 (struct sockaddr_in *) *sa))
1446 return sizeof (struct sockaddr_in);
1452 * Makes a copy of argv that consists of a single memory chunk that can be
1453 * freed with a single call to GNUNET_free();
1455 static char *const *
1456 _make_continuous_arg_copy (int argc,
1459 size_t argvsize = 0;
1463 for (i = 0; i < argc; i++)
1464 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1465 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1466 p = (char *) &new_argv[argc + 1];
1467 for (i = 0; i < argc; i++)
1470 strcpy (p, argv[i]);
1471 p += strlen (argv[i]) + 1;
1473 new_argv[argc] = NULL;
1474 return (char *const *) new_argv;
1479 * Returns utf-8 encoded arguments.
1480 * Does nothing (returns a copy of argc and argv) on any platform
1482 * Returned argv has u8argv[u8argc] == NULL.
1483 * Returned argv is a single memory block, and can be freed with a single
1484 * GNUNET_free() call.
1486 * @param argc argc (as given by main())
1487 * @param argv argv (as given by main())
1488 * @param u8argc a location to store new argc in (though it's th same as argc)
1489 * @param u8argv a location to store new argv in
1490 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1493 GNUNET_STRINGS_get_utf8_args (int argc,
1496 char *const **u8argv)
1503 char **split_u8argv;
1505 wcmd = GetCommandLineW ();
1507 return GNUNET_SYSERR;
1508 wargv = CommandLineToArgvW (wcmd, &wargc);
1510 return GNUNET_SYSERR;
1512 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1514 for (i = 0; i < wargc; i++)
1517 /* Hopefully it will allocate us NUL-terminated strings... */
1518 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1519 if (NULL == split_u8argv[i])
1522 for (j = 0; j < i; j++)
1523 free (split_u8argv[j]);
1524 GNUNET_free (split_u8argv);
1526 return GNUNET_SYSERR;
1530 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1533 for (i = 0; i < wargc; i++)
1534 free (split_u8argv[i]);
1535 free (split_u8argv);
1538 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1547 * Parse the given port policy. The format is
1548 * "[!]SPORT[-DPORT]".
1550 * @param port_policy string to parse
1551 * @param pp policy to fill in
1552 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1553 * @a port_policy is malformed
1556 parse_port_policy (const char *port_policy,
1557 struct GNUNET_STRINGS_PortPolicy *pp)
1567 pp->negate_portrange = GNUNET_YES;
1570 if (2 == sscanf (pos,
1581 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1582 _("Port not in range\n"));
1583 return GNUNET_SYSERR;
1585 pp->start_port = (uint16_t) s;
1586 pp->end_port = (uint16_t) e;
1589 if (1 == sscanf (pos,
1597 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1598 _("Port not in range\n"));
1599 return GNUNET_SYSERR;
1602 pp->start_port = (uint16_t) s;
1603 pp->end_port = (uint16_t) s;
1606 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1607 _("Malformed port policy `%s'\n"),
1609 return GNUNET_SYSERR;
1614 * Parse an IPv4 network policy. The argument specifies a list of
1615 * subnets. The format is
1616 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1617 * be terminated with a semicolon). The network must be given in
1618 * dotted-decimal notation. The netmask can be given in CIDR notation
1619 * (/16) or in dotted-decimal (/255.255.0.0).
1621 * @param routeListX a string specifying the IPv4 subnets
1622 * @return the converted list, terminated with all zeros;
1623 * NULL if the synatx is flawed
1625 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1626 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1634 unsigned int temps[8];
1636 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1642 if (NULL == routeListX)
1644 len = strlen (routeListX);
1647 routeList = GNUNET_strdup (routeListX);
1649 for (i = 0; i < len; i++)
1650 if (routeList[i] == ';')
1652 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1657 for (colon = pos; ':' != routeList[colon]; colon++)
1658 if ( (';' == routeList[colon]) ||
1659 ('\0' == routeList[colon]) )
1661 for (end = colon; ';' != routeList[end]; end++)
1662 if ('\0' == routeList[end])
1664 if ('\0' == routeList[end])
1666 routeList[end] = '\0';
1667 if (':' == routeList[colon])
1669 routeList[colon] = '\0';
1670 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1675 SSCANF (&routeList[pos],
1676 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1688 for (j = 0; j < 8; j++)
1689 if (temps[j] > 0xFF)
1691 LOG (GNUNET_ERROR_TYPE_WARNING,
1692 _("Invalid format for IP: `%s'\n"),
1694 GNUNET_free (result);
1695 GNUNET_free (routeList);
1698 result[i].network.s_addr =
1699 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1701 result[i].netmask.s_addr =
1702 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1708 /* try second notation */
1710 SSCANF (&routeList[pos],
1711 "%u.%u.%u.%u/%u%1s",
1720 for (j = 0; j < 4; j++)
1721 if (temps[j] > 0xFF)
1723 LOG (GNUNET_ERROR_TYPE_WARNING,
1724 _("Invalid format for IP: `%s'\n"),
1726 GNUNET_free (result);
1727 GNUNET_free (routeList);
1730 result[i].network.s_addr =
1731 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1733 if ((slash <= 32) && (slash >= 0))
1735 result[i].netmask.s_addr = 0;
1738 result[i].netmask.s_addr =
1739 (result[i].netmask.s_addr >> 1) + 0x80000000;
1742 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1749 LOG (GNUNET_ERROR_TYPE_WARNING,
1750 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1752 GNUNET_free (result);
1753 GNUNET_free (routeList);
1754 return NULL; /* error */
1757 /* try third notation */
1760 SSCANF (&routeList[pos],
1769 for (j = 0; j < 4; j++)
1770 if (temps[j] > 0xFF)
1772 LOG (GNUNET_ERROR_TYPE_WARNING,
1773 _("Invalid format for IP: `%s'\n"),
1775 GNUNET_free (result);
1776 GNUNET_free (routeList);
1779 result[i].network.s_addr =
1780 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1782 result[i].netmask.s_addr = 0;
1785 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1788 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1793 LOG (GNUNET_ERROR_TYPE_WARNING,
1794 _("Invalid format for IP: `%s'\n"),
1796 GNUNET_free (result);
1797 GNUNET_free (routeList);
1798 return NULL; /* error */
1800 if (pos < strlen (routeList))
1802 LOG (GNUNET_ERROR_TYPE_WARNING,
1803 _("Invalid format: `%s'\n"),
1805 GNUNET_free (result);
1806 GNUNET_free (routeList);
1807 return NULL; /* oops */
1809 GNUNET_free (routeList);
1810 return result; /* ok */
1815 * Parse an IPv6 network policy. The argument specifies a list of
1816 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1817 * (no whitespace, must be terminated with a semicolon). The network
1818 * must be given in colon-hex notation. The netmask must be given in
1819 * CIDR notation (/16) or can be omitted to specify a single host.
1820 * Note that the netmask is mandatory if ports are specified.
1822 * @param routeListX a string specifying the policy
1823 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1825 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1826 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1836 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1843 if (NULL == routeListX)
1845 len = strlen (routeListX);
1848 routeList = GNUNET_strdup (routeListX);
1850 for (i = 0; i < len; i++)
1851 if (';' == routeList[i])
1853 if (';' != routeList[len - 1])
1855 LOG (GNUNET_ERROR_TYPE_WARNING,
1856 _("Invalid network notation (does not end with ';': `%s')\n"),
1858 GNUNET_free (routeList);
1862 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1868 while (';' != routeList[pos])
1871 while ((slash >= start) && (routeList[slash] != '/'))
1876 memset (&result[i].netmask,
1878 sizeof (struct in6_addr));
1883 routeList[pos] = '\0';
1884 for (colon = pos; ':' != routeList[colon]; colon--)
1885 if ('/' == routeList[colon])
1887 if (':' == routeList[colon])
1889 routeList[colon] = '\0';
1890 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1893 GNUNET_free (result);
1894 GNUNET_free (routeList);
1898 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1902 if ( (1 != SSCANF (&routeList[slash + 1],
1909 LOG (GNUNET_ERROR_TYPE_WARNING,
1910 _("Wrong format `%s' for netmask\n"),
1911 &routeList[slash + 1]);
1915 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1917 GNUNET_free (result);
1918 GNUNET_free (routeList);
1924 result[i].netmask.s6_addr[off++] = 0xFF;
1929 result[i].netmask.s6_addr[off] =
1930 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1935 routeList[slash] = '\0';
1936 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1940 LOG (GNUNET_ERROR_TYPE_WARNING,
1941 _("Wrong format `%s' for network\n"),
1942 &routeList[slash + 1]);
1944 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1946 GNUNET_free (result);
1947 GNUNET_free (routeList);
1953 GNUNET_free (routeList);
1959 /** ******************** Base64 encoding ***********/
1961 #define FILLCHAR '='
1963 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1967 * Encode into Base64.
1969 * @param in the data to encode
1970 * @param len the length of the input
1971 * @param output where to write the output (*output should be NULL,
1973 * @return the size of the output
1976 GNUNET_STRINGS_base64_encode (const void *in,
1980 const char *data = in;
1985 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1986 for (size_t i = 0; i < len; ++i)
1990 c = (data[i] >> 2) & 0x3f;
1991 opt[ret++] = cvt[(int) c];
1992 c = (data[i] << 4) & 0x3f;
1994 c |= (data[i] >> 4) & 0x0f;
1995 opt[ret++] = cvt[(int) c];
1998 c = (data[i] << 2) & 0x3f;
2000 c |= (data[i] >> 6) & 0x03;
2001 opt[ret++] = cvt[(int) c];
2006 opt[ret++] = FILLCHAR;
2011 opt[ret++] = cvt[(int) c];
2015 opt[ret++] = FILLCHAR;
2022 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
2023 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
2024 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
2026 :((a) == '/') ? 63 : -1)
2030 * Decode from Base64.
2032 * @param data the data to encode
2033 * @param len the length of the input
2034 * @param output where to write the output (*output should be NULL,
2036 * @return the size of the output
2039 GNUNET_STRINGS_base64_decode (const char *data,
2046 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
2047 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
2049 if (i >= len) goto END; \
2052 output = GNUNET_malloc ((len * 3 / 4) + 8);
2053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054 "base64_decode decoding len=%d\n",
2056 for (size_t i = 0; i < len; ++i)
2062 if (FILLCHAR == data[i])
2064 c = (char) cvtfind (data[i]);
2067 c1 = (char) cvtfind (data[i]);
2068 c = (c << 2) | ((c1 >> 4) & 0x3);
2076 c = (char) cvtfind (c);
2077 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2087 c1 = (char) cvtfind (c1);
2088 c = ((c << 6) & 0xc0) | c1;
2098 /* end of strings.c */