fix bad free
[oweals/gnunet.git] / src / include / gnunet_strings_lib.h
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2013 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your option) any later version.
9
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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @author Christian Grothoff
21  * @author Krista Bennett
22  * @author Gerd Knorr <kraxel@bytesex.org>
23  * @author Ioana Patrascu
24  * @author Tzvetan Horozov
25  *
26  * @file
27  * Strings and string handling functions
28  *
29  * @defgroup strings  Strings library
30  * Strings and string handling functions, including malloc and string tokenizing.
31  * @{
32  */
33
34 #ifndef GNUNET_STRINGS_LIB_H
35 #define GNUNET_STRINGS_LIB_H
36
37 /* we need size_t, and since it can be both unsigned int
38    or unsigned long long, this IS platform dependent;
39    but "stdlib.h" should be portable 'enough' to be
40    unconditionally available... */
41 #include <stdlib.h>
42
43 #ifdef __cplusplus
44 extern "C"
45 {
46 #if 0                           /* keep Emacsens' auto-indent happy */
47 }
48 #endif
49 #endif
50
51 #include "gnunet_time_lib.h"
52
53
54 /**
55  * Convert a given fancy human-readable size to bytes.
56  *
57  * @param fancy_size human readable string (i.e. 1 MB)
58  * @param size set to the size in bytes
59  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
60  */
61 int
62 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
63                                     unsigned long long *size);
64
65
66 /**
67  * Convert a given fancy human-readable time to our internal
68  * representation.
69  *
70  * @param fancy_time human readable string (i.e. 1 minute)
71  * @param rtime set to the relative time
72  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
73  */
74 int
75 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
76                                        struct GNUNET_TIME_Relative *rtime);
77
78
79 /**
80  * @ingroup time
81  * Convert a given fancy human-readable time to our internal
82  * representation.  The human-readable time is expected to be
83  * in local time, whereas the returned value will be in UTC.
84  *
85  * @param fancy_time human readable string (i.e. %Y-%m-%d %H:%M:%S)
86  * @param atime set to the absolute time
87  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
88  */
89 int
90 GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
91                                        struct GNUNET_TIME_Absolute *atime);
92
93
94 /**
95  * Convert a given filesize into a fancy human-readable format.
96  *
97  * @param size number of bytes
98  * @return fancy representation of the size (possibly rounded) for humans
99  */
100 char *
101 GNUNET_STRINGS_byte_size_fancy (unsigned long long size);
102
103
104 /**
105  * Convert the len characters long character sequence
106  * given in input that is in the given input charset
107  * to a string in given output charset.
108  *
109  * @param input input string
110  * @param len number of bytes in @a input
111  * @param input_charset character set used for @a input
112  * @param output_charset desired character set for the return value
113  * @return the converted string (0-terminated),
114  *  if conversion fails, a copy of the orignal
115  *  string is returned.
116  */
117 char *
118 GNUNET_STRINGS_conv (const char *input, size_t len,
119                      const char *input_charset,
120                      const char *output_charset);
121
122
123 /**
124  * Convert the len characters long character sequence
125  * given in input that is in the given charset
126  * to UTF-8.
127  *
128  * @param input the input string (not necessarily 0-terminated)
129  * @param len the number of bytes in the @a input
130  * @param charset character set to convert from
131  * @return the converted string (0-terminated)
132  */
133 char *
134 GNUNET_STRINGS_to_utf8 (const char *input,
135                         size_t len,
136                         const char *charset);
137
138
139 /**
140  * Convert the len bytes-long UTF-8 string
141  * given in input to the given charset.
142  *
143  * @param input the input string (not necessarily 0-terminated)
144  * @param len the number of bytes in the @a input
145  * @param charset character set to convert to
146  * @return the converted string (0-terminated),
147  *  if conversion fails, a copy of the orignal
148  *  string is returned.
149  */
150 char *
151 GNUNET_STRINGS_from_utf8 (const char *input,
152                           size_t len,
153                           const char *charset);
154
155
156 /**
157  * Convert the utf-8 input string to lower case.
158  * Output needs to be allocated appropriately.
159  *
160  * @param input input string
161  * @param output output buffer
162  */
163 void
164 GNUNET_STRINGS_utf8_tolower (const char *input,
165                              char *output);
166
167
168 /**
169  * Convert the utf-8 input string to upper case.
170  * Output needs to be allocated appropriately.
171  *
172  * @param input input string
173  * @param output output buffer
174  */
175 void
176 GNUNET_STRINGS_utf8_toupper (const char *input,
177                              char *output);
178
179
180 /**
181  * Complete filename (a la shell) from abbrevition.
182  *
183  * @param fil the name of the file, may contain ~/ or
184  *        be relative to the current directory
185  * @return the full file name,
186  *          NULL is returned on error
187  */
188 char *
189 GNUNET_STRINGS_filename_expand (const char *fil);
190
191
192 /**
193  * Fill a buffer of the given size with count 0-terminated strings
194  * (given as varargs).  If "buffer" is NULL, only compute the amount
195  * of space required (sum of "strlen(arg)+1").
196  *
197  * Unlike using "snprintf" with "%s", this function will add
198  * 0-terminators after each string.  The
199  * "GNUNET_string_buffer_tokenize" function can be used to parse the
200  * buffer back into individual strings.
201  *
202  * @param buffer the buffer to fill with strings, can
203  *               be NULL in which case only the necessary
204  *               amount of space will be calculated
205  * @param size number of bytes available in buffer
206  * @param count number of strings that follow
207  * @param ... count 0-terminated strings to copy to buffer
208  * @return number of bytes written to the buffer
209  *         (or number of bytes that would have been written)
210  */
211 size_t
212 GNUNET_STRINGS_buffer_fill (char *buffer,
213                             size_t size,
214                             unsigned int count,
215                             ...);
216
217
218 /**
219  * Given a buffer of a given size, find "count" 0-terminated strings
220  * in the buffer and assign the count (varargs) of type "const char**"
221  * to the locations of the respective strings in the buffer.
222  *
223  * @param buffer the buffer to parse FIXME: not 'const', is it?
224  * @param size size of the @a buffer
225  * @param count number of strings to locate
226  * @param ... pointers to where to store the strings
227  * @return offset of the character after the last 0-termination
228  *         in the buffer, or 0 on error.
229  */
230 unsigned int
231 GNUNET_STRINGS_buffer_tokenize (const char *buffer,
232                                 size_t size,
233                                 unsigned int count, ...);
234
235
236
237 /**
238  * @ingroup time
239  * Like `asctime`, except for GNUnet time.  Converts a GNUnet internal
240  * absolute time (which is in UTC) to a string in local time.
241  * Note that the returned value will be overwritten if this function
242  * is called again.
243  *
244  * @param t the absolute time to convert
245  * @return timestamp in human-readable form in local time
246  */
247 const char *
248 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t);
249
250
251 /**
252  * @ingroup time
253  * Give relative time in human-readable fancy format.
254  * This is one of the very few calls in the entire API that is
255  * NOT reentrant!
256  *
257  * @param delta time in milli seconds
258  * @param do_round are we allowed to round a bit?
259  * @return string in human-readable form
260  */
261 const char *
262 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
263                                         int do_round);
264
265
266 /**
267  * "man basename"
268  * Returns a pointer to a part of filename (allocates nothing)!
269  *
270  * @param filename filename to extract basename from
271  * @return short (base) name of the file (that is, everything following the
272  *         last directory separator in filename. If filename ends with a
273  *         directory separator, the result will be a zero-length string.
274  *         If filename has no directory separators, the result is filename
275  *         itself.
276  */
277 const char *
278 GNUNET_STRINGS_get_short_name (const char *filename);
279
280
281 /**
282  * Convert binary data to ASCII encoding using CrockfordBase32.
283  * Does not append 0-terminator, but returns a pointer to the place where
284  * it should be placed, if needed.
285  *
286  * @param data data to encode
287  * @param size size of data (in bytes)
288  * @param out buffer to fill
289  * @param out_size size of the buffer. Must be large enough to hold
290  * ((size*8) + (((size*8) % 5) > 0 ? 5 - ((size*8) % 5) : 0)) / 5
291  * @return pointer to the next byte in 'out' or NULL on error.
292  */
293 char *
294 GNUNET_STRINGS_data_to_string (const void *data,
295                                size_t size,
296                                char *out,
297                                size_t out_size);
298
299
300 /**
301  * Return the base32crockford encoding of the given buffer.
302  *
303  * The returned string will be freshly allocated, and must be free'd
304  * with #GNUNET_free().
305  *
306  * @param buf buffer with data
307  * @param size size of the buffer @a buf
308  * @return freshly allocated, null-terminated string
309  */
310 char *
311 GNUNET_STRINGS_data_to_string_alloc (const void *buf,
312                                      size_t size);
313
314
315 /**
316  * Convert CrockfordBase32 encoding back to data.
317  * @a out_size must match exactly the size of the data before it was encoded.
318  *
319  * @param enc the encoding
320  * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
321  * @param out location where to store the decoded data
322  * @param out_size size of the output buffer @a out
323  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
324  */
325 int
326 GNUNET_STRINGS_string_to_data (const char *enc,
327                                size_t enclen,
328                                void *out,
329                                size_t out_size);
330
331
332 /**
333  * Encode into Base64.
334  *
335  * @param data the data to encode
336  * @param len the length of the input
337  * @param output where to write the output (*output should be NULL,
338  *   is allocated)
339  * @return the size of the output
340  */
341 size_t
342 GNUNET_STRINGS_base64_encode (const char *data, size_t len, char **output);
343
344
345 /**
346  * Decode from Base64.
347  *
348  * @param data the data to encode
349  * @param len the length of the input
350  * @param[out] output where to write the output (*output should be NULL,
351  *   is allocated)
352  * @return the size of the output
353  */
354 size_t
355 GNUNET_STRINGS_base64_decode (const char *data,
356                               size_t len,
357                               char **output);
358
359
360 /**
361  * Convert a peer path to a human-readable string.
362  *
363  * @param pids array of PIDs to convert to a string
364  * @param num_pids length of the @a pids array
365  * @return string representing the array of @a pids
366  */
367 char *
368 GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids,
369                      unsigned int num_pids);
370
371
372 /**
373  * Parse a path that might be an URI.
374  *
375  * @param path path to parse. Must be NULL-terminated.
376  * @param[out] scheme_part pointer to a string that
377  *        represents the URI scheme will be stored. Can be NULL. The string is
378  *        allocated by the function, and should be freed by GNUNET_free() when
379  *        it is no longer needed.
380  * @param path_part a pointer to 'const char *' where a pointer to the path
381  *        part of the URI will be stored. Can be NULL. Points to the same block
382  *        of memory as @a path, and thus must not be freed. Might point to '\0',
383  *        if path part is zero-length.
384  * @return #GNUNET_YES if it's an URI, #GNUNET_NO otherwise. If 'path' is not
385  *         an URI, '* scheme_part' and '*path_part' will remain unchanged
386  *         (if they weren't NULL).
387  */
388 int
389 GNUNET_STRINGS_parse_uri (const char *path,
390                           char **scheme_part,
391                           const char **path_part);
392
393
394 /**
395  * Check whether filename is absolute or not, and if it's an URI
396  *
397  * @param filename filename to check
398  * @param can_be_uri #GNUNET_YES to check for being URI, #GNUNET_NO - to
399  *        assume it's not URI
400  * @param r_is_uri a pointer to an int that is set to #GNUNET_YES if 'filename'
401  *        is URI and to GNUNET_NO otherwise. Can be NULL. If 'can_be_uri' is
402  *        not #GNUNET_YES, *r_is_uri is set to #GNUNET_NO.
403  * @param r_uri_scheme a pointer to a char * that is set to a pointer to URI scheme.
404  *        The string is allocated by the function, and should be freed with
405  *        GNUNET_free (). Can be NULL.
406  * @return #GNUNET_YES if 'filename' is absolute, #GNUNET_NO otherwise.
407  */
408 int
409 GNUNET_STRINGS_path_is_absolute (const char *filename,
410                                  int can_be_uri,
411                                  int *r_is_uri,
412                                  char **r_uri_scheme);
413
414
415 /**
416  * Flags for what we should check a file for.
417  */
418 enum GNUNET_STRINGS_FilenameCheck
419 {
420   /**
421    * Check that it exists.
422    */
423   GNUNET_STRINGS_CHECK_EXISTS = 0x00000001,
424
425   /**
426    * Check that it is a directory.
427    */
428   GNUNET_STRINGS_CHECK_IS_DIRECTORY = 0x00000002,
429
430   /**
431    * Check that it is a link.
432    */
433   GNUNET_STRINGS_CHECK_IS_LINK = 0x00000004,
434
435   /**
436    * Check that the path is an absolute path.
437    */
438   GNUNET_STRINGS_CHECK_IS_ABSOLUTE = 0x00000008
439 };
440
441
442 /**
443  * Perform checks on @a filename.  FIXME: some duplication with
444  * "GNUNET_DISK_"-APIs.  We should unify those.
445  *
446  * @param filename file to check
447  * @param checks checks to perform
448  * @return #GNUNET_YES if all checks pass, #GNUNET_NO if at least one of them
449  *         fails, #GNUNET_SYSERR when a check can't be performed
450  */
451 int
452 GNUNET_STRINGS_check_filename (const char *filename,
453                                enum GNUNET_STRINGS_FilenameCheck checks);
454
455
456 /**
457  * Tries to convert @a zt_addr string to an IPv6 address.
458  * The string is expected to have the format "[ABCD::01]:80".
459  *
460  * @param zt_addr 0-terminated string. May be mangled by the function.
461  * @param addrlen length of zt_addr (not counting 0-terminator).
462  * @param r_buf a buffer to fill. Initially gets filled with zeroes,
463  *        then its sin6_port, sin6_family and sin6_addr are set appropriately.
464  * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
465  *         case the contents of r_buf are undefined.
466  */
467 int
468 GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
469                                 uint16_t addrlen,
470                                 struct sockaddr_in6 *r_buf);
471
472
473 /**
474  * Tries to convert @a zt_addr string to an IPv4 address.
475  * The string is expected to have the format "1.2.3.4:80".
476  *
477  * @param zt_addr 0-terminated string. May be mangled by the function.
478  * @param addrlen length of zt_addr (not counting 0-terminator).
479  * @param r_buf a buffer to fill.
480  * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which case
481  *         the contents of r_buf are undefined.
482  */
483 int
484 GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
485                                 uint16_t addrlen,
486                                 struct sockaddr_in *r_buf);
487
488
489 /**
490  * Parse an address given as a string into a
491  * `struct sockaddr`.
492  *
493  * @param addr the address
494  * @param[out] af set to the parsed address family (i.e. AF_INET)
495  * @param[out] sa set to the parsed address
496  * @return 0 on error, otherwise number of bytes in @a sa
497  */
498 size_t
499 GNUNET_STRINGS_parse_socket_addr (const char *addr,
500                                   uint8_t *af,
501                                   struct sockaddr **sa);
502
503
504 /**
505  * Tries to convert @a addr string to an IP (v4 or v6) address.
506  * Will automatically decide whether to treat 'addr' as v4 or v6 address.
507  *
508  * @param addr a string, may not be 0-terminated.
509  * @param addrlen number of bytes in @a addr (if addr is 0-terminated,
510  *        0-terminator should not be counted towards addrlen).
511  * @param r_buf a buffer to fill.
512  * @return #GNUNET_OK if conversion succeded. #GNUNET_SYSERR otherwise, in which
513  *         case the contents of r_buf are undefined.
514  */
515 int
516 GNUNET_STRINGS_to_address_ip (const char *addr,
517                               uint16_t addrlen,
518                               struct sockaddr_storage *r_buf);
519
520
521 /**
522  * Returns utf-8 encoded arguments.  Does nothing (returns a copy of
523  * @a argc and @a argv) on any platform other than W32.  Returned @a
524  * argv has `u8argv[u8argc] == NULL`.  Returned @a argv is a single
525  * memory block, and can be freed with a single GNUNET_free() call.
526  *
527  * @param argc argc (as given by main())
528  * @param argv argv (as given by main())
529  * @param u8argc a location to store new argc in (though it's th same as argc)
530  * @param u8argv a location to store new argv in
531  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
532  */
533 int
534 GNUNET_STRINGS_get_utf8_args (int argc,
535                               char *const *argv,
536                               int *u8argc,
537                               char *const **u8argv);
538
539
540 /* ***************** IPv4/IPv6 parsing ****************** */
541
542 struct GNUNET_STRINGS_PortPolicy
543 {
544
545   /**
546    * Starting port range (0 if none given).
547    */
548   uint16_t start_port;
549
550   /**
551    * End of port range (0 if none given).
552    */
553   uint16_t end_port;
554
555   /**
556    * #GNUNET_YES if the port range should be negated
557    * ("!" in policy).
558    */
559   int negate_portrange;
560
561 };
562
563
564 /**
565  * @brief IPV4 network in CIDR notation.
566  */
567 struct GNUNET_STRINGS_IPv4NetworkPolicy
568 {
569   /**
570    * IPv4 address.
571    */
572   struct in_addr network;
573
574   /**
575    * IPv4 netmask.
576    */
577   struct in_addr netmask;
578
579   /**
580    * Policy for port access.
581    */
582   struct GNUNET_STRINGS_PortPolicy pp;
583
584 };
585
586
587 /**
588  * @brief network in CIDR notation for IPV6.
589  */
590 struct GNUNET_STRINGS_IPv6NetworkPolicy
591 {
592   /**
593    * IPv6 address.
594    */
595   struct in6_addr network;
596
597   /**
598    * IPv6 netmask.
599    */
600   struct in6_addr netmask;
601
602   /**
603    * Policy for port access.
604    */
605   struct GNUNET_STRINGS_PortPolicy pp;
606
607 };
608
609
610 /**
611  * Parse an IPv4 network policy. The argument specifies a list of
612  * subnets. The format is <tt>(network[/netmask][:[!]SPORT-DPORT];)*</tt>
613  * (no whitespace, must be terminated with a semicolon). The network
614  * must be given in dotted-decimal notation. The netmask can be given
615  * in CIDR notation (/16) or in dotted-decimal (/255.255.0.0).
616  *
617  * @param routeListX a string specifying the IPv4 subnets
618  * @return the converted list, terminated with all zeros;
619  *         NULL if the synatx is flawed
620  */
621 struct GNUNET_STRINGS_IPv4NetworkPolicy *
622 GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX);
623
624
625 /**
626  * Parse an IPv6 network policy. The argument specifies a list of
627  * subnets. The format is <tt>(network[/netmask[:[!]SPORT[-DPORT]]];)*</tt>
628  * (no whitespace, must be terminated with a semicolon). The network
629  * must be given in colon-hex notation.  The netmask must be given in
630  * CIDR notation (/16) or can be omitted to specify a single host.
631  * Note that the netmask is mandatory if ports are specified.
632  *
633  * @param routeListX a string specifying the policy
634  * @return the converted list, 0-terminated, NULL if the synatx is flawed
635  */
636 struct GNUNET_STRINGS_IPv6NetworkPolicy *
637 GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX);
638
639
640
641 #if 0                           /* keep Emacsens' auto-indent happy */
642 {
643 #endif
644 #ifdef __cplusplus
645 }
646 #endif
647
648 /* ifndef GNUNET_UTIL_STRING_H */
649 #endif
650
651 /** @} */  /* end of group */
652
653 /* end of gnunet_util_string.h */