Fix: sessiond: occasional badfd error on repeated SIGTERM
[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 src[i] = -1;
541 }
542 }
543
544 /*
545 * Create a new string using two strings range.
546 */
547 LTTNG_HIDDEN
548 char *utils_strdupdelim(const char *begin, const char *end)
549 {
550 char *str;
551
552 str = zmalloc(end - begin + 1);
553 if (str == NULL) {
554 PERROR("zmalloc strdupdelim");
555 goto error;
556 }
557
558 memcpy(str, begin, end - begin);
559 str[end - begin] = '\0';
560
561 error:
562 return str;
563 }
564
565 /*
566 * Set CLOEXEC flag to the give file descriptor.
567 */
568 LTTNG_HIDDEN
569 int utils_set_fd_cloexec(int fd)
570 {
571 int ret;
572
573 if (fd < 0) {
574 ret = -EINVAL;
575 goto end;
576 }
577
578 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
579 if (ret < 0) {
580 PERROR("fcntl cloexec");
581 ret = -errno;
582 }
583
584 end:
585 return ret;
586 }
587
588 /*
589 * Create pid file to the given path and filename.
590 */
591 LTTNG_HIDDEN
592 int utils_create_pid_file(pid_t pid, const char *filepath)
593 {
594 int ret;
595 FILE *fp;
596
597 assert(filepath);
598
599 fp = fopen(filepath, "w");
600 if (fp == NULL) {
601 PERROR("open pid file %s", filepath);
602 ret = -1;
603 goto error;
604 }
605
606 ret = fprintf(fp, "%d\n", (int) pid);
607 if (ret < 0) {
608 PERROR("fprintf pid file");
609 goto error;
610 }
611
612 if (fclose(fp)) {
613 PERROR("fclose");
614 }
615 DBG("Pid %d written in file %s", (int) pid, filepath);
616 ret = 0;
617 error:
618 return ret;
619 }
620
621 /*
622 * Create lock file to the given path and filename.
623 * Returns the associated file descriptor, -1 on error.
624 */
625 LTTNG_HIDDEN
626 int utils_create_lock_file(const char *filepath)
627 {
628 int ret;
629 int fd;
630 struct flock lock;
631
632 assert(filepath);
633
634 memset(&lock, 0, sizeof(lock));
635 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
636 S_IRGRP | S_IWGRP);
637 if (fd < 0) {
638 PERROR("open lock file %s", filepath);
639 fd = -1;
640 goto error;
641 }
642
643 /*
644 * Attempt to lock the file. If this fails, there is
645 * already a process using the same lock file running
646 * and we should exit.
647 */
648 lock.l_whence = SEEK_SET;
649 lock.l_type = F_WRLCK;
650
651 ret = fcntl(fd, F_SETLK, &lock);
652 if (ret == -1) {
653 PERROR("fcntl lock file");
654 ERR("Could not get lock file %s, another instance is running.",
655 filepath);
656 if (close(fd)) {
657 PERROR("close lock file");
658 }
659 fd = ret;
660 goto error;
661 }
662
663 error:
664 return fd;
665 }
666
667 /*
668 * Create directory using the given path and mode.
669 *
670 * On success, return 0 else a negative error code.
671 */
672 LTTNG_HIDDEN
673 int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
674 {
675 int ret;
676 struct lttng_directory_handle *handle;
677 const struct lttng_credentials creds = {
678 .uid = (uid_t) uid,
679 .gid = (gid_t) gid,
680 };
681
682 handle = lttng_directory_handle_create(NULL);
683 if (!handle) {
684 ret = -1;
685 goto end;
686 }
687 ret = lttng_directory_handle_create_subdirectory_as_user(
688 handle, path, mode,
689 (uid >= 0 || gid >= 0) ? &creds : NULL);
690 end:
691 lttng_directory_handle_put(handle);
692 return ret;
693 }
694
695 /*
696 * Recursively create directory using the given path and mode, under the
697 * provided uid and gid.
698 *
699 * On success, return 0 else a negative error code.
700 */
701 LTTNG_HIDDEN
702 int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
703 {
704 int ret;
705 struct lttng_directory_handle *handle;
706 const struct lttng_credentials creds = {
707 .uid = (uid_t) uid,
708 .gid = (gid_t) gid,
709 };
710
711 handle = lttng_directory_handle_create(NULL);
712 if (!handle) {
713 ret = -1;
714 goto end;
715 }
716 ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
717 handle, path, mode,
718 (uid >= 0 || gid >= 0) ? &creds : NULL);
719 end:
720 lttng_directory_handle_put(handle);
721 return ret;
722 }
723
724 /*
725 * out_stream_path is the output parameter.
726 *
727 * Return 0 on success or else a negative value.
728 */
729 LTTNG_HIDDEN
730 int utils_stream_file_path(const char *path_name, const char *file_name,
731 uint64_t size, uint64_t count, const char *suffix,
732 char *out_stream_path, size_t stream_path_len)
733 {
734 int ret;
735 char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
736 const char *path_separator;
737
738 if (path_name && (path_name[0] == '\0' ||
739 path_name[strlen(path_name) - 1] == '/')) {
740 path_separator = "";
741 } else {
742 path_separator = "/";
743 }
744
745 path_name = path_name ? : "";
746 suffix = suffix ? : "";
747 if (size > 0) {
748 ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
749 count);
750 assert(ret > 0 && ret < sizeof(count_str));
751 }
752
753 ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
754 path_name, path_separator, file_name, count_str,
755 suffix);
756 if (ret < 0 || ret >= stream_path_len) {
757 ERR("Truncation occurred while formatting stream path");
758 ret = -1;
759 } else {
760 ret = 0;
761 }
762 return ret;
763 }
764
765 /**
766 * Parse a string that represents a size in human readable format. It
767 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
768 *
769 * The suffix multiply the integer by:
770 * 'k': 1024
771 * 'M': 1024^2
772 * 'G': 1024^3
773 *
774 * @param str The string to parse.
775 * @param size Pointer to a uint64_t that will be filled with the
776 * resulting size.
777 *
778 * @return 0 on success, -1 on failure.
779 */
780 LTTNG_HIDDEN
781 int utils_parse_size_suffix(const char * const str, uint64_t * const size)
782 {
783 int ret;
784 uint64_t base_size;
785 long shift = 0;
786 const char *str_end;
787 char *num_end;
788
789 if (!str) {
790 DBG("utils_parse_size_suffix: received a NULL string.");
791 ret = -1;
792 goto end;
793 }
794
795 /* strtoull will accept a negative number, but we don't want to. */
796 if (strchr(str, '-') != NULL) {
797 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
798 ret = -1;
799 goto end;
800 }
801
802 /* str_end will point to the \0 */
803 str_end = str + strlen(str);
804 errno = 0;
805 base_size = strtoull(str, &num_end, 0);
806 if (errno != 0) {
807 PERROR("utils_parse_size_suffix strtoull");
808 ret = -1;
809 goto end;
810 }
811
812 if (num_end == str) {
813 /* strtoull parsed nothing, not good. */
814 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
815 ret = -1;
816 goto end;
817 }
818
819 /* Check if a prefix is present. */
820 switch (*num_end) {
821 case 'G':
822 shift = GIBI_LOG2;
823 num_end++;
824 break;
825 case 'M': /* */
826 shift = MEBI_LOG2;
827 num_end++;
828 break;
829 case 'K':
830 case 'k':
831 shift = KIBI_LOG2;
832 num_end++;
833 break;
834 case '\0':
835 break;
836 default:
837 DBG("utils_parse_size_suffix: invalid suffix.");
838 ret = -1;
839 goto end;
840 }
841
842 /* Check for garbage after the valid input. */
843 if (num_end != str_end) {
844 DBG("utils_parse_size_suffix: Garbage after size string.");
845 ret = -1;
846 goto end;
847 }
848
849 *size = base_size << shift;
850
851 /* Check for overflow */
852 if ((*size >> shift) != base_size) {
853 DBG("utils_parse_size_suffix: oops, overflow detected.");
854 ret = -1;
855 goto end;
856 }
857
858 ret = 0;
859 end:
860 return ret;
861 }
862
863 /**
864 * Parse a string that represents a time in human readable format. It
865 * supports decimal integers suffixed by:
866 * "us" for microsecond,
867 * "ms" for millisecond,
868 * "s" for second,
869 * "m" for minute,
870 * "h" for hour
871 *
872 * The suffix multiply the integer by:
873 * "us" : 1
874 * "ms" : 1000
875 * "s" : 1000000
876 * "m" : 60000000
877 * "h" : 3600000000
878 *
879 * Note that unit-less numbers are assumed to be microseconds.
880 *
881 * @param str The string to parse, assumed to be NULL-terminated.
882 * @param time_us Pointer to a uint64_t that will be filled with the
883 * resulting time in microseconds.
884 *
885 * @return 0 on success, -1 on failure.
886 */
887 LTTNG_HIDDEN
888 int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
889 {
890 int ret;
891 uint64_t base_time;
892 uint64_t multiplier = 1;
893 const char *str_end;
894 char *num_end;
895
896 if (!str) {
897 DBG("utils_parse_time_suffix: received a NULL string.");
898 ret = -1;
899 goto end;
900 }
901
902 /* strtoull will accept a negative number, but we don't want to. */
903 if (strchr(str, '-') != NULL) {
904 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
905 ret = -1;
906 goto end;
907 }
908
909 /* str_end will point to the \0 */
910 str_end = str + strlen(str);
911 errno = 0;
912 base_time = strtoull(str, &num_end, 10);
913 if (errno != 0) {
914 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
915 ret = -1;
916 goto end;
917 }
918
919 if (num_end == str) {
920 /* strtoull parsed nothing, not good. */
921 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
922 ret = -1;
923 goto end;
924 }
925
926 /* Check if a prefix is present. */
927 switch (*num_end) {
928 case 'u':
929 /*
930 * Microsecond (us)
931 *
932 * Skip the "us" if the string matches the "us" suffix,
933 * otherwise let the check for the end of the string handle
934 * the error reporting.
935 */
936 if (*(num_end + 1) == 's') {
937 num_end += 2;
938 }
939 break;
940 case 'm':
941 if (*(num_end + 1) == 's') {
942 /* Millisecond (ms) */
943 multiplier = USEC_PER_MSEC;
944 /* Skip the 's' */
945 num_end++;
946 } else {
947 /* Minute (m) */
948 multiplier = USEC_PER_MINUTE;
949 }
950 num_end++;
951 break;
952 case 's':
953 /* Second */
954 multiplier = USEC_PER_SEC;
955 num_end++;
956 break;
957 case 'h':
958 /* Hour */
959 multiplier = USEC_PER_HOURS;
960 num_end++;
961 break;
962 case '\0':
963 break;
964 default:
965 DBG("utils_parse_time_suffix: invalid suffix.");
966 ret = -1;
967 goto end;
968 }
969
970 /* Check for garbage after the valid input. */
971 if (num_end != str_end) {
972 DBG("utils_parse_time_suffix: Garbage after time string.");
973 ret = -1;
974 goto end;
975 }
976
977 *time_us = base_time * multiplier;
978
979 /* Check for overflow */
980 if ((*time_us / multiplier) != base_time) {
981 DBG("utils_parse_time_suffix: oops, overflow detected.");
982 ret = -1;
983 goto end;
984 }
985
986 ret = 0;
987 end:
988 return ret;
989 }
990
991 /*
992 * fls: returns the position of the most significant bit.
993 * Returns 0 if no bit is set, else returns the position of the most
994 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
995 */
996 #if defined(__i386) || defined(__x86_64)
997 static inline unsigned int fls_u32(uint32_t x)
998 {
999 int r;
1000
1001 asm("bsrl %1,%0\n\t"
1002 "jnz 1f\n\t"
1003 "movl $-1,%0\n\t"
1004 "1:\n\t"
1005 : "=r" (r) : "rm" (x));
1006 return r + 1;
1007 }
1008 #define HAS_FLS_U32
1009 #endif
1010
1011 #if defined(__x86_64) && defined(__LP64__)
1012 static inline
1013 unsigned int fls_u64(uint64_t x)
1014 {
1015 long r;
1016
1017 asm("bsrq %1,%0\n\t"
1018 "jnz 1f\n\t"
1019 "movq $-1,%0\n\t"
1020 "1:\n\t"
1021 : "=r" (r) : "rm" (x));
1022 return r + 1;
1023 }
1024 #define HAS_FLS_U64
1025 #endif
1026
1027 #ifndef HAS_FLS_U64
1028 static __attribute__((unused))
1029 unsigned int fls_u64(uint64_t x)
1030 {
1031 unsigned int r = 64;
1032
1033 if (!x)
1034 return 0;
1035
1036 if (!(x & 0xFFFFFFFF00000000ULL)) {
1037 x <<= 32;
1038 r -= 32;
1039 }
1040 if (!(x & 0xFFFF000000000000ULL)) {
1041 x <<= 16;
1042 r -= 16;
1043 }
1044 if (!(x & 0xFF00000000000000ULL)) {
1045 x <<= 8;
1046 r -= 8;
1047 }
1048 if (!(x & 0xF000000000000000ULL)) {
1049 x <<= 4;
1050 r -= 4;
1051 }
1052 if (!(x & 0xC000000000000000ULL)) {
1053 x <<= 2;
1054 r -= 2;
1055 }
1056 if (!(x & 0x8000000000000000ULL)) {
1057 x <<= 1;
1058 r -= 1;
1059 }
1060 return r;
1061 }
1062 #endif
1063
1064 #ifndef HAS_FLS_U32
1065 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1066 {
1067 unsigned int r = 32;
1068
1069 if (!x) {
1070 return 0;
1071 }
1072 if (!(x & 0xFFFF0000U)) {
1073 x <<= 16;
1074 r -= 16;
1075 }
1076 if (!(x & 0xFF000000U)) {
1077 x <<= 8;
1078 r -= 8;
1079 }
1080 if (!(x & 0xF0000000U)) {
1081 x <<= 4;
1082 r -= 4;
1083 }
1084 if (!(x & 0xC0000000U)) {
1085 x <<= 2;
1086 r -= 2;
1087 }
1088 if (!(x & 0x80000000U)) {
1089 x <<= 1;
1090 r -= 1;
1091 }
1092 return r;
1093 }
1094 #endif
1095
1096 /*
1097 * Return the minimum order for which x <= (1UL << order).
1098 * Return -1 if x is 0.
1099 */
1100 LTTNG_HIDDEN
1101 int utils_get_count_order_u32(uint32_t x)
1102 {
1103 if (!x) {
1104 return -1;
1105 }
1106
1107 return fls_u32(x - 1);
1108 }
1109
1110 /*
1111 * Return the minimum order for which x <= (1UL << order).
1112 * Return -1 if x is 0.
1113 */
1114 LTTNG_HIDDEN
1115 int utils_get_count_order_u64(uint64_t x)
1116 {
1117 if (!x) {
1118 return -1;
1119 }
1120
1121 return fls_u64(x - 1);
1122 }
1123
1124 /**
1125 * Obtain the value of LTTNG_HOME environment variable, if exists.
1126 * Otherwise returns the value of HOME.
1127 */
1128 LTTNG_HIDDEN
1129 const char *utils_get_home_dir(void)
1130 {
1131 char *val = NULL;
1132 struct passwd *pwd;
1133
1134 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
1135 if (val != NULL) {
1136 goto end;
1137 }
1138 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
1139 if (val != NULL) {
1140 goto end;
1141 }
1142
1143 /* Fallback on the password file entry. */
1144 pwd = getpwuid(getuid());
1145 if (!pwd) {
1146 goto end;
1147 }
1148 val = pwd->pw_dir;
1149
1150 DBG3("Home directory is '%s'", val);
1151
1152 end:
1153 return val;
1154 }
1155
1156 /**
1157 * Get user's home directory. Dynamically allocated, must be freed
1158 * by the caller.
1159 */
1160 LTTNG_HIDDEN
1161 char *utils_get_user_home_dir(uid_t uid)
1162 {
1163 struct passwd pwd;
1164 struct passwd *result;
1165 char *home_dir = NULL;
1166 char *buf = NULL;
1167 long buflen;
1168 int ret;
1169
1170 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1171 if (buflen == -1) {
1172 goto end;
1173 }
1174 retry:
1175 buf = zmalloc(buflen);
1176 if (!buf) {
1177 goto end;
1178 }
1179
1180 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1181 if (ret || !result) {
1182 if (ret == ERANGE) {
1183 free(buf);
1184 buflen *= 2;
1185 goto retry;
1186 }
1187 goto end;
1188 }
1189
1190 home_dir = strdup(pwd.pw_dir);
1191 end:
1192 free(buf);
1193 return home_dir;
1194 }
1195
1196 /*
1197 * With the given format, fill dst with the time of len maximum siz.
1198 *
1199 * Return amount of bytes set in the buffer or else 0 on error.
1200 */
1201 LTTNG_HIDDEN
1202 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1203 {
1204 size_t ret;
1205 time_t rawtime;
1206 struct tm *timeinfo;
1207
1208 assert(format);
1209 assert(dst);
1210
1211 /* Get date and time for session path */
1212 time(&rawtime);
1213 timeinfo = localtime(&rawtime);
1214 ret = strftime(dst, len, format, timeinfo);
1215 if (ret == 0) {
1216 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
1217 dst, len);
1218 }
1219
1220 return ret;
1221 }
1222
1223 /*
1224 * Return 0 on success and set *gid to the group_ID matching the passed name.
1225 * Else -1 if it cannot be found or an error occurred.
1226 */
1227 LTTNG_HIDDEN
1228 int utils_get_group_id(const char *name, bool warn, gid_t *gid)
1229 {
1230 static volatile int warn_once;
1231 int ret;
1232 long sys_len;
1233 size_t len;
1234 struct group grp;
1235 struct group *result;
1236 struct lttng_dynamic_buffer buffer;
1237
1238 /* Get the system limit, if it exists. */
1239 sys_len = sysconf(_SC_GETGR_R_SIZE_MAX);
1240 if (sys_len == -1) {
1241 len = 1024;
1242 } else {
1243 len = (size_t) sys_len;
1244 }
1245
1246 lttng_dynamic_buffer_init(&buffer);
1247 ret = lttng_dynamic_buffer_set_size(&buffer, len);
1248 if (ret) {
1249 ERR("Failed to allocate group info buffer");
1250 ret = -1;
1251 goto error;
1252 }
1253
1254 while ((ret = getgrnam_r(name, &grp, buffer.data, buffer.size, &result)) == ERANGE) {
1255 const size_t new_len = 2 * buffer.size;
1256
1257 /* Buffer is not big enough, increase its size. */
1258 if (new_len < buffer.size) {
1259 ERR("Group info buffer size overflow");
1260 ret = -1;
1261 goto error;
1262 }
1263
1264 ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
1265 if (ret) {
1266 ERR("Failed to grow group info buffer to %zu bytes",
1267 new_len);
1268 ret = -1;
1269 goto error;
1270 }
1271 }
1272 if (ret) {
1273 PERROR("Failed to get group file entry for group name \"%s\"",
1274 name);
1275 ret = -1;
1276 goto error;
1277 }
1278
1279 /* Group not found. */
1280 if (!result) {
1281 ret = -1;
1282 goto error;
1283 }
1284
1285 *gid = result->gr_gid;
1286 ret = 0;
1287
1288 error:
1289 if (ret && warn && !warn_once) {
1290 WARN("No tracing group detected");
1291 warn_once = 1;
1292 }
1293 lttng_dynamic_buffer_reset(&buffer);
1294 return ret;
1295 }
1296
1297 /*
1298 * Return a newly allocated option string. This string is to be used as the
1299 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1300 * of elements in the long_options array. Returns NULL if the string's
1301 * allocation fails.
1302 */
1303 LTTNG_HIDDEN
1304 char *utils_generate_optstring(const struct option *long_options,
1305 size_t opt_count)
1306 {
1307 int i;
1308 size_t string_len = opt_count, str_pos = 0;
1309 char *optstring;
1310
1311 /*
1312 * Compute the necessary string length. One letter per option, two when an
1313 * argument is necessary, and a trailing NULL.
1314 */
1315 for (i = 0; i < opt_count; i++) {
1316 string_len += long_options[i].has_arg ? 1 : 0;
1317 }
1318
1319 optstring = zmalloc(string_len);
1320 if (!optstring) {
1321 goto end;
1322 }
1323
1324 for (i = 0; i < opt_count; i++) {
1325 if (!long_options[i].name) {
1326 /* Got to the trailing NULL element */
1327 break;
1328 }
1329
1330 if (long_options[i].val != '\0') {
1331 optstring[str_pos++] = (char) long_options[i].val;
1332 if (long_options[i].has_arg) {
1333 optstring[str_pos++] = ':';
1334 }
1335 }
1336 }
1337
1338 end:
1339 return optstring;
1340 }
1341
1342 /*
1343 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1344 * any file. Try to rmdir any empty directory within the hierarchy.
1345 */
1346 LTTNG_HIDDEN
1347 int utils_recursive_rmdir(const char *path)
1348 {
1349 int ret;
1350 struct lttng_directory_handle *handle;
1351
1352 handle = lttng_directory_handle_create(NULL);
1353 if (!handle) {
1354 ret = -1;
1355 goto end;
1356 }
1357 ret = lttng_directory_handle_remove_subdirectory(handle, path);
1358 end:
1359 lttng_directory_handle_put(handle);
1360 return ret;
1361 }
1362
1363 LTTNG_HIDDEN
1364 int utils_truncate_stream_file(int fd, off_t length)
1365 {
1366 int ret;
1367 off_t lseek_ret;
1368
1369 ret = ftruncate(fd, length);
1370 if (ret < 0) {
1371 PERROR("ftruncate");
1372 goto end;
1373 }
1374 lseek_ret = lseek(fd, length, SEEK_SET);
1375 if (lseek_ret < 0) {
1376 PERROR("lseek");
1377 ret = -1;
1378 goto end;
1379 }
1380 end:
1381 return ret;
1382 }
1383
1384 static const char *get_man_bin_path(void)
1385 {
1386 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
1387
1388 if (env_man_path) {
1389 return env_man_path;
1390 }
1391
1392 return DEFAULT_MAN_BIN_PATH;
1393 }
1394
1395 LTTNG_HIDDEN
1396 int utils_show_help(int section, const char *page_name,
1397 const char *help_msg)
1398 {
1399 char section_string[8];
1400 const char *man_bin_path = get_man_bin_path();
1401 int ret = 0;
1402
1403 if (help_msg) {
1404 printf("%s", help_msg);
1405 goto end;
1406 }
1407
1408 /* Section integer -> section string */
1409 ret = sprintf(section_string, "%d", section);
1410 assert(ret > 0 && ret < 8);
1411
1412 /*
1413 * Execute man pager.
1414 *
1415 * We provide -M to man here because LTTng-tools can
1416 * be installed outside /usr, in which case its man pages are
1417 * not located in the default /usr/share/man directory.
1418 */
1419 ret = execlp(man_bin_path, "man", "-M", MANPATH,
1420 section_string, page_name, NULL);
1421
1422 end:
1423 return ret;
1424 }
1425
1426 static
1427 int read_proc_meminfo_field(const char *field, size_t *value)
1428 {
1429 int ret;
1430 FILE *proc_meminfo;
1431 char name[PROC_MEMINFO_FIELD_MAX_NAME_LEN] = {};
1432
1433 proc_meminfo = fopen(PROC_MEMINFO_PATH, "r");
1434 if (!proc_meminfo) {
1435 PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
1436 ret = -1;
1437 goto fopen_error;
1438 }
1439
1440 /*
1441 * Read the contents of /proc/meminfo line by line to find the right
1442 * field.
1443 */
1444 while (!feof(proc_meminfo)) {
1445 unsigned long value_kb;
1446
1447 ret = fscanf(proc_meminfo,
1448 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n",
1449 name, &value_kb);
1450 if (ret == EOF) {
1451 /*
1452 * fscanf() returning EOF can indicate EOF or an error.
1453 */
1454 if (ferror(proc_meminfo)) {
1455 PERROR("Failed to parse " PROC_MEMINFO_PATH);
1456 }
1457 break;
1458 }
1459
1460 if (ret == 2 && strcmp(name, field) == 0) {
1461 /*
1462 * This number is displayed in kilo-bytes. Return the
1463 * number of bytes.
1464 */
1465 *value = ((size_t) value_kb) * 1024;
1466 ret = 0;
1467 goto found;
1468 }
1469 }
1470 /* Reached the end of the file without finding the right field. */
1471 ret = -1;
1472
1473 found:
1474 fclose(proc_meminfo);
1475 fopen_error:
1476 return ret;
1477 }
1478
1479 /*
1480 * Returns an estimate of the number of bytes of memory available based on the
1481 * the information in `/proc/meminfo`. The number returned by this function is
1482 * a best guess.
1483 */
1484 LTTNG_HIDDEN
1485 int utils_get_memory_available(size_t *value)
1486 {
1487 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value);
1488 }
1489
1490 /*
1491 * Returns the total size of the memory on the system in bytes based on the
1492 * the information in `/proc/meminfo`.
1493 */
1494 LTTNG_HIDDEN
1495 int utils_get_memory_total(size_t *value)
1496 {
1497 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value);
1498 }
1499
1500 LTTNG_HIDDEN
1501 int utils_change_working_directory(const char *path)
1502 {
1503 int ret;
1504
1505 assert(path);
1506
1507 DBG("Changing working directory to \"%s\"", path);
1508 ret = chdir(path);
1509 if (ret) {
1510 PERROR("Failed to change working directory to \"%s\"", path);
1511 goto end;
1512 }
1513
1514 /* Check for write access */
1515 if (access(path, W_OK)) {
1516 if (errno == EACCES) {
1517 /*
1518 * Do not treat this as an error since the permission
1519 * might change in the lifetime of the process
1520 */
1521 DBG("Working directory \"%s\" is not writable", path);
1522 } else {
1523 PERROR("Failed to check if working directory \"%s\" is writable",
1524 path);
1525 }
1526 }
1527
1528 end:
1529 return ret;
1530 }
This page took 0.061715 seconds and 5 git commands to generate.