Support minute and hour as time suffixes
[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:
1108 * "us" for microsecond,
1109 * "ms" for millisecond,
1110 * "s" for second,
1111 * "m" for minute,
1112 * "h" for hour
1113 *
1114 * The suffix multiply the integer by:
1115 * "us" : 1
1116 * "ms" : 1000
1117 * "s" : 1000000
1118 * "m" : 60000000
1119 * "h" : 3600000000
1120 *
1121 * Note that unit-less numbers are assumed to be microseconds.
1122 *
1123 * @param str The string to parse, assumed to be NULL-terminated.
1124 * @param time_us Pointer to a uint64_t that will be filled with the
1125 * resulting time in microseconds.
1126 *
1127 * @return 0 on success, -1 on failure.
1128 */
1129 LTTNG_HIDDEN
1130 int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
1131 {
1132 int ret;
1133 uint64_t base_time;
1134 uint64_t multiplier = 1;
1135 const char *str_end;
1136 char *num_end;
1137
1138 if (!str) {
1139 DBG("utils_parse_time_suffix: received a NULL string.");
1140 ret = -1;
1141 goto end;
1142 }
1143
1144 /* strtoull will accept a negative number, but we don't want to. */
1145 if (strchr(str, '-') != NULL) {
1146 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1147 ret = -1;
1148 goto end;
1149 }
1150
1151 /* str_end will point to the \0 */
1152 str_end = str + strlen(str);
1153 errno = 0;
1154 base_time = strtoull(str, &num_end, 10);
1155 if (errno != 0) {
1156 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
1157 ret = -1;
1158 goto end;
1159 }
1160
1161 if (num_end == str) {
1162 /* strtoull parsed nothing, not good. */
1163 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1164 ret = -1;
1165 goto end;
1166 }
1167
1168 /* Check if a prefix is present. */
1169 switch (*num_end) {
1170 case 'u':
1171 /*
1172 * Microsecond (us)
1173 *
1174 * Skip the "us" if the string matches the "us" suffix,
1175 * otherwise let the check for the end of the string handle
1176 * the error reporting.
1177 */
1178 if (*(num_end + 1) == 's') {
1179 num_end += 2;
1180 }
1181 break;
1182 case 'm':
1183 if (*(num_end + 1) == 's') {
1184 /* Millisecond (ms) */
1185 multiplier = USEC_PER_MSEC;
1186 /* Skip the 's' */
1187 num_end++;
1188 } else {
1189 /* Minute (m) */
1190 multiplier = USEC_PER_MINUTE;
1191 }
1192 num_end++;
1193 break;
1194 case 's':
1195 /* Second */
1196 multiplier = USEC_PER_SEC;
1197 num_end++;
1198 break;
1199 case 'h':
1200 /* Hour */
1201 multiplier = USEC_PER_HOURS;
1202 num_end++;
1203 break;
1204 case '\0':
1205 break;
1206 default:
1207 DBG("utils_parse_time_suffix: invalid suffix.");
1208 ret = -1;
1209 goto end;
1210 }
1211
1212 /* Check for garbage after the valid input. */
1213 if (num_end != str_end) {
1214 DBG("utils_parse_time_suffix: Garbage after time string.");
1215 ret = -1;
1216 goto end;
1217 }
1218
1219 *time_us = base_time * multiplier;
1220
1221 /* Check for overflow */
1222 if ((*time_us / multiplier) != base_time) {
1223 DBG("utils_parse_time_suffix: oops, overflow detected.");
1224 ret = -1;
1225 goto end;
1226 }
1227
1228 ret = 0;
1229 end:
1230 return ret;
1231 }
1232
1233 /*
1234 * fls: returns the position of the most significant bit.
1235 * Returns 0 if no bit is set, else returns the position of the most
1236 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1237 */
1238 #if defined(__i386) || defined(__x86_64)
1239 static inline unsigned int fls_u32(uint32_t x)
1240 {
1241 int r;
1242
1243 asm("bsrl %1,%0\n\t"
1244 "jnz 1f\n\t"
1245 "movl $-1,%0\n\t"
1246 "1:\n\t"
1247 : "=r" (r) : "rm" (x));
1248 return r + 1;
1249 }
1250 #define HAS_FLS_U32
1251 #endif
1252
1253 #if defined(__x86_64)
1254 static inline
1255 unsigned int fls_u64(uint64_t x)
1256 {
1257 long r;
1258
1259 asm("bsrq %1,%0\n\t"
1260 "jnz 1f\n\t"
1261 "movq $-1,%0\n\t"
1262 "1:\n\t"
1263 : "=r" (r) : "rm" (x));
1264 return r + 1;
1265 }
1266 #define HAS_FLS_U64
1267 #endif
1268
1269 #ifndef HAS_FLS_U64
1270 static __attribute__((unused))
1271 unsigned int fls_u64(uint64_t x)
1272 {
1273 unsigned int r = 64;
1274
1275 if (!x)
1276 return 0;
1277
1278 if (!(x & 0xFFFFFFFF00000000ULL)) {
1279 x <<= 32;
1280 r -= 32;
1281 }
1282 if (!(x & 0xFFFF000000000000ULL)) {
1283 x <<= 16;
1284 r -= 16;
1285 }
1286 if (!(x & 0xFF00000000000000ULL)) {
1287 x <<= 8;
1288 r -= 8;
1289 }
1290 if (!(x & 0xF000000000000000ULL)) {
1291 x <<= 4;
1292 r -= 4;
1293 }
1294 if (!(x & 0xC000000000000000ULL)) {
1295 x <<= 2;
1296 r -= 2;
1297 }
1298 if (!(x & 0x8000000000000000ULL)) {
1299 x <<= 1;
1300 r -= 1;
1301 }
1302 return r;
1303 }
1304 #endif
1305
1306 #ifndef HAS_FLS_U32
1307 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1308 {
1309 unsigned int r = 32;
1310
1311 if (!x) {
1312 return 0;
1313 }
1314 if (!(x & 0xFFFF0000U)) {
1315 x <<= 16;
1316 r -= 16;
1317 }
1318 if (!(x & 0xFF000000U)) {
1319 x <<= 8;
1320 r -= 8;
1321 }
1322 if (!(x & 0xF0000000U)) {
1323 x <<= 4;
1324 r -= 4;
1325 }
1326 if (!(x & 0xC0000000U)) {
1327 x <<= 2;
1328 r -= 2;
1329 }
1330 if (!(x & 0x80000000U)) {
1331 x <<= 1;
1332 r -= 1;
1333 }
1334 return r;
1335 }
1336 #endif
1337
1338 /*
1339 * Return the minimum order for which x <= (1UL << order).
1340 * Return -1 if x is 0.
1341 */
1342 LTTNG_HIDDEN
1343 int utils_get_count_order_u32(uint32_t x)
1344 {
1345 if (!x) {
1346 return -1;
1347 }
1348
1349 return fls_u32(x - 1);
1350 }
1351
1352 /*
1353 * Return the minimum order for which x <= (1UL << order).
1354 * Return -1 if x is 0.
1355 */
1356 LTTNG_HIDDEN
1357 int utils_get_count_order_u64(uint64_t x)
1358 {
1359 if (!x) {
1360 return -1;
1361 }
1362
1363 return fls_u64(x - 1);
1364 }
1365
1366 /**
1367 * Obtain the value of LTTNG_HOME environment variable, if exists.
1368 * Otherwise returns the value of HOME.
1369 */
1370 LTTNG_HIDDEN
1371 char *utils_get_home_dir(void)
1372 {
1373 char *val = NULL;
1374 struct passwd *pwd;
1375
1376 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
1377 if (val != NULL) {
1378 goto end;
1379 }
1380 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
1381 if (val != NULL) {
1382 goto end;
1383 }
1384
1385 /* Fallback on the password file entry. */
1386 pwd = getpwuid(getuid());
1387 if (!pwd) {
1388 goto end;
1389 }
1390 val = pwd->pw_dir;
1391
1392 DBG3("Home directory is '%s'", val);
1393
1394 end:
1395 return val;
1396 }
1397
1398 /**
1399 * Get user's home directory. Dynamically allocated, must be freed
1400 * by the caller.
1401 */
1402 LTTNG_HIDDEN
1403 char *utils_get_user_home_dir(uid_t uid)
1404 {
1405 struct passwd pwd;
1406 struct passwd *result;
1407 char *home_dir = NULL;
1408 char *buf = NULL;
1409 long buflen;
1410 int ret;
1411
1412 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1413 if (buflen == -1) {
1414 goto end;
1415 }
1416 retry:
1417 buf = zmalloc(buflen);
1418 if (!buf) {
1419 goto end;
1420 }
1421
1422 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1423 if (ret || !result) {
1424 if (ret == ERANGE) {
1425 free(buf);
1426 buflen *= 2;
1427 goto retry;
1428 }
1429 goto end;
1430 }
1431
1432 home_dir = strdup(pwd.pw_dir);
1433 end:
1434 free(buf);
1435 return home_dir;
1436 }
1437
1438 /*
1439 * With the given format, fill dst with the time of len maximum siz.
1440 *
1441 * Return amount of bytes set in the buffer or else 0 on error.
1442 */
1443 LTTNG_HIDDEN
1444 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1445 {
1446 size_t ret;
1447 time_t rawtime;
1448 struct tm *timeinfo;
1449
1450 assert(format);
1451 assert(dst);
1452
1453 /* Get date and time for session path */
1454 time(&rawtime);
1455 timeinfo = localtime(&rawtime);
1456 ret = strftime(dst, len, format, timeinfo);
1457 if (ret == 0) {
1458 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
1459 dst, len);
1460 }
1461
1462 return ret;
1463 }
1464
1465 /*
1466 * Return the group ID matching name, else 0 if it cannot be found.
1467 */
1468 LTTNG_HIDDEN
1469 gid_t utils_get_group_id(const char *name)
1470 {
1471 struct group *grp;
1472
1473 grp = getgrnam(name);
1474 if (!grp) {
1475 static volatile int warn_once;
1476
1477 if (!warn_once) {
1478 WARN("No tracing group detected");
1479 warn_once = 1;
1480 }
1481 return 0;
1482 }
1483 return grp->gr_gid;
1484 }
1485
1486 /*
1487 * Return a newly allocated option string. This string is to be used as the
1488 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1489 * of elements in the long_options array. Returns NULL if the string's
1490 * allocation fails.
1491 */
1492 LTTNG_HIDDEN
1493 char *utils_generate_optstring(const struct option *long_options,
1494 size_t opt_count)
1495 {
1496 int i;
1497 size_t string_len = opt_count, str_pos = 0;
1498 char *optstring;
1499
1500 /*
1501 * Compute the necessary string length. One letter per option, two when an
1502 * argument is necessary, and a trailing NULL.
1503 */
1504 for (i = 0; i < opt_count; i++) {
1505 string_len += long_options[i].has_arg ? 1 : 0;
1506 }
1507
1508 optstring = zmalloc(string_len);
1509 if (!optstring) {
1510 goto end;
1511 }
1512
1513 for (i = 0; i < opt_count; i++) {
1514 if (!long_options[i].name) {
1515 /* Got to the trailing NULL element */
1516 break;
1517 }
1518
1519 if (long_options[i].val != '\0') {
1520 optstring[str_pos++] = (char) long_options[i].val;
1521 if (long_options[i].has_arg) {
1522 optstring[str_pos++] = ':';
1523 }
1524 }
1525 }
1526
1527 end:
1528 return optstring;
1529 }
1530
1531 /*
1532 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1533 * any file. Try to rmdir any empty directory within the hierarchy.
1534 */
1535 LTTNG_HIDDEN
1536 int utils_recursive_rmdir(const char *path)
1537 {
1538 DIR *dir;
1539 size_t path_len;
1540 int dir_fd, ret = 0, closeret, is_empty = 1;
1541 struct dirent *entry;
1542
1543 /* Open directory */
1544 dir = opendir(path);
1545 if (!dir) {
1546 PERROR("Cannot open '%s' path", path);
1547 return -1;
1548 }
1549 dir_fd = lttng_dirfd(dir);
1550 if (dir_fd < 0) {
1551 PERROR("lttng_dirfd");
1552 return -1;
1553 }
1554
1555 path_len = strlen(path);
1556 while ((entry = readdir(dir))) {
1557 struct stat st;
1558 size_t name_len;
1559 char filename[PATH_MAX];
1560
1561 if (!strcmp(entry->d_name, ".")
1562 || !strcmp(entry->d_name, "..")) {
1563 continue;
1564 }
1565
1566 name_len = strlen(entry->d_name);
1567 if (path_len + name_len + 2 > sizeof(filename)) {
1568 ERR("Failed to remove file: path name too long (%s/%s)",
1569 path, entry->d_name);
1570 continue;
1571 }
1572 if (snprintf(filename, sizeof(filename), "%s/%s",
1573 path, entry->d_name) < 0) {
1574 ERR("Failed to format path.");
1575 continue;
1576 }
1577
1578 if (stat(filename, &st)) {
1579 PERROR("stat");
1580 continue;
1581 }
1582
1583 if (S_ISDIR(st.st_mode)) {
1584 char subpath[PATH_MAX];
1585
1586 strncpy(subpath, path, PATH_MAX);
1587 subpath[PATH_MAX - 1] = '\0';
1588 strncat(subpath, "/",
1589 PATH_MAX - strlen(subpath) - 1);
1590 strncat(subpath, entry->d_name,
1591 PATH_MAX - strlen(subpath) - 1);
1592 if (utils_recursive_rmdir(subpath)) {
1593 is_empty = 0;
1594 }
1595 } else if (S_ISREG(st.st_mode)) {
1596 is_empty = 0;
1597 } else {
1598 ret = -EINVAL;
1599 goto end;
1600 }
1601 }
1602 end:
1603 closeret = closedir(dir);
1604 if (closeret) {
1605 PERROR("closedir");
1606 }
1607 if (is_empty) {
1608 DBG3("Attempting rmdir %s", path);
1609 ret = rmdir(path);
1610 }
1611 return ret;
1612 }
1613
1614 LTTNG_HIDDEN
1615 int utils_truncate_stream_file(int fd, off_t length)
1616 {
1617 int ret;
1618 off_t lseek_ret;
1619
1620 ret = ftruncate(fd, length);
1621 if (ret < 0) {
1622 PERROR("ftruncate");
1623 goto end;
1624 }
1625 lseek_ret = lseek(fd, length, SEEK_SET);
1626 if (lseek_ret < 0) {
1627 PERROR("lseek");
1628 ret = -1;
1629 goto end;
1630 }
1631 end:
1632 return ret;
1633 }
1634
1635 static const char *get_man_bin_path(void)
1636 {
1637 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
1638
1639 if (env_man_path) {
1640 return env_man_path;
1641 }
1642
1643 return DEFAULT_MAN_BIN_PATH;
1644 }
1645
1646 LTTNG_HIDDEN
1647 int utils_show_help(int section, const char *page_name,
1648 const char *help_msg)
1649 {
1650 char section_string[8];
1651 const char *man_bin_path = get_man_bin_path();
1652 int ret = 0;
1653
1654 if (help_msg) {
1655 printf("%s", help_msg);
1656 goto end;
1657 }
1658
1659 /* Section integer -> section string */
1660 ret = sprintf(section_string, "%d", section);
1661 assert(ret > 0 && ret < 8);
1662
1663 /*
1664 * Execute man pager.
1665 *
1666 * We provide -M to man here because LTTng-tools can
1667 * be installed outside /usr, in which case its man pages are
1668 * not located in the default /usr/share/man directory.
1669 */
1670 ret = execlp(man_bin_path, "man", "-M", MANPATH,
1671 section_string, page_name, NULL);
1672
1673 end:
1674 return ret;
1675 }
This page took 0.110596 seconds and 5 git commands to generate.