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