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"
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, " "))
219 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
221 if (table[i].name != NULL)
222 last *= table[i].value;
227 if (1 != SSCANF (tok, "%llu", &last))
230 return GNUNET_SYSERR; /* expected number */
242 * Convert a given fancy human-readable size to bytes.
244 * @param fancy_size human readable string (i.e. 1 MB)
245 * @param size set to the size in bytes
246 * @return GNUNET_OK on success, GNUNET_SYSERR on error
249 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
250 unsigned long long *size)
252 static const struct ConversionTable table[] =
257 { "MiB", 1024 * 1024},
258 { "MB", 1000 * 1000},
259 { "GiB", 1024 * 1024 * 1024},
260 { "GB", 1000 * 1000 * 1000},
261 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
262 { "TB", 1000LL * 1000LL * 1000LL * 1024LL},
263 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
264 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
265 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
266 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
270 return convert_with_table (fancy_size,
277 * Convert a given fancy human-readable time to our internal
280 * @param fancy_time human readable string (i.e. 1 minute)
281 * @param rtime set to the relative time
282 * @return GNUNET_OK on success, GNUNET_SYSERR on error
285 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
286 struct GNUNET_TIME_Relative *rtime)
288 static const struct ConversionTable table[] =
295 { "minutes", 60 * 1000},
297 { "h", 60 * 60 * 1000},
298 { "d", 24 * 60 * 60 * 1000},
299 { "day", 24 * 60 * 60 * 1000},
300 { "days", 24 * 60 * 60 * 1000},
301 { "a", 31536000000LL /* year */ },
305 unsigned long long val;
307 if (0 == strcasecmp ("forever", fancy_time))
309 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
312 ret = convert_with_table (fancy_time,
315 rtime->rel_value = (uint64_t) val;
321 * Convert a given fancy human-readable time to our internal
324 * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
325 * @param atime set to the absolute time
326 * @return GNUNET_OK on success, GNUNET_SYSERR on error
329 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
330 struct GNUNET_TIME_Absolute *atime)
335 if (0 == strcasecmp ("end of time", fancy_time))
337 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
340 memset (&tv, 0, sizeof (tv));
341 if ( (NULL == strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
342 (NULL == strptime (fancy_time, "%c", &tv)) &&
343 (NULL == strptime (fancy_time, "%Ec", &tv)) &&
344 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
345 (NULL == strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
346 (NULL == strptime (fancy_time, "%x", &tv)) &&
347 (NULL == strptime (fancy_time, "%Ex", &tv)) &&
348 (NULL == strptime (fancy_time, "%Y-%m-%d", &tv)) &&
349 (NULL == strptime (fancy_time, "%Y-%m", &tv)) &&
350 (NULL == strptime (fancy_time, "%Y", &tv)) )
351 return GNUNET_SYSERR;
353 atime->abs_value = (uint64_t) ((uint64_t) t * 1000LL);
355 atime->abs_value -= 1000LL * timezone;
362 * Convert the len characters long character sequence
363 * given in input that is in the given input charset
364 * to a string in given output charset.
365 * @return the converted string (0-terminated),
366 * if conversion fails, a copy of the orignal
367 * string is returned.
370 GNUNET_STRINGS_conv (const char *input, size_t len, const char *input_charset, const char *output_charset)
374 #if ENABLE_NLS && HAVE_ICONV
381 cd = iconv_open (output_charset, input_charset);
382 if (cd == (iconv_t) - 1)
384 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_open");
385 LOG (GNUNET_ERROR_TYPE_WARNING, _("Character sets requested were `%s'->`%s'\n"),
386 input_charset, output_charset);
387 ret = GNUNET_malloc (len + 1);
388 memcpy (ret, input, len);
392 tmpSize = 3 * len + 4;
393 tmp = GNUNET_malloc (tmpSize);
397 #if FREEBSD || DARWIN || WINDOWS
398 (const char **) &input,
402 &len, &itmp, &finSize) == SIZE_MAX)
404 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv");
407 ret = GNUNET_malloc (len + 1);
408 memcpy (ret, input, len);
412 ret = GNUNET_malloc (tmpSize - finSize + 1);
413 memcpy (ret, tmp, tmpSize - finSize);
414 ret[tmpSize - finSize] = '\0';
416 if (0 != iconv_close (cd))
417 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_close");
420 ret = GNUNET_malloc (len + 1);
421 memcpy (ret, input, len);
429 * Convert the len characters long character sequence
430 * given in input that is in the given charset
432 * @return the converted string (0-terminated),
433 * if conversion fails, a copy of the orignal
434 * string is returned.
437 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
439 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8");
444 * Convert the len bytes-long UTF-8 string
445 * given in input to the given charset.
447 * @return the converted string (0-terminated),
448 * if conversion fails, a copy of the orignal
449 * string is returned.
452 GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
454 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset);
459 * Convert the utf-8 input string to lowercase
460 * Output needs to be allocated appropriately
462 * @param input input string
463 * @param output output buffer
466 GNUNET_STRINGS_utf8_tolower(const char* input, char** output)
471 tmp_in = u8_tolower ((uint8_t*)input, strlen ((char *) input),
472 NULL, UNINORM_NFD, NULL, &len);
473 memcpy(*output, tmp_in, len);
474 (*output)[len] = '\0';
480 * Convert the utf-8 input string to uppercase
481 * Output needs to be allocated appropriately
483 * @param input input string
484 * @param output output buffer
487 GNUNET_STRINGS_utf8_toupper(const char* input, char** output)
492 tmp_in = u8_toupper ((uint8_t*)input, strlen ((char *) input),
493 NULL, UNINORM_NFD, NULL, &len);
494 memcpy(*output, tmp_in, len);
495 (*output)[len] = '\0';
501 * Complete filename (a la shell) from abbrevition.
502 * @param fil the name of the file, may contain ~/ or
503 * be relative to the current directory
504 * @returns the full file name,
505 * NULL is returned on error
508 GNUNET_STRINGS_filename_expand (const char *fil)
525 if (fil[0] == DIR_SEPARATOR)
526 /* absolute path, just copy */
527 return GNUNET_strdup (fil);
530 fm = getenv ("HOME");
533 LOG (GNUNET_ERROR_TYPE_WARNING,
534 _("Failed to expand `$HOME': environment variable `HOME' not set"));
537 fm = GNUNET_strdup (fm);
538 /* do not copy '~' */
541 /* skip over dir seperator to be consistent */
542 if (fil_ptr[0] == DIR_SEPARATOR)
553 buffer = GNUNET_malloc (len);
554 if (getcwd (buffer, len) != NULL)
559 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
562 GNUNET_free (buffer);
565 GNUNET_free (buffer);
570 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
571 buffer = getenv ("PWD"); /* alternative */
573 fm = GNUNET_strdup (buffer);
576 fm = GNUNET_strdup ("./"); /* give up */
578 n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
579 buffer = GNUNET_malloc (n);
580 GNUNET_snprintf (buffer, n, "%s%s%s", fm,
581 (fm[strlen (fm) - 1] ==
582 DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
586 fn = GNUNET_malloc (MAX_PATH + 1);
588 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
590 SetErrnoFromWinError (lRet);
591 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
594 /* is the path relative? */
595 if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
597 char szCurDir[MAX_PATH + 1];
599 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
600 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
602 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
603 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
606 buffer = GNUNET_malloc (MAX_PATH + 1);
607 GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
618 * Give relative time in human-readable fancy format.
620 * @param delta time in milli seconds
621 * @return time as human-readable string
624 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta)
626 const char *unit = _( /* time unit */ "ms");
628 uint64_t dval = delta.rel_value;
630 if (delta.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
631 return GNUNET_strdup (_("forever"));
632 if ( (dval > 5 * 1000) || (0 == (dval % 1000) ))
635 unit = _( /* time unit */ "s");
636 if ( (dval > 5 * 60) || (0 == (dval % 60) ) )
639 unit = _( /* time unit */ "m");
640 if ( (dval > 5 * 60) || (0 == (dval % 60) ))
643 unit = _( /* time unit */ "h");
644 if ( (dval > 5 * 24) || (0 == (dval % 24)) )
648 unit = _( /* time unit */ "day");
650 unit = _( /* time unit */ "days");
655 GNUNET_asprintf (&ret, "%llu %s", dval, unit);
661 * "asctime", except for GNUnet time.
663 * @param t time to convert
664 * @return absolute time in human-readable format
667 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
673 if (t.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
674 return GNUNET_strdup (_("end of time"));
675 tt = t.abs_value / 1000;
677 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp);
678 return GNUNET_strdup (buf);
684 * Returns a pointer to a part of filename (allocates nothing)!
686 * @param filename filename to extract basename from
687 * @return short (base) name of the file (that is, everything following the
688 * last directory separator in filename. If filename ends with a
689 * directory separator, the result will be a zero-length string.
690 * If filename has no directory separators, the result is filename
694 GNUNET_STRINGS_get_short_name (const char *filename)
696 const char *short_fn = filename;
698 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR))
706 * Get the numeric value corresponding to a character.
708 * @param a a character
709 * @return corresponding numeric value
712 getValue__ (unsigned char a)
714 if ((a >= '0') && (a <= '9'))
716 if ((a >= 'A') && (a <= 'V'))
717 return (a - 'A' + 10);
723 * Convert binary data to ASCII encoding. The ASCII encoding is rather
724 * GNUnet specific. It was chosen such that it only uses characters
725 * in [0-9A-V], can be produced without complex arithmetics and uses a
726 * small number of characters.
727 * Does not append 0-terminator, but returns a pointer to the place where
728 * it should be placed, if needed.
730 * @param data data to encode
731 * @param size size of data (in bytes)
732 * @param out buffer to fill
733 * @param out_size size of the buffer. Must be large enough to hold
734 * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5 bytes
735 * @return pointer to the next byte in 'out' or NULL on error.
738 GNUNET_STRINGS_data_to_string (const unsigned char *data, size_t size, char *out, size_t out_size)
741 * 32 characters for encoding
743 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
749 GNUNET_assert (data != NULL);
750 GNUNET_assert (out != NULL);
751 if (out_size < (((size*8) + ((size*8) % 5)) % 5))
760 while ((rpos < size) || (vbit > 0))
762 if ((rpos < size) && (vbit < 5))
764 bits = (bits << 8) | data[rpos++]; /* eat 8 more bits */
769 bits <<= (5 - vbit); /* zero-padding */
770 GNUNET_assert (vbit == ((size * 8) % 5));
773 if (wpos >= out_size)
778 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
781 if (wpos != out_size)
786 GNUNET_assert (vbit == 0);
792 * Convert ASCII encoding back to data
793 * out_size must match exactly the size of the data before it was encoded.
795 * @param enc the encoding
796 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
797 * @param out location where to store the decoded data
798 * @param out_size sizeof the output buffer
799 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
802 GNUNET_STRINGS_string_to_data (const char *enc, size_t enclen,
803 unsigned char *out, size_t out_size)
811 int encoded_len = out_size * 8;
812 if (encoded_len % 5 > 0)
814 vbit = encoded_len % 5; /* padding! */
822 if ((encoded_len + shift) / 5 != enclen)
823 return GNUNET_SYSERR;
827 bits = (ret = getValue__ (enc[--rpos])) >> (5 - encoded_len % 5);
829 return GNUNET_SYSERR;
832 GNUNET_assert (rpos > 0);
833 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
835 return GNUNET_SYSERR;
839 out[--wpos] = (unsigned char) bits;
844 GNUNET_assert (rpos == 0);
845 GNUNET_assert (vbit == 0);
851 * Parse a path that might be an URI.
853 * @param path path to parse. Must be NULL-terminated.
854 * @param scheme_part a pointer to 'char *' where a pointer to a string that
855 * represents the URI scheme will be stored. Can be NULL. The string is
856 * allocated by the function, and should be freed by GNUNET_free() when
857 * it is no longer needed.
858 * @param path_part a pointer to 'const char *' where a pointer to the path
859 * part of the URI will be stored. Can be NULL. Points to the same block
860 * of memory as 'path', and thus must not be freed. Might point to '\0',
861 * if path part is zero-length.
862 * @return GNUNET_YES if it's an URI, GNUNET_NO otherwise. If 'path' is not
863 * an URI, '* scheme_part' and '*path_part' will remain unchanged
864 * (if they weren't NULL).
867 GNUNET_STRINGS_parse_uri (const char *path, char **scheme_part,
868 const char **path_part)
873 const char *post_scheme_part = NULL;
875 for (end = 0, i = 0; !end && i < len; i++)
880 if (path[i] == ':' && i > 0)
885 if (!((path[i] >= 'A' && path[i] <= 'Z') || (path[i] >= 'a' && path[i] <= 'z')
886 || (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || path[i] == '-'
887 || (path[i] == '.')))
900 post_scheme_part = &path[i];
907 if (post_scheme_part == NULL)
911 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1);
912 memcpy (*scheme_part, path, post_scheme_part - path);
913 (*scheme_part)[post_scheme_part - path] = '\0';
916 *path_part = post_scheme_part;
922 * Check whether 'filename' is absolute or not, and if it's an URI
924 * @param filename filename to check
925 * @param can_be_uri GNUNET_YES to check for being URI, GNUNET_NO - to
926 * assume it's not URI
927 * @param r_is_uri a pointer to an int that is set to GNUNET_YES if 'filename'
928 * is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
929 * not GNUNET_YES, *r_is_uri is set to GNUNET_NO.
930 * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
931 * The string is allocated by the function, and should be freed with
932 * GNUNET_free (). Can be NULL.
933 * @return GNUNET_YES if 'filename' is absolute, GNUNET_NO otherwise.
936 GNUNET_STRINGS_path_is_absolute (const char *filename, int can_be_uri,
937 int *r_is_uri, char **r_uri_scheme)
942 const char *post_scheme_path;
945 /* consider POSIX paths to be absolute too, even on W32,
946 * as plibc expansion will fix them for us.
948 if (filename[0] == '/')
952 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
960 GNUNET_free_non_null (uri);
962 len = strlen(post_scheme_path);
963 /* Special check for file:///c:/blah
964 * We want to parse 'c:/', not '/c:/'
966 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
967 post_scheme_path = &post_scheme_path[1];
969 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, GNUNET_NO, NULL, NULL);
976 *r_is_uri = GNUNET_NO;
979 len = strlen (filename);
981 ((filename[0] >= 'A' && filename[0] <= 'Z')
982 || (filename[0] >= 'a' && filename[0] <= 'z'))
983 && filename[1] == ':' && (filename[2] == '/' || filename[2] == '\\'))
990 #define _IFMT 0170000 /* type of file */
991 #define _IFLNK 0120000 /* symbolic link */
992 #define S_ISLNK(m) (((m)&_IFMT) == _IFLNK)
997 * Perform 'checks' on 'filename'
999 * @param filename file to check
1000 * @param checks checks to perform
1001 * @return GNUNET_YES if all checks pass, GNUNET_NO if at least one of them
1002 * fails, GNUNET_SYSERR when a check can't be performed
1005 GNUNET_STRINGS_check_filename (const char *filename,
1006 enum GNUNET_STRINGS_FilenameCheck checks)
1009 if ( (NULL == filename) || (filename[0] == '\0') )
1010 return GNUNET_SYSERR;
1011 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1012 if (!GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL))
1014 if (0 != (checks & (GNUNET_STRINGS_CHECK_EXISTS
1015 | GNUNET_STRINGS_CHECK_IS_DIRECTORY
1016 | GNUNET_STRINGS_CHECK_IS_LINK)))
1018 if (0 != STAT (filename, &st))
1020 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1023 return GNUNET_SYSERR;
1026 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1027 if (!S_ISDIR (st.st_mode))
1029 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1030 if (!S_ISLNK (st.st_mode))
1037 * Tries to convert 'zt_addr' string to an IPv6 address.
1038 * The string is expected to have the format "[ABCD::01]:80".
1040 * @param zt_addr 0-terminated string. May be mangled by the function.
1041 * @param addrlen length of zt_addr (not counting 0-terminator).
1042 * @param r_buf a buffer to fill. Initially gets filled with zeroes,
1043 * then its sin6_port, sin6_family and sin6_addr are set appropriately.
1044 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1045 * case the contents of r_buf are undefined.
1048 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1050 struct sockaddr_in6 *r_buf)
1052 char zbuf[addrlen + 1];
1058 return GNUNET_SYSERR;
1059 memcpy (zbuf, zt_addr, addrlen);
1062 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1063 _("IPv6 address did not start with `['\n"));
1064 return GNUNET_SYSERR;
1066 zbuf[addrlen] = '\0';
1067 port_colon = strrchr (zbuf, ':');
1068 if (NULL == port_colon)
1070 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1071 _("IPv6 address did contain ':' to separate port number\n"));
1072 return GNUNET_SYSERR;
1074 if (']' != *(port_colon - 1))
1076 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1077 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1078 return GNUNET_SYSERR;
1080 ret = SSCANF (port_colon, ":%u", &port);
1081 if ( (1 != ret) || (port > 65535) )
1083 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1084 _("IPv6 address did contain a valid port number after the last ':'\n"));
1085 return GNUNET_SYSERR;
1087 *(port_colon-1) = '\0';
1088 memset (r_buf, 0, sizeof (struct sockaddr_in6));
1089 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1092 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1093 _("Invalid IPv6 address `%s': %s\n"),
1096 return GNUNET_SYSERR;
1098 r_buf->sin6_port = htons (port);
1099 r_buf->sin6_family = AF_INET6;
1100 #if HAVE_SOCKADDR_IN_SIN_LEN
1101 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6);
1108 * Tries to convert 'zt_addr' string to an IPv4 address.
1109 * The string is expected to have the format "1.2.3.4:80".
1111 * @param zt_addr 0-terminated string. May be mangled by the function.
1112 * @param addrlen length of zt_addr (not counting 0-terminator).
1113 * @param r_buf a buffer to fill.
1114 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which case
1115 * the contents of r_buf are undefined.
1118 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, uint16_t addrlen,
1119 struct sockaddr_in *r_buf)
1121 unsigned int temps[4];
1126 return GNUNET_SYSERR;
1127 cnt = SSCANF (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
1129 return GNUNET_SYSERR;
1130 for (cnt = 0; cnt < 4; cnt++)
1131 if (temps[cnt] > 0xFF)
1132 return GNUNET_SYSERR;
1134 return GNUNET_SYSERR;
1135 r_buf->sin_family = AF_INET;
1136 r_buf->sin_port = htons (port);
1137 r_buf->sin_addr.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) +
1138 (temps[2] << 8) + temps[3]);
1139 #if HAVE_SOCKADDR_IN_SIN_LEN
1140 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in);
1147 * Tries to convert 'addr' string to an IP (v4 or v6) address.
1148 * Will automatically decide whether to treat 'addr' as v4 or v6 address.
1150 * @param addr a string, may not be 0-terminated.
1151 * @param addrlen number of bytes in addr (if addr is 0-terminated,
1152 * 0-terminator should not be counted towards addrlen).
1153 * @param r_buf a buffer to fill.
1154 * @return GNUNET_OK if conversion succeded. GNUNET_SYSERR otherwise, in which
1155 * case the contents of r_buf are undefined.
1158 GNUNET_STRINGS_to_address_ip (const char *addr,
1160 struct sockaddr_storage *r_buf)
1163 return GNUNET_STRINGS_to_address_ipv6 (addr, addrlen, (struct sockaddr_in6 *) r_buf);
1164 return GNUNET_STRINGS_to_address_ipv4 (addr, addrlen, (struct sockaddr_in *) r_buf);
1169 * Makes a copy of argv that consists of a single memory chunk that can be
1170 * freed with a single call to GNUNET_free ();
1172 static char *const *
1173 _make_continuous_arg_copy (int argc, char *const *argv)
1175 size_t argvsize = 0;
1179 for (i = 0; i < argc; i++)
1180 argvsize += strlen (argv[i]) + 1 + sizeof (char *);
1181 new_argv = GNUNET_malloc (argvsize + sizeof (char *));
1182 p = (char *) &new_argv[argc + 1];
1183 for (i = 0; i < argc; i++)
1186 strcpy (p, argv[i]);
1187 p += strlen (argv[i]) + 1;
1189 new_argv[argc] = NULL;
1190 return (char *const *) new_argv;
1195 * Returns utf-8 encoded arguments.
1196 * Does nothing (returns a copy of argc and argv) on any platform
1198 * Returned argv has u8argv[u8argc] == NULL.
1199 * Returned argv is a single memory block, and can be freed with a single
1200 * GNUNET_free () call.
1202 * @param argc argc (as given by main())
1203 * @param argv argv (as given by main())
1204 * @param u8argc a location to store new argc in (though it's th same as argc)
1205 * @param u8argv a location to store new argv in
1206 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1209 GNUNET_STRINGS_get_utf8_args (int argc, char *const *argv, int *u8argc, char *const **u8argv)
1216 char **split_u8argv;
1218 wcmd = GetCommandLineW ();
1220 return GNUNET_SYSERR;
1221 wargv = CommandLineToArgvW (wcmd, &wargc);
1223 return GNUNET_SYSERR;
1225 split_u8argv = GNUNET_malloc (argc * sizeof (char *));
1227 for (i = 0; i < wargc; i++)
1230 /* Hopefully it will allocate us NUL-terminated strings... */
1231 split_u8argv[i] = (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1232 if (split_u8argv == NULL)
1235 for (j = 0; j < i; j++)
1236 free (split_u8argv[j]);
1237 GNUNET_free (split_u8argv);
1239 return GNUNET_SYSERR;
1243 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv);
1246 for (i = 0; i < wargc; i++)
1247 free (split_u8argv[i]);
1248 free (split_u8argv);
1251 char *const *new_argv = (char *const *) _make_continuous_arg_copy (argc, argv);
1258 /* end of strings.c */