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