3892cb4ada8b613b2396866e033bf16311abf7a4
[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 #include <assert.h>
22 #include <ctype.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <stdlib.h>
26 #include <string.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
35 #include <common/common.h>
36 #include <common/runas.h>
37
38 #include "utils.h"
39 #include "defaults.h"
40
41 /*
42 * Return a partial realpath(3) of the path even if the full path does not
43 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
44 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
45 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
46 * point directory does not exist.
47 * In case resolved_path is NULL, the string returned was allocated in the
48 * function and thus need to be freed by the caller. The size argument allows
49 * to specify the size of the resolved_path argument if given, or the size to
50 * allocate.
51 */
52 LTTNG_HIDDEN
53 char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
54 {
55 char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
56 const char *next, *prev, *end;
57
58 /* Safety net */
59 if (path == NULL) {
60 goto error;
61 }
62
63 /*
64 * Identify the end of the path, we don't want to treat the
65 * last char if it is a '/', we will just keep it on the side
66 * to be added at the end, and return a value coherent with
67 * the path given as argument
68 */
69 end = path + strlen(path);
70 if (*(end-1) == '/') {
71 end--;
72 }
73
74 /* Initiate the values of the pointers before looping */
75 next = path;
76 prev = next;
77 /* Only to ensure try_path is not NULL to enter the while */
78 try_path = (char *)next;
79
80 /* Resolve the canonical path of the first part of the path */
81 while (try_path != NULL && next != end) {
82 /*
83 * If there is not any '/' left, we want to try with
84 * the full path
85 */
86 next = strpbrk(next + 1, "/");
87 if (next == NULL) {
88 next = end;
89 }
90
91 /* Cut the part we will be trying to resolve */
92 cut_path = strndup(path, next - path);
93 if (cut_path == NULL) {
94 PERROR("strndup");
95 goto error;
96 }
97
98 /* Try to resolve this part */
99 try_path = realpath((char *)cut_path, NULL);
100 if (try_path == NULL) {
101 /*
102 * There was an error, we just want to be assured it
103 * is linked to an unexistent directory, if it's another
104 * reason, we spawn an error
105 */
106 switch (errno) {
107 case ENOENT:
108 /* Ignore the error */
109 break;
110 default:
111 PERROR("realpath (partial_realpath)");
112 goto error;
113 break;
114 }
115 } else {
116 /* Save the place we are before trying the next step */
117 free(try_path_prev);
118 try_path_prev = try_path;
119 prev = next;
120 }
121
122 /* Free the allocated memory */
123 free(cut_path);
124 cut_path = NULL;
125 };
126
127 /* Allocate memory for the resolved path if necessary */
128 if (resolved_path == NULL) {
129 resolved_path = zmalloc(size);
130 if (resolved_path == NULL) {
131 PERROR("zmalloc resolved path");
132 goto error;
133 }
134 }
135
136 /*
137 * If we were able to solve at least partially the path, we can concatenate
138 * what worked and what didn't work
139 */
140 if (try_path_prev != NULL) {
141 /* If we risk to concatenate two '/', we remove one of them */
142 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
143 try_path_prev[strlen(try_path_prev) - 1] = '\0';
144 }
145
146 /*
147 * Duplicate the memory used by prev in case resolved_path and
148 * path are pointers for the same memory space
149 */
150 cut_path = strdup(prev);
151 if (cut_path == NULL) {
152 PERROR("strdup");
153 goto error;
154 }
155
156 /* Concatenate the strings */
157 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
158
159 /* Free the allocated memory */
160 free(cut_path);
161 free(try_path_prev);
162 /*
163 * Else, we just copy the path in our resolved_path to
164 * return it as is
165 */
166 } else {
167 strncpy(resolved_path, path, size);
168 }
169
170 /* Then we return the 'partially' resolved path */
171 return resolved_path;
172
173 error:
174 free(resolved_path);
175 free(cut_path);
176 free(try_path);
177 if (try_path_prev != try_path) {
178 free(try_path_prev);
179 }
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 = strndup(absolute_path, next - absolute_path);
233 if (!start_path) {
234 PERROR("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 = strndup(absolute_path, previous - absolute_path);
253 if (!start_path) {
254 PERROR("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", pid);
483 if (ret < 0) {
484 PERROR("fprintf pid file");
485 }
486
487 fclose(fp);
488 DBG("Pid %d written in file %s", pid, filepath);
489 error:
490 return ret;
491 }
492
493 /*
494 * Create lock file to the given path and filename.
495 * Returns the associated file descriptor, -1 on error.
496 */
497 LTTNG_HIDDEN
498 int utils_create_lock_file(const char *filepath)
499 {
500 int ret;
501 int fd;
502
503 assert(filepath);
504
505 fd = open(filepath, O_CREAT,
506 O_WRONLY | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
507 if (fd < 0) {
508 PERROR("open lock file %s", filepath);
509 ret = -1;
510 goto error;
511 }
512
513 /*
514 * Attempt to lock the file. If this fails, there is
515 * already a process using the same lock file running
516 * and we should exit.
517 */
518 ret = flock(fd, LOCK_EX | LOCK_NB);
519 if (ret) {
520 WARN("Could not get lock file %s, another instance is running.",
521 filepath);
522 close(fd);
523 fd = ret;
524 goto error;
525 }
526
527 error:
528 return fd;
529 }
530
531 /*
532 * Create directory using the given path and mode.
533 *
534 * On success, return 0 else a negative error code.
535 */
536 LTTNG_HIDDEN
537 int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
538 {
539 int ret;
540
541 if (uid < 0 || gid < 0) {
542 ret = mkdir(path, mode);
543 } else {
544 ret = run_as_mkdir(path, mode, uid, gid);
545 }
546 if (ret < 0) {
547 if (errno != EEXIST) {
548 PERROR("mkdir %s, uid %d, gid %d", path ? path : "NULL",
549 uid, gid);
550 } else {
551 ret = 0;
552 }
553 }
554
555 return ret;
556 }
557
558 /*
559 * Internal version of mkdir_recursive. Runs as the current user.
560 * Don't call directly; use utils_mkdir_recursive().
561 *
562 * This function is ominously marked as "unsafe" since it should only
563 * be called by a caller that has transitioned to the uid and gid under which
564 * the directory creation should occur.
565 */
566 LTTNG_HIDDEN
567 int _utils_mkdir_recursive_unsafe(const char *path, mode_t mode)
568 {
569 char *p, tmp[PATH_MAX];
570 size_t len;
571 int ret;
572
573 assert(path);
574
575 ret = snprintf(tmp, sizeof(tmp), "%s", path);
576 if (ret < 0) {
577 PERROR("snprintf mkdir");
578 goto error;
579 }
580
581 len = ret;
582 if (tmp[len - 1] == '/') {
583 tmp[len - 1] = 0;
584 }
585
586 for (p = tmp + 1; *p; p++) {
587 if (*p == '/') {
588 *p = 0;
589 if (tmp[strlen(tmp) - 1] == '.' &&
590 tmp[strlen(tmp) - 2] == '.' &&
591 tmp[strlen(tmp) - 3] == '/') {
592 ERR("Using '/../' is not permitted in the trace path (%s)",
593 tmp);
594 ret = -1;
595 goto error;
596 }
597 ret = mkdir(tmp, mode);
598 if (ret < 0) {
599 if (errno != EEXIST) {
600 PERROR("mkdir recursive");
601 ret = -errno;
602 goto error;
603 }
604 }
605 *p = '/';
606 }
607 }
608
609 ret = mkdir(tmp, mode);
610 if (ret < 0) {
611 if (errno != EEXIST) {
612 PERROR("mkdir recursive last element");
613 ret = -errno;
614 } else {
615 ret = 0;
616 }
617 }
618
619 error:
620 return ret;
621 }
622
623 /*
624 * Recursively create directory using the given path and mode, under the
625 * provided uid and gid.
626 *
627 * On success, return 0 else a negative error code.
628 */
629 LTTNG_HIDDEN
630 int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
631 {
632 int ret;
633
634 if (uid < 0 || gid < 0) {
635 /* Run as current user. */
636 ret = _utils_mkdir_recursive_unsafe(path, mode);
637 } else {
638 ret = run_as_mkdir_recursive(path, mode, uid, gid);
639 }
640 if (ret < 0) {
641 PERROR("mkdir %s, uid %d, gid %d", path ? path : "NULL",
642 uid, gid);
643 }
644
645 return ret;
646 }
647
648 /*
649 * path is the output parameter. It needs to be PATH_MAX len.
650 *
651 * Return 0 on success or else a negative value.
652 */
653 static int utils_stream_file_name(char *path,
654 const char *path_name, const char *file_name,
655 uint64_t size, uint64_t count,
656 const char *suffix)
657 {
658 int ret;
659 char full_path[PATH_MAX];
660 char *path_name_suffix = NULL;
661 char *extra = NULL;
662
663 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
664 path_name, file_name);
665 if (ret < 0) {
666 PERROR("snprintf create output file");
667 goto error;
668 }
669
670 /* Setup extra string if suffix or/and a count is needed. */
671 if (size > 0 && suffix) {
672 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
673 } else if (size > 0) {
674 ret = asprintf(&extra, "_%" PRIu64, count);
675 } else if (suffix) {
676 ret = asprintf(&extra, "%s", suffix);
677 }
678 if (ret < 0) {
679 PERROR("Allocating extra string to name");
680 goto error;
681 }
682
683 /*
684 * If we split the trace in multiple files, we have to add the count at
685 * the end of the tracefile name.
686 */
687 if (extra) {
688 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
689 if (ret < 0) {
690 PERROR("Allocating path name with extra string");
691 goto error_free_suffix;
692 }
693 strncpy(path, path_name_suffix, PATH_MAX - 1);
694 path[PATH_MAX - 1] = '\0';
695 } else {
696 strncpy(path, full_path, PATH_MAX - 1);
697 }
698 path[PATH_MAX - 1] = '\0';
699 ret = 0;
700
701 free(path_name_suffix);
702 error_free_suffix:
703 free(extra);
704 error:
705 return ret;
706 }
707
708 /*
709 * Create the stream file on disk.
710 *
711 * Return 0 on success or else a negative value.
712 */
713 LTTNG_HIDDEN
714 int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
715 uint64_t count, int uid, int gid, char *suffix)
716 {
717 int ret, flags, mode;
718 char path[PATH_MAX];
719
720 ret = utils_stream_file_name(path, path_name, file_name,
721 size, count, suffix);
722 if (ret < 0) {
723 goto error;
724 }
725
726 flags = O_WRONLY | O_CREAT | O_TRUNC;
727 /* Open with 660 mode */
728 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
729
730 if (uid < 0 || gid < 0) {
731 ret = open(path, flags, mode);
732 } else {
733 ret = run_as_open(path, flags, mode, uid, gid);
734 }
735 if (ret < 0) {
736 PERROR("open stream path %s", path);
737 }
738 error:
739 return ret;
740 }
741
742 /*
743 * Unlink the stream tracefile from disk.
744 *
745 * Return 0 on success or else a negative value.
746 */
747 LTTNG_HIDDEN
748 int utils_unlink_stream_file(const char *path_name, char *file_name, uint64_t size,
749 uint64_t count, int uid, int gid, char *suffix)
750 {
751 int ret;
752 char path[PATH_MAX];
753
754 ret = utils_stream_file_name(path, path_name, file_name,
755 size, count, suffix);
756 if (ret < 0) {
757 goto error;
758 }
759 if (uid < 0 || gid < 0) {
760 ret = unlink(path);
761 } else {
762 ret = run_as_unlink(path, uid, gid);
763 }
764 if (ret < 0) {
765 goto error;
766 }
767 error:
768 DBG("utils_unlink_stream_file %s returns %d", path, ret);
769 return ret;
770 }
771
772 /*
773 * Change the output tracefile according to the given size and count The
774 * new_count pointer is set during this operation.
775 *
776 * From the consumer, the stream lock MUST be held before calling this function
777 * because we are modifying the stream status.
778 *
779 * Return 0 on success or else a negative value.
780 */
781 LTTNG_HIDDEN
782 int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
783 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
784 int *stream_fd)
785 {
786 int ret;
787
788 assert(new_count);
789 assert(stream_fd);
790
791 ret = close(out_fd);
792 if (ret < 0) {
793 PERROR("Closing tracefile");
794 goto error;
795 }
796
797 if (count > 0) {
798 /*
799 * In tracefile rotation, for the relay daemon we need
800 * to unlink the old file if present, because it may
801 * still be open in reading by the live thread, and we
802 * need to ensure that we do not overwrite the content
803 * between get_index and get_packet. Since we have no
804 * way to verify integrity of the data content compared
805 * to the associated index, we need to ensure the reader
806 * has exclusive access to the file content, and that
807 * the open of the data file is performed in get_index.
808 * Unlinking the old file rather than overwriting it
809 * achieves this.
810 */
811 *new_count = (*new_count + 1) % count;
812 ret = utils_unlink_stream_file(path_name, file_name,
813 size, *new_count, uid, gid, 0);
814 if (ret < 0 && errno != ENOENT) {
815 goto error;
816 }
817 } else {
818 (*new_count)++;
819 }
820
821 ret = utils_create_stream_file(path_name, file_name, size, *new_count,
822 uid, gid, 0);
823 if (ret < 0) {
824 goto error;
825 }
826 *stream_fd = ret;
827
828 /* Success. */
829 ret = 0;
830
831 error:
832 return ret;
833 }
834
835
836 /**
837 * Parse a string that represents a size in human readable format. It
838 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
839 *
840 * The suffix multiply the integer by:
841 * 'k': 1024
842 * 'M': 1024^2
843 * 'G': 1024^3
844 *
845 * @param str The string to parse.
846 * @param size Pointer to a uint64_t that will be filled with the
847 * resulting size.
848 *
849 * @return 0 on success, -1 on failure.
850 */
851 LTTNG_HIDDEN
852 int utils_parse_size_suffix(const char * const str, uint64_t * const size)
853 {
854 int ret;
855 uint64_t base_size;
856 long shift = 0;
857 const char *str_end;
858 char *num_end;
859
860 if (!str) {
861 DBG("utils_parse_size_suffix: received a NULL string.");
862 ret = -1;
863 goto end;
864 }
865
866 /* strtoull will accept a negative number, but we don't want to. */
867 if (strchr(str, '-') != NULL) {
868 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
869 ret = -1;
870 goto end;
871 }
872
873 /* str_end will point to the \0 */
874 str_end = str + strlen(str);
875 errno = 0;
876 base_size = strtoull(str, &num_end, 0);
877 if (errno != 0) {
878 PERROR("utils_parse_size_suffix strtoull");
879 ret = -1;
880 goto end;
881 }
882
883 if (num_end == str) {
884 /* strtoull parsed nothing, not good. */
885 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
886 ret = -1;
887 goto end;
888 }
889
890 /* Check if a prefix is present. */
891 switch (*num_end) {
892 case 'G':
893 shift = GIBI_LOG2;
894 num_end++;
895 break;
896 case 'M': /* */
897 shift = MEBI_LOG2;
898 num_end++;
899 break;
900 case 'K':
901 case 'k':
902 shift = KIBI_LOG2;
903 num_end++;
904 break;
905 case '\0':
906 break;
907 default:
908 DBG("utils_parse_size_suffix: invalid suffix.");
909 ret = -1;
910 goto end;
911 }
912
913 /* Check for garbage after the valid input. */
914 if (num_end != str_end) {
915 DBG("utils_parse_size_suffix: Garbage after size string.");
916 ret = -1;
917 goto end;
918 }
919
920 *size = base_size << shift;
921
922 /* Check for overflow */
923 if ((*size >> shift) != base_size) {
924 DBG("utils_parse_size_suffix: oops, overflow detected.");
925 ret = -1;
926 goto end;
927 }
928
929 ret = 0;
930 end:
931 return ret;
932 }
933
934 /*
935 * fls: returns the position of the most significant bit.
936 * Returns 0 if no bit is set, else returns the position of the most
937 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
938 */
939 #if defined(__i386) || defined(__x86_64)
940 static inline unsigned int fls_u32(uint32_t x)
941 {
942 int r;
943
944 asm("bsrl %1,%0\n\t"
945 "jnz 1f\n\t"
946 "movl $-1,%0\n\t"
947 "1:\n\t"
948 : "=r" (r) : "rm" (x));
949 return r + 1;
950 }
951 #define HAS_FLS_U32
952 #endif
953
954 #ifndef HAS_FLS_U32
955 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
956 {
957 unsigned int r = 32;
958
959 if (!x) {
960 return 0;
961 }
962 if (!(x & 0xFFFF0000U)) {
963 x <<= 16;
964 r -= 16;
965 }
966 if (!(x & 0xFF000000U)) {
967 x <<= 8;
968 r -= 8;
969 }
970 if (!(x & 0xF0000000U)) {
971 x <<= 4;
972 r -= 4;
973 }
974 if (!(x & 0xC0000000U)) {
975 x <<= 2;
976 r -= 2;
977 }
978 if (!(x & 0x80000000U)) {
979 x <<= 1;
980 r -= 1;
981 }
982 return r;
983 }
984 #endif
985
986 /*
987 * Return the minimum order for which x <= (1UL << order).
988 * Return -1 if x is 0.
989 */
990 LTTNG_HIDDEN
991 int utils_get_count_order_u32(uint32_t x)
992 {
993 if (!x) {
994 return -1;
995 }
996
997 return fls_u32(x - 1);
998 }
999
1000 /**
1001 * Obtain the value of LTTNG_HOME environment variable, if exists.
1002 * Otherwise returns the value of HOME.
1003 */
1004 LTTNG_HIDDEN
1005 char *utils_get_home_dir(void)
1006 {
1007 char *val = NULL;
1008 struct passwd *pwd;
1009
1010 val = getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
1011 if (val != NULL) {
1012 goto end;
1013 }
1014 val = getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
1015 if (val != NULL) {
1016 goto end;
1017 }
1018
1019 /* Fallback on the password file entry. */
1020 pwd = getpwuid(getuid());
1021 if (!pwd) {
1022 goto end;
1023 }
1024 val = pwd->pw_dir;
1025
1026 DBG3("Home directory is '%s'", val);
1027
1028 end:
1029 return val;
1030 }
1031
1032 /**
1033 * Get user's home directory. Dynamically allocated, must be freed
1034 * by the caller.
1035 */
1036 LTTNG_HIDDEN
1037 char *utils_get_user_home_dir(uid_t uid)
1038 {
1039 struct passwd pwd;
1040 struct passwd *result;
1041 char *home_dir = NULL;
1042 char *buf = NULL;
1043 long buflen;
1044 int ret;
1045
1046 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1047 if (buflen == -1) {
1048 goto end;
1049 }
1050 retry:
1051 buf = zmalloc(buflen);
1052 if (!buf) {
1053 goto end;
1054 }
1055
1056 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1057 if (ret || !result) {
1058 if (ret == ERANGE) {
1059 free(buf);
1060 buflen *= 2;
1061 goto retry;
1062 }
1063 goto end;
1064 }
1065
1066 home_dir = strdup(pwd.pw_dir);
1067 end:
1068 free(buf);
1069 return home_dir;
1070 }
1071
1072 /*
1073 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
1074 * Otherwise returns NULL.
1075 */
1076 LTTNG_HIDDEN
1077 char *utils_get_kmod_probes_list(void)
1078 {
1079 return getenv(DEFAULT_LTTNG_KMOD_PROBES);
1080 }
1081
1082 /*
1083 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
1084 * exists. Otherwise returns NULL.
1085 */
1086 LTTNG_HIDDEN
1087 char *utils_get_extra_kmod_probes_list(void)
1088 {
1089 return getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES);
1090 }
1091
1092 /*
1093 * With the given format, fill dst with the time of len maximum siz.
1094 *
1095 * Return amount of bytes set in the buffer or else 0 on error.
1096 */
1097 LTTNG_HIDDEN
1098 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1099 {
1100 size_t ret;
1101 time_t rawtime;
1102 struct tm *timeinfo;
1103
1104 assert(format);
1105 assert(dst);
1106
1107 /* Get date and time for session path */
1108 time(&rawtime);
1109 timeinfo = localtime(&rawtime);
1110 ret = strftime(dst, len, format, timeinfo);
1111 if (ret == 0) {
1112 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
1113 dst, len);
1114 }
1115
1116 return ret;
1117 }
1118
1119 /*
1120 * Return the group ID matching name, else 0 if it cannot be found.
1121 */
1122 LTTNG_HIDDEN
1123 gid_t utils_get_group_id(const char *name)
1124 {
1125 struct group *grp;
1126
1127 grp = getgrnam(name);
1128 if (!grp) {
1129 static volatile int warn_once;
1130
1131 if (!warn_once) {
1132 WARN("No tracing group detected");
1133 warn_once = 1;
1134 }
1135 return 0;
1136 }
1137 return grp->gr_gid;
1138 }
1139
1140 /*
1141 * Return a newly allocated option string. This string is to be used as the
1142 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1143 * of elements in the long_options array. Returns NULL if the string's
1144 * allocation fails.
1145 */
1146 LTTNG_HIDDEN
1147 char *utils_generate_optstring(const struct option *long_options,
1148 size_t opt_count)
1149 {
1150 int i;
1151 size_t string_len = opt_count, str_pos = 0;
1152 char *optstring;
1153
1154 /*
1155 * Compute the necessary string length. One letter per option, two when an
1156 * argument is necessary, and a trailing NULL.
1157 */
1158 for (i = 0; i < opt_count; i++) {
1159 string_len += long_options[i].has_arg ? 1 : 0;
1160 }
1161
1162 optstring = zmalloc(string_len);
1163 if (!optstring) {
1164 goto end;
1165 }
1166
1167 for (i = 0; i < opt_count; i++) {
1168 if (!long_options[i].name) {
1169 /* Got to the trailing NULL element */
1170 break;
1171 }
1172
1173 optstring[str_pos++] = (char)long_options[i].val;
1174 if (long_options[i].has_arg) {
1175 optstring[str_pos++] = ':';
1176 }
1177 }
1178
1179 end:
1180 return optstring;
1181 }
This page took 0.051075 seconds and 3 git commands to generate.