directory-handle: make lttng_directory_handle_stat public
[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 #include <unistd.h>
34
35 #include <common/common.h>
36 #include <common/readwrite.h>
37 #include <common/runas.h>
38 #include <common/compat/getenv.h>
39 #include <common/compat/string.h>
40 #include <common/compat/dirent.h>
41 #include <common/compat/directory-handle.h>
42 #include <common/dynamic-buffer.h>
43 #include <common/string-utils/format.h>
44 #include <lttng/constant.h>
45
46 #include "utils.h"
47 #include "defaults.h"
48 #include "time.h"
49
50 #define PROC_MEMINFO_PATH "/proc/meminfo"
51 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
52 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
53
54 /* The length of the longest field of `/proc/meminfo`. */
55 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
56
57 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
58 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
59 #else
60 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
61 #endif
62
63 /*
64 * Return a partial realpath(3) of the path even if the full path does not
65 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
66 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
67 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
68 * point directory does not exist.
69 * In case resolved_path is NULL, the string returned was allocated in the
70 * function and thus need to be freed by the caller. The size argument allows
71 * to specify the size of the resolved_path argument if given, or the size to
72 * allocate.
73 */
74 LTTNG_HIDDEN
75 char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
76 {
77 char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
78 const char *next, *prev, *end;
79
80 /* Safety net */
81 if (path == NULL) {
82 goto error;
83 }
84
85 /*
86 * Identify the end of the path, we don't want to treat the
87 * last char if it is a '/', we will just keep it on the side
88 * to be added at the end, and return a value coherent with
89 * the path given as argument
90 */
91 end = path + strlen(path);
92 if (*(end-1) == '/') {
93 end--;
94 }
95
96 /* Initiate the values of the pointers before looping */
97 next = path;
98 prev = next;
99 /* Only to ensure try_path is not NULL to enter the while */
100 try_path = (char *)next;
101
102 /* Resolve the canonical path of the first part of the path */
103 while (try_path != NULL && next != end) {
104 char *try_path_buf = NULL;
105
106 /*
107 * If there is not any '/' left, we want to try with
108 * the full path
109 */
110 next = strpbrk(next + 1, "/");
111 if (next == NULL) {
112 next = end;
113 }
114
115 /* Cut the part we will be trying to resolve */
116 cut_path = lttng_strndup(path, next - path);
117 if (cut_path == NULL) {
118 PERROR("lttng_strndup");
119 goto error;
120 }
121
122 try_path_buf = zmalloc(LTTNG_PATH_MAX);
123 if (!try_path_buf) {
124 PERROR("zmalloc");
125 goto error;
126 }
127
128 /* Try to resolve this part */
129 try_path = realpath((char *) cut_path, try_path_buf);
130 if (try_path == NULL) {
131 free(try_path_buf);
132 /*
133 * There was an error, we just want to be assured it
134 * is linked to an unexistent directory, if it's another
135 * reason, we spawn an error
136 */
137 switch (errno) {
138 case ENOENT:
139 /* Ignore the error */
140 break;
141 default:
142 PERROR("realpath (partial_realpath)");
143 goto error;
144 break;
145 }
146 } else {
147 /* Save the place we are before trying the next step */
148 try_path_buf = NULL;
149 free(try_path_prev);
150 try_path_prev = try_path;
151 prev = next;
152 }
153
154 /* Free the allocated memory */
155 free(cut_path);
156 cut_path = NULL;
157 }
158
159 /* Allocate memory for the resolved path if necessary */
160 if (resolved_path == NULL) {
161 resolved_path = zmalloc(size);
162 if (resolved_path == NULL) {
163 PERROR("zmalloc resolved path");
164 goto error;
165 }
166 }
167
168 /*
169 * If we were able to solve at least partially the path, we can concatenate
170 * what worked and what didn't work
171 */
172 if (try_path_prev != NULL) {
173 /* If we risk to concatenate two '/', we remove one of them */
174 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
175 try_path_prev[strlen(try_path_prev) - 1] = '\0';
176 }
177
178 /*
179 * Duplicate the memory used by prev in case resolved_path and
180 * path are pointers for the same memory space
181 */
182 cut_path = strdup(prev);
183 if (cut_path == NULL) {
184 PERROR("strdup");
185 goto error;
186 }
187
188 /* Concatenate the strings */
189 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
190
191 /* Free the allocated memory */
192 free(cut_path);
193 free(try_path_prev);
194 cut_path = NULL;
195 try_path_prev = NULL;
196 /*
197 * Else, we just copy the path in our resolved_path to
198 * return it as is
199 */
200 } else {
201 strncpy(resolved_path, path, size);
202 }
203
204 /* Then we return the 'partially' resolved path */
205 return resolved_path;
206
207 error:
208 free(resolved_path);
209 free(cut_path);
210 free(try_path);
211 if (try_path_prev != try_path) {
212 free(try_path_prev);
213 }
214 return NULL;
215 }
216
217 static
218 int expand_double_slashes_dot_and_dotdot(char *path)
219 {
220 size_t expanded_path_len, path_len;
221 const char *curr_char, *path_last_char, *next_slash, *prev_slash;
222
223 path_len = strlen(path);
224 path_last_char = &path[path_len];
225
226 if (path_len == 0) {
227 goto error;
228 }
229
230 expanded_path_len = 0;
231
232 /* We iterate over the provided path to expand the "//", "../" and "./" */
233 for (curr_char = path; curr_char <= path_last_char; curr_char = next_slash + 1) {
234 /* Find the next forward slash. */
235 size_t curr_token_len;
236
237 if (curr_char == path_last_char) {
238 expanded_path_len++;
239 break;
240 }
241
242 next_slash = memchr(curr_char, '/', path_last_char - curr_char);
243 if (next_slash == NULL) {
244 /* Reached the end of the provided path. */
245 next_slash = path_last_char;
246 }
247
248 /* Compute how long is the previous token. */
249 curr_token_len = next_slash - curr_char;
250 switch(curr_token_len) {
251 case 0:
252 /*
253 * The pointer has not move meaning that curr_char is
254 * pointing to a slash. It that case there is no token
255 * to copy, so continue the iteration to find the next
256 * token
257 */
258 continue;
259 case 1:
260 /*
261 * The pointer moved 1 character. Check if that
262 * character is a dot ('.'), if it is: omit it, else
263 * copy the token to the normalized path.
264 */
265 if (curr_char[0] == '.') {
266 continue;
267 }
268 break;
269 case 2:
270 /*
271 * The pointer moved 2 characters. Check if these
272 * characters are double dots ('..'). If that is the
273 * case, we need to remove the last token of the
274 * normalized path.
275 */
276 if (curr_char[0] == '.' && curr_char[1] == '.') {
277 /*
278 * Find the previous path component by
279 * using the memrchr function to find the
280 * previous forward slash and substract that
281 * len to the resulting path.
282 */
283 prev_slash = lttng_memrchr(path, '/', expanded_path_len);
284 /*
285 * If prev_slash is NULL, we reached the
286 * beginning of the path. We can't go back any
287 * further.
288 */
289 if (prev_slash != NULL) {
290 expanded_path_len = prev_slash - path;
291 }
292 continue;
293 }
294 break;
295 default:
296 break;
297 }
298
299 /*
300 * Copy the current token which is neither a '.' nor a '..'.
301 */
302 path[expanded_path_len++] = '/';
303 memcpy(&path[expanded_path_len], curr_char, curr_token_len);
304 expanded_path_len += curr_token_len;
305 }
306
307 if (expanded_path_len == 0) {
308 path[expanded_path_len++] = '/';
309 }
310
311 path[expanded_path_len] = '\0';
312 return 0;
313 error:
314 return -1;
315 }
316
317 /*
318 * Make a full resolution of the given path even if it doesn't exist.
319 * This function uses the utils_partial_realpath function to resolve
320 * symlinks and relatives paths at the start of the string, and
321 * implements functionnalities to resolve the './' and '../' strings
322 * in the middle of a path. This function is only necessary because
323 * realpath(3) does not accept to resolve unexistent paths.
324 * The returned string was allocated in the function, it is thus of
325 * the responsibility of the caller to free this memory.
326 */
327 static
328 char *_utils_expand_path(const char *path, bool keep_symlink)
329 {
330 int ret;
331 char *absolute_path = NULL;
332 char *last_token;
333 bool is_dot, is_dotdot;
334
335 /* Safety net */
336 if (path == NULL) {
337 goto error;
338 }
339
340 /* Allocate memory for the absolute_path */
341 absolute_path = zmalloc(LTTNG_PATH_MAX);
342 if (absolute_path == NULL) {
343 PERROR("zmalloc expand path");
344 goto error;
345 }
346
347 if (path[0] == '/') {
348 ret = lttng_strncpy(absolute_path, path, LTTNG_PATH_MAX);
349 if (ret) {
350 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX);
351 goto error;
352 }
353 } else {
354 /*
355 * This is a relative path. We need to get the present working
356 * directory and start the path walk from there.
357 */
358 char current_working_dir[LTTNG_PATH_MAX];
359 char *cwd_ret;
360
361 cwd_ret = getcwd(current_working_dir, sizeof(current_working_dir));
362 if (!cwd_ret) {
363 goto error;
364 }
365 /*
366 * Get the number of character in the CWD and allocate an array
367 * to can hold it and the path provided by the caller.
368 */
369 ret = snprintf(absolute_path, LTTNG_PATH_MAX, "%s/%s",
370 current_working_dir, path);
371 if (ret >= LTTNG_PATH_MAX) {
372 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
373 current_working_dir, path, LTTNG_PATH_MAX);
374 goto error;
375 }
376 }
377
378 if (keep_symlink) {
379 /* Resolve partially our path */
380 absolute_path = utils_partial_realpath(absolute_path,
381 absolute_path, LTTNG_PATH_MAX);
382 if (!absolute_path) {
383 goto error;
384 }
385 }
386
387 ret = expand_double_slashes_dot_and_dotdot(absolute_path);
388 if (ret) {
389 goto error;
390 }
391
392 /* Identify the last token */
393 last_token = strrchr(absolute_path, '/');
394
395 /* Verify that this token is not a relative path */
396 is_dotdot = (strcmp(last_token, "/..") == 0);
397 is_dot = (strcmp(last_token, "/.") == 0);
398
399 /* If it is, take action */
400 if (is_dot || is_dotdot) {
401 /* For both, remove this token */
402 *last_token = '\0';
403
404 /* If it was a reference to parent directory, go back one more time */
405 if (is_dotdot) {
406 last_token = strrchr(absolute_path, '/');
407
408 /* If there was only one level left, we keep the first '/' */
409 if (last_token == absolute_path) {
410 last_token++;
411 }
412
413 *last_token = '\0';
414 }
415 }
416
417 return absolute_path;
418
419 error:
420 free(absolute_path);
421 return NULL;
422 }
423 LTTNG_HIDDEN
424 char *utils_expand_path(const char *path)
425 {
426 return _utils_expand_path(path, true);
427 }
428
429 LTTNG_HIDDEN
430 char *utils_expand_path_keep_symlink(const char *path)
431 {
432 return _utils_expand_path(path, false);
433 }
434 /*
435 * Create a pipe in dst.
436 */
437 LTTNG_HIDDEN
438 int utils_create_pipe(int *dst)
439 {
440 int ret;
441
442 if (dst == NULL) {
443 return -1;
444 }
445
446 ret = pipe(dst);
447 if (ret < 0) {
448 PERROR("create pipe");
449 }
450
451 return ret;
452 }
453
454 /*
455 * Create pipe and set CLOEXEC flag to both fd.
456 *
457 * Make sure the pipe opened by this function are closed at some point. Use
458 * utils_close_pipe().
459 */
460 LTTNG_HIDDEN
461 int utils_create_pipe_cloexec(int *dst)
462 {
463 int ret, i;
464
465 if (dst == NULL) {
466 return -1;
467 }
468
469 ret = utils_create_pipe(dst);
470 if (ret < 0) {
471 goto error;
472 }
473
474 for (i = 0; i < 2; i++) {
475 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
476 if (ret < 0) {
477 PERROR("fcntl pipe cloexec");
478 goto error;
479 }
480 }
481
482 error:
483 return ret;
484 }
485
486 /*
487 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
488 *
489 * Make sure the pipe opened by this function are closed at some point. Use
490 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
491 * support OSes other than Linux 2.6.23+.
492 */
493 LTTNG_HIDDEN
494 int utils_create_pipe_cloexec_nonblock(int *dst)
495 {
496 int ret, i;
497
498 if (dst == NULL) {
499 return -1;
500 }
501
502 ret = utils_create_pipe(dst);
503 if (ret < 0) {
504 goto error;
505 }
506
507 for (i = 0; i < 2; i++) {
508 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
509 if (ret < 0) {
510 PERROR("fcntl pipe cloexec");
511 goto error;
512 }
513 /*
514 * Note: we override any flag that could have been
515 * previously set on the fd.
516 */
517 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
518 if (ret < 0) {
519 PERROR("fcntl pipe nonblock");
520 goto error;
521 }
522 }
523
524 error:
525 return ret;
526 }
527
528 /*
529 * Close both read and write side of the pipe.
530 */
531 LTTNG_HIDDEN
532 void utils_close_pipe(int *src)
533 {
534 int i, ret;
535
536 if (src == NULL) {
537 return;
538 }
539
540 for (i = 0; i < 2; i++) {
541 /* Safety check */
542 if (src[i] < 0) {
543 continue;
544 }
545
546 ret = close(src[i]);
547 if (ret) {
548 PERROR("close pipe");
549 }
550 }
551 }
552
553 /*
554 * Create a new string using two strings range.
555 */
556 LTTNG_HIDDEN
557 char *utils_strdupdelim(const char *begin, const char *end)
558 {
559 char *str;
560
561 str = zmalloc(end - begin + 1);
562 if (str == NULL) {
563 PERROR("zmalloc strdupdelim");
564 goto error;
565 }
566
567 memcpy(str, begin, end - begin);
568 str[end - begin] = '\0';
569
570 error:
571 return str;
572 }
573
574 /*
575 * Set CLOEXEC flag to the give file descriptor.
576 */
577 LTTNG_HIDDEN
578 int utils_set_fd_cloexec(int fd)
579 {
580 int ret;
581
582 if (fd < 0) {
583 ret = -EINVAL;
584 goto end;
585 }
586
587 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
588 if (ret < 0) {
589 PERROR("fcntl cloexec");
590 ret = -errno;
591 }
592
593 end:
594 return ret;
595 }
596
597 /*
598 * Create pid file to the given path and filename.
599 */
600 LTTNG_HIDDEN
601 int utils_create_pid_file(pid_t pid, const char *filepath)
602 {
603 int ret;
604 FILE *fp;
605
606 assert(filepath);
607
608 fp = fopen(filepath, "w");
609 if (fp == NULL) {
610 PERROR("open pid file %s", filepath);
611 ret = -1;
612 goto error;
613 }
614
615 ret = fprintf(fp, "%d\n", (int) pid);
616 if (ret < 0) {
617 PERROR("fprintf pid file");
618 goto error;
619 }
620
621 if (fclose(fp)) {
622 PERROR("fclose");
623 }
624 DBG("Pid %d written in file %s", (int) pid, filepath);
625 ret = 0;
626 error:
627 return ret;
628 }
629
630 /*
631 * Create lock file to the given path and filename.
632 * Returns the associated file descriptor, -1 on error.
633 */
634 LTTNG_HIDDEN
635 int utils_create_lock_file(const char *filepath)
636 {
637 int ret;
638 int fd;
639 struct flock lock;
640
641 assert(filepath);
642
643 memset(&lock, 0, sizeof(lock));
644 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
645 S_IRGRP | S_IWGRP);
646 if (fd < 0) {
647 PERROR("open lock file %s", filepath);
648 fd = -1;
649 goto error;
650 }
651
652 /*
653 * Attempt to lock the file. If this fails, there is
654 * already a process using the same lock file running
655 * and we should exit.
656 */
657 lock.l_whence = SEEK_SET;
658 lock.l_type = F_WRLCK;
659
660 ret = fcntl(fd, F_SETLK, &lock);
661 if (ret == -1) {
662 PERROR("fcntl lock file");
663 ERR("Could not get lock file %s, another instance is running.",
664 filepath);
665 if (close(fd)) {
666 PERROR("close lock file");
667 }
668 fd = ret;
669 goto error;
670 }
671
672 error:
673 return fd;
674 }
675
676 /*
677 * Create directory using the given path and mode.
678 *
679 * On success, return 0 else a negative error code.
680 */
681 LTTNG_HIDDEN
682 int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
683 {
684 int ret;
685 struct lttng_directory_handle *handle;
686 const struct lttng_credentials creds = {
687 .uid = (uid_t) uid,
688 .gid = (gid_t) gid,
689 };
690
691 handle = lttng_directory_handle_create(NULL);
692 if (!handle) {
693 ret = -1;
694 goto end;
695 }
696 ret = lttng_directory_handle_create_subdirectory_as_user(
697 handle, path, mode,
698 (uid >= 0 || gid >= 0) ? &creds : NULL);
699 end:
700 lttng_directory_handle_put(handle);
701 return ret;
702 }
703
704 /*
705 * Recursively create directory using the given path and mode, under the
706 * provided uid and gid.
707 *
708 * On success, return 0 else a negative error code.
709 */
710 LTTNG_HIDDEN
711 int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
712 {
713 int ret;
714 struct lttng_directory_handle *handle;
715 const struct lttng_credentials creds = {
716 .uid = (uid_t) uid,
717 .gid = (gid_t) gid,
718 };
719
720 handle = lttng_directory_handle_create(NULL);
721 if (!handle) {
722 ret = -1;
723 goto end;
724 }
725 ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
726 handle, path, mode,
727 (uid >= 0 || gid >= 0) ? &creds : NULL);
728 end:
729 lttng_directory_handle_put(handle);
730 return ret;
731 }
732
733 /*
734 * out_stream_path is the output parameter.
735 *
736 * Return 0 on success or else a negative value.
737 */
738 LTTNG_HIDDEN
739 int utils_stream_file_path(const char *path_name, const char *file_name,
740 uint64_t size, uint64_t count, const char *suffix,
741 char *out_stream_path, size_t stream_path_len)
742 {
743 int ret;
744 char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
745 const char *path_separator;
746
747 if (path_name && (path_name[0] == '\0' ||
748 path_name[strlen(path_name) - 1] == '/')) {
749 path_separator = "";
750 } else {
751 path_separator = "/";
752 }
753
754 path_name = path_name ? : "";
755 suffix = suffix ? : "";
756 if (size > 0) {
757 ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
758 count);
759 assert(ret > 0 && ret < sizeof(count_str));
760 }
761
762 ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
763 path_name, path_separator, file_name, count_str,
764 suffix);
765 if (ret < 0 || ret >= stream_path_len) {
766 ERR("Truncation occurred while formatting stream path");
767 ret = -1;
768 } else {
769 ret = 0;
770 }
771 return ret;
772 }
773
774 /**
775 * Parse a string that represents a size in human readable format. It
776 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
777 *
778 * The suffix multiply the integer by:
779 * 'k': 1024
780 * 'M': 1024^2
781 * 'G': 1024^3
782 *
783 * @param str The string to parse.
784 * @param size Pointer to a uint64_t that will be filled with the
785 * resulting size.
786 *
787 * @return 0 on success, -1 on failure.
788 */
789 LTTNG_HIDDEN
790 int utils_parse_size_suffix(const char * const str, uint64_t * const size)
791 {
792 int ret;
793 uint64_t base_size;
794 long shift = 0;
795 const char *str_end;
796 char *num_end;
797
798 if (!str) {
799 DBG("utils_parse_size_suffix: received a NULL string.");
800 ret = -1;
801 goto end;
802 }
803
804 /* strtoull will accept a negative number, but we don't want to. */
805 if (strchr(str, '-') != NULL) {
806 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
807 ret = -1;
808 goto end;
809 }
810
811 /* str_end will point to the \0 */
812 str_end = str + strlen(str);
813 errno = 0;
814 base_size = strtoull(str, &num_end, 0);
815 if (errno != 0) {
816 PERROR("utils_parse_size_suffix strtoull");
817 ret = -1;
818 goto end;
819 }
820
821 if (num_end == str) {
822 /* strtoull parsed nothing, not good. */
823 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
824 ret = -1;
825 goto end;
826 }
827
828 /* Check if a prefix is present. */
829 switch (*num_end) {
830 case 'G':
831 shift = GIBI_LOG2;
832 num_end++;
833 break;
834 case 'M': /* */
835 shift = MEBI_LOG2;
836 num_end++;
837 break;
838 case 'K':
839 case 'k':
840 shift = KIBI_LOG2;
841 num_end++;
842 break;
843 case '\0':
844 break;
845 default:
846 DBG("utils_parse_size_suffix: invalid suffix.");
847 ret = -1;
848 goto end;
849 }
850
851 /* Check for garbage after the valid input. */
852 if (num_end != str_end) {
853 DBG("utils_parse_size_suffix: Garbage after size string.");
854 ret = -1;
855 goto end;
856 }
857
858 *size = base_size << shift;
859
860 /* Check for overflow */
861 if ((*size >> shift) != base_size) {
862 DBG("utils_parse_size_suffix: oops, overflow detected.");
863 ret = -1;
864 goto end;
865 }
866
867 ret = 0;
868 end:
869 return ret;
870 }
871
872 /**
873 * Parse a string that represents a time in human readable format. It
874 * supports decimal integers suffixed by:
875 * "us" for microsecond,
876 * "ms" for millisecond,
877 * "s" for second,
878 * "m" for minute,
879 * "h" for hour
880 *
881 * The suffix multiply the integer by:
882 * "us" : 1
883 * "ms" : 1000
884 * "s" : 1000000
885 * "m" : 60000000
886 * "h" : 3600000000
887 *
888 * Note that unit-less numbers are assumed to be microseconds.
889 *
890 * @param str The string to parse, assumed to be NULL-terminated.
891 * @param time_us Pointer to a uint64_t that will be filled with the
892 * resulting time in microseconds.
893 *
894 * @return 0 on success, -1 on failure.
895 */
896 LTTNG_HIDDEN
897 int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
898 {
899 int ret;
900 uint64_t base_time;
901 uint64_t multiplier = 1;
902 const char *str_end;
903 char *num_end;
904
905 if (!str) {
906 DBG("utils_parse_time_suffix: received a NULL string.");
907 ret = -1;
908 goto end;
909 }
910
911 /* strtoull will accept a negative number, but we don't want to. */
912 if (strchr(str, '-') != NULL) {
913 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
914 ret = -1;
915 goto end;
916 }
917
918 /* str_end will point to the \0 */
919 str_end = str + strlen(str);
920 errno = 0;
921 base_time = strtoull(str, &num_end, 10);
922 if (errno != 0) {
923 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
924 ret = -1;
925 goto end;
926 }
927
928 if (num_end == str) {
929 /* strtoull parsed nothing, not good. */
930 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
931 ret = -1;
932 goto end;
933 }
934
935 /* Check if a prefix is present. */
936 switch (*num_end) {
937 case 'u':
938 /*
939 * Microsecond (us)
940 *
941 * Skip the "us" if the string matches the "us" suffix,
942 * otherwise let the check for the end of the string handle
943 * the error reporting.
944 */
945 if (*(num_end + 1) == 's') {
946 num_end += 2;
947 }
948 break;
949 case 'm':
950 if (*(num_end + 1) == 's') {
951 /* Millisecond (ms) */
952 multiplier = USEC_PER_MSEC;
953 /* Skip the 's' */
954 num_end++;
955 } else {
956 /* Minute (m) */
957 multiplier = USEC_PER_MINUTE;
958 }
959 num_end++;
960 break;
961 case 's':
962 /* Second */
963 multiplier = USEC_PER_SEC;
964 num_end++;
965 break;
966 case 'h':
967 /* Hour */
968 multiplier = USEC_PER_HOURS;
969 num_end++;
970 break;
971 case '\0':
972 break;
973 default:
974 DBG("utils_parse_time_suffix: invalid suffix.");
975 ret = -1;
976 goto end;
977 }
978
979 /* Check for garbage after the valid input. */
980 if (num_end != str_end) {
981 DBG("utils_parse_time_suffix: Garbage after time string.");
982 ret = -1;
983 goto end;
984 }
985
986 *time_us = base_time * multiplier;
987
988 /* Check for overflow */
989 if ((*time_us / multiplier) != base_time) {
990 DBG("utils_parse_time_suffix: oops, overflow detected.");
991 ret = -1;
992 goto end;
993 }
994
995 ret = 0;
996 end:
997 return ret;
998 }
999
1000 /*
1001 * fls: returns the position of the most significant bit.
1002 * Returns 0 if no bit is set, else returns the position of the most
1003 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1004 */
1005 #if defined(__i386) || defined(__x86_64)
1006 static inline unsigned int fls_u32(uint32_t x)
1007 {
1008 int r;
1009
1010 asm("bsrl %1,%0\n\t"
1011 "jnz 1f\n\t"
1012 "movl $-1,%0\n\t"
1013 "1:\n\t"
1014 : "=r" (r) : "rm" (x));
1015 return r + 1;
1016 }
1017 #define HAS_FLS_U32
1018 #endif
1019
1020 #if defined(__x86_64) && defined(__LP64__)
1021 static inline
1022 unsigned int fls_u64(uint64_t x)
1023 {
1024 long r;
1025
1026 asm("bsrq %1,%0\n\t"
1027 "jnz 1f\n\t"
1028 "movq $-1,%0\n\t"
1029 "1:\n\t"
1030 : "=r" (r) : "rm" (x));
1031 return r + 1;
1032 }
1033 #define HAS_FLS_U64
1034 #endif
1035
1036 #ifndef HAS_FLS_U64
1037 static __attribute__((unused))
1038 unsigned int fls_u64(uint64_t x)
1039 {
1040 unsigned int r = 64;
1041
1042 if (!x)
1043 return 0;
1044
1045 if (!(x & 0xFFFFFFFF00000000ULL)) {
1046 x <<= 32;
1047 r -= 32;
1048 }
1049 if (!(x & 0xFFFF000000000000ULL)) {
1050 x <<= 16;
1051 r -= 16;
1052 }
1053 if (!(x & 0xFF00000000000000ULL)) {
1054 x <<= 8;
1055 r -= 8;
1056 }
1057 if (!(x & 0xF000000000000000ULL)) {
1058 x <<= 4;
1059 r -= 4;
1060 }
1061 if (!(x & 0xC000000000000000ULL)) {
1062 x <<= 2;
1063 r -= 2;
1064 }
1065 if (!(x & 0x8000000000000000ULL)) {
1066 x <<= 1;
1067 r -= 1;
1068 }
1069 return r;
1070 }
1071 #endif
1072
1073 #ifndef HAS_FLS_U32
1074 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1075 {
1076 unsigned int r = 32;
1077
1078 if (!x) {
1079 return 0;
1080 }
1081 if (!(x & 0xFFFF0000U)) {
1082 x <<= 16;
1083 r -= 16;
1084 }
1085 if (!(x & 0xFF000000U)) {
1086 x <<= 8;
1087 r -= 8;
1088 }
1089 if (!(x & 0xF0000000U)) {
1090 x <<= 4;
1091 r -= 4;
1092 }
1093 if (!(x & 0xC0000000U)) {
1094 x <<= 2;
1095 r -= 2;
1096 }
1097 if (!(x & 0x80000000U)) {
1098 x <<= 1;
1099 r -= 1;
1100 }
1101 return r;
1102 }
1103 #endif
1104
1105 /*
1106 * Return the minimum order for which x <= (1UL << order).
1107 * Return -1 if x is 0.
1108 */
1109 LTTNG_HIDDEN
1110 int utils_get_count_order_u32(uint32_t x)
1111 {
1112 if (!x) {
1113 return -1;
1114 }
1115
1116 return fls_u32(x - 1);
1117 }
1118
1119 /*
1120 * Return the minimum order for which x <= (1UL << order).
1121 * Return -1 if x is 0.
1122 */
1123 LTTNG_HIDDEN
1124 int utils_get_count_order_u64(uint64_t x)
1125 {
1126 if (!x) {
1127 return -1;
1128 }
1129
1130 return fls_u64(x - 1);
1131 }
1132
1133 /**
1134 * Obtain the value of LTTNG_HOME environment variable, if exists.
1135 * Otherwise returns the value of HOME.
1136 */
1137 LTTNG_HIDDEN
1138 const char *utils_get_home_dir(void)
1139 {
1140 char *val = NULL;
1141 struct passwd *pwd;
1142
1143 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
1144 if (val != NULL) {
1145 goto end;
1146 }
1147 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
1148 if (val != NULL) {
1149 goto end;
1150 }
1151
1152 /* Fallback on the password file entry. */
1153 pwd = getpwuid(getuid());
1154 if (!pwd) {
1155 goto end;
1156 }
1157 val = pwd->pw_dir;
1158
1159 DBG3("Home directory is '%s'", val);
1160
1161 end:
1162 return val;
1163 }
1164
1165 /**
1166 * Get user's home directory. Dynamically allocated, must be freed
1167 * by the caller.
1168 */
1169 LTTNG_HIDDEN
1170 char *utils_get_user_home_dir(uid_t uid)
1171 {
1172 struct passwd pwd;
1173 struct passwd *result;
1174 char *home_dir = NULL;
1175 char *buf = NULL;
1176 long buflen;
1177 int ret;
1178
1179 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1180 if (buflen == -1) {
1181 goto end;
1182 }
1183 retry:
1184 buf = zmalloc(buflen);
1185 if (!buf) {
1186 goto end;
1187 }
1188
1189 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1190 if (ret || !result) {
1191 if (ret == ERANGE) {
1192 free(buf);
1193 buflen *= 2;
1194 goto retry;
1195 }
1196 goto end;
1197 }
1198
1199 home_dir = strdup(pwd.pw_dir);
1200 end:
1201 free(buf);
1202 return home_dir;
1203 }
1204
1205 /*
1206 * With the given format, fill dst with the time of len maximum siz.
1207 *
1208 * Return amount of bytes set in the buffer or else 0 on error.
1209 */
1210 LTTNG_HIDDEN
1211 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1212 {
1213 size_t ret;
1214 time_t rawtime;
1215 struct tm *timeinfo;
1216
1217 assert(format);
1218 assert(dst);
1219
1220 /* Get date and time for session path */
1221 time(&rawtime);
1222 timeinfo = localtime(&rawtime);
1223 ret = strftime(dst, len, format, timeinfo);
1224 if (ret == 0) {
1225 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
1226 dst, len);
1227 }
1228
1229 return ret;
1230 }
1231
1232 /*
1233 * Return 0 on success and set *gid to the group_ID matching the passed name.
1234 * Else -1 if it cannot be found or an error occurred.
1235 */
1236 LTTNG_HIDDEN
1237 int utils_get_group_id(const char *name, bool warn, gid_t *gid)
1238 {
1239 static volatile int warn_once;
1240 int ret;
1241 long sys_len;
1242 size_t len;
1243 struct group grp;
1244 struct group *result;
1245 struct lttng_dynamic_buffer buffer;
1246
1247 /* Get the system limit, if it exists. */
1248 sys_len = sysconf(_SC_GETGR_R_SIZE_MAX);
1249 if (sys_len == -1) {
1250 len = 1024;
1251 } else {
1252 len = (size_t) sys_len;
1253 }
1254
1255 lttng_dynamic_buffer_init(&buffer);
1256 ret = lttng_dynamic_buffer_set_size(&buffer, len);
1257 if (ret) {
1258 ERR("Failed to allocate group info buffer");
1259 ret = -1;
1260 goto error;
1261 }
1262
1263 while ((ret = getgrnam_r(name, &grp, buffer.data, buffer.size, &result)) == ERANGE) {
1264 const size_t new_len = 2 * buffer.size;
1265
1266 /* Buffer is not big enough, increase its size. */
1267 if (new_len < buffer.size) {
1268 ERR("Group info buffer size overflow");
1269 ret = -1;
1270 goto error;
1271 }
1272
1273 ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
1274 if (ret) {
1275 ERR("Failed to grow group info buffer to %zu bytes",
1276 new_len);
1277 ret = -1;
1278 goto error;
1279 }
1280 }
1281 if (ret) {
1282 PERROR("Failed to get group file entry for group name \"%s\"",
1283 name);
1284 ret = -1;
1285 goto error;
1286 }
1287
1288 /* Group not found. */
1289 if (!result) {
1290 ret = -1;
1291 goto error;
1292 }
1293
1294 *gid = result->gr_gid;
1295 ret = 0;
1296
1297 error:
1298 if (ret && warn && !warn_once) {
1299 WARN("No tracing group detected");
1300 warn_once = 1;
1301 }
1302 lttng_dynamic_buffer_reset(&buffer);
1303 return ret;
1304 }
1305
1306 /*
1307 * Return a newly allocated option string. This string is to be used as the
1308 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1309 * of elements in the long_options array. Returns NULL if the string's
1310 * allocation fails.
1311 */
1312 LTTNG_HIDDEN
1313 char *utils_generate_optstring(const struct option *long_options,
1314 size_t opt_count)
1315 {
1316 int i;
1317 size_t string_len = opt_count, str_pos = 0;
1318 char *optstring;
1319
1320 /*
1321 * Compute the necessary string length. One letter per option, two when an
1322 * argument is necessary, and a trailing NULL.
1323 */
1324 for (i = 0; i < opt_count; i++) {
1325 string_len += long_options[i].has_arg ? 1 : 0;
1326 }
1327
1328 optstring = zmalloc(string_len);
1329 if (!optstring) {
1330 goto end;
1331 }
1332
1333 for (i = 0; i < opt_count; i++) {
1334 if (!long_options[i].name) {
1335 /* Got to the trailing NULL element */
1336 break;
1337 }
1338
1339 if (long_options[i].val != '\0') {
1340 optstring[str_pos++] = (char) long_options[i].val;
1341 if (long_options[i].has_arg) {
1342 optstring[str_pos++] = ':';
1343 }
1344 }
1345 }
1346
1347 end:
1348 return optstring;
1349 }
1350
1351 /*
1352 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1353 * any file. Try to rmdir any empty directory within the hierarchy.
1354 */
1355 LTTNG_HIDDEN
1356 int utils_recursive_rmdir(const char *path)
1357 {
1358 int ret;
1359 struct lttng_directory_handle *handle;
1360
1361 handle = lttng_directory_handle_create(NULL);
1362 if (!handle) {
1363 ret = -1;
1364 goto end;
1365 }
1366 ret = lttng_directory_handle_remove_subdirectory(handle, path);
1367 end:
1368 lttng_directory_handle_put(handle);
1369 return ret;
1370 }
1371
1372 LTTNG_HIDDEN
1373 int utils_truncate_stream_file(int fd, off_t length)
1374 {
1375 int ret;
1376 off_t lseek_ret;
1377
1378 ret = ftruncate(fd, length);
1379 if (ret < 0) {
1380 PERROR("ftruncate");
1381 goto end;
1382 }
1383 lseek_ret = lseek(fd, length, SEEK_SET);
1384 if (lseek_ret < 0) {
1385 PERROR("lseek");
1386 ret = -1;
1387 goto end;
1388 }
1389 end:
1390 return ret;
1391 }
1392
1393 static const char *get_man_bin_path(void)
1394 {
1395 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
1396
1397 if (env_man_path) {
1398 return env_man_path;
1399 }
1400
1401 return DEFAULT_MAN_BIN_PATH;
1402 }
1403
1404 LTTNG_HIDDEN
1405 int utils_show_help(int section, const char *page_name,
1406 const char *help_msg)
1407 {
1408 char section_string[8];
1409 const char *man_bin_path = get_man_bin_path();
1410 int ret = 0;
1411
1412 if (help_msg) {
1413 printf("%s", help_msg);
1414 goto end;
1415 }
1416
1417 /* Section integer -> section string */
1418 ret = sprintf(section_string, "%d", section);
1419 assert(ret > 0 && ret < 8);
1420
1421 /*
1422 * Execute man pager.
1423 *
1424 * We provide -M to man here because LTTng-tools can
1425 * be installed outside /usr, in which case its man pages are
1426 * not located in the default /usr/share/man directory.
1427 */
1428 ret = execlp(man_bin_path, "man", "-M", MANPATH,
1429 section_string, page_name, NULL);
1430
1431 end:
1432 return ret;
1433 }
1434
1435 static
1436 int read_proc_meminfo_field(const char *field, size_t *value)
1437 {
1438 int ret;
1439 FILE *proc_meminfo;
1440 char name[PROC_MEMINFO_FIELD_MAX_NAME_LEN] = {};
1441
1442 proc_meminfo = fopen(PROC_MEMINFO_PATH, "r");
1443 if (!proc_meminfo) {
1444 PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
1445 ret = -1;
1446 goto fopen_error;
1447 }
1448
1449 /*
1450 * Read the contents of /proc/meminfo line by line to find the right
1451 * field.
1452 */
1453 while (!feof(proc_meminfo)) {
1454 unsigned long value_kb;
1455
1456 ret = fscanf(proc_meminfo,
1457 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n",
1458 name, &value_kb);
1459 if (ret == EOF) {
1460 /*
1461 * fscanf() returning EOF can indicate EOF or an error.
1462 */
1463 if (ferror(proc_meminfo)) {
1464 PERROR("Failed to parse " PROC_MEMINFO_PATH);
1465 }
1466 break;
1467 }
1468
1469 if (ret == 2 && strcmp(name, field) == 0) {
1470 /*
1471 * This number is displayed in kilo-bytes. Return the
1472 * number of bytes.
1473 */
1474 *value = ((size_t) value_kb) * 1024;
1475 ret = 0;
1476 goto found;
1477 }
1478 }
1479 /* Reached the end of the file without finding the right field. */
1480 ret = -1;
1481
1482 found:
1483 fclose(proc_meminfo);
1484 fopen_error:
1485 return ret;
1486 }
1487
1488 /*
1489 * Returns an estimate of the number of bytes of memory available based on the
1490 * the information in `/proc/meminfo`. The number returned by this function is
1491 * a best guess.
1492 */
1493 LTTNG_HIDDEN
1494 int utils_get_memory_available(size_t *value)
1495 {
1496 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value);
1497 }
1498
1499 /*
1500 * Returns the total size of the memory on the system in bytes based on the
1501 * the information in `/proc/meminfo`.
1502 */
1503 LTTNG_HIDDEN
1504 int utils_get_memory_total(size_t *value)
1505 {
1506 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value);
1507 }
1508
1509 LTTNG_HIDDEN
1510 int utils_change_working_directory(const char *path)
1511 {
1512 int ret;
1513
1514 assert(path);
1515
1516 DBG("Changing working directory to \"%s\"", path);
1517 ret = chdir(path);
1518 if (ret) {
1519 PERROR("Failed to change working directory to \"%s\"", path);
1520 goto end;
1521 }
1522
1523 /* Check for write access */
1524 if (access(path, W_OK)) {
1525 if (errno == EACCES) {
1526 /*
1527 * Do not treat this as an error since the permission
1528 * might change in the lifetime of the process
1529 */
1530 DBG("Working directory \"%s\" is not writable", path);
1531 } else {
1532 PERROR("Failed to check if working directory \"%s\" is writable",
1533 path);
1534 }
1535 }
1536
1537 end:
1538 return ret;
1539 }
This page took 0.061982 seconds and 4 git commands to generate.