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