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