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