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