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