2 This file is part of GNUnet.
3 Copyright (C) 2005-2013 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.
22 * @file util/strings.c
23 * @brief string functions
25 * @author Christian Grothoff
32 #include "gnunet_crypto_lib.h"
33 #include "gnunet_strings_lib.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 * Fill a buffer of the given size with
45 * count 0-terminated strings (given as varargs).
46 * If "buffer" is NULL, only compute the amount of
47 * space required (sum of "strlen(arg)+1").
49 * Unlike using "snprintf" with "%s", this function
50 * will add 0-terminators after each string. The
51 * #GNUNET_string_buffer_tokenize() function can be
52 * used to parse the buffer back into individual
55 * @param buffer the buffer to fill with strings, can
56 * be NULL in which case only the necessary
57 * amount of space will be calculated
58 * @param size number of bytes available in buffer
59 * @param count number of strings that follow
60 * @param ... count 0-terminated strings to copy to buffer
61 * @return number of bytes written to the buffer
62 * (or number of bytes that would have been written)
65 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
76 s = va_arg (ap, const char *);
78 slen = strlen (s) + 1;
81 GNUNET_assert (needed + slen <= size);
82 memcpy (&buffer[needed], s, slen);
93 * Given a buffer of a given size, find "count"
94 * 0-terminated strings in the buffer and assign
95 * the count (varargs) of type "const char**" to the
96 * locations of the respective strings in the
99 * @param buffer the buffer to parse
100 * @param size size of the buffer
101 * @param count number of strings to locate
102 * @return offset of the character after the last 0-termination
103 * in the buffer, or 0 on error.
106 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
107 unsigned int count, ...)
115 va_start (ap, count);
118 r = va_arg (ap, const char **);
121 while ((needed < size) && (buffer[needed] != '\0'))
126 return 0; /* error */
129 needed++; /* skip 0-termination */
138 * Convert a given filesize into a fancy human-readable format.
140 * @param size number of bytes
141 * @return fancy representation of the size (possibly rounded) for humans
144 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
146 const char *unit = _( /* size unit */ "b");
169 ret = GNUNET_malloc (32);
170 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
176 * Unit conversion table entry for 'convert_with_table'.
178 struct ConversionTable
181 * Name of the unit (or NULL for end of table).
186 * Factor to apply for this unit.
188 unsigned long long value;
193 * Convert a string of the form "4 X 5 Y" into a numeric value
194 * by interpreting "X" and "Y" as units and then multiplying
195 * the numbers with the values associated with the respective
196 * unit from the conversion table.
198 * @param input input string to parse
199 * @param table table with the conversion of unit names to numbers
200 * @param output where to store the result
201 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
204 convert_with_table (const char *input,
205 const struct ConversionTable *table,
206 unsigned long long *output)
208 unsigned long long ret;
211 unsigned long long last;
216 in = GNUNET_strdup (input);
217 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
222 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
224 if (table[i].name != NULL)
226 last *= table[i].value;
227 break; /* next tok */
234 last = strtoull (tok, &endptr, 10);
235 if ((0 != errno) || (endptr == tok))
238 return GNUNET_SYSERR; /* expected number */
240 if ('\0' == endptr[0])
241 break; /* next tok */
243 tok = endptr; /* and re-check (handles times like "10s") */
245 } while (GNUNET_YES);
255 * Convert a given fancy human-readable size to bytes.
257 * @param fancy_size human readable string (i.e. 1 MB)
258 * @param size set to the size in bytes
259 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
262 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
263 unsigned long long *size)
265 static const struct ConversionTable table[] =
270 { "MiB", 1024 * 1024},
271 { "MB", 1000 * 1000},
272 { "GiB", 1024 * 1024 * 1024},
273 { "GB", 1000 * 1000 * 1000},
274 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
275 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
276 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
277 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
278 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
279 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
283 return convert_with_table (fancy_size,
290 * Convert a given fancy human-readable time to our internal
293 * @param fancy_time human readable string (i.e. 1 minute)
294 * @param rtime set to the relative time
295 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
298 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
299 struct GNUNET_TIME_Relative *rtime)
301 static const struct ConversionTable table[] =
305 { "s", 1000 * 1000LL },
306 { "\"", 1000 * 1000LL },
307 { "m", 60 * 1000 * 1000LL},
308 { "min", 60 * 1000 * 1000LL},
309 { "minutes", 60 * 1000 * 1000LL},
310 { "'", 60 * 1000 * 1000LL},
311 { "h", 60 * 60 * 1000 * 1000LL},
312 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
313 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
314 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
315 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
316 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
317 { "year", 31536000000000LL /* year */ },
318 { "years", 31536000000000LL /* year */ },
319 { "a", 31536000000000LL /* year */ },
323 unsigned long long val;
325 if (0 == strcasecmp ("forever", fancy_time))
327 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
330 ret = convert_with_table (fancy_time,
333 rtime->rel_value_us = (uint64_t) val;
339 * Convert a given fancy human-readable time to our internal
340 * representation. The human-readable time is expected to be
341 * in local time, whereas the returned value will be in UTC.
343 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
344 * @param atime set to the absolute time
345 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
348 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
349 struct GNUNET_TIME_Absolute *atime)
354 if (0 == strcasecmp ("end of time", fancy_time))
356 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
359 memset (&tv, 0, sizeof (tv));
360 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
361 (NULL == strptime (fancy_time, "%c", &tv)) &&
362 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
363 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
364 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
365 (NULL == strptime (fancy_time, "%x", &tv)) &&
366 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
367 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
368 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
369 (NULL == strptime (fancy_time, "%Y", &tv)) )
370 return GNUNET_SYSERR;
372 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
378 * Convert the len characters long character sequence
379 * given in input that is in the given input charset
380 * to a string in given output charset.
382 * @param input input string
383 * @param len number of bytes in @a input
384 * @param input_charset character set used for @a input
385 * @param output_charset desired character set for the return value
386 * @return the converted string (0-terminated),
387 * if conversion fails, a copy of the orignal
388 * string is returned.
391 GNUNET_STRINGS_conv (const char *input,
393 const char *input_charset,
394 const char *output_charset)
398 char *encoded_string;
399 size_t u8_string_length;
400 size_t encoded_string_length;
402 u8_string = u8_conv_from_encoding (input_charset,
407 if (NULL == u8_string)
409 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
412 if (0 == strcmp (output_charset, "UTF-8"))
414 ret = GNUNET_malloc (u8_string_length + 1);
415 memcpy (ret, u8_string, u8_string_length);
416 ret[u8_string_length] = '\0';
420 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
421 u8_string, u8_string_length,
423 &encoded_string_length);
425 if (NULL == encoded_string)
427 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
430 ret = GNUNET_malloc (encoded_string_length + 1);
431 memcpy (ret, encoded_string, encoded_string_length);
432 ret[encoded_string_length] = '\0';
433 free (encoded_string);
436 LOG (GNUNET_ERROR_TYPE_WARNING,
437 _("Character sets requested were `%s'->`%s'\n"),
438 "UTF-8", output_charset);
439 ret = GNUNET_malloc (len + 1);
440 memcpy (ret, input, len);
447 * Convert the len characters long character sequence
448 * given in input that is in the given charset
451 * @param input the input string (not necessarily 0-terminated)
452 * @param len the number of bytes in the @a input
453 * @param charset character set to convert from
454 * @return the converted string (0-terminated),
455 * if conversion fails, a copy of the orignal
456 * string is returned.
459 GNUNET_STRINGS_to_utf8 (const char *input,
463 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
468 * Convert the len bytes-long UTF-8 string
469 * given in input to the given charset.
471 * @param input the input string (not necessarily 0-terminated)
472 * @param len the number of bytes in the @a input
473 * @param charset character set to convert to
474 * @return the converted string (0-terminated),
475 * if conversion fails, a copy of the orignal
476 * string is returned.
479 GNUNET_STRINGS_from_utf8 (const char *input,
483 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
488 * Convert the utf-8 input string to lowercase.
489 * Output needs to be allocated appropriately.
491 * @param input input string
492 * @param output output buffer
495 GNUNET_STRINGS_utf8_tolower (const char *input,
501 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
502 NULL, UNINORM_NFD, NULL, &len);
503 memcpy(output, tmp_in, len);
510 * Convert the utf-8 input string to uppercase.
511 * Output needs to be allocated appropriately.
513 * @param input input string
514 * @param output output buffer
517 GNUNET_STRINGS_utf8_toupper(const char *input,
523 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
524 NULL, UNINORM_NFD, NULL, &len);
525 memcpy (output, tmp_in, len);
532 * Complete filename (a la shell) from abbrevition.
533 * @param fil the name of the file, may contain ~/ or
534 * be relative to the current directory
535 * @returns the full file name,
536 * NULL is returned on error
539 GNUNET_STRINGS_filename_expand (const char *fil)
556 if (fil[0] == DIR_SEPARATOR)
557 /* absolute path, just copy */
558 return GNUNET_strdup (fil);
561 fm = getenv ("HOME");
564 LOG (GNUNET_ERROR_TYPE_WARNING,
565 _("Failed to expand `$HOME': environment variable `HOME' not set"));
568 fm = GNUNET_strdup (fm);
569 /* do not copy '~' */
572 /* skip over dir seperator to be consistent */
573 if (fil_ptr[0] == DIR_SEPARATOR)
584 buffer = GNUNET_malloc (len);
585 if (getcwd (buffer, len) != NULL)
590 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
593 GNUNET_free (buffer);
596 GNUNET_free (buffer);
601 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
602 buffer = getenv ("PWD"); /* alternative */
604 fm = GNUNET_strdup (buffer);
607 fm = GNUNET_strdup ("./"); /* give up */
609 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
610 buffer = GNUNET_malloc (n);
611 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
612 (fm[strlen (fm) - 1] ==
613 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
617 fn = GNUNET_malloc (MAX_PATH + 1);
619 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
621 SetErrnoFromWinError (lRet);
622 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
625 /* is the path relative? */
626 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
628 char szCurDir[MAX_PATH + 1];
630 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
631 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
633 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
634 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
637 buffer = GNUNET_malloc (MAX_PATH + 1);
638 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
649 * Give relative time in human-readable fancy format.
650 * This is one of the very few calls in the entire API that is
653 * @param delta time in milli seconds
654 * @param do_round are we allowed to round a bit?
655 * @return time as human-readable string
658 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
661 static char buf[128];
662 const char *unit = _( /* time unit */ "µs");
663 uint64_t dval = delta.rel_value_us;
665 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
667 if (0 == delta.rel_value_us)
669 if ( ( (GNUNET_YES == do_round) &&
670 (dval > 5 * 1000) ) ||
671 (0 == (dval % 1000) ))
674 unit = _( /* time unit */ "ms");
675 if ( ( (GNUNET_YES == do_round) &&
676 (dval > 5 * 1000) ) ||
677 (0 == (dval % 1000) ))
680 unit = _( /* time unit */ "s");
681 if ( ( (GNUNET_YES == do_round) &&
683 (0 == (dval % 60) ) )
686 unit = _( /* time unit */ "m");
687 if ( ( (GNUNET_YES == do_round) &&
692 unit = _( /* time unit */ "h");
693 if ( ( (GNUNET_YES == do_round) &&
699 unit = _( /* time unit */ "day");
701 unit = _( /* time unit */ "days");
707 GNUNET_snprintf (buf, sizeof (buf),
708 "%llu %s", dval, unit);
714 * "asctime", except for GNUnet time. Converts a GNUnet internal
715 * absolute time (which is in UTC) to a string in local time.
716 * Note that the returned value will be overwritten if this function
719 * @param t the absolute time to convert
720 * @return timestamp in human-readable form in local time
723 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
725 static char buf[255];
729 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
730 return _("end of time");
731 tt = t.abs_value_us / 1000LL / 1000LL;
732 tp = localtime (&tt);
733 /* This is hacky, but i don't know a way to detect libc character encoding.
734 * Just expect utf8 from glibc these days.
735 * As for msvcrt, use the wide variant, which always returns utf16
736 * (otherwise we'd have to detect current codepage or use W32API character
737 * set conversion routines to convert to UTF8).
740 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
743 static wchar_t wbuf[255];
747 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
748 L"%a %b %d %H:%M:%S %Y", tp);
750 ssize = sizeof (buf);
751 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
752 (uint8_t *) buf, &ssize);
753 if (conved != (uint8_t *) buf)
755 strncpy (buf, (char *) conved, sizeof (buf));
767 * Returns a pointer to a part of filename (allocates nothing)!
769 * @param filename filename to extract basename from
770 * @return short (base) name of the file (that is, everything following the
771 * last directory separator in filename. If filename ends with a
772 * directory separator, the result will be a zero-length string.
773 * If filename has no directory separators, the result is filename
777 GNUNET_STRINGS_get_short_name (const char *filename)
779 const char *short_fn = filename;
781 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
789 * Get the decoded value corresponding to a character according to Crockford
792 * @param a a character
793 * @return corresponding numeric value
796 getValue__ (unsigned char a)
812 /* also consider U to be V */
820 if ((a >= '0') && (a <= '9'))
822 if ((a >= 'a') && (a <= 'z'))
824 /* return (a - 'a' + 10); */
826 if ((a >= 'A') && (a <= 'Z'))
836 return (a - 'A' + 10 - dec);
843 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
844 * Returns a pointer to the byte after the last byte in the string, that
845 * is where the 0-terminator was placed if there was room.
847 * @param data data to encode
848 * @param size size of data (in bytes)
849 * @param out buffer to fill
850 * @param out_size size of the buffer. Must be large enough to hold
851 * (size * 8 + 4) / 5 bytes
852 * @return pointer to the next byte in @a out or NULL on error.
855 GNUNET_STRINGS_data_to_string (const void *data,
861 * 32 characters for encoding
863 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
868 const unsigned char *udata;
871 if (out_size < (size * 8 + 4) / 5)
880 while ((rpos < size) || (vbit > 0))
882 if ((rpos < size) && (vbit < 5))
884 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
889 bits <<= (5 - vbit); /* zero-padding */
890 GNUNET_assert (vbit == ((size * 8) % 5));
893 if (wpos >= out_size)
898 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
901 GNUNET_assert (0 == vbit);
909 * Return the base32crockford encoding of the given buffer.
911 * The returned string will be freshly allocated, and must be free'd
912 * with GNUNET_free().
914 * @param buffer with data
915 * @param size size of the buffer
916 * @return freshly allocated, null-terminated string
919 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
923 size_t len = size * 8;
929 str_buf = GNUNET_malloc (len + 1);
930 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
933 GNUNET_free (str_buf);
942 * Convert Crockford Base32hex encoding back to data.
943 * @a out_size must match exactly the size of the data before it was encoded.
945 * @param enc the encoding
946 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
947 * @param out location where to store the decoded data
948 * @param out_size size of the output buffer @a out
949 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
952 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
953 void *out, size_t out_size)
962 unsigned int encoded_len = out_size * 8;
968 return GNUNET_SYSERR;
973 if ((encoded_len % 5) > 0)
975 vbit = encoded_len % 5; /* padding! */
977 bits = (ret = getValue__ (enc[--rpos])) >> shift;
983 bits = (ret = getValue__ (enc[--rpos]));
985 if ((encoded_len + shift) / 5 != enclen)
986 return GNUNET_SYSERR;
988 return GNUNET_SYSERR;
994 return GNUNET_SYSERR;
996 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
998 return GNUNET_SYSERR;
1002 uout[--wpos] = (unsigned char) bits;
1009 return GNUNET_SYSERR;
1015 * Parse a path that might be an URI.
1017 * @param path path to parse. Must be NULL-terminated.
1018 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1019 * represents the URI scheme will be stored. Can be NULL. The string is
1020 * allocated by the function, and should be freed by GNUNET_free() when
1021 * it is no longer needed.
1022 * @param path_part a pointer to 'const char *' where a pointer to the path
1023 * part of the URI will be stored. Can be NULL. Points to the same block
1024 * of memory as 'path', and thus must not be freed. Might point to '\0',
1025 * if path part is zero-length.
1026 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1027 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1028 * (if they weren't NULL).
1031 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
1032 const char **path_part)
1037 const char *post_scheme_part = NULL;
1038 len = strlen (path);
1039 for (end = 0, i = 0; !end && i < len; i++)
1044 if (path[i] == ':' && i > 0)
1049 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1050 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1051 || (path[i] == '.')))
1064 post_scheme_part = &path[i];
1071 if (post_scheme_part == NULL)
1075 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1076 memcpy (*scheme_part, path, post_scheme_part - path);
1077 (*scheme_part)[post_scheme_part - path] = '\0';
1080 *path_part = post_scheme_part;
1086 * Check whether @a filename is absolute or not, and if it's an URI
1088 * @param filename filename to check
1089 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1090 * assume it's not URI
1091 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1092 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1093 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1094 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1095 * The string is allocated by the function, and should be freed with
1096 * GNUNET_free(). Can be NULL.
1097 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1100 GNUNET_STRINGS_path_is_absolute (const char *filename,
1103 char **r_uri_scheme)
1108 const char *post_scheme_path;
1111 /* consider POSIX paths to be absolute too, even on W32,
1112 * as plibc expansion will fix them for us.
1114 if (filename[0] == '/')
1118 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1124 *r_uri_scheme = uri;
1126 GNUNET_free_non_null (uri);
1128 len = strlen(post_scheme_path);
1129 /* Special check for file:///c:/blah
1130 * We want to parse 'c:/', not '/c:/'
1132 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1133 post_scheme_path = &post_scheme_path[1];
1135 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1141 *r_is_uri = GNUNET_NO;
1144 len = strlen (filename);
1146 ((filename[0] >= 'A' && filename[0] <= 'Z')
1147 || (filename[0] >= 'a' && filename[0] <= 'z'))
1148 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1155 #define _IFMT 0170000 /* type of file */
1156 #define _IFLNK 0120000 /* symbolic link */
1157 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1162 * Perform @a checks on @a filename.
1164 * @param filename file to check
1165 * @param checks checks to perform
1166 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1167 * fails, #GNUNET_SYSERR when a check can't be performed
1170 GNUNET_STRINGS_check_filename (const char *filename,
1171 enum GNUNET_STRINGS_FilenameCheck checks)
1174 if ( (NULL == filename) || (filename[0] == '\0') )
1175 return GNUNET_SYSERR;
1176 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1177 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1179 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1180 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1181 | GNUNET_STRINGS_CHECK_IS_LINK)))
1183 if (0 != STAT (filename, &st))
1185 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1188 return GNUNET_SYSERR;
1191 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1192 if (!S_ISDIR (st.st_mode))
1194 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1195 if (!S_ISLNK (st.st_mode))
1202 * Tries to convert 'zt_addr' string to an IPv6 address.
1203 * The string is expected to have the format "[ABCD::01]:80".
1205 * @param zt_addr 0-terminated string. May be mangled by the function.
1206 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1207 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1208 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1209 * @return #GNUNET_OK if conversion succeded.
1210 * #GNUNET_SYSERR otherwise, in which
1211 * case the contents of @a r_buf are undefined.
1214 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1216 struct sockaddr_in6 *r_buf)
1218 char zbuf[addrlen + 1];
1224 return GNUNET_SYSERR;
1225 memcpy (zbuf, zt_addr, addrlen);
1228 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1229 _("IPv6 address did not start with `['\n"));
1230 return GNUNET_SYSERR;
1232 zbuf[addrlen] = '\0';
1233 port_colon = strrchr (zbuf, ':');
1234 if (NULL == port_colon)
1236 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1237 _("IPv6 address did contain ':' to separate port number\n"));
1238 return GNUNET_SYSERR;
1240 if (']' != *(port_colon - 1))
1242 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1243 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1244 return GNUNET_SYSERR;
1246 ret = SSCANF (port_colon, ":%u", &port);
1247 if ( (1 != ret) || (port > 65535) )
1249 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1250 _("IPv6 address did contain a valid port number after the last ':'\n"));
1251 return GNUNET_SYSERR;
1253 *(port_colon-1) = '\0';
1254 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1255 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1258 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1259 _("Invalid IPv6 address `%s': %s\n"),
1262 return GNUNET_SYSERR;
1264 r_buf->sin6_port = htons (port);
1265 r_buf->sin6_family = AF_INET6;
1266 #if HAVE_SOCKADDR_IN_SIN_LEN
1267 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1274 * Tries to convert 'zt_addr' string to an IPv4 address.
1275 * The string is expected to have the format "1.2.3.4:80".
1277 * @param zt_addr 0-terminated string. May be mangled by the function.
1278 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1279 * @param r_buf a buffer to fill.
1280 * @return #GNUNET_OK if conversion succeded.
1281 * #GNUNET_SYSERR otherwise, in which case
1282 * the contents of @a r_buf are undefined.
1285 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1286 struct sockaddr_in *r_buf)
1288 unsigned int temps[4];
1293 return GNUNET_SYSERR;
1294 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1296 return GNUNET_SYSERR;
1297 for (cnt = 0; cnt < 4; cnt++)
1298 if (temps[cnt] > 0xFF)
1299 return GNUNET_SYSERR;
1301 return GNUNET_SYSERR;
1302 r_buf->sin_family = AF_INET;
1303 r_buf->sin_port = htons (port);
1304 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1305 (temps[2] << 8) + temps[3]);
1306 #if HAVE_SOCKADDR_IN_SIN_LEN
1307 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1314 * Tries to convert @a addr string to an IP (v4 or v6) address.
1315 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1317 * @param addr a string, may not be 0-terminated.
1318 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1319 * 0-terminator should not be counted towards addrlen).
1320 * @param r_buf a buffer to fill.
1321 * @return #GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1322 * case the contents of r_buf are undefined.
1325 GNUNET_STRINGS_to_address_ip (const char *addr,
1327 struct sockaddr_storage *r_buf)
1330 return GNUNET_STRINGS_to_address_ipv6 (addr,
1332 (struct sockaddr_in6 *) r_buf);
1333 return GNUNET_STRINGS_to_address_ipv4 (addr,
1335 (struct sockaddr_in *) r_buf);
1340 * Makes a copy of argv that consists of a single memory chunk that can be
1341 * freed with a single call to GNUNET_free();
1343 static char *const *
1344 _make_continuous_arg_copy (int argc,
1347 size_t argvsize = 0;
1351 for (i = 0; i < argc; i++)
1352 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1353 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1354 p = (char *) &new_argv[argc + 1];
1355 for (i = 0; i < argc; i++)
1358 strcpy (p, argv[i]);
1359 p += strlen (argv[i]) + 1;
1361 new_argv[argc] = NULL;
1362 return (char *const *) new_argv;
1367 * Returns utf-8 encoded arguments.
1368 * Does nothing (returns a copy of argc and argv) on any platform
1370 * Returned argv has u8argv[u8argc] == NULL.
1371 * Returned argv is a single memory block, and can be freed with a single
1372 * GNUNET_free() call.
1374 * @param argc argc (as given by main())
1375 * @param argv argv (as given by main())
1376 * @param u8argc a location to store new argc in (though it's th same as argc)
1377 * @param u8argv a location to store new argv in
1378 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1381 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1388 char **split_u8argv;
1390 wcmd = GetCommandLineW ();
1392 return GNUNET_SYSERR;
1393 wargv = CommandLineToArgvW (wcmd, &wargc);
1395 return GNUNET_SYSERR;
1397 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1399 for (i = 0; i < wargc; i++)
1402 /* Hopefully it will allocate us NUL-terminated strings... */
1403 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1404 if (NULL == split_u8argv[i])
1407 for (j = 0; j < i; j++)
1408 free (split_u8argv[j]);
1409 GNUNET_free (split_u8argv);
1411 return GNUNET_SYSERR;
1415 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1418 for (i = 0; i < wargc; i++)
1419 free (split_u8argv[i]);
1420 free (split_u8argv);
1423 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1432 * Parse the given port policy. The format is
1433 * "[!]SPORT[-DPORT]".
1435 * @param port_policy string to parse
1436 * @param pp policy to fill in
1437 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1438 * @a port_policy is malformed
1441 parse_port_policy (const char *port_policy,
1442 struct GNUNET_STRINGS_PortPolicy *pp)
1452 pp->negate_portrange = GNUNET_YES;
1455 if (2 == sscanf (pos,
1464 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1465 _("Port not in range\n"));
1466 return GNUNET_SYSERR;
1468 pp->start_port = (uint16_t) s;
1469 pp->end_port = (uint16_t) e;
1472 if (1 == sscanf (pos,
1480 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1481 _("Port not in range\n"));
1482 return GNUNET_SYSERR;
1485 pp->start_port = (uint16_t) s;
1486 pp->end_port = (uint16_t) s;
1489 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1490 _("Malformed port policy `%s'\n"),
1492 return GNUNET_SYSERR;
1497 * Parse an IPv4 network policy. The argument specifies a list of
1498 * subnets. The format is
1499 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1500 * be terminated with a semicolon). The network must be given in
1501 * dotted-decimal notation. The netmask can be given in CIDR notation
1502 * (/16) or in dotted-decimal (/255.255.0.0).
1504 * @param routeListX a string specifying the IPv4 subnets
1505 * @return the converted list, terminated with all zeros;
1506 * NULL if the synatx is flawed
1508 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1509 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1517 unsigned int temps[8];
1519 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1524 if (NULL == routeListX)
1526 len = strlen (routeListX);
1529 routeList = GNUNET_strdup (routeListX);
1531 for (i = 0; i < len; i++)
1532 if (routeList[i] == ';')
1534 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1539 for (colon = pos; ':' != routeList[colon]; colon++)
1540 if ( (';' == routeList[colon]) ||
1541 ('\0' == routeList[colon]) )
1543 for (end = colon; ';' != routeList[end]; end++)
1544 if ('\0' == routeList[end])
1546 if ('\0' == routeList[end])
1548 routeList[end] = '\0';
1549 if (':' == routeList[colon])
1551 routeList[colon] = '\0';
1552 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1557 SSCANF (&routeList[pos],
1558 "%u.%u.%u.%u/%u.%u.%u.%u",
1569 for (j = 0; j < 8; j++)
1570 if (temps[j] > 0xFF)
1572 LOG (GNUNET_ERROR_TYPE_WARNING,
1573 _("Invalid format for IP: `%s'\n"),
1575 GNUNET_free (result);
1576 GNUNET_free (routeList);
1579 result[i].network.s_addr =
1580 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1582 result[i].netmask.s_addr =
1583 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1589 /* try second notation */
1591 SSCANF (&routeList[pos],
1600 for (j = 0; j < 4; j++)
1601 if (temps[j] > 0xFF)
1603 LOG (GNUNET_ERROR_TYPE_WARNING,
1604 _("Invalid format for IP: `%s'\n"),
1606 GNUNET_free (result);
1607 GNUNET_free (routeList);
1610 result[i].network.s_addr =
1611 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1613 if ((slash <= 32) && (slash >= 0))
1615 result[i].netmask.s_addr = 0;
1618 result[i].netmask.s_addr =
1619 (result[i].netmask.s_addr >> 1) + 0x80000000;
1622 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1629 LOG (GNUNET_ERROR_TYPE_WARNING,
1630 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1632 GNUNET_free (result);
1633 GNUNET_free (routeList);
1634 return NULL; /* error */
1637 /* try third notation */
1640 SSCANF (&routeList[pos],
1648 for (j = 0; j < 4; j++)
1649 if (temps[j] > 0xFF)
1651 LOG (GNUNET_ERROR_TYPE_WARNING,
1652 _("Invalid format for IP: `%s'\n"),
1654 GNUNET_free (result);
1655 GNUNET_free (routeList);
1658 result[i].network.s_addr =
1659 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1661 result[i].netmask.s_addr = 0;
1664 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1667 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1672 LOG (GNUNET_ERROR_TYPE_WARNING,
1673 _("Invalid format for IP: `%s'\n"),
1675 GNUNET_free (result);
1676 GNUNET_free (routeList);
1677 return NULL; /* error */
1679 if (pos < strlen (routeList))
1681 LOG (GNUNET_ERROR_TYPE_WARNING,
1682 _("Invalid format: `%s'\n"),
1684 GNUNET_free (result);
1685 GNUNET_free (routeList);
1686 return NULL; /* oops */
1688 GNUNET_free (routeList);
1689 return result; /* ok */
1694 * Parse an IPv6 network policy. The argument specifies a list of
1695 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1696 * (no whitespace, must be terminated with a semicolon). The network
1697 * must be given in colon-hex notation. The netmask must be given in
1698 * CIDR notation (/16) or can be omitted to specify a single host.
1699 * Note that the netmask is mandatory if ports are specified.
1701 * @param routeListX a string specifying the policy
1702 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1704 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1705 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1715 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1721 if (NULL == routeListX)
1723 len = strlen (routeListX);
1726 routeList = GNUNET_strdup (routeListX);
1728 for (i = 0; i < len; i++)
1729 if (';' == routeList[i])
1731 if (';' != routeList[len - 1])
1733 LOG (GNUNET_ERROR_TYPE_WARNING,
1734 _("Invalid network notation (does not end with ';': `%s')\n"),
1736 GNUNET_free (routeList);
1740 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1746 while (';' != routeList[pos])
1749 while ((slash >= start) && (routeList[slash] != '/'))
1754 memset (&result[i].netmask,
1756 sizeof (struct in6_addr));
1761 routeList[pos] = '\0';
1762 for (colon = pos; ':' != routeList[colon]; colon--)
1763 if ('/' == routeList[colon])
1765 if (':' == routeList[colon])
1767 routeList[colon] = '\0';
1768 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1771 GNUNET_free (result);
1772 GNUNET_free (routeList);
1776 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1780 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1783 LOG (GNUNET_ERROR_TYPE_WARNING,
1784 _("Wrong format `%s' for netmask\n"),
1785 &routeList[slash + 1]);
1789 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1791 GNUNET_free (result);
1792 GNUNET_free (routeList);
1798 result[i].netmask.s6_addr[off++] = 0xFF;
1803 result[i].netmask.s6_addr[off] =
1804 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1809 routeList[slash] = '\0';
1810 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1814 LOG (GNUNET_ERROR_TYPE_WARNING,
1815 _("Wrong format `%s' for network\n"),
1816 &routeList[slash + 1]);
1818 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1820 GNUNET_free (result);
1821 GNUNET_free (routeList);
1827 GNUNET_free (routeList);
1833 /** ******************** Base64 encoding ***********/
1835 #define FILLCHAR '='
1837 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1841 * Encode into Base64.
1843 * @param data the data to encode
1844 * @param len the length of the input
1845 * @param output where to write the output (*output should be NULL,
1847 * @return the size of the output
1850 GNUNET_STRINGS_base64_encode (const char *data,
1860 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1862 for (i = 0; i < len; ++i)
1864 c = (data[i] >> 2) & 0x3f;
1865 opt[ret++] = cvt[(int) c];
1866 c = (data[i] << 4) & 0x3f;
1868 c |= (data[i] >> 4) & 0x0f;
1869 opt[ret++] = cvt[(int) c];
1872 c = (data[i] << 2) & 0x3f;
1874 c |= (data[i] >> 6) & 0x03;
1875 opt[ret++] = cvt[(int) c];
1880 opt[ret++] = FILLCHAR;
1885 opt[ret++] = cvt[(int) c];
1889 opt[ret++] = FILLCHAR;
1892 opt[ret++] = FILLCHAR;
1896 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
1897 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
1898 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
1900 :((a) == '/') ? 63 : -1)
1904 * Decode from Base64.
1906 * @param data the data to encode
1907 * @param len the length of the input
1908 * @param output where to write the output (*output should be NULL,
1910 * @return the size of the output
1913 GNUNET_STRINGS_base64_decode (const char *data,
1914 size_t len, char **output)
1921 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
1922 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
1924 if (i >= len) goto END; \
1927 *output = GNUNET_malloc ((len * 3 / 4) + 8);
1928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929 "base64_decode decoding len=%d\n",
1931 for (i = 0; i < len; ++i)
1934 if (FILLCHAR == data[i])
1936 c = (char) cvtfind (data[i]);
1939 c1 = (char) cvtfind (data[i]);
1940 c = (c << 2) | ((c1 >> 4) & 0x3);
1941 (*output)[ret++] = c;
1948 c = (char) cvtfind (c);
1949 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
1950 (*output)[ret++] = c1;
1959 c1 = (char) cvtfind (c1);
1960 c = ((c << 6) & 0xc0) | c1;
1961 (*output)[ret++] = c;
1972 /* end of strings.c */