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;
376 * Convert the len characters long character sequence
377 * given in input that is in the given input charset
378 * to a string in given output charset.
380 * @param input input string
381 * @param len number of bytes in @a input
382 * @param input_charset character set used for @a input
383 * @param ouptut_charset desired character set for the return value
384 * @return the converted string (0-terminated),
385 * if conversion fails, a copy of the orignal
386 * string is returned.
389 GNUNET_STRINGS_conv (const char *input,
391 const char *input_charset,
392 const char *output_charset)
396 char *encoded_string;
397 size_t u8_string_length;
398 size_t encoded_string_length;
400 u8_string = u8_conv_from_encoding (input_charset,
405 if (NULL == u8_string)
407 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
410 if (0 == strcmp (output_charset, "UTF-8"))
412 ret = GNUNET_malloc (u8_string_length + 1);
413 memcpy (ret, u8_string, u8_string_length);
414 ret[u8_string_length] = '\0';
418 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
419 u8_string, u8_string_length,
421 &encoded_string_length);
423 if (NULL == encoded_string)
425 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
428 ret = GNUNET_malloc (encoded_string_length + 1);
429 memcpy (ret, encoded_string, encoded_string_length);
430 ret[encoded_string_length] = '\0';
431 free (encoded_string);
434 LOG (GNUNET_ERROR_TYPE_WARNING, _("Character sets requested were `%s'->`%s'\n"),
435 "UTF-8", output_charset);
436 ret = GNUNET_malloc (len + 1);
437 memcpy (ret, input, len);
444 * Convert the len characters long character sequence
445 * given in input that is in the given charset
448 * @param input the input string (not necessarily 0-terminated)
449 * @param len the number of bytes in the @a input
450 * @param charset character set to convert from
451 * @return the converted string (0-terminated),
452 * if conversion fails, a copy of the orignal
453 * string is returned.
456 GNUNET_STRINGS_to_utf8 (const char *input,
460 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
465 * Convert the len bytes-long UTF-8 string
466 * given in input to the given charset.
468 * @param input the input string (not necessarily 0-terminated)
469 * @param len the number of bytes in the @a input
470 * @param charset character set to convert to
471 * @return the converted string (0-terminated),
472 * if conversion fails, a copy of the orignal
473 * string is returned.
476 GNUNET_STRINGS_from_utf8 (const char *input,
480 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
485 * Convert the utf-8 input string to lowercase
486 * Output needs to be allocated appropriately
488 * @param input input string
489 * @param output output buffer
492 GNUNET_STRINGS_utf8_tolower(const char* input, char** output)
497 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
498 NULL, UNINORM_NFD, NULL, &len);
499 memcpy(*output, tmp_in, len);
500 (*output)[len] = '\0';
506 * Convert the utf-8 input string to uppercase
507 * Output needs to be allocated appropriately
509 * @param input input string
510 * @param output output buffer
513 GNUNET_STRINGS_utf8_toupper(const char* input, char** output)
518 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
519 NULL, UNINORM_NFD, NULL, &len);
520 memcpy(*output, tmp_in, len);
521 (*output)[len] = '\0';
527 * Complete filename (a la shell) from abbrevition.
528 * @param fil the name of the file, may contain ~/ or
529 * be relative to the current directory
530 * @returns the full file name,
531 * NULL is returned on error
534 GNUNET_STRINGS_filename_expand (const char *fil)
551 if (fil[0] == DIR_SEPARATOR)
552 /* absolute path, just copy */
553 return GNUNET_strdup (fil);
556 fm = getenv ("HOME");
559 LOG (GNUNET_ERROR_TYPE_WARNING,
560 _("Failed to expand `$HOME': environment variable `HOME' not set"));
563 fm = GNUNET_strdup (fm);
564 /* do not copy '~' */
567 /* skip over dir seperator to be consistent */
568 if (fil_ptr[0] == DIR_SEPARATOR)
579 buffer = GNUNET_malloc (len);
580 if (getcwd (buffer, len) != NULL)
585 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
588 GNUNET_free (buffer);
591 GNUNET_free (buffer);
596 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
597 buffer = getenv ("PWD"); /* alternative */
599 fm = GNUNET_strdup (buffer);
602 fm = GNUNET_strdup ("./"); /* give up */
604 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
605 buffer = GNUNET_malloc (n);
606 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
607 (fm[strlen (fm) - 1] ==
608 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
612 fn = GNUNET_malloc (MAX_PATH + 1);
614 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
616 SetErrnoFromWinError (lRet);
617 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
620 /* is the path relative? */
621 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
623 char szCurDir[MAX_PATH + 1];
625 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
626 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
628 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
629 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
632 buffer = GNUNET_malloc (MAX_PATH + 1);
633 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
644 * Give relative time in human-readable fancy format.
645 * This is one of the very few calls in the entire API that is
648 * @param delta time in milli seconds
649 * @param do_round are we allowed to round a bit?
650 * @return time as human-readable string
653 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
656 static char buf[128];
657 const char *unit = _( /* time unit */ "µs");
658 uint64_t dval = delta.rel_value_us;
660 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
662 if (0 == delta.rel_value_us)
664 if ( ( (GNUNET_YES == do_round) &&
665 (dval > 5 * 1000) ) ||
666 (0 == (dval % 1000) ))
669 unit = _( /* time unit */ "ms");
670 if ( ( (GNUNET_YES == do_round) &&
671 (dval > 5 * 1000) ) ||
672 (0 == (dval % 1000) ))
675 unit = _( /* time unit */ "s");
676 if ( ( (GNUNET_YES == do_round) &&
678 (0 == (dval % 60) ) )
681 unit = _( /* time unit */ "m");
682 if ( ( (GNUNET_YES == do_round) &&
687 unit = _( /* time unit */ "h");
688 if ( ( (GNUNET_YES == do_round) &&
694 unit = _( /* time unit */ "day");
696 unit = _( /* time unit */ "days");
702 GNUNET_snprintf (buf, sizeof (buf),
703 "%llu %s", dval, unit);
709 * "asctime", except for GNUnet time. Converts a GNUnet internal
710 * absolute time (which is in UTC) to a string in local time.
711 * Note that the returned value will be overwritten if this function
714 * @param t time to convert
715 * @return absolute time in human-readable format
718 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
720 static char buf[255];
724 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
725 return _("end of time");
726 tt = t.abs_value_us / 1000LL / 1000LL;
728 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
735 * Returns a pointer to a part of filename (allocates nothing)!
737 * @param filename filename to extract basename from
738 * @return short (base) name of the file (that is, everything following the
739 * last directory separator in filename. If filename ends with a
740 * directory separator, the result will be a zero-length string.
741 * If filename has no directory separators, the result is filename
745 GNUNET_STRINGS_get_short_name (const char *filename)
747 const char *short_fn = filename;
749 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
757 * Get the numeric value corresponding to a character.
759 * @param a a character
760 * @return corresponding numeric value
763 getValue__ (unsigned char a)
765 if ((a >= '0') && (a <= '9'))
767 if ((a >= 'A') && (a <= 'V'))
768 return (a - 'A' + 10);
774 * Convert binary data to ASCII encoding. The ASCII encoding is rather
775 * GNUnet specific. It was chosen such that it only uses characters
776 * in [0-9A-V], can be produced without complex arithmetics and uses a
777 * small number of characters.
778 * Does not append 0-terminator, but returns a pointer to the place where
779 * it should be placed, if needed.
781 * @param data data to encode
782 * @param size size of data (in bytes)
783 * @param out buffer to fill
784 * @param out_size size of the buffer. Must be large enough to hold
785 * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
786 * @return pointer to the next byte in 'out' or NULL on error.
789 GNUNET_STRINGS_data_to_string (const void *data, size_t size, char *out, size_t out_size)
792 * 32 characters for encoding
794 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
799 const unsigned char *udata;
801 GNUNET_assert (data != NULL);
802 GNUNET_assert (out != NULL);
804 if (out_size < (((size*8) + ((size*8) % 5)) % 5))
813 while ((rpos < size) || (vbit > 0))
815 if ((rpos < size) && (vbit < 5))
817 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
822 bits <<= (5 - vbit); /* zero-padding */
823 GNUNET_assert (vbit == ((size * 8) % 5));
826 if (wpos >= out_size)
831 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
834 GNUNET_assert (vbit == 0);
842 * Convert ASCII encoding back to data
843 * out_size must match exactly the size of the data before it was encoded.
845 * @param enc the encoding
846 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
847 * @param out location where to store the decoded data
848 * @param out_size size of the output buffer
849 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
852 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
853 void *out, size_t out_size)
862 unsigned int encoded_len = out_size * 8;
868 return GNUNET_SYSERR;
873 if ((encoded_len % 5) > 0)
875 vbit = encoded_len % 5; /* padding! */
877 bits = (ret = getValue__ (enc[--rpos])) >> (5 - (encoded_len % 5));
883 bits = (ret = getValue__ (enc[--rpos]));
885 if ((encoded_len + shift) / 5 != enclen)
886 return GNUNET_SYSERR;
888 return GNUNET_SYSERR;
894 return GNUNET_SYSERR;
896 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
898 return GNUNET_SYSERR;
902 uout[--wpos] = (unsigned char) bits;
909 return GNUNET_SYSERR;
915 * Parse a path that might be an URI.
917 * @param path path to parse. Must be NULL-terminated.
918 * @param scheme_part a pointer to 'char *' where a pointer to a string that
919 * represents the URI scheme will be stored. Can be NULL. The string is
920 * allocated by the function, and should be freed by GNUNET_free() when
921 * it is no longer needed.
922 * @param path_part a pointer to 'const char *' where a pointer to the path
923 * part of the URI will be stored. Can be NULL. Points to the same block
924 * of memory as 'path', and thus must not be freed. Might point to '\0',
925 * if path part is zero-length.
926 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
927 * an URI, '* scheme_part' and '*path_part' will remain unchanged
928 * (if they weren't NULL).
931 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
932 const char **path_part)
937 const char *post_scheme_part = NULL;
939 for (end = 0, i = 0; !end && i < len; i++)
944 if (path[i] == ':' && i > 0)
949 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
950 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
951 || (path[i] == '.')))
964 post_scheme_part = &path[i];
971 if (post_scheme_part == NULL)
975 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
976 memcpy (*scheme_part, path, post_scheme_part - path);
977 (*scheme_part)[post_scheme_part - path] = '\0';
980 *path_part = post_scheme_part;
986 * Check whether 'filename' is absolute or not, and if it's an URI
988 * @param filename filename to check
989 * @param can_be_uri GNUNET_YES to check for being URI, GNUNET_NO - to
990 * assume it's not URI
991 * @param r_is_uri a pointer to an int that is set to GNUNET_YES if 'filename'
992 * is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
993 * not GNUNET_YES, *r_is_uri is set to GNUNET_NO.
994 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
995 * The string is allocated by the function, and should be freed with
996 * GNUNET_free (). Can be NULL.
997 * @return GNUNET_YES if 'filename' is absolute, GNUNET_NO otherwise.
1000 GNUNET_STRINGS_path_is_absolute (const char *filename, int can_be_uri,
1001 int *r_is_uri, char **r_uri_scheme)
1006 const char *post_scheme_path;
1009 /* consider POSIX paths to be absolute too, even on W32,
1010 * as plibc expansion will fix them for us.
1012 if (filename[0] == '/')
1016 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1022 *r_uri_scheme = uri;
1024 GNUNET_free_non_null (uri);
1026 len = strlen(post_scheme_path);
1027 /* Special check for file:///c:/blah
1028 * We want to parse 'c:/', not '/c:/'
1030 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1031 post_scheme_path = &post_scheme_path[1];
1033 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1039 *r_is_uri = GNUNET_NO;
1042 len = strlen (filename);
1044 ((filename[0] >= 'A' && filename[0] <= 'Z')
1045 || (filename[0] >= 'a' && filename[0] <= 'z'))
1046 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1053 #define _IFMT 0170000 /* type of file */
1054 #define _IFLNK 0120000 /* symbolic link */
1055 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1060 * Perform 'checks' on 'filename'
1062 * @param filename file to check
1063 * @param checks checks to perform
1064 * @return GNUNET_YES if all checks pass, GNUNET_NO if at least one of them
1065 * fails, GNUNET_SYSERR when a check can't be performed
1068 GNUNET_STRINGS_check_filename (const char *filename,
1069 enum GNUNET_STRINGS_FilenameCheck checks)
1072 if ( (NULL == filename) || (filename[0] == '\0') )
1073 return GNUNET_SYSERR;
1074 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1075 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1077 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1078 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1079 | GNUNET_STRINGS_CHECK_IS_LINK)))
1081 if (0 != STAT (filename, &st))
1083 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1086 return GNUNET_SYSERR;
1089 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1090 if (!S_ISDIR (st.st_mode))
1092 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1093 if (!S_ISLNK (st.st_mode))
1100 * Tries to convert 'zt_addr' string to an IPv6 address.
1101 * The string is expected to have the format "[ABCD::01]:80".
1103 * @param zt_addr 0-terminated string. May be mangled by the function.
1104 * @param addrlen length of zt_addr (not counting 0-terminator).
1105 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1106 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1107 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1108 * case the contents of r_buf are undefined.
1111 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1113 struct sockaddr_in6 *r_buf)
1115 char zbuf[addrlen + 1];
1121 return GNUNET_SYSERR;
1122 memcpy (zbuf, zt_addr, addrlen);
1125 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1126 _("IPv6 address did not start with `['\n"));
1127 return GNUNET_SYSERR;
1129 zbuf[addrlen] = '\0';
1130 port_colon = strrchr (zbuf, ':');
1131 if (NULL == port_colon)
1133 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1134 _("IPv6 address did contain ':' to separate port number\n"));
1135 return GNUNET_SYSERR;
1137 if (']' != *(port_colon - 1))
1139 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1140 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1141 return GNUNET_SYSERR;
1143 ret = SSCANF (port_colon, ":%u", &port);
1144 if ( (1 != ret) || (port > 65535) )
1146 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1147 _("IPv6 address did contain a valid port number after the last ':'\n"));
1148 return GNUNET_SYSERR;
1150 *(port_colon-1) = '\0';
1151 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1152 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1155 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1156 _("Invalid IPv6 address `%s': %s\n"),
1159 return GNUNET_SYSERR;
1161 r_buf->sin6_port = htons (port);
1162 r_buf->sin6_family = AF_INET6;
1163 #if HAVE_SOCKADDR_IN_SIN_LEN
1164 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1171 * Tries to convert 'zt_addr' string to an IPv4 address.
1172 * The string is expected to have the format "1.2.3.4:80".
1174 * @param zt_addr 0-terminated string. May be mangled by the function.
1175 * @param addrlen length of zt_addr (not counting 0-terminator).
1176 * @param r_buf a buffer to fill.
1177 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which case
1178 * the contents of r_buf are undefined.
1181 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1182 struct sockaddr_in *r_buf)
1184 unsigned int temps[4];
1189 return GNUNET_SYSERR;
1190 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1192 return GNUNET_SYSERR;
1193 for (cnt = 0; cnt < 4; cnt++)
1194 if (temps[cnt] > 0xFF)
1195 return GNUNET_SYSERR;
1197 return GNUNET_SYSERR;
1198 r_buf->sin_family = AF_INET;
1199 r_buf->sin_port = htons (port);
1200 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1201 (temps[2] << 8) + temps[3]);
1202 #if HAVE_SOCKADDR_IN_SIN_LEN
1203 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1210 * Tries to convert 'addr' string to an IP (v4 or v6) address.
1211 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1213 * @param addr a string, may not be 0-terminated.
1214 * @param addrlen number of bytes in addr (if addr is 0-terminated,
1215 * 0-terminator should not be counted towards addrlen).
1216 * @param r_buf a buffer to fill.
1217 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1218 * case the contents of r_buf are undefined.
1221 GNUNET_STRINGS_to_address_ip (const char *addr,
1223 struct sockaddr_storage *r_buf)
1226 return GNUNET_STRINGS_to_address_ipv6 (addr, addrlen, (struct sockaddr_in6 *) r_buf);
1227 return GNUNET_STRINGS_to_address_ipv4 (addr, addrlen, (struct sockaddr_in *) r_buf);
1232 * Makes a copy of argv that consists of a single memory chunk that can be
1233 * freed with a single call to GNUNET_free ();
1235 static char *const *
1236 _make_continuous_arg_copy (int argc, char *const *argv)
1238 size_t argvsize = 0;
1242 for (i = 0; i < argc; i++)
1243 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1244 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1245 p = (char *) &new_argv[argc + 1];
1246 for (i = 0; i < argc; i++)
1249 strcpy (p, argv[i]);
1250 p += strlen (argv[i]) + 1;
1252 new_argv[argc] = NULL;
1253 return (char *const *) new_argv;
1258 * Returns utf-8 encoded arguments.
1259 * Does nothing (returns a copy of argc and argv) on any platform
1261 * Returned argv has u8argv[u8argc] == NULL.
1262 * Returned argv is a single memory block, and can be freed with a single
1263 * GNUNET_free () call.
1265 * @param argc argc (as given by main())
1266 * @param argv argv (as given by main())
1267 * @param u8argc a location to store new argc in (though it's th same as argc)
1268 * @param u8argv a location to store new argv in
1269 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1272 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1279 char **split_u8argv;
1281 wcmd = GetCommandLineW ();
1283 return GNUNET_SYSERR;
1284 wargv = CommandLineToArgvW (wcmd, &wargc);
1286 return GNUNET_SYSERR;
1288 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1290 for (i = 0; i < wargc; i++)
1293 /* Hopefully it will allocate us NUL-terminated strings... */
1294 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1295 if (NULL == split_u8argv[i])
1298 for (j = 0; j < i; j++)
1299 free (split_u8argv[j]);
1300 GNUNET_free (split_u8argv);
1302 return GNUNET_SYSERR;
1306 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1309 for (i = 0; i < wargc; i++)
1310 free (split_u8argv[i]);
1311 free (split_u8argv);
1314 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1321 /* end of strings.c */