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