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