Clean-up: unchecked return value
[lttng-tools.git] / src / common / utils.c
1 /*
2 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 Raphaël Beamonte <raphael.beamonte@gmail.com>
4 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 *
6 * SPDX-License-Identifier: GPL-2.0-only
7 *
8 */
9
10 #define _LGPL_SOURCE
11 #include <assert.h>
12 #include <ctype.h>
13 #include <fcntl.h>
14 #include <limits.h>
15 #include <stdlib.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <inttypes.h>
20 #include <grp.h>
21 #include <pwd.h>
22 #include <sys/file.h>
23 #include <unistd.h>
24
25 #include <common/common.h>
26 #include <common/readwrite.h>
27 #include <common/runas.h>
28 #include <common/compat/getenv.h>
29 #include <common/compat/string.h>
30 #include <common/compat/dirent.h>
31 #include <common/compat/directory-handle.h>
32 #include <common/dynamic-buffer.h>
33 #include <common/string-utils/format.h>
34 #include <lttng/constant.h>
35
36 #include "utils.h"
37 #include "defaults.h"
38 #include "time.h"
39
40 #define PROC_MEMINFO_PATH "/proc/meminfo"
41 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
42 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
43
44 /* The length of the longest field of `/proc/meminfo`. */
45 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
46
47 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
48 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
49 #else
50 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
51 #endif
52
53 /*
54 * Return a partial realpath(3) of the path even if the full path does not
55 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
56 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
57 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
58 * point directory does not exist.
59 * In case resolved_path is NULL, the string returned was allocated in the
60 * function and thus need to be freed by the caller. The size argument allows
61 * to specify the size of the resolved_path argument if given, or the size to
62 * allocate.
63 */
64 LTTNG_HIDDEN
65 char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
66 {
67 char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
68 const char *next, *prev, *end;
69
70 /* Safety net */
71 if (path == NULL) {
72 goto error;
73 }
74
75 /*
76 * Identify the end of the path, we don't want to treat the
77 * last char if it is a '/', we will just keep it on the side
78 * to be added at the end, and return a value coherent with
79 * the path given as argument
80 */
81 end = path + strlen(path);
82 if (*(end-1) == '/') {
83 end--;
84 }
85
86 /* Initiate the values of the pointers before looping */
87 next = path;
88 prev = next;
89 /* Only to ensure try_path is not NULL to enter the while */
90 try_path = (char *)next;
91
92 /* Resolve the canonical path of the first part of the path */
93 while (try_path != NULL && next != end) {
94 char *try_path_buf = NULL;
95
96 /*
97 * If there is not any '/' left, we want to try with
98 * the full path
99 */
100 next = strpbrk(next + 1, "/");
101 if (next == NULL) {
102 next = end;
103 }
104
105 /* Cut the part we will be trying to resolve */
106 cut_path = lttng_strndup(path, next - path);
107 if (cut_path == NULL) {
108 PERROR("lttng_strndup");
109 goto error;
110 }
111
112 try_path_buf = zmalloc(LTTNG_PATH_MAX);
113 if (!try_path_buf) {
114 PERROR("zmalloc");
115 goto error;
116 }
117
118 /* Try to resolve this part */
119 try_path = realpath((char *) cut_path, try_path_buf);
120 if (try_path == NULL) {
121 free(try_path_buf);
122 /*
123 * There was an error, we just want to be assured it
124 * is linked to an unexistent directory, if it's another
125 * reason, we spawn an error
126 */
127 switch (errno) {
128 case ENOENT:
129 /* Ignore the error */
130 break;
131 default:
132 PERROR("realpath (partial_realpath)");
133 goto error;
134 break;
135 }
136 } else {
137 /* Save the place we are before trying the next step */
138 try_path_buf = NULL;
139 free(try_path_prev);
140 try_path_prev = try_path;
141 prev = next;
142 }
143
144 /* Free the allocated memory */
145 free(cut_path);
146 cut_path = NULL;
147 }
148
149 /* Allocate memory for the resolved path if necessary */
150 if (resolved_path == NULL) {
151 resolved_path = zmalloc(size);
152 if (resolved_path == NULL) {
153 PERROR("zmalloc resolved path");
154 goto error;
155 }
156 }
157
158 /*
159 * If we were able to solve at least partially the path, we can concatenate
160 * what worked and what didn't work
161 */
162 if (try_path_prev != NULL) {
163 /* If we risk to concatenate two '/', we remove one of them */
164 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
165 try_path_prev[strlen(try_path_prev) - 1] = '\0';
166 }
167
168 /*
169 * Duplicate the memory used by prev in case resolved_path and
170 * path are pointers for the same memory space
171 */
172 cut_path = strdup(prev);
173 if (cut_path == NULL) {
174 PERROR("strdup");
175 goto error;
176 }
177
178 /* Concatenate the strings */
179 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
180
181 /* Free the allocated memory */
182 free(cut_path);
183 free(try_path_prev);
184 cut_path = NULL;
185 try_path_prev = NULL;
186 /*
187 * Else, we just copy the path in our resolved_path to
188 * return it as is
189 */
190 } else {
191 strncpy(resolved_path, path, size);
192 }
193
194 /* Then we return the 'partially' resolved path */
195 return resolved_path;
196
197 error:
198 free(resolved_path);
199 free(cut_path);
200 free(try_path);
201 if (try_path_prev != try_path) {
202 free(try_path_prev);
203 }
204 return NULL;
205 }
206
207 static
208 int expand_double_slashes_dot_and_dotdot(char *path)
209 {
210 size_t expanded_path_len, path_len;
211 const char *curr_char, *path_last_char, *next_slash, *prev_slash;
212
213 path_len = strlen(path);
214 path_last_char = &path[path_len];
215
216 if (path_len == 0) {
217 goto error;
218 }
219
220 expanded_path_len = 0;
221
222 /* We iterate over the provided path to expand the "//", "../" and "./" */
223 for (curr_char = path; curr_char <= path_last_char; curr_char = next_slash + 1) {
224 /* Find the next forward slash. */
225 size_t curr_token_len;
226
227 if (curr_char == path_last_char) {
228 expanded_path_len++;
229 break;
230 }
231
232 next_slash = memchr(curr_char, '/', path_last_char - curr_char);
233 if (next_slash == NULL) {
234 /* Reached the end of the provided path. */
235 next_slash = path_last_char;
236 }
237
238 /* Compute how long is the previous token. */
239 curr_token_len = next_slash - curr_char;
240 switch(curr_token_len) {
241 case 0:
242 /*
243 * The pointer has not move meaning that curr_char is
244 * pointing to a slash. It that case there is no token
245 * to copy, so continue the iteration to find the next
246 * token
247 */
248 continue;
249 case 1:
250 /*
251 * The pointer moved 1 character. Check if that
252 * character is a dot ('.'), if it is: omit it, else
253 * copy the token to the normalized path.
254 */
255 if (curr_char[0] == '.') {
256 continue;
257 }
258 break;
259 case 2:
260 /*
261 * The pointer moved 2 characters. Check if these
262 * characters are double dots ('..'). If that is the
263 * case, we need to remove the last token of the
264 * normalized path.
265 */
266 if (curr_char[0] == '.' && curr_char[1] == '.') {
267 /*
268 * Find the previous path component by
269 * using the memrchr function to find the
270 * previous forward slash and substract that
271 * len to the resulting path.
272 */
273 prev_slash = lttng_memrchr(path, '/', expanded_path_len);
274 /*
275 * If prev_slash is NULL, we reached the
276 * beginning of the path. We can't go back any
277 * further.
278 */
279 if (prev_slash != NULL) {
280 expanded_path_len = prev_slash - path;
281 }
282 continue;
283 }
284 break;
285 default:
286 break;
287 }
288
289 /*
290 * Copy the current token which is neither a '.' nor a '..'.
291 */
292 path[expanded_path_len++] = '/';
293 memcpy(&path[expanded_path_len], curr_char, curr_token_len);
294 expanded_path_len += curr_token_len;
295 }
296
297 if (expanded_path_len == 0) {
298 path[expanded_path_len++] = '/';
299 }
300
301 path[expanded_path_len] = '\0';
302 return 0;
303 error:
304 return -1;
305 }
306
307 /*
308 * Make a full resolution of the given path even if it doesn't exist.
309 * This function uses the utils_partial_realpath function to resolve
310 * symlinks and relatives paths at the start of the string, and
311 * implements functionnalities to resolve the './' and '../' strings
312 * in the middle of a path. This function is only necessary because
313 * realpath(3) does not accept to resolve unexistent paths.
314 * The returned string was allocated in the function, it is thus of
315 * the responsibility of the caller to free this memory.
316 */
317 static
318 char *_utils_expand_path(const char *path, bool keep_symlink)
319 {
320 int ret;
321 char *absolute_path = NULL;
322 char *last_token;
323 bool is_dot, is_dotdot;
324
325 /* Safety net */
326 if (path == NULL) {
327 goto error;
328 }
329
330 /* Allocate memory for the absolute_path */
331 absolute_path = zmalloc(LTTNG_PATH_MAX);
332 if (absolute_path == NULL) {
333 PERROR("zmalloc expand path");
334 goto error;
335 }
336
337 if (path[0] == '/') {
338 ret = lttng_strncpy(absolute_path, path, LTTNG_PATH_MAX);
339 if (ret) {
340 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX);
341 goto error;
342 }
343 } else {
344 /*
345 * This is a relative path. We need to get the present working
346 * directory and start the path walk from there.
347 */
348 char current_working_dir[LTTNG_PATH_MAX];
349 char *cwd_ret;
350
351 cwd_ret = getcwd(current_working_dir, sizeof(current_working_dir));
352 if (!cwd_ret) {
353 goto error;
354 }
355 /*
356 * Get the number of character in the CWD and allocate an array
357 * to can hold it and the path provided by the caller.
358 */
359 ret = snprintf(absolute_path, LTTNG_PATH_MAX, "%s/%s",
360 current_working_dir, path);
361 if (ret >= LTTNG_PATH_MAX) {
362 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
363 current_working_dir, path, LTTNG_PATH_MAX);
364 goto error;
365 }
366 }
367
368 if (keep_symlink) {
369 /* Resolve partially our path */
370 absolute_path = utils_partial_realpath(absolute_path,
371 absolute_path, LTTNG_PATH_MAX);
372 if (!absolute_path) {
373 goto error;
374 }
375 }
376
377 ret = expand_double_slashes_dot_and_dotdot(absolute_path);
378 if (ret) {
379 goto error;
380 }
381
382 /* Identify the last token */
383 last_token = strrchr(absolute_path, '/');
384
385 /* Verify that this token is not a relative path */
386 is_dotdot = (strcmp(last_token, "/..") == 0);
387 is_dot = (strcmp(last_token, "/.") == 0);
388
389 /* If it is, take action */
390 if (is_dot || is_dotdot) {
391 /* For both, remove this token */
392 *last_token = '\0';
393
394 /* If it was a reference to parent directory, go back one more time */
395 if (is_dotdot) {
396 last_token = strrchr(absolute_path, '/');
397
398 /* If there was only one level left, we keep the first '/' */
399 if (last_token == absolute_path) {
400 last_token++;
401 }
402
403 *last_token = '\0';
404 }
405 }
406
407 return absolute_path;
408
409 error:
410 free(absolute_path);
411 return NULL;
412 }
413 LTTNG_HIDDEN
414 char *utils_expand_path(const char *path)
415 {
416 return _utils_expand_path(path, true);
417 }
418
419 LTTNG_HIDDEN
420 char *utils_expand_path_keep_symlink(const char *path)
421 {
422 return _utils_expand_path(path, false);
423 }
424 /*
425 * Create a pipe in dst.
426 */
427 LTTNG_HIDDEN
428 int utils_create_pipe(int *dst)
429 {
430 int ret;
431
432 if (dst == NULL) {
433 return -1;
434 }
435
436 ret = pipe(dst);
437 if (ret < 0) {
438 PERROR("create pipe");
439 }
440
441 return ret;
442 }
443
444 /*
445 * Create pipe and set CLOEXEC flag to both fd.
446 *
447 * Make sure the pipe opened by this function are closed at some point. Use
448 * utils_close_pipe().
449 */
450 LTTNG_HIDDEN
451 int utils_create_pipe_cloexec(int *dst)
452 {
453 int ret, i;
454
455 if (dst == NULL) {
456 return -1;
457 }
458
459 ret = utils_create_pipe(dst);
460 if (ret < 0) {
461 goto error;
462 }
463
464 for (i = 0; i < 2; i++) {
465 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
466 if (ret < 0) {
467 PERROR("fcntl pipe cloexec");
468 goto error;
469 }
470 }
471
472 error:
473 return ret;
474 }
475
476 /*
477 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
478 *
479 * Make sure the pipe opened by this function are closed at some point. Use
480 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
481 * support OSes other than Linux 2.6.23+.
482 */
483 LTTNG_HIDDEN
484 int utils_create_pipe_cloexec_nonblock(int *dst)
485 {
486 int ret, i;
487
488 if (dst == NULL) {
489 return -1;
490 }
491
492 ret = utils_create_pipe(dst);
493 if (ret < 0) {
494 goto error;
495 }
496
497 for (i = 0; i < 2; i++) {
498 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
499 if (ret < 0) {
500 PERROR("fcntl pipe cloexec");
501 goto error;
502 }
503 /*
504 * Note: we override any flag that could have been
505 * previously set on the fd.
506 */
507 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
508 if (ret < 0) {
509 PERROR("fcntl pipe nonblock");
510 goto error;
511 }
512 }
513
514 error:
515 return ret;
516 }
517
518 /*
519 * Close both read and write side of the pipe.
520 */
521 LTTNG_HIDDEN
522 void utils_close_pipe(int *src)
523 {
524 int i, ret;
525
526 if (src == NULL) {
527 return;
528 }
529
530 for (i = 0; i < 2; i++) {
531 /* Safety check */
532 if (src[i] < 0) {
533 continue;
534 }
535
536 ret = close(src[i]);
537 if (ret) {
538 PERROR("close pipe");
539 }
540 }
541 }
542
543 /*
544 * Create a new string using two strings range.
545 */
546 LTTNG_HIDDEN
547 char *utils_strdupdelim(const char *begin, const char *end)
548 {
549 char *str;
550
551 str = zmalloc(end - begin + 1);
552 if (str == NULL) {
553 PERROR("zmalloc strdupdelim");
554 goto error;
555 }
556
557 memcpy(str, begin, end - begin);
558 str[end - begin] = '\0';
559
560 error:
561 return str;
562 }
563
564 /*
565 * Set CLOEXEC flag to the give file descriptor.
566 */
567 LTTNG_HIDDEN
568 int utils_set_fd_cloexec(int fd)
569 {
570 int ret;
571
572 if (fd < 0) {
573 ret = -EINVAL;
574 goto end;
575 }
576
577 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
578 if (ret < 0) {
579 PERROR("fcntl cloexec");
580 ret = -errno;
581 }
582
583 end:
584 return ret;
585 }
586
587 /*
588 * Create pid file to the given path and filename.
589 */
590 LTTNG_HIDDEN
591 int utils_create_pid_file(pid_t pid, const char *filepath)
592 {
593 int ret;
594 FILE *fp;
595
596 assert(filepath);
597
598 fp = fopen(filepath, "w");
599 if (fp == NULL) {
600 PERROR("open pid file %s", filepath);
601 ret = -1;
602 goto error;
603 }
604
605 ret = fprintf(fp, "%d\n", (int) pid);
606 if (ret < 0) {
607 PERROR("fprintf pid file");
608 goto error;
609 }
610
611 if (fclose(fp)) {
612 PERROR("fclose");
613 }
614 DBG("Pid %d written in file %s", (int) pid, filepath);
615 ret = 0;
616 error:
617 return ret;
618 }
619
620 /*
621 * Create lock file to the given path and filename.
622 * Returns the associated file descriptor, -1 on error.
623 */
624 LTTNG_HIDDEN
625 int utils_create_lock_file(const char *filepath)
626 {
627 int ret;
628 int fd;
629 struct flock lock;
630
631 assert(filepath);
632
633 memset(&lock, 0, sizeof(lock));
634 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
635 S_IRGRP | S_IWGRP);
636 if (fd < 0) {
637 PERROR("open lock file %s", filepath);
638 fd = -1;
639 goto error;
640 }
641
642 /*
643 * Attempt to lock the file. If this fails, there is
644 * already a process using the same lock file running
645 * and we should exit.
646 */
647 lock.l_whence = SEEK_SET;
648 lock.l_type = F_WRLCK;
649
650 ret = fcntl(fd, F_SETLK, &lock);
651 if (ret == -1) {
652 PERROR("fcntl lock file");
653 ERR("Could not get lock file %s, another instance is running.",
654 filepath);
655 if (close(fd)) {
656 PERROR("close lock file");
657 }
658 fd = ret;
659 goto error;
660 }
661
662 error:
663 return fd;
664 }
665
666 /*
667 * Create directory using the given path and mode.
668 *
669 * On success, return 0 else a negative error code.
670 */
671 LTTNG_HIDDEN
672 int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
673 {
674 int ret;
675 struct lttng_directory_handle *handle;
676 const struct lttng_credentials creds = {
677 .uid = (uid_t) uid,
678 .gid = (gid_t) gid,
679 };
680
681 handle = lttng_directory_handle_create(NULL);
682 if (!handle) {
683 ret = -1;
684 goto end;
685 }
686 ret = lttng_directory_handle_create_subdirectory_as_user(
687 handle, path, mode,
688 (uid >= 0 || gid >= 0) ? &creds : NULL);
689 end:
690 lttng_directory_handle_put(handle);
691 return ret;
692 }
693
694 /*
695 * Recursively create directory using the given path and mode, under the
696 * provided uid and gid.
697 *
698 * On success, return 0 else a negative error code.
699 */
700 LTTNG_HIDDEN
701 int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
702 {
703 int ret;
704 struct lttng_directory_handle *handle;
705 const struct lttng_credentials creds = {
706 .uid = (uid_t) uid,
707 .gid = (gid_t) gid,
708 };
709
710 handle = lttng_directory_handle_create(NULL);
711 if (!handle) {
712 ret = -1;
713 goto end;
714 }
715 ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
716 handle, path, mode,
717 (uid >= 0 || gid >= 0) ? &creds : NULL);
718 end:
719 lttng_directory_handle_put(handle);
720 return ret;
721 }
722
723 /*
724 * out_stream_path is the output parameter.
725 *
726 * Return 0 on success or else a negative value.
727 */
728 LTTNG_HIDDEN
729 int utils_stream_file_path(const char *path_name, const char *file_name,
730 uint64_t size, uint64_t count, const char *suffix,
731 char *out_stream_path, size_t stream_path_len)
732 {
733 int ret;
734 char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
735 const char *path_separator;
736
737 if (path_name && (path_name[0] == '\0' ||
738 path_name[strlen(path_name) - 1] == '/')) {
739 path_separator = "";
740 } else {
741 path_separator = "/";
742 }
743
744 path_name = path_name ? : "";
745 suffix = suffix ? : "";
746 if (size > 0) {
747 ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
748 count);
749 assert(ret > 0 && ret < sizeof(count_str));
750 }
751
752 ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
753 path_name, path_separator, file_name, count_str,
754 suffix);
755 if (ret < 0 || ret >= stream_path_len) {
756 ERR("Truncation occurred while formatting stream path");
757 ret = -1;
758 } else {
759 ret = 0;
760 }
761 return ret;
762 }
763
764 /**
765 * Parse a string that represents a size in human readable format. It
766 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
767 *
768 * The suffix multiply the integer by:
769 * 'k': 1024
770 * 'M': 1024^2
771 * 'G': 1024^3
772 *
773 * @param str The string to parse.
774 * @param size Pointer to a uint64_t that will be filled with the
775 * resulting size.
776 *
777 * @return 0 on success, -1 on failure.
778 */
779 LTTNG_HIDDEN
780 int utils_parse_size_suffix(const char * const str, uint64_t * const size)
781 {
782 int ret;
783 uint64_t base_size;
784 long shift = 0;
785 const char *str_end;
786 char *num_end;
787
788 if (!str) {
789 DBG("utils_parse_size_suffix: received a NULL string.");
790 ret = -1;
791 goto end;
792 }
793
794 /* strtoull will accept a negative number, but we don't want to. */
795 if (strchr(str, '-') != NULL) {
796 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
797 ret = -1;
798 goto end;
799 }
800
801 /* str_end will point to the \0 */
802 str_end = str + strlen(str);
803 errno = 0;
804 base_size = strtoull(str, &num_end, 0);
805 if (errno != 0) {
806 PERROR("utils_parse_size_suffix strtoull");
807 ret = -1;
808 goto end;
809 }
810
811 if (num_end == str) {
812 /* strtoull parsed nothing, not good. */
813 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
814 ret = -1;
815 goto end;
816 }
817
818 /* Check if a prefix is present. */
819 switch (*num_end) {
820 case 'G':
821 shift = GIBI_LOG2;
822 num_end++;
823 break;
824 case 'M': /* */
825 shift = MEBI_LOG2;
826 num_end++;
827 break;
828 case 'K':
829 case 'k':
830 shift = KIBI_LOG2;
831 num_end++;
832 break;
833 case '\0':
834 break;
835 default:
836 DBG("utils_parse_size_suffix: invalid suffix.");
837 ret = -1;
838 goto end;
839 }
840
841 /* Check for garbage after the valid input. */
842 if (num_end != str_end) {
843 DBG("utils_parse_size_suffix: Garbage after size string.");
844 ret = -1;
845 goto end;
846 }
847
848 *size = base_size << shift;
849
850 /* Check for overflow */
851 if ((*size >> shift) != base_size) {
852 DBG("utils_parse_size_suffix: oops, overflow detected.");
853 ret = -1;
854 goto end;
855 }
856
857 ret = 0;
858 end:
859 return ret;
860 }
861
862 /**
863 * Parse a string that represents a time in human readable format. It
864 * supports decimal integers suffixed by:
865 * "us" for microsecond,
866 * "ms" for millisecond,
867 * "s" for second,
868 * "m" for minute,
869 * "h" for hour
870 *
871 * The suffix multiply the integer by:
872 * "us" : 1
873 * "ms" : 1000
874 * "s" : 1000000
875 * "m" : 60000000
876 * "h" : 3600000000
877 *
878 * Note that unit-less numbers are assumed to be microseconds.
879 *
880 * @param str The string to parse, assumed to be NULL-terminated.
881 * @param time_us Pointer to a uint64_t that will be filled with the
882 * resulting time in microseconds.
883 *
884 * @return 0 on success, -1 on failure.
885 */
886 LTTNG_HIDDEN
887 int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
888 {
889 int ret;
890 uint64_t base_time;
891 uint64_t multiplier = 1;
892 const char *str_end;
893 char *num_end;
894
895 if (!str) {
896 DBG("utils_parse_time_suffix: received a NULL string.");
897 ret = -1;
898 goto end;
899 }
900
901 /* strtoull will accept a negative number, but we don't want to. */
902 if (strchr(str, '-') != NULL) {
903 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
904 ret = -1;
905 goto end;
906 }
907
908 /* str_end will point to the \0 */
909 str_end = str + strlen(str);
910 errno = 0;
911 base_time = strtoull(str, &num_end, 10);
912 if (errno != 0) {
913 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
914 ret = -1;
915 goto end;
916 }
917
918 if (num_end == str) {
919 /* strtoull parsed nothing, not good. */
920 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
921 ret = -1;
922 goto end;
923 }
924
925 /* Check if a prefix is present. */
926 switch (*num_end) {
927 case 'u':
928 /*
929 * Microsecond (us)
930 *
931 * Skip the "us" if the string matches the "us" suffix,
932 * otherwise let the check for the end of the string handle
933 * the error reporting.
934 */
935 if (*(num_end + 1) == 's') {
936 num_end += 2;
937 }
938 break;
939 case 'm':
940 if (*(num_end + 1) == 's') {
941 /* Millisecond (ms) */
942 multiplier = USEC_PER_MSEC;
943 /* Skip the 's' */
944 num_end++;
945 } else {
946 /* Minute (m) */
947 multiplier = USEC_PER_MINUTE;
948 }
949 num_end++;
950 break;
951 case 's':
952 /* Second */
953 multiplier = USEC_PER_SEC;
954 num_end++;
955 break;
956 case 'h':
957 /* Hour */
958 multiplier = USEC_PER_HOURS;
959 num_end++;
960 break;
961 case '\0':
962 break;
963 default:
964 DBG("utils_parse_time_suffix: invalid suffix.");
965 ret = -1;
966 goto end;
967 }
968
969 /* Check for garbage after the valid input. */
970 if (num_end != str_end) {
971 DBG("utils_parse_time_suffix: Garbage after time string.");
972 ret = -1;
973 goto end;
974 }
975
976 *time_us = base_time * multiplier;
977
978 /* Check for overflow */
979 if ((*time_us / multiplier) != base_time) {
980 DBG("utils_parse_time_suffix: oops, overflow detected.");
981 ret = -1;
982 goto end;
983 }
984
985 ret = 0;
986 end:
987 return ret;
988 }
989
990 /*
991 * fls: returns the position of the most significant bit.
992 * Returns 0 if no bit is set, else returns the position of the most
993 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
994 */
995 #if defined(__i386) || defined(__x86_64)
996 static inline unsigned int fls_u32(uint32_t x)
997 {
998 int r;
999
1000 asm("bsrl %1,%0\n\t"
1001 "jnz 1f\n\t"
1002 "movl $-1,%0\n\t"
1003 "1:\n\t"
1004 : "=r" (r) : "rm" (x));
1005 return r + 1;
1006 }
1007 #define HAS_FLS_U32
1008 #endif
1009
1010 #if defined(__x86_64) && defined(__LP64__)
1011 static inline
1012 unsigned int fls_u64(uint64_t x)
1013 {
1014 long r;
1015
1016 asm("bsrq %1,%0\n\t"
1017 "jnz 1f\n\t"
1018 "movq $-1,%0\n\t"
1019 "1:\n\t"
1020 : "=r" (r) : "rm" (x));
1021 return r + 1;
1022 }
1023 #define HAS_FLS_U64
1024 #endif
1025
1026 #ifndef HAS_FLS_U64
1027 static __attribute__((unused))
1028 unsigned int fls_u64(uint64_t x)
1029 {
1030 unsigned int r = 64;
1031
1032 if (!x)
1033 return 0;
1034
1035 if (!(x & 0xFFFFFFFF00000000ULL)) {
1036 x <<= 32;
1037 r -= 32;
1038 }
1039 if (!(x & 0xFFFF000000000000ULL)) {
1040 x <<= 16;
1041 r -= 16;
1042 }
1043 if (!(x & 0xFF00000000000000ULL)) {
1044 x <<= 8;
1045 r -= 8;
1046 }
1047 if (!(x & 0xF000000000000000ULL)) {
1048 x <<= 4;
1049 r -= 4;
1050 }
1051 if (!(x & 0xC000000000000000ULL)) {
1052 x <<= 2;
1053 r -= 2;
1054 }
1055 if (!(x & 0x8000000000000000ULL)) {
1056 x <<= 1;
1057 r -= 1;
1058 }
1059 return r;
1060 }
1061 #endif
1062
1063 #ifndef HAS_FLS_U32
1064 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1065 {
1066 unsigned int r = 32;
1067
1068 if (!x) {
1069 return 0;
1070 }
1071 if (!(x & 0xFFFF0000U)) {
1072 x <<= 16;
1073 r -= 16;
1074 }
1075 if (!(x & 0xFF000000U)) {
1076 x <<= 8;
1077 r -= 8;
1078 }
1079 if (!(x & 0xF0000000U)) {
1080 x <<= 4;
1081 r -= 4;
1082 }
1083 if (!(x & 0xC0000000U)) {
1084 x <<= 2;
1085 r -= 2;
1086 }
1087 if (!(x & 0x80000000U)) {
1088 x <<= 1;
1089 r -= 1;
1090 }
1091 return r;
1092 }
1093 #endif
1094
1095 /*
1096 * Return the minimum order for which x <= (1UL << order).
1097 * Return -1 if x is 0.
1098 */
1099 LTTNG_HIDDEN
1100 int utils_get_count_order_u32(uint32_t x)
1101 {
1102 if (!x) {
1103 return -1;
1104 }
1105
1106 return fls_u32(x - 1);
1107 }
1108
1109 /*
1110 * Return the minimum order for which x <= (1UL << order).
1111 * Return -1 if x is 0.
1112 */
1113 LTTNG_HIDDEN
1114 int utils_get_count_order_u64(uint64_t x)
1115 {
1116 if (!x) {
1117 return -1;
1118 }
1119
1120 return fls_u64(x - 1);
1121 }
1122
1123 /**
1124 * Obtain the value of LTTNG_HOME environment variable, if exists.
1125 * Otherwise returns the value of HOME.
1126 */
1127 LTTNG_HIDDEN
1128 const char *utils_get_home_dir(void)
1129 {
1130 char *val = NULL;
1131 struct passwd *pwd;
1132
1133 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
1134 if (val != NULL) {
1135 goto end;
1136 }
1137 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
1138 if (val != NULL) {
1139 goto end;
1140 }
1141
1142 /* Fallback on the password file entry. */
1143 pwd = getpwuid(getuid());
1144 if (!pwd) {
1145 goto end;
1146 }
1147 val = pwd->pw_dir;
1148
1149 DBG3("Home directory is '%s'", val);
1150
1151 end:
1152 return val;
1153 }
1154
1155 /**
1156 * Get user's home directory. Dynamically allocated, must be freed
1157 * by the caller.
1158 */
1159 LTTNG_HIDDEN
1160 char *utils_get_user_home_dir(uid_t uid)
1161 {
1162 struct passwd pwd;
1163 struct passwd *result;
1164 char *home_dir = NULL;
1165 char *buf = NULL;
1166 long buflen;
1167 int ret;
1168
1169 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1170 if (buflen == -1) {
1171 goto end;
1172 }
1173 retry:
1174 buf = zmalloc(buflen);
1175 if (!buf) {
1176 goto end;
1177 }
1178
1179 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1180 if (ret || !result) {
1181 if (ret == ERANGE) {
1182 free(buf);
1183 buflen *= 2;
1184 goto retry;
1185 }
1186 goto end;
1187 }
1188
1189 home_dir = strdup(pwd.pw_dir);
1190 end:
1191 free(buf);
1192 return home_dir;
1193 }
1194
1195 /*
1196 * With the given format, fill dst with the time of len maximum siz.
1197 *
1198 * Return amount of bytes set in the buffer or else 0 on error.
1199 */
1200 LTTNG_HIDDEN
1201 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1202 {
1203 size_t ret;
1204 time_t rawtime;
1205 struct tm *timeinfo;
1206
1207 assert(format);
1208 assert(dst);
1209
1210 /* Get date and time for session path */
1211 time(&rawtime);
1212 timeinfo = localtime(&rawtime);
1213 ret = strftime(dst, len, format, timeinfo);
1214 if (ret == 0) {
1215 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
1216 dst, len);
1217 }
1218
1219 return ret;
1220 }
1221
1222 /*
1223 * Return 0 on success and set *gid to the group_ID matching the passed name.
1224 * Else -1 if it cannot be found or an error occurred.
1225 */
1226 LTTNG_HIDDEN
1227 int utils_get_group_id(const char *name, bool warn, gid_t *gid)
1228 {
1229 static volatile int warn_once;
1230 int ret;
1231 long sys_len;
1232 size_t len;
1233 struct group grp;
1234 struct group *result;
1235 struct lttng_dynamic_buffer buffer;
1236
1237 /* Get the system limit, if it exists. */
1238 sys_len = sysconf(_SC_GETGR_R_SIZE_MAX);
1239 if (sys_len == -1) {
1240 len = 1024;
1241 } else {
1242 len = (size_t) sys_len;
1243 }
1244
1245 lttng_dynamic_buffer_init(&buffer);
1246 ret = lttng_dynamic_buffer_set_size(&buffer, len);
1247 if (ret) {
1248 ERR("Failed to allocate group info buffer");
1249 ret = -1;
1250 goto error;
1251 }
1252
1253 while ((ret = getgrnam_r(name, &grp, buffer.data, buffer.size, &result)) == ERANGE) {
1254 const size_t new_len = 2 * buffer.size;
1255
1256 /* Buffer is not big enough, increase its size. */
1257 if (new_len < buffer.size) {
1258 ERR("Group info buffer size overflow");
1259 ret = -1;
1260 goto error;
1261 }
1262
1263 ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
1264 if (ret) {
1265 ERR("Failed to grow group info buffer to %zu bytes",
1266 new_len);
1267 ret = -1;
1268 goto error;
1269 }
1270 }
1271 if (ret) {
1272 PERROR("Failed to get group file entry for group name \"%s\"",
1273 name);
1274 ret = -1;
1275 goto error;
1276 }
1277
1278 /* Group not found. */
1279 if (!result) {
1280 ret = -1;
1281 goto error;
1282 }
1283
1284 *gid = result->gr_gid;
1285 ret = 0;
1286
1287 error:
1288 if (ret && warn && !warn_once) {
1289 WARN("No tracing group detected");
1290 warn_once = 1;
1291 }
1292 lttng_dynamic_buffer_reset(&buffer);
1293 return ret;
1294 }
1295
1296 /*
1297 * Return a newly allocated option string. This string is to be used as the
1298 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1299 * of elements in the long_options array. Returns NULL if the string's
1300 * allocation fails.
1301 */
1302 LTTNG_HIDDEN
1303 char *utils_generate_optstring(const struct option *long_options,
1304 size_t opt_count)
1305 {
1306 int i;
1307 size_t string_len = opt_count, str_pos = 0;
1308 char *optstring;
1309
1310 /*
1311 * Compute the necessary string length. One letter per option, two when an
1312 * argument is necessary, and a trailing NULL.
1313 */
1314 for (i = 0; i < opt_count; i++) {
1315 string_len += long_options[i].has_arg ? 1 : 0;
1316 }
1317
1318 optstring = zmalloc(string_len);
1319 if (!optstring) {
1320 goto end;
1321 }
1322
1323 for (i = 0; i < opt_count; i++) {
1324 if (!long_options[i].name) {
1325 /* Got to the trailing NULL element */
1326 break;
1327 }
1328
1329 if (long_options[i].val != '\0') {
1330 optstring[str_pos++] = (char) long_options[i].val;
1331 if (long_options[i].has_arg) {
1332 optstring[str_pos++] = ':';
1333 }
1334 }
1335 }
1336
1337 end:
1338 return optstring;
1339 }
1340
1341 /*
1342 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1343 * any file. Try to rmdir any empty directory within the hierarchy.
1344 */
1345 LTTNG_HIDDEN
1346 int utils_recursive_rmdir(const char *path)
1347 {
1348 int ret;
1349 struct lttng_directory_handle *handle;
1350
1351 handle = lttng_directory_handle_create(NULL);
1352 if (!handle) {
1353 ret = -1;
1354 goto end;
1355 }
1356 ret = lttng_directory_handle_remove_subdirectory(handle, path);
1357 end:
1358 lttng_directory_handle_put(handle);
1359 return ret;
1360 }
1361
1362 LTTNG_HIDDEN
1363 int utils_truncate_stream_file(int fd, off_t length)
1364 {
1365 int ret;
1366 off_t lseek_ret;
1367
1368 ret = ftruncate(fd, length);
1369 if (ret < 0) {
1370 PERROR("ftruncate");
1371 goto end;
1372 }
1373 lseek_ret = lseek(fd, length, SEEK_SET);
1374 if (lseek_ret < 0) {
1375 PERROR("lseek");
1376 ret = -1;
1377 goto end;
1378 }
1379 end:
1380 return ret;
1381 }
1382
1383 static const char *get_man_bin_path(void)
1384 {
1385 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
1386
1387 if (env_man_path) {
1388 return env_man_path;
1389 }
1390
1391 return DEFAULT_MAN_BIN_PATH;
1392 }
1393
1394 LTTNG_HIDDEN
1395 int utils_show_help(int section, const char *page_name,
1396 const char *help_msg)
1397 {
1398 char section_string[8];
1399 const char *man_bin_path = get_man_bin_path();
1400 int ret = 0;
1401
1402 if (help_msg) {
1403 printf("%s", help_msg);
1404 goto end;
1405 }
1406
1407 /* Section integer -> section string */
1408 ret = sprintf(section_string, "%d", section);
1409 assert(ret > 0 && ret < 8);
1410
1411 /*
1412 * Execute man pager.
1413 *
1414 * We provide -M to man here because LTTng-tools can
1415 * be installed outside /usr, in which case its man pages are
1416 * not located in the default /usr/share/man directory.
1417 */
1418 ret = execlp(man_bin_path, "man", "-M", MANPATH,
1419 section_string, page_name, NULL);
1420
1421 end:
1422 return ret;
1423 }
1424
1425 static
1426 int read_proc_meminfo_field(const char *field, size_t *value)
1427 {
1428 int ret;
1429 FILE *proc_meminfo;
1430 char name[PROC_MEMINFO_FIELD_MAX_NAME_LEN] = {};
1431
1432 proc_meminfo = fopen(PROC_MEMINFO_PATH, "r");
1433 if (!proc_meminfo) {
1434 PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
1435 ret = -1;
1436 goto fopen_error;
1437 }
1438
1439 /*
1440 * Read the contents of /proc/meminfo line by line to find the right
1441 * field.
1442 */
1443 while (!feof(proc_meminfo)) {
1444 unsigned long value_kb;
1445
1446 ret = fscanf(proc_meminfo,
1447 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n",
1448 name, &value_kb);
1449 if (ret == EOF) {
1450 /*
1451 * fscanf() returning EOF can indicate EOF or an error.
1452 */
1453 if (ferror(proc_meminfo)) {
1454 PERROR("Failed to parse " PROC_MEMINFO_PATH);
1455 }
1456 break;
1457 }
1458
1459 if (ret == 2 && strcmp(name, field) == 0) {
1460 /*
1461 * This number is displayed in kilo-bytes. Return the
1462 * number of bytes.
1463 */
1464 *value = ((size_t) value_kb) * 1024;
1465 ret = 0;
1466 goto found;
1467 }
1468 }
1469 /* Reached the end of the file without finding the right field. */
1470 ret = -1;
1471
1472 found:
1473 fclose(proc_meminfo);
1474 fopen_error:
1475 return ret;
1476 }
1477
1478 /*
1479 * Returns an estimate of the number of bytes of memory available based on the
1480 * the information in `/proc/meminfo`. The number returned by this function is
1481 * a best guess.
1482 */
1483 LTTNG_HIDDEN
1484 int utils_get_memory_available(size_t *value)
1485 {
1486 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value);
1487 }
1488
1489 /*
1490 * Returns the total size of the memory on the system in bytes based on the
1491 * the information in `/proc/meminfo`.
1492 */
1493 LTTNG_HIDDEN
1494 int utils_get_memory_total(size_t *value)
1495 {
1496 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value);
1497 }
1498
1499 LTTNG_HIDDEN
1500 int utils_change_working_directory(const char *path)
1501 {
1502 int ret;
1503
1504 assert(path);
1505
1506 DBG("Changing working directory to \"%s\"", path);
1507 ret = chdir(path);
1508 if (ret) {
1509 PERROR("Failed to change working directory to \"%s\"", path);
1510 goto end;
1511 }
1512
1513 /* Check for write access */
1514 if (access(path, W_OK)) {
1515 if (errno == EACCES) {
1516 /*
1517 * Do not treat this as an error since the permission
1518 * might change in the lifetime of the process
1519 */
1520 DBG("Working directory \"%s\" is not writable", path);
1521 } else {
1522 PERROR("Failed to check if working directory \"%s\" is writable",
1523 path);
1524 }
1525 }
1526
1527 end:
1528 return ret;
1529 }
This page took 0.089584 seconds and 4 git commands to generate.