2 This file is part of GNUnet.
3 (C) 2005-2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/strings.c
23 * @brief string functions
25 * @author Christian Grothoff
32 #include "gnunet_util_lib.h"
37 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
39 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
43 * Fill a buffer of the given size with
44 * count 0-terminated strings (given as varargs).
45 * If "buffer" is NULL, only compute the amount of
46 * space required (sum of "strlen(arg)+1").
48 * Unlike using "snprintf" with "%s", this function
49 * will add 0-terminators after each string. The
50 * "GNUNET_string_buffer_tokenize" function can be
51 * used to parse the buffer back into individual
54 * @param buffer the buffer to fill with strings, can
55 * be NULL in which case only the necessary
56 * amount of space will be calculated
57 * @param size number of bytes available in buffer
58 * @param count number of strings that follow
59 * @param ... count 0-terminated strings to copy to buffer
60 * @return number of bytes written to the buffer
61 * (or number of bytes that would have been written)
64 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
75 s = va_arg (ap, const char *);
77 slen = strlen (s) + 1;
80 GNUNET_assert (needed + slen <= size);
81 memcpy (&buffer[needed], s, slen);
92 * Given a buffer of a given size, find "count"
93 * 0-terminated strings in the buffer and assign
94 * the count (varargs) of type "const char**" to the
95 * locations of the respective strings in the
98 * @param buffer the buffer to parse
99 * @param size size of the buffer
100 * @param count number of strings to locate
101 * @return offset of the character after the last 0-termination
102 * in the buffer, or 0 on error.
105 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
106 unsigned int count, ...)
114 va_start (ap, count);
117 r = va_arg (ap, const char **);
120 while ((needed < size) && (buffer[needed] != '\0'))
125 return 0; /* error */
128 needed++; /* skip 0-termination */
137 * Convert a given filesize into a fancy human-readable format.
139 * @param size number of bytes
140 * @return fancy representation of the size (possibly rounded) for humans
143 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
145 const char *unit = _( /* size unit */ "b");
168 ret = GNUNET_malloc (32);
169 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
175 * Unit conversion table entry for 'convert_with_table'.
177 struct ConversionTable
180 * Name of the unit (or NULL for end of table).
185 * Factor to apply for this unit.
187 unsigned long long value;
192 * Convert a string of the form "4 X 5 Y" into a numeric value
193 * by interpreting "X" and "Y" as units and then multiplying
194 * the numbers with the values associated with the respective
195 * unit from the conversion table.
197 * @param input input string to parse
198 * @param table table with the conversion of unit names to numbers
199 * @param output where to store the result
200 * @return GNUNET_OK on success, GNUNET_SYSERR on error
203 convert_with_table (const char *input,
204 const struct ConversionTable *table,
205 unsigned long long *output)
207 unsigned long long ret;
210 unsigned long long last;
215 in = GNUNET_strdup (input);
216 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
221 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
223 if (table[i].name != NULL)
225 last *= table[i].value;
226 break; /* next tok */
233 last = strtoull (tok, &endptr, 10);
234 if ((0 != errno) || (endptr == tok))
237 return GNUNET_SYSERR; /* expected number */
239 if ('\0' == endptr[0])
240 break; /* next tok */
242 tok = endptr; /* and re-check (handles times like "10s") */
244 } while (GNUNET_YES);
254 * Convert a given fancy human-readable size to bytes.
256 * @param fancy_size human readable string (i.e. 1 MB)
257 * @param size set to the size in bytes
258 * @return GNUNET_OK on success, GNUNET_SYSERR on error
261 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
262 unsigned long long *size)
264 static const struct ConversionTable table[] =
269 { "MiB", 1024 * 1024},
270 { "MB", 1000 * 1000},
271 { "GiB", 1024 * 1024 * 1024},
272 { "GB", 1000 * 1000 * 1000},
273 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
274 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
275 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
276 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
277 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
278 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
282 return convert_with_table (fancy_size,
289 * Convert a given fancy human-readable time to our internal
292 * @param fancy_time human readable string (i.e. 1 minute)
293 * @param rtime set to the relative time
294 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
297 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
298 struct GNUNET_TIME_Relative *rtime)
300 static const struct ConversionTable table[] =
304 { "s", 1000 * 1000LL },
305 { "\"", 1000 * 1000LL },
306 { "m", 60 * 1000 * 1000LL},
307 { "min", 60 * 1000 * 1000LL},
308 { "minutes", 60 * 1000 * 1000LL},
309 { "'", 60 * 1000 * 1000LL},
310 { "h", 60 * 60 * 1000 * 1000LL},
311 { "d", 24 * 60 * 60 * 1000LL * 1000LL},
312 { "day", 24 * 60 * 60 * 1000LL * 1000LL},
313 { "days", 24 * 60 * 60 * 1000LL * 1000LL},
314 { "a", 31536000000000LL /* year */ },
318 unsigned long long val;
320 if (0 == strcasecmp ("forever", fancy_time))
322 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
325 ret = convert_with_table (fancy_time,
328 rtime->rel_value_us = (uint64_t) val;
334 * Convert a given fancy human-readable time to our internal
335 * representation. The human-readable time is expected to be
336 * in local time, whereas the returned value will be in UTC.
338 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
339 * @param atime set to the absolute time
340 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
343 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
344 struct GNUNET_TIME_Absolute *atime)
349 if (0 == strcasecmp ("end of time", fancy_time))
351 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
354 memset (&tv, 0, sizeof (tv));
355 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
356 (NULL == strptime (fancy_time, "%c", &tv)) &&
357 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
358 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
359 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
360 (NULL == strptime (fancy_time, "%x", &tv)) &&
361 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
362 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
363 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
364 (NULL == strptime (fancy_time, "%Y", &tv)) )
365 return GNUNET_SYSERR;
367 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL);
369 atime->abs_value_us -= 1000LL * 1000LL * timezone;
370 #elif defined WINDOWS
373 TIME_ZONE_INFORMATION tzi;
374 tzv = GetTimeZoneInformation (&tzi);
375 if (TIME_ZONE_ID_INVALID != tzv)
377 atime->abs_value_us -= 1000LL * 1000LL * tzi.Bias * 60LL;
386 * Convert the len characters long character sequence
387 * given in input that is in the given input charset
388 * to a string in given output charset.
390 * @param input input string
391 * @param len number of bytes in @a input
392 * @param input_charset character set used for @a input
393 * @param output_charset desired character set for the return value
394 * @return the converted string (0-terminated),
395 * if conversion fails, a copy of the orignal
396 * string is returned.
399 GNUNET_STRINGS_conv (const char *input,
401 const char *input_charset,
402 const char *output_charset)
406 char *encoded_string;
407 size_t u8_string_length;
408 size_t encoded_string_length;
410 u8_string = u8_conv_from_encoding (input_charset,
415 if (NULL == u8_string)
417 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
420 if (0 == strcmp (output_charset, "UTF-8"))
422 ret = GNUNET_malloc (u8_string_length + 1);
423 memcpy (ret, u8_string, u8_string_length);
424 ret[u8_string_length] = '\0';
428 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
429 u8_string, u8_string_length,
431 &encoded_string_length);
433 if (NULL == encoded_string)
435 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
438 ret = GNUNET_malloc (encoded_string_length + 1);
439 memcpy (ret, encoded_string, encoded_string_length);
440 ret[encoded_string_length] = '\0';
441 free (encoded_string);
444 LOG (GNUNET_ERROR_TYPE_WARNING, _("Character sets requested were `%s'->`%s'\n"),
445 "UTF-8", output_charset);
446 ret = GNUNET_malloc (len + 1);
447 memcpy (ret, input, len);
454 * Convert the len characters long character sequence
455 * given in input that is in the given charset
458 * @param input the input string (not necessarily 0-terminated)
459 * @param len the number of bytes in the @a input
460 * @param charset character set to convert from
461 * @return the converted string (0-terminated),
462 * if conversion fails, a copy of the orignal
463 * string is returned.
466 GNUNET_STRINGS_to_utf8 (const char *input,
470 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
475 * Convert the len bytes-long UTF-8 string
476 * given in input to the given charset.
478 * @param input the input string (not necessarily 0-terminated)
479 * @param len the number of bytes in the @a input
480 * @param charset character set to convert to
481 * @return the converted string (0-terminated),
482 * if conversion fails, a copy of the orignal
483 * string is returned.
486 GNUNET_STRINGS_from_utf8 (const char *input,
490 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
495 * Convert the utf-8 input string to lowercase.
496 * Output needs to be allocated appropriately.
498 * @param input input string
499 * @param output output buffer
502 GNUNET_STRINGS_utf8_tolower (const char *input,
508 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
509 NULL, UNINORM_NFD, NULL, &len);
510 memcpy(output, tmp_in, len);
517 * Convert the utf-8 input string to uppercase.
518 * Output needs to be allocated appropriately.
520 * @param input input string
521 * @param output output buffer
524 GNUNET_STRINGS_utf8_toupper(const char *input,
530 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
531 NULL, UNINORM_NFD, NULL, &len);
532 memcpy (output, tmp_in, len);
539 * Complete filename (a la shell) from abbrevition.
540 * @param fil the name of the file, may contain ~/ or
541 * be relative to the current directory
542 * @returns the full file name,
543 * NULL is returned on error
546 GNUNET_STRINGS_filename_expand (const char *fil)
563 if (fil[0] == DIR_SEPARATOR)
564 /* absolute path, just copy */
565 return GNUNET_strdup (fil);
568 fm = getenv ("HOME");
571 LOG (GNUNET_ERROR_TYPE_WARNING,
572 _("Failed to expand `$HOME': environment variable `HOME' not set"));
575 fm = GNUNET_strdup (fm);
576 /* do not copy '~' */
579 /* skip over dir seperator to be consistent */
580 if (fil_ptr[0] == DIR_SEPARATOR)
591 buffer = GNUNET_malloc (len);
592 if (getcwd (buffer, len) != NULL)
597 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
600 GNUNET_free (buffer);
603 GNUNET_free (buffer);
608 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
609 buffer = getenv ("PWD"); /* alternative */
611 fm = GNUNET_strdup (buffer);
614 fm = GNUNET_strdup ("./"); /* give up */
616 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
617 buffer = GNUNET_malloc (n);
618 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
619 (fm[strlen (fm) - 1] ==
620 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
624 fn = GNUNET_malloc (MAX_PATH + 1);
626 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
628 SetErrnoFromWinError (lRet);
629 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
632 /* is the path relative? */
633 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
635 char szCurDir[MAX_PATH + 1];
637 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
638 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
640 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
641 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
644 buffer = GNUNET_malloc (MAX_PATH + 1);
645 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
656 * Give relative time in human-readable fancy format.
657 * This is one of the very few calls in the entire API that is
660 * @param delta time in milli seconds
661 * @param do_round are we allowed to round a bit?
662 * @return time as human-readable string
665 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
668 static char buf[128];
669 const char *unit = _( /* time unit */ "µs");
670 uint64_t dval = delta.rel_value_us;
672 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
674 if (0 == delta.rel_value_us)
676 if ( ( (GNUNET_YES == do_round) &&
677 (dval > 5 * 1000) ) ||
678 (0 == (dval % 1000) ))
681 unit = _( /* time unit */ "ms");
682 if ( ( (GNUNET_YES == do_round) &&
683 (dval > 5 * 1000) ) ||
684 (0 == (dval % 1000) ))
687 unit = _( /* time unit */ "s");
688 if ( ( (GNUNET_YES == do_round) &&
690 (0 == (dval % 60) ) )
693 unit = _( /* time unit */ "m");
694 if ( ( (GNUNET_YES == do_round) &&
699 unit = _( /* time unit */ "h");
700 if ( ( (GNUNET_YES == do_round) &&
706 unit = _( /* time unit */ "day");
708 unit = _( /* time unit */ "days");
714 GNUNET_snprintf (buf, sizeof (buf),
715 "%llu %s", dval, unit);
721 * "asctime", except for GNUnet time. Converts a GNUnet internal
722 * absolute time (which is in UTC) to a string in local time.
723 * Note that the returned value will be overwritten if this function
726 * @param t the absolute time to convert
727 * @return timestamp in human-readable form in local time
730 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
732 static char buf[255];
736 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
737 return _("end of time");
738 tt = t.abs_value_us / 1000LL / 1000LL;
740 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
747 * Returns a pointer to a part of filename (allocates nothing)!
749 * @param filename filename to extract basename from
750 * @return short (base) name of the file (that is, everything following the
751 * last directory separator in filename. If filename ends with a
752 * directory separator, the result will be a zero-length string.
753 * If filename has no directory separators, the result is filename
757 GNUNET_STRINGS_get_short_name (const char *filename)
759 const char *short_fn = filename;
761 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
769 * Get the numeric value corresponding to a character.
771 * @param a a character
772 * @return corresponding numeric value
775 getValue__ (unsigned char a)
777 if ((a >= '0') && (a <= '9'))
779 if ((a >= 'A') && (a <= 'V'))
780 return (a - 'A' + 10);
786 * Convert binary data to ASCII encoding. The ASCII encoding is rather
787 * GNUnet specific. It was chosen such that it only uses characters
788 * in [0-9A-V], can be produced without complex arithmetics and uses a
789 * small number of characters.
790 * Does not append 0-terminator, but returns a pointer to the place where
791 * it should be placed, if needed.
793 * @param data data to encode
794 * @param size size of data (in bytes)
795 * @param out buffer to fill
796 * @param out_size size of the buffer. Must be large enough to hold
797 * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
798 * @return pointer to the next byte in 'out' or NULL on error.
801 GNUNET_STRINGS_data_to_string (const void *data, size_t size, char *out, size_t out_size)
804 * 32 characters for encoding
806 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
811 const unsigned char *udata;
813 GNUNET_assert (data != NULL);
814 GNUNET_assert (out != NULL);
816 if (out_size < (((size*8) + ((size*8) % 5)) % 5))
825 while ((rpos < size) || (vbit > 0))
827 if ((rpos < size) && (vbit < 5))
829 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
834 bits <<= (5 - vbit); /* zero-padding */
835 GNUNET_assert (vbit == ((size * 8) % 5));
838 if (wpos >= out_size)
843 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
846 GNUNET_assert (vbit == 0);
854 * Convert ASCII encoding back to data
855 * out_size must match exactly the size of the data before it was encoded.
857 * @param enc the encoding
858 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
859 * @param out location where to store the decoded data
860 * @param out_size size of the output buffer
861 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
864 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
865 void *out, size_t out_size)
874 unsigned int encoded_len = out_size * 8;
880 return GNUNET_SYSERR;
885 if ((encoded_len % 5) > 0)
887 vbit = encoded_len % 5; /* padding! */
889 bits = (ret = getValue__ (enc[--rpos])) >> (5 - (encoded_len % 5));
895 bits = (ret = getValue__ (enc[--rpos]));
897 if ((encoded_len + shift) / 5 != enclen)
898 return GNUNET_SYSERR;
900 return GNUNET_SYSERR;
906 return GNUNET_SYSERR;
908 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
910 return GNUNET_SYSERR;
914 uout[--wpos] = (unsigned char) bits;
921 return GNUNET_SYSERR;
927 * Parse a path that might be an URI.
929 * @param path path to parse. Must be NULL-terminated.
930 * @param scheme_part a pointer to 'char *' where a pointer to a string that
931 * represents the URI scheme will be stored. Can be NULL. The string is
932 * allocated by the function, and should be freed by GNUNET_free() when
933 * it is no longer needed.
934 * @param path_part a pointer to 'const char *' where a pointer to the path
935 * part of the URI will be stored. Can be NULL. Points to the same block
936 * of memory as 'path', and thus must not be freed. Might point to '\0',
937 * if path part is zero-length.
938 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
939 * an URI, '* scheme_part' and '*path_part' will remain unchanged
940 * (if they weren't NULL).
943 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
944 const char **path_part)
949 const char *post_scheme_part = NULL;
951 for (end = 0, i = 0; !end && i < len; i++)
956 if (path[i] == ':' && i > 0)
961 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
962 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
963 || (path[i] == '.')))
976 post_scheme_part = &path[i];
983 if (post_scheme_part == NULL)
987 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
988 memcpy (*scheme_part, path, post_scheme_part - path);
989 (*scheme_part)[post_scheme_part - path] = '\0';
992 *path_part = post_scheme_part;
998 * Check whether @a filename is absolute or not, and if it's an URI
1000 * @param filename filename to check
1001 * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
1002 * assume it's not URI
1003 * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if @a filename
1004 * is URI and to #GNUNET_NO otherwise. Can be NULL. If @a can_be_uri is
1005 * not #GNUNET_YES, `* r_is_uri` is set to #GNUNET_NO.
1006 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
1007 * The string is allocated by the function, and should be freed with
1008 * GNUNET_free(). Can be NULL.
1009 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1012 GNUNET_STRINGS_path_is_absolute (const char *filename,
1015 char **r_uri_scheme)
1020 const char *post_scheme_path;
1023 /* consider POSIX paths to be absolute too, even on W32,
1024 * as plibc expansion will fix them for us.
1026 if (filename[0] == '/')
1030 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1036 *r_uri_scheme = uri;
1038 GNUNET_free_non_null (uri);
1040 len = strlen(post_scheme_path);
1041 /* Special check for file:///c:/blah
1042 * We want to parse 'c:/', not '/c:/'
1044 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1045 post_scheme_path = &post_scheme_path[1];
1047 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1053 *r_is_uri = GNUNET_NO;
1056 len = strlen (filename);
1058 ((filename[0] >= 'A' && filename[0] <= 'Z')
1059 || (filename[0] >= 'a' && filename[0] <= 'z'))
1060 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1067 #define _IFMT 0170000 /* type of file */
1068 #define _IFLNK 0120000 /* symbolic link */
1069 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1074 * Perform @a checks on @a filename.
1076 * @param filename file to check
1077 * @param checks checks to perform
1078 * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
1079 * fails, #GNUNET_SYSERR when a check can't be performed
1082 GNUNET_STRINGS_check_filename (const char *filename,
1083 enum GNUNET_STRINGS_FilenameCheck checks)
1086 if ( (NULL == filename) || (filename[0] == '\0') )
1087 return GNUNET_SYSERR;
1088 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1089 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1091 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1092 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1093 | GNUNET_STRINGS_CHECK_IS_LINK)))
1095 if (0 != STAT (filename, &st))
1097 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1100 return GNUNET_SYSERR;
1103 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1104 if (!S_ISDIR (st.st_mode))
1106 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1107 if (!S_ISLNK (st.st_mode))
1114 * Tries to convert 'zt_addr' string to an IPv6 address.
1115 * The string is expected to have the format "[ABCD::01]:80".
1117 * @param zt_addr 0-terminated string. May be mangled by the function.
1118 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1119 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1120 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1121 * @return #GNUNET_OK if conversion succeded.
1122 * #GNUNET_SYSERR otherwise, in which
1123 * case the contents of @a r_buf are undefined.
1126 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1128 struct sockaddr_in6 *r_buf)
1130 char zbuf[addrlen + 1];
1136 return GNUNET_SYSERR;
1137 memcpy (zbuf, zt_addr, addrlen);
1140 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1141 _("IPv6 address did not start with `['\n"));
1142 return GNUNET_SYSERR;
1144 zbuf[addrlen] = '\0';
1145 port_colon = strrchr (zbuf, ':');
1146 if (NULL == port_colon)
1148 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1149 _("IPv6 address did contain ':' to separate port number\n"));
1150 return GNUNET_SYSERR;
1152 if (']' != *(port_colon - 1))
1154 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1155 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1156 return GNUNET_SYSERR;
1158 ret = SSCANF (port_colon, ":%u", &port);
1159 if ( (1 != ret) || (port > 65535) )
1161 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1162 _("IPv6 address did contain a valid port number after the last ':'\n"));
1163 return GNUNET_SYSERR;
1165 *(port_colon-1) = '\0';
1166 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1167 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1170 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1171 _("Invalid IPv6 address `%s': %s\n"),
1174 return GNUNET_SYSERR;
1176 r_buf->sin6_port = htons (port);
1177 r_buf->sin6_family = AF_INET6;
1178 #if HAVE_SOCKADDR_IN_SIN_LEN
1179 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1186 * Tries to convert 'zt_addr' string to an IPv4 address.
1187 * The string is expected to have the format "1.2.3.4:80".
1189 * @param zt_addr 0-terminated string. May be mangled by the function.
1190 * @param addrlen length of @a zt_addr (not counting 0-terminator).
1191 * @param r_buf a buffer to fill.
1192 * @return #GNUNET_OK if conversion succeded.
1193 * #GNUNET_SYSERR otherwise, in which case
1194 * the contents of @a r_buf are undefined.
1197 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1198 struct sockaddr_in *r_buf)
1200 unsigned int temps[4];
1205 return GNUNET_SYSERR;
1206 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1208 return GNUNET_SYSERR;
1209 for (cnt = 0; cnt < 4; cnt++)
1210 if (temps[cnt] > 0xFF)
1211 return GNUNET_SYSERR;
1213 return GNUNET_SYSERR;
1214 r_buf->sin_family = AF_INET;
1215 r_buf->sin_port = htons (port);
1216 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1217 (temps[2] << 8) + temps[3]);
1218 #if HAVE_SOCKADDR_IN_SIN_LEN
1219 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1226 * Tries to convert @a addr string to an IP (v4 or v6) address.
1227 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1229 * @param addr a string, may not be 0-terminated.
1230 * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
1231 * 0-terminator should not be counted towards addrlen).
1232 * @param r_buf a buffer to fill.
1233 * @return #GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1234 * case the contents of r_buf are undefined.
1237 GNUNET_STRINGS_to_address_ip (const char *addr,
1239 struct sockaddr_storage *r_buf)
1242 return GNUNET_STRINGS_to_address_ipv6 (addr,
1244 (struct sockaddr_in6 *) r_buf);
1245 return GNUNET_STRINGS_to_address_ipv4 (addr,
1247 (struct sockaddr_in *) r_buf);
1252 * Makes a copy of argv that consists of a single memory chunk that can be
1253 * freed with a single call to GNUNET_free ();
1255 static char *const *
1256 _make_continuous_arg_copy (int argc,
1259 size_t argvsize = 0;
1263 for (i = 0; i < argc; i++)
1264 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1265 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1266 p = (char *) &new_argv[argc + 1];
1267 for (i = 0; i < argc; i++)
1270 strcpy (p, argv[i]);
1271 p += strlen (argv[i]) + 1;
1273 new_argv[argc] = NULL;
1274 return (char *const *) new_argv;
1279 * Returns utf-8 encoded arguments.
1280 * Does nothing (returns a copy of argc and argv) on any platform
1282 * Returned argv has u8argv[u8argc] == NULL.
1283 * Returned argv is a single memory block, and can be freed with a single
1284 * GNUNET_free () call.
1286 * @param argc argc (as given by main())
1287 * @param argv argv (as given by main())
1288 * @param u8argc a location to store new argc in (though it's th same as argc)
1289 * @param u8argv a location to store new argv in
1290 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1293 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1300 char **split_u8argv;
1302 wcmd = GetCommandLineW ();
1304 return GNUNET_SYSERR;
1305 wargv = CommandLineToArgvW (wcmd, &wargc);
1307 return GNUNET_SYSERR;
1309 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1311 for (i = 0; i < wargc; i++)
1314 /* Hopefully it will allocate us NUL-terminated strings... */
1315 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1316 if (NULL == split_u8argv[i])
1319 for (j = 0; j < i; j++)
1320 free (split_u8argv[j]);
1321 GNUNET_free (split_u8argv);
1323 return GNUNET_SYSERR;
1327 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1330 for (i = 0; i < wargc; i++)
1331 free (split_u8argv[i]);
1332 free (split_u8argv);
1335 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1344 * Parse the given port policy. The format is
1345 * "[!]SPORT[-DPORT]".
1347 * @param port_policy string to parse
1348 * @param pp policy to fill in
1349 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
1350 * @a port_policy is malformed
1353 parse_port_policy (const char *port_policy,
1354 struct GNUNET_STRINGS_PortPolicy *pp)
1364 pp->negate_portrange = GNUNET_YES;
1367 if (2 == sscanf (pos,
1376 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1377 _("Port not in range\n"));
1378 return GNUNET_SYSERR;
1380 pp->start_port = (uint16_t) s;
1381 pp->end_port = (uint16_t) e;
1384 if (1 == sscanf (pos,
1392 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1393 _("Port not in range\n"));
1394 return GNUNET_SYSERR;
1397 pp->start_port = (uint16_t) s;
1398 pp->end_port = (uint16_t) s;
1401 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1402 _("Malformed port policy `%s'\n"),
1404 return GNUNET_SYSERR;
1409 * Parse an IPv4 network policy. The argument specifies a list of
1410 * subnets. The format is
1411 * <tt>(network[/netmask][:SPORT[-DPORT]];)*</tt> (no whitespace, must
1412 * be terminated with a semicolon). The network must be given in
1413 * dotted-decimal notation. The netmask can be given in CIDR notation
1414 * (/16) or in dotted-decimal (/255.255.0.0).
1416 * @param routeListX a string specifying the IPv4 subnets
1417 * @return the converted list, terminated with all zeros;
1418 * NULL if the synatx is flawed
1420 struct GNUNET_STRINGS_IPv4NetworkPolicy *
1421 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1429 unsigned int temps[8];
1431 struct GNUNET_STRINGS_IPv4NetworkPolicy *result;
1436 if (NULL == routeListX)
1438 len = strlen (routeListX);
1441 routeList = GNUNET_strdup (routeListX);
1443 for (i = 0; i < len; i++)
1444 if (routeList[i] == ';')
1446 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * (count + 1));
1451 for (colon = pos; ':' != routeList[colon]; colon++)
1452 if ( (';' == routeList[colon]) ||
1453 ('\0' == routeList[colon]) )
1456 for (end = colon; ';' != routeList[end]; end++)
1457 if ('\0' == routeList[end])
1459 if ('\0' == routeList[end])
1461 routeList[end] = '\0';
1462 if (':' == routeList[colon])
1464 routeList[colon] = '\0';
1465 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1470 SSCANF (&routeList[pos],
1471 "%u.%u.%u.%u/%u.%u.%u.%u",
1482 for (j = 0; j < 8; j++)
1483 if (temps[j] > 0xFF)
1485 LOG (GNUNET_ERROR_TYPE_WARNING,
1486 _("Invalid format for IP: `%s'\n"),
1488 GNUNET_free (result);
1489 GNUNET_free (routeList);
1492 result[i].network.s_addr =
1493 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1495 result[i].netmask.s_addr =
1496 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
1502 /* try second notation */
1504 SSCANF (&routeList[pos],
1513 for (j = 0; j < 4; j++)
1514 if (temps[j] > 0xFF)
1516 LOG (GNUNET_ERROR_TYPE_WARNING,
1517 _("Invalid format for IP: `%s'\n"),
1519 GNUNET_free (result);
1520 GNUNET_free (routeList);
1523 result[i].network.s_addr =
1524 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1526 if ((slash <= 32) && (slash >= 0))
1528 result[i].netmask.s_addr = 0;
1531 result[i].netmask.s_addr =
1532 (result[i].netmask.s_addr >> 1) + 0x80000000;
1535 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1542 LOG (GNUNET_ERROR_TYPE_WARNING,
1543 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1545 GNUNET_free (result);
1546 GNUNET_free (routeList);
1547 return NULL; /* error */
1550 /* try third notation */
1553 SSCANF (&routeList[pos],
1561 for (j = 0; j < 4; j++)
1562 if (temps[j] > 0xFF)
1564 LOG (GNUNET_ERROR_TYPE_WARNING,
1565 _("Invalid format for IP: `%s'\n"),
1567 GNUNET_free (result);
1568 GNUNET_free (routeList);
1571 result[i].network.s_addr =
1572 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
1574 result[i].netmask.s_addr = 0;
1577 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1580 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1585 LOG (GNUNET_ERROR_TYPE_WARNING,
1586 _("Invalid format for IP: `%s'\n"),
1588 GNUNET_free (result);
1589 GNUNET_free (routeList);
1590 return NULL; /* error */
1592 if (pos < strlen (routeList))
1594 LOG (GNUNET_ERROR_TYPE_WARNING,
1595 _("Invalid format: `%s'\n"),
1597 GNUNET_free (result);
1598 GNUNET_free (routeList);
1599 return NULL; /* oops */
1601 GNUNET_free (routeList);
1602 return result; /* ok */
1607 * Parse an IPv6 network policy. The argument specifies a list of
1608 * subnets. The format is <tt>(network[/netmask[:SPORT[-DPORT]]];)*</tt>
1609 * (no whitespace, must be terminated with a semicolon). The network
1610 * must be given in colon-hex notation. The netmask must be given in
1611 * CIDR notation (/16) or can be omitted to specify a single host.
1612 * Note that the netmask is mandatory if ports are specified.
1614 * @param routeListX a string specifying the policy
1615 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1617 struct GNUNET_STRINGS_IPv6NetworkPolicy *
1618 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1628 struct GNUNET_STRINGS_IPv6NetworkPolicy *result;
1634 if (NULL == routeListX)
1636 len = strlen (routeListX);
1639 routeList = GNUNET_strdup (routeListX);
1641 for (i = 0; i < len; i++)
1642 if (';' == routeList[i])
1644 if (';' != routeList[len - 1])
1646 LOG (GNUNET_ERROR_TYPE_WARNING,
1647 _("Invalid network notation (does not end with ';': `%s')\n"),
1649 GNUNET_free (routeList);
1653 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * (count + 1));
1659 while (';' != routeList[pos])
1662 while ((slash >= start) && (routeList[slash] != '/'))
1667 memset (&result[i].netmask,
1669 sizeof (struct in6_addr));
1674 routeList[pos] = '\0';
1675 for (colon = pos; ':' != routeList[colon]; colon--)
1676 if ('/' == routeList[colon])
1678 if (':' == routeList[colon])
1680 routeList[colon] = '\0';
1681 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1],
1684 GNUNET_free (result);
1685 GNUNET_free (routeList);
1689 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
1693 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits > 128))
1696 LOG (GNUNET_ERROR_TYPE_WARNING,
1697 _("Wrong format `%s' for netmask\n"),
1698 &routeList[slash + 1]);
1702 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1704 GNUNET_free (result);
1705 GNUNET_free (routeList);
1711 result[i].netmask.s6_addr[off++] = 0xFF;
1716 result[i].netmask.s6_addr[off] =
1717 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1722 routeList[slash] = '\0';
1723 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1727 LOG (GNUNET_ERROR_TYPE_WARNING,
1728 _("Wrong format `%s' for network\n"),
1729 &routeList[slash + 1]);
1731 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1733 GNUNET_free (result);
1734 GNUNET_free (routeList);
1740 GNUNET_free (routeList);
1745 /* end of strings.c */