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