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