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