Debian Codegraph @

src/common/util.c

raw symbols SCIP
1 /*
2 * Copyright 2009 Red Hat Inc., Durham, North Carolina.
3 * All Rights Reserved.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library 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 GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 * Authors:
20 * Maros Barabas <[email protected]>
21 * Lukas Kuklinek <[email protected]>
22 */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <time.h>
29 #include <fcntl.h>
30 #include <string.h>
31 #include <ctype.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <math.h>
35 #include <sys/stat.h>
36
37 #include "util.h"
38 #include "_error.h"
39 #include "oscap.h"
40 #include "oscap_helpers.h"
41 #include "oscap_pcre.h"
42 #include "debug_priv.h"
43
44 #ifdef OS_WINDOWS
45 #include <stdlib.h>
46 #include <windows.h>
47 #else
48 #include <libgen.h>
49 #include <strings.h>
50 #endif
51
52 #define PATH_SEPARATOR '/'
53
54 char *oscap_generate_random_string(size_t len, char *charset)
55 {
56 char default_charset[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
57 char *res = NULL;
58 charset = (charset != NULL && strlen(charset) > 0) ? charset : default_charset;
59 size_t charset_len = strlen(charset);
60 if (len > 0) {
61 srand(time(NULL));
62 res = malloc(len+1);
63 res[len] = 0;
64 while (len-- > 0) {
65 size_t index = (double) rand() / RAND_MAX * (charset_len-1);
66 res[len] = charset[index];
67 }
68 }
69 return res;
70 }
71
72 int oscap_string_to_enum(const struct oscap_string_map *map, const char *str)
73 {
74 __attribute__nonnull__(map);
75
76 while (map->string && (str == NULL || strcmp(map->string, str) != 0))
77 ++map;
78 return map->value;
79 }
80
81 const char *oscap_enum_to_string(const struct oscap_string_map *map, int val)
82 {
83 __attribute__nonnull__(map);
84
85 while (map->string && map->value != val)
86 ++map;
87 return map->string;
88 }
89
90 static const size_t CPE_SPLIT_INIT_ALLOC = 8;
91
92 char **oscap_split(char *str, const char *delim)
93 {
94
95 __attribute__nonnull__(str);
96
97 char **stringp = &str;
98 int alloc = CPE_SPLIT_INIT_ALLOC;
99 char **fields = malloc(alloc * sizeof(char *));
100 if (!fields)
101 return NULL;
102
103 int i = 0;
104 while (*stringp) {
105 if (i + 2 > alloc) {
106 void *old = fields;
107 alloc *= 2;
108 fields = realloc(fields, alloc * sizeof(char *));
109 if (fields == NULL) {
110 free(old);
111 return NULL;
112 }
113 }
114 fields[i++] = strsep(stringp, delim);
115 }
116 fields[i] = NULL;
117
118 return fields;
119 }
120
121 char *oscap_trim(char *str)
122 {
123 int off, i = 0;
124
125 if (str == NULL)
126 return (NULL);
127
128 /* left trim */
129 while (isspace(str[i])) ++i;
130
131 off = i;
132
133 /* move */
134 while (1) {
135 str[i - off] = str[i];
136 if (str[i] == '\0')
137 break;
138 ++i;
139 }
140
141 i -= off;
142
143 /* right trim */
144 while (i > 0) {
145 if (!isspace(str[--i])) {
146 str[i + 1] = '\0';
147 break;
148 }
149 }
150
151 return str;
152 }
153
154 char *oscap_vsprintf(const char *fmt, va_list ap)
155 {
156 if (fmt == NULL) return NULL;
157
158 char *ret = NULL;
159 va_list args;
160 va_copy(args, ap);
161
162 char foo[2];
163 int length = vsnprintf(foo, 1, fmt, ap);
164 if (length < 0) goto cleanup;
165
166 ret = malloc(sizeof(char) * (length + 1));
167 vsprintf(ret, fmt, args);
168 assert(ret[length] == '\0');
169
170 cleanup:
171 va_end(args);
172 return ret;
173 }
174
175 char *oscap_sprintf(const char *fmt, ...)
176 {
177 char *ret = NULL;
178 va_list ap;
179 va_start(ap, fmt);
180 ret = oscap_vsprintf(fmt, ap);
181 va_end(ap);
182 return ret;
183 }
184
185 char *oscap_rtrim(char *str, char ch)
186 {
187 if (str == NULL) return NULL;
188 for (char *pos = str + strlen(str) - 1; pos >= str; --pos) {
189 if (*pos == ch) *pos = '\0';
190 else break;
191 }
192 return str;
193 }
194
195 void oscap_strtoupper(char *str)
196 {
197 if (!str) return;
198 for (; *str; ++str) *str = toupper(*str);
199 }
200
201 char *oscap_expand_ipv6(const char *input)
202 {
203 // we have to do a double pass because we need to know the number of
204 // specified components, :: will fill up to a total of 8 if encountered
205
206 const char* input_it = input;
207 unsigned short component_count = 1; // fencepost, we start with 1
208 while (*input_it) {
209 if (*input_it == ':') {
210 // don't count ::1 as 2 components
211 if (input_it != input)
212 component_count++;
213
214 // the next character is either a part of a component or another ':'
215 // in any case we don't want to count it
216 input_it++;
217 }
218
219 input_it++;
220 }
221
222 // IPv6 is at most eight 4-tuples of [0-9a-f] with 7 separators, plus \0
223 char* ret = malloc(8 * 4 * sizeof(char) + 7 + 1);
224 char* output_it = ret;
225
226 input_it = input;
227 while (*input_it) {
228 // signifies that we have finished writing a component this iteration
229 bool closed_component = false;
230
231 if (*input_it == ':') {
232 const char next = *(input_it + 1 * sizeof(char));
233 if (next == ':') {
234 // skip one extra char to skip over the whole ::
235 input_it++;
236
237 for (unsigned short i = component_count; i < 8; ++i) {
238 // don't add leading separators
239 if (output_it != ret)
240 *output_it++ = ':';
241
242 *output_it++ = '0';
243 closed_component = true;
244 }
245 }
246 else {
247 closed_component = true;
248 }
249 }
250 else {
251 *output_it++ = *input_it;
252 }
253
254 input_it++;
255
256 // if this was not the last char of the input add a separator
257 if (closed_component && *input_it)
258 *output_it++ = ':';
259 }
260
261 *output_it = '\0';
262
263 return ret;
264 }
265
266 char *oscap_realpath(const char *path, char *resolved_path)
267 {
268 #ifdef OS_WINDOWS
269 return _fullpath(resolved_path, path, PATH_MAX);
270 #else
271 return realpath(path, resolved_path);
272 #endif
273 }
274
275 char *oscap_basename(char *path)
276 {
277 #ifdef OS_WINDOWS
278 char fname[_MAX_FNAME];
279 char ext[_MAX_EXT];
280 _splitpath_s(path, NULL, 0, NULL, 0, fname, _MAX_FNAME, ext, _MAX_EXT);
281 size_t base_len = strlen(fname) + strlen(ext) + 1;
282 char *base = malloc(base_len);
283 strncpy(base, fname, base_len);
284 strncat(base, ext, base_len - strlen(base) - 1);
285 return base;
286 #else
287 char *base = basename(path);
288 return oscap_strdup(base);
289 #endif
290 }
291
292 #ifdef OS_WINDOWS
293 char *oscap_dirname(char *path)
294 {
295 if (path == NULL || *path == '\0' || (strchr(path, '/') == NULL && strchr(path, '\\') == NULL)) {
296 return strdup(".");
297 }
298 char dir[_MAX_DIR];
299 char drive[_MAX_DRIVE];
300 char dirname[_MAX_PATH];
301 _splitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, NULL, 0, NULL, 0);
302 _makepath_s(dirname, _MAX_PATH, drive, dir, NULL, NULL);
303 oscap_rtrim(dirname, '/');
304 oscap_rtrim(dirname, '\\');
305 return oscap_strdup(dirname);
306 }
307 #else
308 char *oscap_dirname(char *path)
309 {
310 char *dirpath = dirname(path);
311 return oscap_strdup(dirpath);
312 }
313 #endif
314
315 int oscap_strcasecmp(const char *s1, const char *s2)
316 {
317 #ifdef OS_WINDOWS
318 return _stricmp(s1, s2);
319 #else
320 return strcasecmp(s1, s2);
321 #endif
322 }
323
324 int oscap_strncasecmp(const char *s1, const char *s2, size_t n)
325 {
326 #ifdef OS_WINDOWS
327 return _strnicmp(s1, s2, n);
328 #else
329 return strncasecmp(s1, s2, n);
330 #endif
331 }
332
333 char *oscap_strtok_r(char *str, const char *delim, char **saveptr)
334 {
335 #ifdef OS_WINDOWS
336 return strtok_s(str, delim, saveptr);
337 #else
338 return strtok_r(str, delim, saveptr);
339 #endif
340 }
341
342 char *oscap_strerror_r(int errnum, char *buf, size_t buflen)
343 {
344 #ifdef OS_WINDOWS
345 strerror_s(buf, buflen, errnum);
346 return buf;
347 #elif defined(OS_APPLE) || defined(OS_FREEBSD)
348 strerror_r(errnum, buf, buflen);
349 return buf;
350 #else
351 return strerror_r(errnum, buf, buflen);
352 #endif
353 }
354
355 char *oscap_path_join(const char *path1, const char *path2)
356 {
357 if (path1 == NULL) {
358 return oscap_strdup(path2);
359 }
360 if (path2 == NULL) {
361 return oscap_strdup(path1);
362 }
363 size_t path1_len = strlen(path1);
364 size_t path2_len = strlen(path2);
365 size_t path2_shift = 0;
366 while (path1_len >= 1 && path1[path1_len - 1] == PATH_SEPARATOR) {
367 path1_len--;
368 }
369 while (path2_shift < path2_len && path2[path2_shift] == PATH_SEPARATOR) {
370 path2_shift++;
371 }
372 path2_len -= path2_shift;
373 const size_t joined_path_len = path1_len + 1 + path2_len;
374 char *joined_path = malloc(joined_path_len + 1);
375 strncpy(joined_path, path1, path1_len);
376 joined_path[path1_len++] = PATH_SEPARATOR;
377 strncpy(joined_path + path1_len, path2 + path2_shift, path2_len);
378 joined_path[joined_path_len] = '\0';
379 return joined_path;
380 }
381
382 #ifndef OS_WINDOWS
383 FILE *oscap_fopen_with_prefix(const char *prefix, const char *path)
384 {
385 FILE *fp;
386 if (prefix != NULL) {
387 char *path_with_prefix = oscap_sprintf("%s%s", prefix, path);
388 fp = fopen(path_with_prefix, "r");
389 free(path_with_prefix);
390 } else {
391 fp = fopen(path, "r");
392 }
393 return fp;
394 }
395 #endif
396
397 #ifdef OS_WINDOWS
398 char *oscap_windows_wstr_to_str(const wchar_t *wstr)
399 {
400 if (wstr == NULL) {
401 return NULL;
402 }
403 const int required_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
404 char *str = malloc(required_size);
405 WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, required_size, NULL, NULL);
406 return str;
407 }
408
409 wchar_t *oscap_windows_str_to_wstr(const char *str)
410 {
411 if (str == NULL) {
412 return NULL;
413 }
414 const int required_size = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
415 wchar_t *wstr = malloc(required_size * sizeof(wchar_t));
416 MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, required_size);
417 return wstr;
418 }
419
420 char *oscap_windows_error_message(unsigned long error_code)
421 {
422 wchar_t *buffer = NULL;
423 /* According to FormatMessage documentation, if FORMAT_MESSAGE_ALLOCATE_BUFFER
424 * flag is set, the buffer must be freed by LocalFree and must be casted to LPWSTR.
425 */
426 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
427 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
428 NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
429 (LPWSTR) &buffer, 0, NULL);
430 char *error_message = oscap_windows_wstr_to_str(buffer);
431 LocalFree(buffer);
432 return error_message;
433 }
434 #endif
435
436 int oscap_open_writable(const char *filename)
437 {
438 #ifdef OS_WINDOWS
439 int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, S_IREAD|S_IWRITE);
440 #else
441 int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC,
442 S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
443 #endif
444 if (fd == -1) {
445 if (errno == EACCES) {
446 /* File already exists and we aren't allowed to create a new one
447 with the same name */
448 #ifdef OS_WINDOWS
449 fd = open(filename, O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE);
450 #else
451 fd = open(filename, O_WRONLY|O_TRUNC,
452 S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
453 #endif
454 }
455 if (fd == -1) {
456 oscap_seterr(OSCAP_EFAMILY_OSCAP,
457 "Could not open output file '%s': %s",
458 filename, strerror(errno));
459 return -1;
460 }
461 }
462 return fd;
463 }
464
465 bool oscap_path_startswith(const char *path, const char *prefix)
466 {
467 bool res = true;
468 const char *del = "/";
469 char *path_dup = oscap_strdup(path);
470 char **path_split = oscap_split(path_dup, del);
471 char *prefix_dup = oscap_strdup(prefix);
472 char **prefix_split = oscap_split(prefix_dup, del);
473 int i = 0, j = 0;
474 while (prefix_split[i] && path_split[j]) {
475 if (!strcmp(prefix_split[i], "")) {
476 ++i;
477 continue;
478 }
479 if (!strcmp(path_split[j], "")) {
480 ++j;
481 continue;
482 }
483 if (strcmp(prefix_split[i], path_split[j])) {
484 res = false;
485 break;
486 }
487 ++i;
488 ++j;
489 }
490 free(path_dup);
491 free(path_split);
492 free(prefix_dup);
493 free(prefix_split);
494 return res;
495 }
496
497 char *oscap_concat(char *str1, char *str2)
498 {
499 if (str1 == NULL || str2 == NULL)
500 return str1;
501 size_t str1_len = strlen(str1);
502 size_t str2_len = strlen(str2);
503 str1 = realloc(str1, str1_len + str2_len + 1);
504 strncat(str1, str2, str2_len);
505 return str1;
506 }
507
508 char *oscap_indent(const char *str, int indent)
509 {
510 if (str == NULL) {
511 return NULL;
512 }
513 if (indent <= 0) {
514 return oscap_strdup(str);
515 }
516
517 size_t line_count = 1;
518 for (const char *p = str; *p; p++) {
519 if (*p == '\n' && *(p + 1) != '\0') {
520 line_count++;
521 }
522 }
523
524 size_t str_len = strlen(str);
525 size_t result_len = str_len + (indent * line_count);
526 char *result = malloc(result_len + 1);
527 if (result == NULL) {
528 return NULL;
529 }
530
531 char *dst = result;
532 const char *src = str;
533
534 if (*src != '\n') {
535 for (int i = 0; i < indent; i++) {
536 *dst++ = ' ';
537 }
538 }
539
540 while (*src) {
541 *dst++ = *src;
542 if (*src == '\n' && *(src + 1) != '\0' && *(src + 1) != '\n') {
543 // Add indent after newline (unless it's the last character)
544 for (int i = 0; i < indent; i++) {
545 *dst++ = ' ';
546 }
547 }
548 src++;
549 }
550
551 *dst = '\0';
552 return result;
553 }
554
555 char *oscap_remove_excess_whitespace(const char *str)
556 {
557 if (str == NULL) {
558 return NULL;
559 }
560
561 size_t str_len = strlen(str);
562 char *result = malloc(str_len + 1);
563 if (result == NULL) {
564 return NULL;
565 }
566
567 const char *src = str;
568 char *dst = result;
569 bool at_line_start = true;
570 int trailing_spaces = 0;
571
572 while (*src) {
573 if (*src == '\n') {
574 trailing_spaces = 0;
575 if (!at_line_start) {
576 *dst++ = '\n';
577 }
578 at_line_start = true;
579 src++;
580 } else if (at_line_start && isspace(*src)) {
581 src++;
582 } else if (isspace(*src)) {
583 trailing_spaces++;
584 src++;
585 } else {
586 at_line_start = false;
587 for (int i = 0; i < trailing_spaces; i++) {
588 *dst++ = ' ';
589 }
590 trailing_spaces = 0;
591 *dst++ = *src++;
592 }
593 }
594
595 *dst = '\0';
596 return result;
597 }