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