2 This file is part of GNUnet.
3 (C) 2005, 2006 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 2, 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_common.h"
33 #include "gnunet_strings_lib.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 * Fill a buffer of the given size with
45 * count 0-terminated strings (given as varargs).
46 * If "buffer" is NULL, only compute the amount of
47 * space required (sum of "strlen(arg)+1").
49 * Unlike using "snprintf" with "%s", this function
50 * will add 0-terminators after each string. The
51 * "GNUNET_string_buffer_tokenize" function can be
52 * used to parse the buffer back into individual
55 * @param buffer the buffer to fill with strings, can
56 * be NULL in which case only the necessary
57 * amount of space will be calculated
58 * @param size number of bytes available in buffer
59 * @param count number of strings that follow
60 * @param ... count 0-terminated strings to copy to buffer
61 * @return number of bytes written to the buffer
62 * (or number of bytes that would have been written)
65 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
76 s = va_arg (ap, const char *);
78 slen = strlen (s) + 1;
81 GNUNET_assert (needed + slen <= size);
82 memcpy (&buffer[needed], s, slen);
93 * Given a buffer of a given size, find "count"
94 * 0-terminated strings in the buffer and assign
95 * the count (varargs) of type "const char**" to the
96 * locations of the respective strings in the
99 * @param buffer the buffer to parse
100 * @param size size of the buffer
101 * @param count number of strings to locate
102 * @return offset of the character after the last 0-termination
103 * in the buffer, or 0 on error.
106 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
107 unsigned int count, ...)
115 va_start (ap, count);
118 r = va_arg (ap, const char **);
121 while ((needed < size) && (buffer[needed] != '\0'))
126 return 0; /* error */
129 needed++; /* skip 0-termination */
138 * Convert a given filesize into a fancy human-readable format.
140 * @param size number of bytes
141 * @return fancy representation of the size (possibly rounded) for humans
144 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
146 const char *unit = _( /* size unit */ "b");
169 ret = GNUNET_malloc (32);
170 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
176 * Unit conversion table entry for 'convert_with_table'.
178 struct ConversionTable
181 * Name of the unit (or NULL for end of table).
186 * Factor to apply for this unit.
188 unsigned long long value;
193 * Convert a string of the form "4 X 5 Y" into a numeric value
194 * by interpreting "X" and "Y" as units and then multiplying
195 * the numbers with the values associated with the respective
196 * unit from the conversion table.
198 * @param input input string to parse
199 * @param table table with the conversion of unit names to numbers
200 * @param output where to store the result
201 * @return GNUNET_OK on success, GNUNET_SYSERR on error
204 convert_with_table (const char *input,
205 const struct ConversionTable *table,
206 unsigned long long *output)
208 unsigned long long ret;
211 unsigned long long last;
216 in = GNUNET_strdup (input);
217 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
222 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
224 if (table[i].name != NULL)
226 last *= table[i].value;
227 break; /* next tok */
234 last = strtoull (tok, &endptr, 10);
235 if ((0 != errno) || (endptr == tok))
238 return GNUNET_SYSERR; /* expected number */
240 if ('\0' == endptr[0])
241 break; /* next tok */
243 tok = endptr; /* and re-check (handles times like "10s") */
245 } while (GNUNET_YES);
255 * Convert a given fancy human-readable size to bytes.
257 * @param fancy_size human readable string (i.e. 1 MB)
258 * @param size set to the size in bytes
259 * @return GNUNET_OK on success, GNUNET_SYSERR on error
262 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
263 unsigned long long *size)
265 static const struct ConversionTable table[] =
270 { "MiB", 1024 * 1024},
271 { "MB", 1000 * 1000},
272 { "GiB", 1024 * 1024 * 1024},
273 { "GB", 1000 * 1000 * 1000},
274 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
275 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
276 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
277 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
278 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
279 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
283 return convert_with_table (fancy_size,
290 * Convert a given fancy human-readable time to our internal
293 * @param fancy_time human readable string (i.e. 1 minute)
294 * @param rtime set to the relative time
295 * @return GNUNET_OK on success, GNUNET_SYSERR on error
298 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
299 struct GNUNET_TIME_Relative *rtime)
301 static const struct ConversionTable table[] =
308 { "minutes", 60 * 1000},
310 { "h", 60 * 60 * 1000},
311 { "d", 24 * 60 * 60 * 1000},
312 { "day", 24 * 60 * 60 * 1000},
313 { "days", 24 * 60 * 60 * 1000},
314 { "a", 31536000000LL /* 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 = (uint64_t) val;
334 * Convert a given fancy human-readable time to our internal
337 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
338 * @param atime set to the absolute time
339 * @return GNUNET_OK on success, GNUNET_SYSERR on error
342 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
343 struct GNUNET_TIME_Absolute *atime)
348 if (0 == strcasecmp ("end of time", fancy_time))
350 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
353 memset (&tv, 0, sizeof (tv));
354 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
355 (NULL == strptime (fancy_time, "%c", &tv)) &&
356 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
357 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
358 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
359 (NULL == strptime (fancy_time, "%x", &tv)) &&
360 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
361 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
362 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
363 (NULL == strptime (fancy_time, "%Y", &tv)) )
364 return GNUNET_SYSERR;
366 atime->abs_value = (uint64_t) ((uint64_t) t * 1000LL);
368 atime->abs_value -= 1000LL * timezone;
375 * Convert the len characters long character sequence
376 * given in input that is in the given input charset
377 * to a string in given output charset.
378 * @return the converted string (0-terminated),
379 * if conversion fails, a copy of the orignal
380 * string is returned.
383 GNUNET_STRINGS_conv (const char *input, size_t len, const char *input_charset, const char *output_charset)
387 char *encoded_string;
388 size_t u8_string_length;
389 size_t encoded_string_length;
391 u8_string = u8_conv_from_encoding (input_charset,
396 if (NULL == u8_string)
398 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
401 if (0 == strcmp (output_charset, "UTF-8"))
403 ret = GNUNET_malloc (u8_string_length + 1);
404 memcpy (ret, u8_string, u8_string_length);
405 ret[u8_string_length] = '\0';
409 encoded_string = u8_conv_to_encoding (output_charset, iconveh_error,
410 u8_string, u8_string_length,
412 &encoded_string_length);
414 if (NULL == encoded_string)
416 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
419 ret = GNUNET_malloc (encoded_string_length + 1);
420 memcpy (ret, encoded_string, encoded_string_length);
421 ret[encoded_string_length] = '\0';
422 free (encoded_string);
425 LOG (GNUNET_ERROR_TYPE_WARNING, _("Character sets requested were `%s'->`%s'\n"),
426 "UTF-8", output_charset);
427 ret = GNUNET_malloc (len + 1);
428 memcpy (ret, input, len);
435 * Convert the len characters long character sequence
436 * given in input that is in the given charset
438 * @return the converted string (0-terminated),
439 * if conversion fails, a copy of the orignal
440 * string is returned.
443 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
445 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
450 * Convert the len bytes-long UTF-8 string
451 * given in input to the given charset.
453 * @return the converted string (0-terminated),
454 * if conversion fails, a copy of the orignal
455 * string is returned.
458 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
460 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
465 * Convert the utf-8 input string to lowercase
466 * Output needs to be allocated appropriately
468 * @param input input string
469 * @param output output buffer
472 GNUNET_STRINGS_utf8_tolower(const char* input, char** output)
477 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
478 NULL, UNINORM_NFD, NULL, &len);
479 memcpy(*output, tmp_in, len);
480 (*output)[len] = '\0';
486 * Convert the utf-8 input string to uppercase
487 * Output needs to be allocated appropriately
489 * @param input input string
490 * @param output output buffer
493 GNUNET_STRINGS_utf8_toupper(const char* input, char** output)
498 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
499 NULL, UNINORM_NFD, NULL, &len);
500 memcpy(*output, tmp_in, len);
501 (*output)[len] = '\0';
507 * Complete filename (a la shell) from abbrevition.
508 * @param fil the name of the file, may contain ~/ or
509 * be relative to the current directory
510 * @returns the full file name,
511 * NULL is returned on error
514 GNUNET_STRINGS_filename_expand (const char *fil)
531 if (fil[0] == DIR_SEPARATOR)
532 /* absolute path, just copy */
533 return GNUNET_strdup (fil);
536 fm = getenv ("HOME");
539 LOG (GNUNET_ERROR_TYPE_WARNING,
540 _("Failed to expand `$HOME': environment variable `HOME' not set"));
543 fm = GNUNET_strdup (fm);
544 /* do not copy '~' */
547 /* skip over dir seperator to be consistent */
548 if (fil_ptr[0] == DIR_SEPARATOR)
559 buffer = GNUNET_malloc (len);
560 if (getcwd (buffer, len) != NULL)
565 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
568 GNUNET_free (buffer);
571 GNUNET_free (buffer);
576 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
577 buffer = getenv ("PWD"); /* alternative */
579 fm = GNUNET_strdup (buffer);
582 fm = GNUNET_strdup ("./"); /* give up */
584 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
585 buffer = GNUNET_malloc (n);
586 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
587 (fm[strlen (fm) - 1] ==
588 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
592 fn = GNUNET_malloc (MAX_PATH + 1);
594 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
596 SetErrnoFromWinError (lRet);
597 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
600 /* is the path relative? */
601 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
603 char szCurDir[MAX_PATH + 1];
605 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
606 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
608 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
609 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
612 buffer = GNUNET_malloc (MAX_PATH + 1);
613 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
624 * Give relative time in human-readable fancy format.
625 * This is one of the very few calls in the entire API that is
628 * @param delta time in milli seconds
629 * @param do_round are we allowed to round a bit?
630 * @return time as human-readable string
633 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
636 static char buf[128];
637 const char *unit = _( /* time unit */ "ms");
638 uint64_t dval = delta.rel_value;
640 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value == delta.rel_value)
642 if (0 == delta.rel_value)
644 if ( ( (GNUNET_YES == do_round) &&
645 (dval > 5 * 1000) ) ||
646 (0 == (dval % 1000) ))
649 unit = _( /* time unit */ "s");
650 if ( ( (GNUNET_YES == do_round) &&
652 (0 == (dval % 60) ) )
655 unit = _( /* time unit */ "m");
656 if ( ( (GNUNET_YES == do_round) &&
661 unit = _( /* time unit */ "h");
662 if ( ( (GNUNET_YES == do_round) &&
668 unit = _( /* time unit */ "day");
670 unit = _( /* time unit */ "days");
675 GNUNET_snprintf (buf, sizeof (buf),
676 "%llu %s", dval, unit);
682 * "asctime", except for GNUnet time.
683 * This is one of the very few calls in the entire API that is
686 * @param t time to convert
687 * @return absolute time in human-readable format
690 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
692 static char buf[255];
696 if (t.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
697 return _("end of time");
698 tt = t.abs_value / 1000;
700 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
707 * Returns a pointer to a part of filename (allocates nothing)!
709 * @param filename filename to extract basename from
710 * @return short (base) name of the file (that is, everything following the
711 * last directory separator in filename. If filename ends with a
712 * directory separator, the result will be a zero-length string.
713 * If filename has no directory separators, the result is filename
717 GNUNET_STRINGS_get_short_name (const char *filename)
719 const char *short_fn = filename;
721 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
729 * Get the numeric value corresponding to a character.
731 * @param a a character
732 * @return corresponding numeric value
735 getValue__ (unsigned char a)
737 if ((a >= '0') && (a <= '9'))
739 if ((a >= 'A') && (a <= 'V'))
740 return (a - 'A' + 10);
746 * Convert binary data to ASCII encoding. The ASCII encoding is rather
747 * GNUnet specific. It was chosen such that it only uses characters
748 * in [0-9A-V], can be produced without complex arithmetics and uses a
749 * small number of characters.
750 * Does not append 0-terminator, but returns a pointer to the place where
751 * it should be placed, if needed.
753 * @param data data to encode
754 * @param size size of data (in bytes)
755 * @param out buffer to fill
756 * @param out_size size of the buffer. Must be large enough to hold
757 * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
758 * @return pointer to the next byte in 'out' or NULL on error.
761 GNUNET_STRINGS_data_to_string (const void *data, size_t size, char *out, size_t out_size)
764 * 32 characters for encoding
766 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
771 const unsigned char *udata;
773 GNUNET_assert (data != NULL);
774 GNUNET_assert (out != NULL);
776 if (out_size < (((size*8) + ((size*8) % 5)) % 5))
785 while ((rpos < size) || (vbit > 0))
787 if ((rpos < size) && (vbit < 5))
789 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
794 bits <<= (5 - vbit); /* zero-padding */
795 GNUNET_assert (vbit == ((size * 8) % 5));
798 if (wpos >= out_size)
803 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
806 GNUNET_assert (vbit == 0);
814 * Convert ASCII encoding back to data
815 * out_size must match exactly the size of the data before it was encoded.
817 * @param enc the encoding
818 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
819 * @param out location where to store the decoded data
820 * @param out_size sizeof the output buffer
821 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
824 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
825 void *out, size_t out_size)
834 int encoded_len = out_size * 8;
837 if (encoded_len % 5 > 0)
839 vbit = encoded_len % 5; /* padding! */
847 if ((encoded_len + shift) / 5 != enclen)
848 return GNUNET_SYSERR;
852 bits = (ret = getValue__ (enc[--rpos])) >> (5 - encoded_len % 5);
854 return GNUNET_SYSERR;
858 return GNUNET_SYSERR;
859 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
861 return GNUNET_SYSERR;
865 uout[--wpos] = (unsigned char) bits;
872 return GNUNET_SYSERR;
878 * Parse a path that might be an URI.
880 * @param path path to parse. Must be NULL-terminated.
881 * @param scheme_part a pointer to 'char *' where a pointer to a string that
882 * represents the URI scheme will be stored. Can be NULL. The string is
883 * allocated by the function, and should be freed by GNUNET_free() when
884 * it is no longer needed.
885 * @param path_part a pointer to 'const char *' where a pointer to the path
886 * part of the URI will be stored. Can be NULL. Points to the same block
887 * of memory as 'path', and thus must not be freed. Might point to '\0',
888 * if path part is zero-length.
889 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
890 * an URI, '* scheme_part' and '*path_part' will remain unchanged
891 * (if they weren't NULL).
894 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
895 const char **path_part)
900 const char *post_scheme_part = NULL;
902 for (end = 0, i = 0; !end && i < len; i++)
907 if (path[i] == ':' && i > 0)
912 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
913 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
914 || (path[i] == '.')))
927 post_scheme_part = &path[i];
934 if (post_scheme_part == NULL)
938 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
939 memcpy (*scheme_part, path, post_scheme_part - path);
940 (*scheme_part)[post_scheme_part - path] = '\0';
943 *path_part = post_scheme_part;
949 * Check whether 'filename' is absolute or not, and if it's an URI
951 * @param filename filename to check
952 * @param can_be_uri GNUNET_YES to check for being URI, GNUNET_NO - to
953 * assume it's not URI
954 * @param r_is_uri a pointer to an int that is set to GNUNET_YES if 'filename'
955 * is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
956 * not GNUNET_YES, *r_is_uri is set to GNUNET_NO.
957 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
958 * The string is allocated by the function, and should be freed with
959 * GNUNET_free (). Can be NULL.
960 * @return GNUNET_YES if 'filename' is absolute, GNUNET_NO otherwise.
963 GNUNET_STRINGS_path_is_absolute (const char *filename, int can_be_uri,
964 int *r_is_uri, char **r_uri_scheme)
969 const char *post_scheme_path;
972 /* consider POSIX paths to be absolute too, even on W32,
973 * as plibc expansion will fix them for us.
975 if (filename[0] == '/')
979 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
987 GNUNET_free_non_null (uri);
989 len = strlen(post_scheme_path);
990 /* Special check for file:///c:/blah
991 * We want to parse 'c:/', not '/c:/'
993 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
994 post_scheme_path = &post_scheme_path[1];
996 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
1002 *r_is_uri = GNUNET_NO;
1005 len = strlen (filename);
1007 ((filename[0] >= 'A' && filename[0] <= 'Z')
1008 || (filename[0] >= 'a' && filename[0] <= 'z'))
1009 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
1016 #define _IFMT 0170000 /* type of file */
1017 #define _IFLNK 0120000 /* symbolic link */
1018 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
1023 * Perform 'checks' on 'filename'
1025 * @param filename file to check
1026 * @param checks checks to perform
1027 * @return GNUNET_YES if all checks pass, GNUNET_NO if at least one of them
1028 * fails, GNUNET_SYSERR when a check can't be performed
1031 GNUNET_STRINGS_check_filename (const char *filename,
1032 enum GNUNET_STRINGS_FilenameCheck checks)
1035 if ( (NULL == filename) || (filename[0] == '\0') )
1036 return GNUNET_SYSERR;
1037 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1038 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1040 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1041 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1042 | GNUNET_STRINGS_CHECK_IS_LINK)))
1044 if (0 != STAT (filename, &st))
1046 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1049 return GNUNET_SYSERR;
1052 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1053 if (!S_ISDIR (st.st_mode))
1055 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1056 if (!S_ISLNK (st.st_mode))
1063 * Tries to convert 'zt_addr' string to an IPv6 address.
1064 * The string is expected to have the format "[ABCD::01]:80".
1066 * @param zt_addr 0-terminated string. May be mangled by the function.
1067 * @param addrlen length of zt_addr (not counting 0-terminator).
1068 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1069 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1070 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1071 * case the contents of r_buf are undefined.
1074 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1076 struct sockaddr_in6 *r_buf)
1078 char zbuf[addrlen + 1];
1084 return GNUNET_SYSERR;
1085 memcpy (zbuf, zt_addr, addrlen);
1088 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1089 _("IPv6 address did not start with `['\n"));
1090 return GNUNET_SYSERR;
1092 zbuf[addrlen] = '\0';
1093 port_colon = strrchr (zbuf, ':');
1094 if (NULL == port_colon)
1096 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1097 _("IPv6 address did contain ':' to separate port number\n"));
1098 return GNUNET_SYSERR;
1100 if (']' != *(port_colon - 1))
1102 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1103 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1104 return GNUNET_SYSERR;
1106 ret = SSCANF (port_colon, ":%u", &port);
1107 if ( (1 != ret) || (port > 65535) )
1109 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1110 _("IPv6 address did contain a valid port number after the last ':'\n"));
1111 return GNUNET_SYSERR;
1113 *(port_colon-1) = '\0';
1114 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1115 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1118 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1119 _("Invalid IPv6 address `%s': %s\n"),
1122 return GNUNET_SYSERR;
1124 r_buf->sin6_port = htons (port);
1125 r_buf->sin6_family = AF_INET6;
1126 #if HAVE_SOCKADDR_IN_SIN_LEN
1127 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1134 * Tries to convert 'zt_addr' string to an IPv4 address.
1135 * The string is expected to have the format "1.2.3.4:80".
1137 * @param zt_addr 0-terminated string. May be mangled by the function.
1138 * @param addrlen length of zt_addr (not counting 0-terminator).
1139 * @param r_buf a buffer to fill.
1140 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which case
1141 * the contents of r_buf are undefined.
1144 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1145 struct sockaddr_in *r_buf)
1147 unsigned int temps[4];
1152 return GNUNET_SYSERR;
1153 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1155 return GNUNET_SYSERR;
1156 for (cnt = 0; cnt < 4; cnt++)
1157 if (temps[cnt] > 0xFF)
1158 return GNUNET_SYSERR;
1160 return GNUNET_SYSERR;
1161 r_buf->sin_family = AF_INET;
1162 r_buf->sin_port = htons (port);
1163 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1164 (temps[2] << 8) + temps[3]);
1165 #if HAVE_SOCKADDR_IN_SIN_LEN
1166 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1173 * Tries to convert 'addr' string to an IP (v4 or v6) address.
1174 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1176 * @param addr a string, may not be 0-terminated.
1177 * @param addrlen number of bytes in addr (if addr is 0-terminated,
1178 * 0-terminator should not be counted towards addrlen).
1179 * @param r_buf a buffer to fill.
1180 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1181 * case the contents of r_buf are undefined.
1184 GNUNET_STRINGS_to_address_ip (const char *addr,
1186 struct sockaddr_storage *r_buf)
1189 return GNUNET_STRINGS_to_address_ipv6 (addr, addrlen, (struct sockaddr_in6 *) r_buf);
1190 return GNUNET_STRINGS_to_address_ipv4 (addr, addrlen, (struct sockaddr_in *) r_buf);
1195 * Makes a copy of argv that consists of a single memory chunk that can be
1196 * freed with a single call to GNUNET_free ();
1198 static char *const *
1199 _make_continuous_arg_copy (int argc, char *const *argv)
1201 size_t argvsize = 0;
1205 for (i = 0; i < argc; i++)
1206 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1207 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1208 p = (char *) &new_argv[argc + 1];
1209 for (i = 0; i < argc; i++)
1212 strcpy (p, argv[i]);
1213 p += strlen (argv[i]) + 1;
1215 new_argv[argc] = NULL;
1216 return (char *const *) new_argv;
1221 * Returns utf-8 encoded arguments.
1222 * Does nothing (returns a copy of argc and argv) on any platform
1224 * Returned argv has u8argv[u8argc] == NULL.
1225 * Returned argv is a single memory block, and can be freed with a single
1226 * GNUNET_free () call.
1228 * @param argc argc (as given by main())
1229 * @param argv argv (as given by main())
1230 * @param u8argc a location to store new argc in (though it's th same as argc)
1231 * @param u8argv a location to store new argv in
1232 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1235 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1242 char **split_u8argv;
1244 wcmd = GetCommandLineW ();
1246 return GNUNET_SYSERR;
1247 wargv = CommandLineToArgvW (wcmd, &wargc);
1249 return GNUNET_SYSERR;
1251 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1253 for (i = 0; i < wargc; i++)
1256 /* Hopefully it will allocate us NUL-terminated strings... */
1257 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1258 if (split_u8argv == NULL)
1261 for (j = 0; j < i; j++)
1262 free (split_u8argv[j]);
1263 GNUNET_free (split_u8argv);
1265 return GNUNET_SYSERR;
1269 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1272 for (i = 0; i < wargc; i++)
1273 free (split_u8argv[i]);
1274 free (split_u8argv);
1277 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1284 /* end of strings.c */