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