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