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 GNUNET_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 { "minute", 60 * 1000 * 1000LL},
310 { "minutes", 60 * 1000 * 1000LL},
311 { "'", 60 * 1000 * 1000LL},
312 { "h", 60 * 60 * 1000 * 1000LL},
313 { "hour", 60 * 60 * 1000 * 1000LL},
314 { "hours", 60 * 60 * 1000 * 1000LL},
315 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
316 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
317 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
318 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
319 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL},
320 { "year", 31536000000000LL /* year */ },
321 { "years", 31536000000000LL /* year */ },
322 { "a", 31536000000000LL /* year */ },
326 unsigned long long val;
328 if (0 == strcasecmp ("forever", fancy_time))
330 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
333 ret = convert_with_table (fancy_time,
336 rtime->rel_value_us = (uint64_t) val;
342 * Convert a given fancy human-readable time to our internal
343 * representation. The human-readable time is expected to be
344 * in local time, whereas the returned value will be in UTC.
346 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
347 * @param atime set to the absolute time
348 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
351 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
352 struct GNUNET_TIME_Absolute *atime)
357 if (0 == strcasecmp ("end of time",
360 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
363 memset (&tv, 0, sizeof (tv));
364 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
365 (NULL == strptime (fancy_time, "%c", &tv)) &&
366 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
367 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
368 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
369 (NULL == strptime (fancy_time, "%x", &tv)) &&
370 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
371 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
372 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
373 (NULL == strptime (fancy_time, "%Y", &tv)) )
374 return GNUNET_SYSERR;
376 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
382 * Convert the len characters long character sequence
383 * given in input that is in the given input charset
384 * to a string in given output charset.
386 * @param input input string
387 * @param len number of bytes in @a input
388 * @param input_charset character set used for @a input
389 * @param output_charset desired character set for the return value
390 * @return the converted string (0-terminated),
391 * if conversion fails, a copy of the orignal
392 * string is returned.
395 GNUNET_STRINGS_conv (const char *input,
397 const char *input_charset,
398 const char *output_charset)
402 char *encoded_string;
403 size_t u8_string_length;
404 size_t encoded_string_length;
406 u8_string = u8_conv_from_encoding (input_charset,
411 if (NULL == u8_string)
413 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
416 if (0 == strcmp (output_charset, "UTF-8"))
418 ret = GNUNET_malloc (u8_string_length + 1);
419 GNUNET_memcpy (ret, u8_string, u8_string_length);
420 ret[u8_string_length] = '\0';
424 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
425 u8_string, u8_string_length,
427 &encoded_string_length);
429 if (NULL == encoded_string)
431 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
434 ret = GNUNET_malloc (encoded_string_length + 1);
435 GNUNET_memcpy (ret, encoded_string, encoded_string_length);
436 ret[encoded_string_length] = '\0';
437 free (encoded_string);
440 LOG (GNUNET_ERROR_TYPE_WARNING,
441 _("Character sets requested were `%s'->`%s'\n"),
442 "UTF-8", output_charset);
443 ret = GNUNET_malloc (len + 1);
444 GNUNET_memcpy (ret, input, len);
451 * Convert the len characters long character sequence
452 * given in input that is in the given charset
455 * @param input the input string (not necessarily 0-terminated)
456 * @param len the number of bytes in the @a input
457 * @param charset character set to convert from
458 * @return the converted string (0-terminated),
459 * if conversion fails, a copy of the orignal
460 * string is returned.
463 GNUNET_STRINGS_to_utf8 (const char *input,
467 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
472 * Convert the len bytes-long UTF-8 string
473 * given in input to the given charset.
475 * @param input the input string (not necessarily 0-terminated)
476 * @param len the number of bytes in the @a input
477 * @param charset character set to convert to
478 * @return the converted string (0-terminated),
479 * if conversion fails, a copy of the orignal
480 * string is returned.
483 GNUNET_STRINGS_from_utf8 (const char *input,
487 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
492 * Convert the utf-8 input string to lowercase.
493 * Output needs to be allocated appropriately.
495 * @param input input string
496 * @param output output buffer
499 GNUNET_STRINGS_utf8_tolower (const char *input,
505 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
506 NULL, UNINORM_NFD, NULL, &len);
507 GNUNET_memcpy(output, tmp_in, len);
514 * Convert the utf-8 input string to uppercase.
515 * Output needs to be allocated appropriately.
517 * @param input input string
518 * @param output output buffer
521 GNUNET_STRINGS_utf8_toupper(const char *input,
527 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
528 NULL, UNINORM_NFD, NULL, &len);
529 GNUNET_memcpy (output, tmp_in, len);
536 * Complete filename (a la shell) from abbrevition.
537 * @param fil the name of the file, may contain ~/ or
538 * be relative to the current directory
539 * @returns the full file name,
540 * NULL is returned on error
543 GNUNET_STRINGS_filename_expand (const char *fil)
560 if (fil[0] == DIR_SEPARATOR)
561 /* absolute path, just copy */
562 return GNUNET_strdup (fil);
565 fm = getenv ("HOME");
568 LOG (GNUNET_ERROR_TYPE_WARNING,
569 _("Failed to expand `$HOME': environment variable `HOME' not set"));
572 fm = GNUNET_strdup (fm);
573 /* do not copy '~' */
576 /* skip over dir seperator to be consistent */
577 if (fil_ptr[0] == DIR_SEPARATOR)
588 buffer = GNUNET_malloc (len);
589 if (getcwd (buffer, len) != NULL)
594 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
597 GNUNET_free (buffer);
600 GNUNET_free (buffer);
605 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
606 buffer = getenv ("PWD"); /* alternative */
608 fm = GNUNET_strdup (buffer);
611 fm = GNUNET_strdup ("./"); /* give up */
613 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
614 buffer = GNUNET_malloc (n);
615 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
616 (fm[strlen (fm) - 1] ==
617 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
621 fn = GNUNET_malloc (MAX_PATH + 1);
623 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
625 SetErrnoFromWinError (lRet);
626 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
629 /* is the path relative? */
630 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
632 char szCurDir[MAX_PATH + 1];
634 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
635 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
637 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
638 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
641 buffer = GNUNET_malloc (MAX_PATH + 1);
642 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
653 * Give relative time in human-readable fancy format.
654 * This is one of the very few calls in the entire API that is
657 * @param delta time in milli seconds
658 * @param do_round are we allowed to round a bit?
659 * @return time as human-readable string
662 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
665 static char buf[128];
666 const char *unit = _( /* time unit */ "µs");
667 uint64_t dval = delta.rel_value_us;
669 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
671 if (0 == delta.rel_value_us)
673 if ( ( (GNUNET_YES == do_round) &&
674 (dval > 5 * 1000) ) ||
675 (0 == (dval % 1000) ))
678 unit = _( /* time unit */ "ms");
679 if ( ( (GNUNET_YES == do_round) &&
680 (dval > 5 * 1000) ) ||
681 (0 == (dval % 1000) ))
684 unit = _( /* time unit */ "s");
685 if ( ( (GNUNET_YES == do_round) &&
687 (0 == (dval % 60) ) )
690 unit = _( /* time unit */ "m");
691 if ( ( (GNUNET_YES == do_round) &&
696 unit = _( /* time unit */ "h");
697 if ( ( (GNUNET_YES == do_round) &&
703 unit = _( /* time unit */ "day");
705 unit = _( /* time unit */ "days");
711 GNUNET_snprintf (buf, sizeof (buf),
712 "%llu %s", dval, unit);
718 * "asctime", except for GNUnet time. Converts a GNUnet internal
719 * absolute time (which is in UTC) to a string in local time.
720 * Note that the returned value will be overwritten if this function
723 * @param t the absolute time to convert
724 * @return timestamp in human-readable form in local time
727 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
729 static char buf[255];
733 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
734 return _("end of time");
735 tt = t.abs_value_us / 1000LL / 1000LL;
736 tp = localtime (&tt);
737 /* This is hacky, but i don't know a way to detect libc character encoding.
738 * Just expect utf8 from glibc these days.
739 * As for msvcrt, use the wide variant, which always returns utf16
740 * (otherwise we'd have to detect current codepage or use W32API character
741 * set conversion routines to convert to UTF8).
744 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
747 static wchar_t wbuf[255];
751 wcsftime (wbuf, sizeof (wbuf) / sizeof (wchar_t),
752 L"%a %b %d %H:%M:%S %Y", tp);
754 ssize = sizeof (buf);
755 conved = u16_to_u8 (wbuf, sizeof (wbuf) / sizeof (wchar_t),
756 (uint8_t *) buf, &ssize);
757 if (conved != (uint8_t *) buf)
759 strncpy (buf, (char *) conved, sizeof (buf));
771 * Returns a pointer to a part of filename (allocates nothing)!
773 * @param filename filename to extract basename from
774 * @return short (base) name of the file (that is, everything following the
775 * last directory separator in filename. If filename ends with a
776 * directory separator, the result will be a zero-length string.
777 * If filename has no directory separators, the result is filename
781 GNUNET_STRINGS_get_short_name (const char *filename)
783 const char *short_fn = filename;
785 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
793 * Get the decoded value corresponding to a character according to Crockford
796 * @param a a character
797 * @return corresponding numeric value
800 getValue__ (unsigned char a)
816 /* also consider U to be V */
824 if ((a >= '0') && (a <= '9'))
826 if ((a >= 'a') && (a <= 'z'))
828 /* return (a - 'a' + 10); */
830 if ((a >= 'A') && (a <= 'Z'))
840 return (a - 'A' + 10 - dec);
847 * Convert binary data to ASCII encoding using Crockford Base32 encoding.
848 * Returns a pointer to the byte after the last byte in the string, that
849 * is where the 0-terminator was placed if there was room.
851 * @param data data to encode
852 * @param size size of data (in bytes)
853 * @param out buffer to fill
854 * @param out_size size of the buffer. Must be large enough to hold
855 * (size * 8 + 4) / 5 bytes
856 * @return pointer to the next byte in @a out or NULL on error.
859 GNUNET_STRINGS_data_to_string (const void *data,
865 * 32 characters for encoding
867 static char *encTable__ = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
872 const unsigned char *udata;
875 if (out_size < (size * 8 + 4) / 5)
884 while ((rpos < size) || (vbit > 0))
886 if ((rpos < size) && (vbit < 5))
888 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
893 bits <<= (5 - vbit); /* zero-padding */
894 GNUNET_assert (vbit == ((size * 8) % 5));
897 if (wpos >= out_size)
902 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
905 GNUNET_assert (0 == vbit);
913 * Return the base32crockford encoding of the given buffer.
915 * The returned string will be freshly allocated, and must be free'd
916 * with GNUNET_free().
918 * @param buffer with data
919 * @param size size of the buffer
920 * @return freshly allocated, null-terminated string
923 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
927 size_t len = size * 8;
933 str_buf = GNUNET_malloc (len + 1);
934 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len);
937 GNUNET_free (str_buf);
946 * Convert Crockford Base32hex encoding back to data.
947 * @a out_size must match exactly the size of the data before it was encoded.
949 * @param enc the encoding
950 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
951 * @param out location where to store the decoded data
952 * @param out_size size of the output buffer @a out
953 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
956 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
957 void *out, size_t out_size)
966 unsigned int encoded_len = out_size * 8;
972 return GNUNET_SYSERR;
977 if ((encoded_len % 5) > 0)
979 vbit = encoded_len % 5; /* padding! */
981 bits = (ret = getValue__ (enc[--rpos])) >> shift;
987 bits = (ret = getValue__ (enc[--rpos]));
989 if ((encoded_len + shift) / 5 != enclen)
990 return GNUNET_SYSERR;
992 return GNUNET_SYSERR;
998 return GNUNET_SYSERR;
1000 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
1002 return GNUNET_SYSERR;
1006 uout[--wpos] = (unsigned char) bits;
1013 return GNUNET_SYSERR;
1019 * Parse a path that might be an URI.
1021 * @param path path to parse. Must be NULL-terminated.
1022 * @param scheme_part a pointer to 'char *' where a pointer to a string that
1023 * represents the URI scheme will be stored. Can be NULL. The string is
1024 * allocated by the function, and should be freed by GNUNET_free() when
1025 * it is no longer needed.
1026 * @param path_part a pointer to 'const char *' where a pointer to the path
1027 * part of the URI will be stored. Can be NULL. Points to the same block
1028 * of memory as 'path', and thus must not be freed. Might point to '\0',
1029 * if path part is zero-length.
1030 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
1031 * an URI, '* scheme_part' and '*path_part' will remain unchanged
1032 * (if they weren't NULL).
1035 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
1036 const char **path_part)
1041 const char *post_scheme_part = NULL;
1042 len = strlen (path);
1043 for (end = 0, i = 0; !end && i < len; i++)
1048 if (path[i] == ':' && i > 0)
1053 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
1054 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
1055 || (path[i] == '.')))
1068 post_scheme_part = &path[i];
1075 if (post_scheme_part == NULL)
1079 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
1080 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path);
1081 (*scheme_part)[post_scheme_part - path] = '\0';
1084 *path_part = post_scheme_part;
1090 * Check whether @a filename is absolute or not, and if it's an URI
1092 * @param filename filename to check
1093 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1094 * assume it's not URI
1095 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1096 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1097 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1098 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1099 * The string is allocated by the function, and should be freed with
1100 * GNUNET_free(). Can be NULL.
1101 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1104 GNUNET_STRINGS_path_is_absolute (const char *filename,
1107 char **r_uri_scheme)
1112 const char *post_scheme_path;
1115 /* consider POSIX paths to be absolute too, even on W32,
1116 * as plibc expansion will fix them for us.
1118 if (filename[0] == '/')
1122 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1128 *r_uri_scheme = uri;
1130 GNUNET_free_non_null (uri);
1132 len = strlen(post_scheme_path);
1133 /* Special check for file:///c:/blah
1134 * We want to parse 'c:/', not '/c:/'
1136 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1137 post_scheme_path = &post_scheme_path[1];
1139 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1145 *r_is_uri = GNUNET_NO;
1148 len = strlen (filename);
1150 ((filename[0] >= 'A' && filename[0] <= 'Z')
1151 || (filename[0] >= 'a' && filename[0] <= 'z'))
1152 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1159 #define _IFMT 0170000 /* type of file */
1160 #define _IFLNK 0120000 /* symbolic link */
1161 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1166 * Perform @a checks on @a filename.
1168 * @param filename file to check
1169 * @param checks checks to perform
1170 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1171 * fails, #GNUNET_SYSERR when a check can't be performed
1174 GNUNET_STRINGS_check_filename (const char *filename,
1175 enum GNUNET_STRINGS_FilenameCheck checks)
1178 if ( (NULL == filename) || (filename[0] == '\0') )
1179 return GNUNET_SYSERR;
1180 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1181 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1183 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1184 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1185 | GNUNET_STRINGS_CHECK_IS_LINK)))
1187 if (0 != STAT (filename, &st))
1189 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1192 return GNUNET_SYSERR;
1195 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1196 if (!S_ISDIR (st.st_mode))
1198 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1199 if (!S_ISLNK (st.st_mode))
1206 * Tries to convert 'zt_addr' string to an IPv6 address.
1207 * The string is expected to have the format "[ABCD::01]:80".
1209 * @param zt_addr 0-terminated string. May be mangled by the function.
1210 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1211 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1212 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1213 * @return #GNUNET_OK if conversion succeded.
1214 * #GNUNET_SYSERR otherwise, in which
1215 * case the contents of @a r_buf are undefined.
1218 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1220 struct sockaddr_in6 *r_buf)
1222 char zbuf[addrlen + 1];
1228 return GNUNET_SYSERR;
1229 GNUNET_memcpy (zbuf, zt_addr, addrlen);
1232 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1233 _("IPv6 address did not start with `['\n"));
1234 return GNUNET_SYSERR;
1236 zbuf[addrlen] = '\0';
1237 port_colon = strrchr (zbuf, ':');
1238 if (NULL == port_colon)
1240 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1241 _("IPv6 address did contain ':' to separate port number\n"));
1242 return GNUNET_SYSERR;
1244 if (']' != *(port_colon - 1))
1246 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1247 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1248 return GNUNET_SYSERR;
1250 ret = SSCANF (port_colon, ":%u", &port);
1251 if ( (1 != ret) || (port > 65535) )
1253 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1254 _("IPv6 address did contain a valid port number after the last ':'\n"));
1255 return GNUNET_SYSERR;
1257 *(port_colon-1) = '\0';
1258 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1259 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1262 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1263 _("Invalid IPv6 address `%s': %s\n"),
1266 return GNUNET_SYSERR;
1268 r_buf->sin6_port = htons (port);
1269 r_buf->sin6_family = AF_INET6;
1270 #if HAVE_SOCKADDR_IN_SIN_LEN
1271 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1278 * Tries to convert 'zt_addr' string to an IPv4 address.
1279 * The string is expected to have the format "1.2.3.4:80".
1281 * @param zt_addr 0-terminated string. May be mangled by the function.
1282 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1283 * @param r_buf a buffer to fill.
1284 * @return #GNUNET_OK if conversion succeded.
1285 * #GNUNET_SYSERR otherwise, in which case
1286 * the contents of @a r_buf are undefined.
1289 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1290 struct sockaddr_in *r_buf)
1292 unsigned int temps[4];
1297 return GNUNET_SYSERR;
1298 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1300 return GNUNET_SYSERR;
1301 for (cnt = 0; cnt < 4; cnt++)
1302 if (temps[cnt] > 0xFF)
1303 return GNUNET_SYSERR;
1305 return GNUNET_SYSERR;
1306 r_buf->sin_family = AF_INET;
1307 r_buf->sin_port = htons (port);
1308 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1309 (temps[2] << 8) + temps[3]);
1310 #if HAVE_SOCKADDR_IN_SIN_LEN
1311 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1318 * Tries to convert @a addr string to an IP (v4 or v6) address.
1319 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1321 * @param addr a string, may not be 0-terminated.
1322 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1323 * 0-terminator should not be counted towards addrlen).
1324 * @param r_buf a buffer to fill.
1325 * @return #GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1326 * case the contents of r_buf are undefined.
1329 GNUNET_STRINGS_to_address_ip (const char *addr,
1331 struct sockaddr_storage *r_buf)
1334 return GNUNET_STRINGS_to_address_ipv6 (addr,
1336 (struct sockaddr_in6 *) r_buf);
1337 return GNUNET_STRINGS_to_address_ipv4 (addr,
1339 (struct sockaddr_in *) r_buf);
1344 * Makes a copy of argv that consists of a single memory chunk that can be
1345 * freed with a single call to GNUNET_free();
1347 static char *const *
1348 _make_continuous_arg_copy (int argc,
1351 size_t argvsize = 0;
1355 for (i = 0; i < argc; i++)
1356 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1357 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1358 p = (char *) &new_argv[argc + 1];
1359 for (i = 0; i < argc; i++)
1362 strcpy (p, argv[i]);
1363 p += strlen (argv[i]) + 1;
1365 new_argv[argc] = NULL;
1366 return (char *const *) new_argv;
1371 * Returns utf-8 encoded arguments.
1372 * Does nothing (returns a copy of argc and argv) on any platform
1374 * Returned argv has u8argv[u8argc] == NULL.
1375 * Returned argv is a single memory block, and can be freed with a single
1376 * GNUNET_free() call.
1378 * @param argc argc (as given by main())
1379 * @param argv argv (as given by main())
1380 * @param u8argc a location to store new argc in (though it's th same as argc)
1381 * @param u8argv a location to store new argv in
1382 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1385 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1392 char **split_u8argv;
1394 wcmd = GetCommandLineW ();
1396 return GNUNET_SYSERR;
1397 wargv = CommandLineToArgvW (wcmd, &wargc);
1399 return GNUNET_SYSERR;
1401 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1403 for (i = 0; i < wargc; i++)
1406 /* Hopefully it will allocate us NUL-terminated strings... */
1407 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1408 if (NULL == split_u8argv[i])
1411 for (j = 0; j < i; j++)
1412 free (split_u8argv[j]);
1413 GNUNET_free (split_u8argv);
1415 return GNUNET_SYSERR;
1419 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1422 for (i = 0; i < wargc; i++)
1423 free (split_u8argv[i]);
1424 free (split_u8argv);
1427 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1436 * Parse the given port policy. The format is
1437 * "[!]SPORT[-DPORT]".
1439 * @param port_policy string to parse
1440 * @param pp policy to fill in
1441 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1442 * @a port_policy is malformed
1445 parse_port_policy (const char *port_policy,
1446 struct GNUNET_STRINGS_PortPolicy *pp)
1456 pp->negate_portrange = GNUNET_YES;
1459 if (2 == sscanf (pos,
1468 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1469 _("Port not in range\n"));
1470 return GNUNET_SYSERR;
1472 pp->start_port = (uint16_t) s;
1473 pp->end_port = (uint16_t) e;
1476 if (1 == sscanf (pos,
1484 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1485 _("Port not in range\n"));
1486 return GNUNET_SYSERR;
1489 pp->start_port = (uint16_t) s;
1490 pp->end_port = (uint16_t) s;
1493 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1494 _("Malformed port policy `%s'\n"),
1496 return GNUNET_SYSERR;
1501 * Parse an IPv4 network policy. The argument specifies a list of
1502 * subnets. The format is
1503 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1504 * be terminated with a semicolon). The network must be given in
1505 * dotted-decimal notation. The netmask can be given in CIDR notation
1506 * (/16) or in dotted-decimal (/255.255.0.0).
1508 * @param routeListX a string specifying the IPv4 subnets
1509 * @return the converted list, terminated with all zeros;
1510 * NULL if the synatx is flawed
1512 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1513 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1521 unsigned int temps[8];
1523 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1528 if (NULL == routeListX)
1530 len = strlen (routeListX);
1533 routeList = GNUNET_strdup (routeListX);
1535 for (i = 0; i < len; i++)
1536 if (routeList[i] == ';')
1538 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1543 for (colon = pos; ':' != routeList[colon]; colon++)
1544 if ( (';' == routeList[colon]) ||
1545 ('\0' == routeList[colon]) )
1547 for (end = colon; ';' != routeList[end]; end++)
1548 if ('\0' == routeList[end])
1550 if ('\0' == routeList[end])
1552 routeList[end] = '\0';
1553 if (':' == routeList[colon])
1555 routeList[colon] = '\0';
1556 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1561 SSCANF (&routeList[pos],
1562 "%u.%u.%u.%u/%u.%u.%u.%u",
1573 for (j = 0; j < 8; j++)
1574 if (temps[j] > 0xFF)
1576 LOG (GNUNET_ERROR_TYPE_WARNING,
1577 _("Invalid format for IP: `%s'\n"),
1579 GNUNET_free (result);
1580 GNUNET_free (routeList);
1583 result[i].network.s_addr =
1584 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1586 result[i].netmask.s_addr =
1587 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1593 /* try second notation */
1595 SSCANF (&routeList[pos],
1604 for (j = 0; j < 4; j++)
1605 if (temps[j] > 0xFF)
1607 LOG (GNUNET_ERROR_TYPE_WARNING,
1608 _("Invalid format for IP: `%s'\n"),
1610 GNUNET_free (result);
1611 GNUNET_free (routeList);
1614 result[i].network.s_addr =
1615 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1617 if ((slash <= 32) && (slash >= 0))
1619 result[i].netmask.s_addr = 0;
1622 result[i].netmask.s_addr =
1623 (result[i].netmask.s_addr >> 1) + 0x80000000;
1626 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1633 LOG (GNUNET_ERROR_TYPE_WARNING,
1634 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1636 GNUNET_free (result);
1637 GNUNET_free (routeList);
1638 return NULL; /* error */
1641 /* try third notation */
1644 SSCANF (&routeList[pos],
1652 for (j = 0; j < 4; j++)
1653 if (temps[j] > 0xFF)
1655 LOG (GNUNET_ERROR_TYPE_WARNING,
1656 _("Invalid format for IP: `%s'\n"),
1658 GNUNET_free (result);
1659 GNUNET_free (routeList);
1662 result[i].network.s_addr =
1663 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1665 result[i].netmask.s_addr = 0;
1668 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1671 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1676 LOG (GNUNET_ERROR_TYPE_WARNING,
1677 _("Invalid format for IP: `%s'\n"),
1679 GNUNET_free (result);
1680 GNUNET_free (routeList);
1681 return NULL; /* error */
1683 if (pos < strlen (routeList))
1685 LOG (GNUNET_ERROR_TYPE_WARNING,
1686 _("Invalid format: `%s'\n"),
1688 GNUNET_free (result);
1689 GNUNET_free (routeList);
1690 return NULL; /* oops */
1692 GNUNET_free (routeList);
1693 return result; /* ok */
1698 * Parse an IPv6 network policy. The argument specifies a list of
1699 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1700 * (no whitespace, must be terminated with a semicolon). The network
1701 * must be given in colon-hex notation. The netmask must be given in
1702 * CIDR notation (/16) or can be omitted to specify a single host.
1703 * Note that the netmask is mandatory if ports are specified.
1705 * @param routeListX a string specifying the policy
1706 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1708 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1709 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1719 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1725 if (NULL == routeListX)
1727 len = strlen (routeListX);
1730 routeList = GNUNET_strdup (routeListX);
1732 for (i = 0; i < len; i++)
1733 if (';' == routeList[i])
1735 if (';' != routeList[len - 1])
1737 LOG (GNUNET_ERROR_TYPE_WARNING,
1738 _("Invalid network notation (does not end with ';': `%s')\n"),
1740 GNUNET_free (routeList);
1744 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1750 while (';' != routeList[pos])
1753 while ((slash >= start) && (routeList[slash] != '/'))
1758 memset (&result[i].netmask,
1760 sizeof (struct in6_addr));
1765 routeList[pos] = '\0';
1766 for (colon = pos; ':' != routeList[colon]; colon--)
1767 if ('/' == routeList[colon])
1769 if (':' == routeList[colon])
1771 routeList[colon] = '\0';
1772 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1775 GNUNET_free (result);
1776 GNUNET_free (routeList);
1780 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1784 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1787 LOG (GNUNET_ERROR_TYPE_WARNING,
1788 _("Wrong format `%s' for netmask\n"),
1789 &routeList[slash + 1]);
1793 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1795 GNUNET_free (result);
1796 GNUNET_free (routeList);
1802 result[i].netmask.s6_addr[off++] = 0xFF;
1807 result[i].netmask.s6_addr[off] =
1808 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1813 routeList[slash] = '\0';
1814 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1818 LOG (GNUNET_ERROR_TYPE_WARNING,
1819 _("Wrong format `%s' for network\n"),
1820 &routeList[slash + 1]);
1822 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1824 GNUNET_free (result);
1825 GNUNET_free (routeList);
1831 GNUNET_free (routeList);
1837 /** ******************** Base64 encoding ***********/
1839 #define FILLCHAR '='
1841 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/";
1845 * Encode into Base64.
1847 * @param data the data to encode
1848 * @param len the length of the input
1849 * @param output where to write the output (*output should be NULL,
1851 * @return the size of the output
1854 GNUNET_STRINGS_base64_encode (const char *data,
1864 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8);
1866 for (i = 0; i < len; ++i)
1868 c = (data[i] >> 2) & 0x3f;
1869 opt[ret++] = cvt[(int) c];
1870 c = (data[i] << 4) & 0x3f;
1872 c |= (data[i] >> 4) & 0x0f;
1873 opt[ret++] = cvt[(int) c];
1876 c = (data[i] << 2) & 0x3f;
1878 c |= (data[i] >> 6) & 0x03;
1879 opt[ret++] = cvt[(int) c];
1884 opt[ret++] = FILLCHAR;
1889 opt[ret++] = cvt[(int) c];
1893 opt[ret++] = FILLCHAR;
1896 opt[ret++] = FILLCHAR;
1900 #define cvtfind(a)( (((a) >= 'A')&&((a) <= 'Z'))? (a)-'A'\
1901 :(((a)>='a')&&((a)<='z')) ? (a)-'a'+26\
1902 :(((a)>='0')&&((a)<='9')) ? (a)-'0'+52\
1904 :((a) == '/') ? 63 : -1)
1908 * Decode from Base64.
1910 * @param data the data to encode
1911 * @param len the length of the input
1912 * @param output where to write the output (*output should be NULL,
1914 * @return the size of the output
1917 GNUNET_STRINGS_base64_decode (const char *data,
1918 size_t len, char **output)
1925 #define CHECK_CRLF while (data[i] == '\r' || data[i] == '\n') {\
1926 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, "ignoring CR/LF\n"); \
1928 if (i >= len) goto END; \
1931 *output = GNUNET_malloc ((len * 3 / 4) + 8);
1932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1933 "base64_decode decoding len=%d\n",
1935 for (i = 0; i < len; ++i)
1938 if (FILLCHAR == data[i])
1940 c = (char) cvtfind (data[i]);
1943 c1 = (char) cvtfind (data[i]);
1944 c = (c << 2) | ((c1 >> 4) & 0x3);
1945 (*output)[ret++] = c;
1952 c = (char) cvtfind (c);
1953 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
1954 (*output)[ret++] = c1;
1963 c1 = (char) cvtfind (c1);
1964 c = ((c << 6) & 0xc0) | c1;
1965 (*output)[ret++] = c;
1976 /* end of strings.c */