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