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