cfengine  3.15.4
About: CFEngine is a configuration management system for configuring and maintaining Unix-like computers (using an own high level policy language). Community version.
  Fossies Dox: cfengine-3.15.4.tar.gz  ("unofficial" and yet experimental doxygen-generated source code documentation)  

string_lib.h
Go to the documentation of this file.
1 /*
2  Copyright 2020 Northern.tech AS
3 
4  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.
5 
6  This program is free software; you can redistribute it and/or modify it
7  under the terms of the GNU General Public License as published by the
8  Free Software Foundation; version 3.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program; if not, write to the Free Software
17  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
18 
19  To the extent this program is licensed as part of the Enterprise
20  versions of CFEngine, the applicable Commercial Open Source License
21  (COSL) may apply to this file if you as a licensee so wish it. See
22  included file COSL.txt.
23 */
24 
25 #ifndef CFENGINE_STRING_LIB_H
26 #define CFENGINE_STRING_LIB_H
27 
28 #include <stdbool.h> // bool
29 #include <stdint.h> // int64_t
30 #include <string.h> // strstr()
31 #include <stdarg.h> // va_list
32 #include <compiler.h>
33 #include <sequence.h>
34 
35 
36 typedef struct
37 {
38  const char *data;
39  size_t len;
40 } StringRef;
41 
42 
43 #define NULL_OR_EMPTY(str) \
44  ((str == NULL) || (str[0] == '\0'))
45 
46 #define NOT_NULL_AND_EMPTY(str) \
47  ((str != NULL) && (str[0] == '\0'))
48 
49 #define STARTSWITH(str,start) \
50  (strncmp(str,start,strlen(start)) == 0)
51 
52 #define SAFENULL(str) \
53  (str != NULL ? str : "(null)")
54 
55 #ifndef EMPTY_STRING_TO_NULL
56 #define EMPTY_STRING_TO_NULL(string) ((SafeStringLength(string) != 0)? string : NULL)
57 #endif
58 #ifndef NULL_TO_EMPTY_STRING
59 #define NULL_TO_EMPTY_STRING(string) (string? string : "")
60 #endif
61 
62 unsigned int StringHash (const char *str, unsigned int seed);
63 unsigned int StringHash_untyped(const void *str, unsigned int seed);
64 
65 char ToLower(char ch);
66 char ToUpper(char ch);
67 void ToUpperStrInplace(char *str);
68 void ToLowerStrInplace(char *str);
69 
70 int StringToLong(const char *str, long *value_out) FUNC_WARN_UNUSED_RESULT;
71 void LogStringToLongError(const char *str_attempted, const char *id, int error_code);
72 long StringToLongDefaultOnError(const char *str, long default_return);
73 long StringToLongExitOnError(const char *str);
74 long StringToLongUnsafe(const char *str); // Deprecated, do not use
75 int StringToInt64(const char *str, int64_t *value_out);
76 int64_t StringToInt64DefaultOnError(const char *str, int64_t default_return);
77 int64_t StringToInt64ExitOnError(const char *str);
78 
79 char *StringFromLong(long number);
80 double StringToDouble(const char *str);
81 char *StringFromDouble(double number);
82 char *NULLStringToEmpty(char *str);
83 
84 bool StringIsNumeric(const char *name);
85 bool StringIsPrintable(const char *name);
86 
87 /**
88  * @brief Check if a char is "printable", replacement for isprint
89  *
90  * isprint takes a (signed) int, so if you send in a (signed) char there is an
91  * implicit cast. This can be problematic, since 0xF0 becomes 0xFFFFF0.
92  *
93  * Additionally, at least on HPUX, isprint returns true for some values above
94  * 127, depending on locale.
95  *
96  * Thus, this replacement works the same everywhere, and can be used when you
97  * want predictable results, even though it will return false for some values
98  * which might be possible to print in your environment / locale.
99  *
100  * @param c [in] Character to evaluate
101  * @return True if c is part of the printable ascii range
102  */
103 static inline bool CharIsPrintableAscii(const char c)
104 {
105  return (c >= ' ' && c <= '~');
106 }
107 bool EmptyString(const char *s);
108 
109 static inline bool StringContains(const char *const haystack, const char *const needle)
110 {
111  return (strstr(haystack, needle) != NULL);
112 }
113 
114 static inline bool StringContainsChar(const char *const haystack, const char needle)
115 {
116  return (strchr(haystack, needle) != NULL);
117 }
118 
119 size_t StringBytesToHex(char *dst, size_t dst_size,
120  const unsigned char *src_bytes, size_t src_len);
121 
122 char *SafeStringDuplicate(const char *str);
123 char *SafeStringNDuplicate(const char *str, size_t size);
124 int SafeStringLength(const char *str);
125 
126 int StringSafeCompare(const char *a, const char *b);
127 bool StringEqual (const char *a, const char *b);
128 
129 int StringSafeCompareN(const char *a, const char *b, size_t n);
130 bool StringEqualN (const char *a, const char *b, size_t n);
131 
132 int StringSafeCompare_IgnoreCase(const char *a, const char *b);
133 bool StringEqual_IgnoreCase (const char *a, const char *b);
134 
135 int StringSafeCompareN_IgnoreCase(const char *a, const char *b, size_t n);
136 bool StringEqualN_IgnoreCase (const char *a, const char *b, size_t n);
137 
138 bool StringEqual_untyped(const void *a, const void *b);
139 
140 char *StringConcatenate(size_t count, const char *first, ...);
141 char *StringSubstring(const char *source, size_t source_len, int start, int len);
142 
143 /* Allocates the result */
144 char *SearchAndReplace(const char *source, const char *search, const char *replace);
145 
146 ssize_t StringReplace(char *buf, size_t buf_size, const char *find, const char *replace);
147 
148 bool IsStrIn(const char *str, const char *const strs[]);
149 bool IsStrCaseIn(const char *str, const char *const strs[]);
150 
151 size_t StringCountTokens(const char *str, size_t len, const char *seps);
152 StringRef StringGetToken(const char *str, size_t len, size_t index, const char *seps);
153 
154 char **String2StringArray(const char *str, char separator);
155 void FreeStringArray(char **strs);
156 
157 int CountChar(const char *string, char sp);
158 void ReplaceChar(char *in, char *out, int outSz, char from, char to);
159 void ReplaceTrailingChar(char *str, char from, char to);
160 char *EscapeCharCopy(const char *str, char to_escape, char escape_with);
161 
162 char *ScanPastChars(char *scanpast, char *input);
163 
164 /**
165  * @brief Strips the newline character off a string, in place
166  * @param str The string to strip
167  * @param max_length Maximum length of input string
168  * @return 0 if successful, -1 if the input string was longer than allowed (max_length).
169  */
170 int StripTrailingNewline(char *str, size_t max_length);
171 
172 /**
173  * @brief Remove trailing spaces
174  * @param str
175  * @param max_length Maximum length of input string
176  * @return 0 if successful, -1 if Chop was called on a string that seemed to have no terminator
177  */
178 int Chop(char *str, size_t max_length);
179 
180 char *TrimWhitespace(char *s);
181 size_t TrimCSVLineCRLF(char *data);
182 size_t TrimCSVLineCRLFStrict(char *data);
183 
184 /**
185  * @brief Erase part of a string using memmove()
186  *
187  * String must be NUL-terminated. Indices from start, up to but not including
188  * end are erased. The number of bytes erased is end - start. If start == end,
189  * no bytes are erased. Assumes: 0 <= start <= end <= strlen(s)
190  */
191 void StringCloseHole(char *s, int start, int end);
192 
193 /**
194  * @brief Check if a string ends with the given suffix
195  * @param str
196  * @param suffix
197  * @param case_fold whether the comparison is case-insensitive
198  * @return True if suffix matches
199  */
200 bool StringEndsWithCase(const char *str, const char *suffix, const bool case_fold);
201 
202 /**
203  * @brief Check if a string ends with the given suffix
204  * @param str
205  * @param suffix
206  * @return True if suffix matches
207  */
208 bool StringEndsWith(const char *str, const char *suffix);
209 
210 /**
211  * @brief Check if a string starts with the given prefix
212  * @param str
213  * @param prefix
214  * @return True if prefix matches
215  */
216 bool StringStartsWith(const char *str, const char *prefix);
217 
218 /**
219  * @brief Format string like vsprintf and return formatted string allocated
220  * on heap as a return value.
221  */
222 char *StringVFormat(const char *fmt, va_list ap);
223 
224 /**
225  * @brief Format string like sprintf and return formatted string allocated on
226  * heap as a return value.
227  *
228  * @param format Formatting string
229 
230  * @return formatted string (on heap) or NULL in case of error. errno is set in
231  * the latter case (see errno codes for sprintf).
232  */
233 char *StringFormat(const char *fmt, ...) FUNC_ATTR_PRINTF(1, 2);
234 
235 /**
236  * @brief Copy a string from `from` to `to` (a buffer of at least buf_size)
237  *
238  * The destination (`to`) is guaranteed to be NUL terminated,
239  * `to[buf_size-1]` will always be '\0'. If the string is shorter
240  * the additional trailing bytes are also zeroed.
241  *
242  * The source (`from`) must either be NUL terminated or big enough
243  * to read buf_size characters, even though only buf_size - 1 of them
244  * end up in the output buffer.
245  *
246  * The return value is equal to `strlen(to)`, for large data sizes this
247  * is useful since it doesn't require a second pass through the data.
248  * The return value should be checked, if it is >= buf_size, it means
249  * the string was truncated because it was too long. Expressed in another
250  * way, the return value is the number of bytes read from the input (`from`)
251  * excluding the terminating `\0` byte (up to buf_size characters will be
252  * read).
253  *
254  * @note `from` and `to` must not overlap
255  * @warning Regardless of `strlen(from)`, `to` must be at least `buf_size` big
256  * @param[in] from String to copy from, up to buf_size bytes are read
257  * @param[out] to Output buffer (minimum buf_size), always '\0' terminated
258  * @param[in] buf_size Maximum buffer size to write (including '\0' byte)
259  * @return String length of `to`, or `buf_size` in case of overflow
260  */
261 size_t StringCopy(const char *from, char *to, size_t buf_size);
262 
263 void *memcchr(const void *buf, int c, size_t buf_size);
264 
265 bool StringNotMatchingSetCapped(const char *isp, int limit,
266  const char *exclude, char *obuf);
267 
268 /**
269  * @brief Appends src to dst, but will not exceed n bytes in dst, including the terminating null.
270  * @param dst Destination string.
271  * @param src Source string.
272  * @param n Total size of dst buffer. The string will be truncated if this is exceeded.
273  * @return True if append was successful, false if the operation caused an overflow.
274  */
275 bool StringAppend(char *dst, const char *src, size_t n);
276 
277 char *StringCanonify(char *dst, const char *src);
278 bool PathAppend(char *path, size_t path_size, const char *leaf, char sep);
279 
280 void StrCat(char *dst, size_t dst_size, size_t *dst_len,
281  const char *src, size_t src_len);
282 void StrCatDelim(char *dst, size_t dst_size, size_t *dst_len,
283  const char *src, char sep);
284 
285 void CanonifyNameInPlace(char *str);
286 
287 /**
288  * @brief Check if a command line argument matches a short or long option
289  *
290  * Useful for smaller binaries, when getopt seems overkill and you just want
291  * something simple. A match means it's either equal to shortopt or equal to
292  * (the first part of) longopt. shortopt is compared case sensitively,
293  * while longopt is compared case insensitively.
294  *
295  * As an example, `--INFO` would match the longopt `--inform`.
296  *
297  * It doesn't (cannot) detect ambiguities when there are multiple options.
298  * In many cases, where you need more flexibility and consistency, it's better
299  * to use getopt or something similar.
300  *
301  * @param[in] supplied User supplied argument from command line (trimmed word)
302  * @param[out] longopt Long option alternative to check (ex. "--help")
303  * @param[out] shortopt Short option alternative to check (ex. "-H")
304  * @return True if `supplied` _matches_ `longopt` or `shortopt`
305  */
307  const char *supplied, const char *longopt, const char *shortopt);
308 
309 #endif
static int input(void)
Definition: cf3lex.c:2154
#define FUNC_ATTR_PRINTF(string_index, first_to_check)
Definition: compiler.h:52
#define FUNC_WARN_UNUSED_RESULT
Definition: compiler.h:55
#define NULL
Definition: getopt1.c:56
#define const
Definition: getopt.c:38
void ToUpperStrInplace(char *str)
Definition: string_lib.c:152
char * StringFromDouble(double number)
Definition: string_lib.c:741
bool StringEqual_IgnoreCase(const char *a, const char *b)
Definition: string_lib.c:296
bool StringEndsWith(const char *str, const char *suffix)
Check if a string ends with the given suffix.
Definition: string_lib.c:1330
bool StringAppend(char *dst, const char *src, size_t n)
Appends src to dst, but will not exceed n bytes in dst, including the terminating null.
Definition: string_lib.c:1408
static bool CharIsPrintableAscii(const char c)
Check if a char is "printable", replacement for isprint.
Definition: string_lib.h:103
bool StringStartsWith(const char *str, const char *prefix)
Check if a string starts with the given prefix.
Definition: string_lib.c:1335
char * StringSubstring(const char *source, size_t source_len, int start, int len)
Definition: string_lib.c:391
char * SafeStringDuplicate(const char *str)
Definition: string_lib.c:172
size_t TrimCSVLineCRLF(char *data)
Remove the CRLF at the end of a CSV line, if it exists.
Definition: string_lib.c:1237
static bool StringContainsChar(const char *const haystack, const char needle)
Definition: string_lib.h:114
size_t TrimCSVLineCRLFStrict(char *data)
Remove the CRLF at the end of a non-empty CSV line, if it exists.
Definition: string_lib.c:1271
void StrCatDelim(char *dst, size_t dst_size, size_t *dst_len, const char *src, char sep)
Definition: string_lib.c:1534
bool IsStrCaseIn(const char *str, const char *const strs[])
Definition: string_lib.c:796
bool StringNotMatchingSetCapped(const char *isp, int limit, const char *exclude, char *obuf)
Definition: string_lib.c:1389
void * memcchr(const void *buf, int c, size_t buf_size)
Definition: string_lib.c:1364
int64_t StringToInt64DefaultOnError(const char *str, int64_t default_return)
Converts a string to int64_t, with a default value in case of errors.
Definition: string_lib.c:685
int StringSafeCompareN_IgnoreCase(const char *a, const char *b, size_t n)
Definition: string_lib.c:281
bool StringIsPrintable(const char *name)
Definition: string_lib.c:441
bool IsStrIn(const char *str, const char *const strs[])
Definition: string_lib.c:782
int StringToInt64(const char *str, int64_t *value_out)
Converts a string of numerals in base 10 to 64-bit signed int.
Definition: string_lib.c:608
bool StringEqualN_IgnoreCase(const char *a, const char *b, size_t n)
Definition: string_lib.c:301
bool StringEndsWithCase(const char *str, const char *suffix, const bool case_fold)
Check if a string ends with the given suffix.
Definition: string_lib.c:1301
size_t StringCountTokens(const char *str, size_t len, const char *seps)
Definition: string_lib.c:945
bool StringEqual_untyped(const void *a, const void *b)
Definition: string_lib.c:306
char ** String2StringArray(const char *str, char separator)
Definition: string_lib.c:1022
char ToLower(char ch)
Definition: string_lib.c:119
long StringToLongUnsafe(const char *str)
Convert a string of numerals to a long integer (deprecated).
Definition: string_lib.c:707
int StringToLong(const char *str, long *value_out)
Converts a string of numerals in base 10 to a long integer.
Definition: string_lib.c:485
bool EmptyString(const char *s)
Definition: string_lib.c:454
char * NULLStringToEmpty(char *str)
Definition: string_lib.c:748
char * TrimWhitespace(char *s)
Definition: string_lib.c:1196
size_t StringCopy(const char *from, char *to, size_t buf_size)
Copy a string from from to to (a buffer of at least buf_size)
Definition: string_lib.c:60
char ToUpper(char ch)
Definition: string_lib.c:133
char * ScanPastChars(char *scanpast, char *input)
Definition: string_lib.c:1126
char * StringCanonify(char *dst, const char *src)
Definition: string_lib.c:1430
int Chop(char *str, size_t max_length)
Remove trailing spaces.
Definition: string_lib.c:1174
char * StringVFormat(const char *fmt, va_list ap)
Format string like vsprintf and return formatted string allocated on heap as a return value.
Definition: string_lib.c:37
unsigned int StringHash_untyped(const void *str, unsigned int seed)
Definition: string_lib.c:114
int StripTrailingNewline(char *str, size_t max_length)
Strips the newline character off a string, in place.
Definition: string_lib.c:1138
long StringToLongDefaultOnError(const char *str, long default_return)
Converts a string of numerals in base 10 to a long integer, uses a default value if errors occur.
Definition: string_lib.c:560
double StringToDouble(const char *str)
Definition: string_lib.c:729
void ReplaceTrailingChar(char *str, char from, char to)
Definition: string_lib.c:922
void FreeStringArray(char **strs)
Definition: string_lib.c:1072
bool PathAppend(char *path, size_t path_size, const char *leaf, char sep)
Definition: string_lib.c:1454
void StrCat(char *dst, size_t dst_size, size_t *dst_len, const char *src, size_t src_len)
Definition: string_lib.c:1494
int StringSafeCompareN(const char *a, const char *b, size_t n)
Definition: string_lib.c:241
void ReplaceChar(char *in, char *out, int outSz, char from, char to)
Definition: string_lib.c:839
bool StringIsNumeric(const char *name)
Definition: string_lib.c:428
char * StringFromLong(long number)
Definition: string_lib.c:720
bool StringMatchesOption(const char *supplied, const char *longopt, const char *shortopt)
Check if a command line argument matches a short or long option.
Definition: string_lib.c:1585
int CountChar(const char *string, char sp)
Definition: string_lib.c:810
void CanonifyNameInPlace(char *str)
Definition: string_lib.c:1574
bool StringEqual(const char *a, const char *b)
Definition: string_lib.c:256
unsigned int StringHash(const char *str, unsigned int seed)
Definition: string_lib.c:90
ssize_t StringReplace(char *buf, size_t buf_size, const char *find, const char *replace)
Definition: string_lib.c:868
void LogStringToLongError(const char *str_attempted, const char *id, int error_code)
Log StringToLong conversion error with an identifier for debugging.
Definition: string_lib.c:529
char * EscapeCharCopy(const char *str, char to_escape, char escape_with)
Definition: string_lib.c:1091
StringRef StringGetToken(const char *str, size_t len, size_t index, const char *seps)
Definition: string_lib.c:1003
char * StringConcatenate(size_t count, const char *first,...)
Definition: string_lib.c:348
int64_t StringToInt64ExitOnError(const char *str)
Convert a string to int64_t, exits if parsing fails.
Definition: string_lib.c:662
char * SafeStringNDuplicate(const char *str, size_t size)
Definition: string_lib.c:184
int StringSafeCompare_IgnoreCase(const char *a, const char *b)
Definition: string_lib.c:266
long StringToLongExitOnError(const char *str)
Converts a string of numerals in base 10 to a long integer, exits on error.
Definition: string_lib.c:584
char * StringFormat(const char *fmt,...)
Format string like sprintf and return formatted string allocated on heap as a return value.
Definition: string_lib.c:51
void StringCloseHole(char *s, int start, int end)
Erase part of a string using memmove()
Definition: string_lib.c:1287
int StringSafeCompare(const char *a, const char *b)
Definition: string_lib.c:226
int SafeStringLength(const char *str)
Definition: string_lib.c:196
char * SearchAndReplace(const char *source, const char *search, const char *replace)
Definition: string_lib.c:313
bool StringEqualN(const char *a, const char *b, size_t n)
Definition: string_lib.c:261
static bool StringContains(const char *const haystack, const char *const needle)
Definition: string_lib.h:109
void ToLowerStrInplace(char *str)
Definition: string_lib.c:162
size_t StringBytesToHex(char *dst, size_t dst_size, const unsigned char *src_bytes, size_t src_len)
Definition: string_lib.c:762
char * strstr(const char *haystack, const char *needle)
Definition: strstr.c:35
size_t len
Definition: string_lib.h:39
const char * data
Definition: string_lib.h:38