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>
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.
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
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.
27 #include <sys/types.h>
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 <lttng/constant.h>
48 #define PROC_MEMINFO_PATH "/proc/meminfo"
49 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
50 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
52 /* The length of the longest field of `/proc/meminfo`. */
53 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
55 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
56 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
58 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
62 * Return a partial realpath(3) of the path even if the full path does not
63 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
64 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
65 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
66 * point directory does not exist.
67 * In case resolved_path is NULL, the string returned was allocated in the
68 * function and thus need to be freed by the caller. The size argument allows
69 * to specify the size of the resolved_path argument if given, or the size to
73 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
75 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
76 const char *next
, *prev
, *end
;
84 * Identify the end of the path, we don't want to treat the
85 * last char if it is a '/', we will just keep it on the side
86 * to be added at the end, and return a value coherent with
87 * the path given as argument
89 end
= path
+ strlen(path
);
90 if (*(end
-1) == '/') {
94 /* Initiate the values of the pointers before looping */
97 /* Only to ensure try_path is not NULL to enter the while */
98 try_path
= (char *)next
;
100 /* Resolve the canonical path of the first part of the path */
101 while (try_path
!= NULL
&& next
!= end
) {
102 char *try_path_buf
= NULL
;
105 * If there is not any '/' left, we want to try with
108 next
= strpbrk(next
+ 1, "/");
113 /* Cut the part we will be trying to resolve */
114 cut_path
= lttng_strndup(path
, next
- path
);
115 if (cut_path
== NULL
) {
116 PERROR("lttng_strndup");
120 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
126 /* Try to resolve this part */
127 try_path
= realpath((char *) cut_path
, try_path_buf
);
128 if (try_path
== NULL
) {
131 * There was an error, we just want to be assured it
132 * is linked to an unexistent directory, if it's another
133 * reason, we spawn an error
137 /* Ignore the error */
140 PERROR("realpath (partial_realpath)");
145 /* Save the place we are before trying the next step */
148 try_path_prev
= try_path
;
152 /* Free the allocated memory */
157 /* Allocate memory for the resolved path if necessary */
158 if (resolved_path
== NULL
) {
159 resolved_path
= zmalloc(size
);
160 if (resolved_path
== NULL
) {
161 PERROR("zmalloc resolved path");
167 * If we were able to solve at least partially the path, we can concatenate
168 * what worked and what didn't work
170 if (try_path_prev
!= NULL
) {
171 /* If we risk to concatenate two '/', we remove one of them */
172 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
173 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
177 * Duplicate the memory used by prev in case resolved_path and
178 * path are pointers for the same memory space
180 cut_path
= strdup(prev
);
181 if (cut_path
== NULL
) {
186 /* Concatenate the strings */
187 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
189 /* Free the allocated memory */
193 try_path_prev
= NULL
;
195 * Else, we just copy the path in our resolved_path to
199 strncpy(resolved_path
, path
, size
);
202 /* Then we return the 'partially' resolved path */
203 return resolved_path
;
209 if (try_path_prev
!= try_path
) {
216 int expand_double_slashes_dot_and_dotdot(char *path
)
218 size_t expanded_path_len
, path_len
;
219 const char *curr_char
, *path_last_char
, *next_slash
, *prev_slash
;
221 path_len
= strlen(path
);
222 path_last_char
= &path
[path_len
];
228 expanded_path_len
= 0;
230 /* We iterate over the provided path to expand the "//", "../" and "./" */
231 for (curr_char
= path
; curr_char
<= path_last_char
; curr_char
= next_slash
+ 1) {
232 /* Find the next forward slash. */
233 size_t curr_token_len
;
235 if (curr_char
== path_last_char
) {
240 next_slash
= memchr(curr_char
, '/', path_last_char
- curr_char
);
241 if (next_slash
== NULL
) {
242 /* Reached the end of the provided path. */
243 next_slash
= path_last_char
;
246 /* Compute how long is the previous token. */
247 curr_token_len
= next_slash
- curr_char
;
248 switch(curr_token_len
) {
251 * The pointer has not move meaning that curr_char is
252 * pointing to a slash. It that case there is no token
253 * to copy, so continue the iteration to find the next
259 * The pointer moved 1 character. Check if that
260 * character is a dot ('.'), if it is: omit it, else
261 * copy the token to the normalized path.
263 if (curr_char
[0] == '.') {
269 * The pointer moved 2 characters. Check if these
270 * characters are double dots ('..'). If that is the
271 * case, we need to remove the last token of the
274 if (curr_char
[0] == '.' && curr_char
[1] == '.') {
276 * Find the previous path component by
277 * using the memrchr function to find the
278 * previous forward slash and substract that
279 * len to the resulting path.
281 prev_slash
= lttng_memrchr(path
, '/', expanded_path_len
);
283 * If prev_slash is NULL, we reached the
284 * beginning of the path. We can't go back any
287 if (prev_slash
!= NULL
) {
288 expanded_path_len
= prev_slash
- path
;
298 * Copy the current token which is neither a '.' nor a '..'.
300 path
[expanded_path_len
++] = '/';
301 memcpy(&path
[expanded_path_len
], curr_char
, curr_token_len
);
302 expanded_path_len
+= curr_token_len
;
305 if (expanded_path_len
== 0) {
306 path
[expanded_path_len
++] = '/';
309 path
[expanded_path_len
] = '\0';
316 * Make a full resolution of the given path even if it doesn't exist.
317 * This function uses the utils_partial_realpath function to resolve
318 * symlinks and relatives paths at the start of the string, and
319 * implements functionnalities to resolve the './' and '../' strings
320 * in the middle of a path. This function is only necessary because
321 * realpath(3) does not accept to resolve unexistent paths.
322 * The returned string was allocated in the function, it is thus of
323 * the responsibility of the caller to free this memory.
326 char *_utils_expand_path(const char *path
, bool keep_symlink
)
329 char *absolute_path
= NULL
;
331 bool is_dot
, is_dotdot
;
338 /* Allocate memory for the absolute_path */
339 absolute_path
= zmalloc(LTTNG_PATH_MAX
);
340 if (absolute_path
== NULL
) {
341 PERROR("zmalloc expand path");
345 if (path
[0] == '/') {
346 ret
= lttng_strncpy(absolute_path
, path
, LTTNG_PATH_MAX
);
348 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX
);
353 * This is a relative path. We need to get the present working
354 * directory and start the path walk from there.
356 char current_working_dir
[LTTNG_PATH_MAX
];
359 cwd_ret
= getcwd(current_working_dir
, sizeof(current_working_dir
));
364 * Get the number of character in the CWD and allocate an array
365 * to can hold it and the path provided by the caller.
367 ret
= snprintf(absolute_path
, LTTNG_PATH_MAX
, "%s/%s",
368 current_working_dir
, path
);
369 if (ret
>= LTTNG_PATH_MAX
) {
370 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
371 current_working_dir
, path
, LTTNG_PATH_MAX
);
377 /* Resolve partially our path */
378 absolute_path
= utils_partial_realpath(absolute_path
,
379 absolute_path
, LTTNG_PATH_MAX
);
382 ret
= expand_double_slashes_dot_and_dotdot(absolute_path
);
387 /* Identify the last token */
388 last_token
= strrchr(absolute_path
, '/');
390 /* Verify that this token is not a relative path */
391 is_dotdot
= (strcmp(last_token
, "/..") == 0);
392 is_dot
= (strcmp(last_token
, "/.") == 0);
394 /* If it is, take action */
395 if (is_dot
|| is_dotdot
) {
396 /* For both, remove this token */
399 /* If it was a reference to parent directory, go back one more time */
401 last_token
= strrchr(absolute_path
, '/');
403 /* If there was only one level left, we keep the first '/' */
404 if (last_token
== absolute_path
) {
412 return absolute_path
;
419 char *utils_expand_path(const char *path
)
421 return _utils_expand_path(path
, true);
425 char *utils_expand_path_keep_symlink(const char *path
)
427 return _utils_expand_path(path
, false);
430 * Create a pipe in dst.
433 int utils_create_pipe(int *dst
)
443 PERROR("create pipe");
450 * Create pipe and set CLOEXEC flag to both fd.
452 * Make sure the pipe opened by this function are closed at some point. Use
453 * utils_close_pipe().
456 int utils_create_pipe_cloexec(int *dst
)
464 ret
= utils_create_pipe(dst
);
469 for (i
= 0; i
< 2; i
++) {
470 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
472 PERROR("fcntl pipe cloexec");
482 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
484 * Make sure the pipe opened by this function are closed at some point. Use
485 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
486 * support OSes other than Linux 2.6.23+.
489 int utils_create_pipe_cloexec_nonblock(int *dst
)
497 ret
= utils_create_pipe(dst
);
502 for (i
= 0; i
< 2; i
++) {
503 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
505 PERROR("fcntl pipe cloexec");
509 * Note: we override any flag that could have been
510 * previously set on the fd.
512 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
514 PERROR("fcntl pipe nonblock");
524 * Close both read and write side of the pipe.
527 void utils_close_pipe(int *src
)
535 for (i
= 0; i
< 2; i
++) {
543 PERROR("close pipe");
549 * Create a new string using two strings range.
552 char *utils_strdupdelim(const char *begin
, const char *end
)
556 str
= zmalloc(end
- begin
+ 1);
558 PERROR("zmalloc strdupdelim");
562 memcpy(str
, begin
, end
- begin
);
563 str
[end
- begin
] = '\0';
570 * Set CLOEXEC flag to the give file descriptor.
573 int utils_set_fd_cloexec(int fd
)
582 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
584 PERROR("fcntl cloexec");
593 * Create pid file to the given path and filename.
596 int utils_create_pid_file(pid_t pid
, const char *filepath
)
603 fp
= fopen(filepath
, "w");
605 PERROR("open pid file %s", filepath
);
610 ret
= fprintf(fp
, "%d\n", (int) pid
);
612 PERROR("fprintf pid file");
619 DBG("Pid %d written in file %s", (int) pid
, filepath
);
626 * Create lock file to the given path and filename.
627 * Returns the associated file descriptor, -1 on error.
630 int utils_create_lock_file(const char *filepath
)
638 memset(&lock
, 0, sizeof(lock
));
639 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
642 PERROR("open lock file %s", filepath
);
648 * Attempt to lock the file. If this fails, there is
649 * already a process using the same lock file running
650 * and we should exit.
652 lock
.l_whence
= SEEK_SET
;
653 lock
.l_type
= F_WRLCK
;
655 ret
= fcntl(fd
, F_SETLK
, &lock
);
657 PERROR("fcntl lock file");
658 ERR("Could not get lock file %s, another instance is running.",
661 PERROR("close lock file");
672 * Create directory using the given path and mode.
674 * On success, return 0 else a negative error code.
677 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
680 struct lttng_directory_handle handle
;
681 struct lttng_credentials creds
= {
686 (void) lttng_directory_handle_init(&handle
, NULL
);
687 ret
= lttng_directory_handle_create_subdirectory_as_user(
689 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
690 lttng_directory_handle_fini(&handle
);
695 * Recursively create directory using the given path and mode, under the
696 * provided uid and gid.
698 * On success, return 0 else a negative error code.
701 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
704 struct lttng_directory_handle handle
;
705 struct lttng_credentials creds
= {
710 (void) lttng_directory_handle_init(&handle
, NULL
);
711 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
713 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
714 lttng_directory_handle_fini(&handle
);
719 * path is the output parameter. It needs to be PATH_MAX len.
721 * Return 0 on success or else a negative value.
723 static int utils_stream_file_name(char *path
,
724 const char *path_name
, const char *file_name
,
725 uint64_t size
, uint64_t count
,
729 char full_path
[PATH_MAX
];
730 char *path_name_suffix
= NULL
;
733 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
734 path_name
, file_name
);
736 PERROR("snprintf create output file");
740 /* Setup extra string if suffix or/and a count is needed. */
741 if (size
> 0 && suffix
) {
742 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
743 } else if (size
> 0) {
744 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
746 ret
= asprintf(&extra
, "%s", suffix
);
749 PERROR("Allocating extra string to name");
754 * If we split the trace in multiple files, we have to add the count at
755 * the end of the tracefile name.
758 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
760 PERROR("Allocating path name with extra string");
761 goto error_free_suffix
;
763 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
764 path
[PATH_MAX
- 1] = '\0';
766 ret
= lttng_strncpy(path
, full_path
, PATH_MAX
);
768 ERR("Failed to copy stream file name");
769 goto error_free_suffix
;
772 path
[PATH_MAX
- 1] = '\0';
775 free(path_name_suffix
);
783 * Create the stream file on disk.
785 * Return 0 on success or else a negative value.
788 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
789 uint64_t count
, int uid
, int gid
, char *suffix
)
791 int ret
, flags
, mode
;
794 ret
= utils_stream_file_name(path
, path_name
, file_name
,
795 size
, count
, suffix
);
801 * With the session rotation feature on the relay, we might need to seek
802 * and truncate a tracefile, so we need read and write access.
804 flags
= O_RDWR
| O_CREAT
| O_TRUNC
;
805 /* Open with 660 mode */
806 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
808 if (uid
< 0 || gid
< 0) {
809 ret
= open(path
, flags
, mode
);
811 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
814 PERROR("open stream path %s", path
);
821 * Unlink the stream tracefile from disk.
823 * Return 0 on success or else a negative value.
826 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
827 uint64_t count
, int uid
, int gid
, char *suffix
)
832 ret
= utils_stream_file_name(path
, path_name
, file_name
,
833 size
, count
, suffix
);
837 if (uid
< 0 || gid
< 0) {
840 ret
= run_as_unlink(path
, uid
, gid
);
846 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
851 * Change the output tracefile according to the given size and count The
852 * new_count pointer is set during this operation.
854 * From the consumer, the stream lock MUST be held before calling this function
855 * because we are modifying the stream status.
857 * Return 0 on success or else a negative value.
860 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
861 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
870 PERROR("Closing tracefile");
877 * In tracefile rotation, for the relay daemon we need
878 * to unlink the old file if present, because it may
879 * still be open in reading by the live thread, and we
880 * need to ensure that we do not overwrite the content
881 * between get_index and get_packet. Since we have no
882 * way to verify integrity of the data content compared
883 * to the associated index, we need to ensure the reader
884 * has exclusive access to the file content, and that
885 * the open of the data file is performed in get_index.
886 * Unlinking the old file rather than overwriting it
890 *new_count
= (*new_count
+ 1) % count
;
892 ret
= utils_unlink_stream_file(path_name
, file_name
, size
,
893 new_count
? *new_count
: 0, uid
, gid
, 0);
894 if (ret
< 0 && errno
!= ENOENT
) {
903 ret
= utils_create_stream_file(path_name
, file_name
, size
,
904 new_count
? *new_count
: 0, uid
, gid
, 0);
919 * Parse a string that represents a size in human readable format. It
920 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
922 * The suffix multiply the integer by:
927 * @param str The string to parse.
928 * @param size Pointer to a uint64_t that will be filled with the
931 * @return 0 on success, -1 on failure.
934 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
943 DBG("utils_parse_size_suffix: received a NULL string.");
948 /* strtoull will accept a negative number, but we don't want to. */
949 if (strchr(str
, '-') != NULL
) {
950 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
955 /* str_end will point to the \0 */
956 str_end
= str
+ strlen(str
);
958 base_size
= strtoull(str
, &num_end
, 0);
960 PERROR("utils_parse_size_suffix strtoull");
965 if (num_end
== str
) {
966 /* strtoull parsed nothing, not good. */
967 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
972 /* Check if a prefix is present. */
990 DBG("utils_parse_size_suffix: invalid suffix.");
995 /* Check for garbage after the valid input. */
996 if (num_end
!= str_end
) {
997 DBG("utils_parse_size_suffix: Garbage after size string.");
1002 *size
= base_size
<< shift
;
1004 /* Check for overflow */
1005 if ((*size
>> shift
) != base_size
) {
1006 DBG("utils_parse_size_suffix: oops, overflow detected.");
1017 * Parse a string that represents a time in human readable format. It
1018 * supports decimal integers suffixed by:
1019 * "us" for microsecond,
1020 * "ms" for millisecond,
1025 * The suffix multiply the integer by:
1032 * Note that unit-less numbers are assumed to be microseconds.
1034 * @param str The string to parse, assumed to be NULL-terminated.
1035 * @param time_us Pointer to a uint64_t that will be filled with the
1036 * resulting time in microseconds.
1038 * @return 0 on success, -1 on failure.
1041 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
1045 uint64_t multiplier
= 1;
1046 const char *str_end
;
1050 DBG("utils_parse_time_suffix: received a NULL string.");
1055 /* strtoull will accept a negative number, but we don't want to. */
1056 if (strchr(str
, '-') != NULL
) {
1057 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1062 /* str_end will point to the \0 */
1063 str_end
= str
+ strlen(str
);
1065 base_time
= strtoull(str
, &num_end
, 10);
1067 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
1072 if (num_end
== str
) {
1073 /* strtoull parsed nothing, not good. */
1074 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1079 /* Check if a prefix is present. */
1085 * Skip the "us" if the string matches the "us" suffix,
1086 * otherwise let the check for the end of the string handle
1087 * the error reporting.
1089 if (*(num_end
+ 1) == 's') {
1094 if (*(num_end
+ 1) == 's') {
1095 /* Millisecond (ms) */
1096 multiplier
= USEC_PER_MSEC
;
1101 multiplier
= USEC_PER_MINUTE
;
1107 multiplier
= USEC_PER_SEC
;
1112 multiplier
= USEC_PER_HOURS
;
1118 DBG("utils_parse_time_suffix: invalid suffix.");
1123 /* Check for garbage after the valid input. */
1124 if (num_end
!= str_end
) {
1125 DBG("utils_parse_time_suffix: Garbage after time string.");
1130 *time_us
= base_time
* multiplier
;
1132 /* Check for overflow */
1133 if ((*time_us
/ multiplier
) != base_time
) {
1134 DBG("utils_parse_time_suffix: oops, overflow detected.");
1145 * fls: returns the position of the most significant bit.
1146 * Returns 0 if no bit is set, else returns the position of the most
1147 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1149 #if defined(__i386) || defined(__x86_64)
1150 static inline unsigned int fls_u32(uint32_t x
)
1154 asm("bsrl %1,%0\n\t"
1158 : "=r" (r
) : "rm" (x
));
1164 #if defined(__x86_64)
1166 unsigned int fls_u64(uint64_t x
)
1170 asm("bsrq %1,%0\n\t"
1174 : "=r" (r
) : "rm" (x
));
1181 static __attribute__((unused
))
1182 unsigned int fls_u64(uint64_t x
)
1184 unsigned int r
= 64;
1189 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1193 if (!(x
& 0xFFFF000000000000ULL
)) {
1197 if (!(x
& 0xFF00000000000000ULL
)) {
1201 if (!(x
& 0xF000000000000000ULL
)) {
1205 if (!(x
& 0xC000000000000000ULL
)) {
1209 if (!(x
& 0x8000000000000000ULL
)) {
1218 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1220 unsigned int r
= 32;
1225 if (!(x
& 0xFFFF0000U
)) {
1229 if (!(x
& 0xFF000000U
)) {
1233 if (!(x
& 0xF0000000U
)) {
1237 if (!(x
& 0xC0000000U
)) {
1241 if (!(x
& 0x80000000U
)) {
1250 * Return the minimum order for which x <= (1UL << order).
1251 * Return -1 if x is 0.
1254 int utils_get_count_order_u32(uint32_t x
)
1260 return fls_u32(x
- 1);
1264 * Return the minimum order for which x <= (1UL << order).
1265 * Return -1 if x is 0.
1268 int utils_get_count_order_u64(uint64_t x
)
1274 return fls_u64(x
- 1);
1278 * Obtain the value of LTTNG_HOME environment variable, if exists.
1279 * Otherwise returns the value of HOME.
1282 char *utils_get_home_dir(void)
1287 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1291 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1296 /* Fallback on the password file entry. */
1297 pwd
= getpwuid(getuid());
1303 DBG3("Home directory is '%s'", val
);
1310 * Get user's home directory. Dynamically allocated, must be freed
1314 char *utils_get_user_home_dir(uid_t uid
)
1317 struct passwd
*result
;
1318 char *home_dir
= NULL
;
1323 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1328 buf
= zmalloc(buflen
);
1333 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1334 if (ret
|| !result
) {
1335 if (ret
== ERANGE
) {
1343 home_dir
= strdup(pwd
.pw_dir
);
1350 * With the given format, fill dst with the time of len maximum siz.
1352 * Return amount of bytes set in the buffer or else 0 on error.
1355 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1359 struct tm
*timeinfo
;
1364 /* Get date and time for session path */
1366 timeinfo
= localtime(&rawtime
);
1367 ret
= strftime(dst
, len
, format
, timeinfo
);
1369 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1377 * Return the group ID matching name, else 0 if it cannot be found.
1380 gid_t
utils_get_group_id(const char *name
)
1384 grp
= getgrnam(name
);
1386 static volatile int warn_once
;
1389 WARN("No tracing group detected");
1398 * Return a newly allocated option string. This string is to be used as the
1399 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1400 * of elements in the long_options array. Returns NULL if the string's
1404 char *utils_generate_optstring(const struct option
*long_options
,
1408 size_t string_len
= opt_count
, str_pos
= 0;
1412 * Compute the necessary string length. One letter per option, two when an
1413 * argument is necessary, and a trailing NULL.
1415 for (i
= 0; i
< opt_count
; i
++) {
1416 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1419 optstring
= zmalloc(string_len
);
1424 for (i
= 0; i
< opt_count
; i
++) {
1425 if (!long_options
[i
].name
) {
1426 /* Got to the trailing NULL element */
1430 if (long_options
[i
].val
!= '\0') {
1431 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1432 if (long_options
[i
].has_arg
) {
1433 optstring
[str_pos
++] = ':';
1443 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1444 * any file. Try to rmdir any empty directory within the hierarchy.
1447 int utils_recursive_rmdir(const char *path
)
1451 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1452 struct dirent
*entry
;
1454 /* Open directory */
1455 dir
= opendir(path
);
1457 PERROR("Cannot open '%s' path", path
);
1460 dir_fd
= lttng_dirfd(dir
);
1462 PERROR("lttng_dirfd");
1466 path_len
= strlen(path
);
1467 while ((entry
= readdir(dir
))) {
1470 char filename
[PATH_MAX
];
1472 if (!strcmp(entry
->d_name
, ".")
1473 || !strcmp(entry
->d_name
, "..")) {
1477 name_len
= strlen(entry
->d_name
);
1478 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1479 ERR("Failed to remove file: path name too long (%s/%s)",
1480 path
, entry
->d_name
);
1483 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1484 path
, entry
->d_name
) < 0) {
1485 ERR("Failed to format path.");
1489 if (stat(filename
, &st
)) {
1494 if (S_ISDIR(st
.st_mode
)) {
1495 char subpath
[PATH_MAX
];
1497 strncpy(subpath
, path
, PATH_MAX
);
1498 subpath
[PATH_MAX
- 1] = '\0';
1499 strncat(subpath
, "/",
1500 PATH_MAX
- strlen(subpath
) - 1);
1501 strncat(subpath
, entry
->d_name
,
1502 PATH_MAX
- strlen(subpath
) - 1);
1503 if (utils_recursive_rmdir(subpath
)) {
1506 } else if (S_ISREG(st
.st_mode
)) {
1514 closeret
= closedir(dir
);
1519 DBG3("Attempting rmdir %s", path
);
1526 int utils_truncate_stream_file(int fd
, off_t length
)
1531 ret
= ftruncate(fd
, length
);
1533 PERROR("ftruncate");
1536 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1537 if (lseek_ret
< 0) {
1546 static const char *get_man_bin_path(void)
1548 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1551 return env_man_path
;
1554 return DEFAULT_MAN_BIN_PATH
;
1558 int utils_show_help(int section
, const char *page_name
,
1559 const char *help_msg
)
1561 char section_string
[8];
1562 const char *man_bin_path
= get_man_bin_path();
1566 printf("%s", help_msg
);
1570 /* Section integer -> section string */
1571 ret
= sprintf(section_string
, "%d", section
);
1572 assert(ret
> 0 && ret
< 8);
1575 * Execute man pager.
1577 * We provide -M to man here because LTTng-tools can
1578 * be installed outside /usr, in which case its man pages are
1579 * not located in the default /usr/share/man directory.
1581 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1582 section_string
, page_name
, NULL
);
1589 int read_proc_meminfo_field(const char *field
, size_t *value
)
1593 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1595 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1596 if (!proc_meminfo
) {
1597 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1603 * Read the contents of /proc/meminfo line by line to find the right
1606 while (!feof(proc_meminfo
)) {
1607 unsigned long value_kb
;
1609 ret
= fscanf(proc_meminfo
,
1610 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1614 * fscanf() returning EOF can indicate EOF or an error.
1616 if (ferror(proc_meminfo
)) {
1617 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1622 if (ret
== 2 && strcmp(name
, field
) == 0) {
1624 * This number is displayed in kilo-bytes. Return the
1627 *value
= ((size_t) value_kb
) * 1024;
1632 /* Reached the end of the file without finding the right field. */
1636 fclose(proc_meminfo
);
1642 * Returns an estimate of the number of bytes of memory available based on the
1643 * the information in `/proc/meminfo`. The number returned by this function is
1647 int utils_get_memory_available(size_t *value
)
1649 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1653 * Returns the total size of the memory on the system in bytes based on the
1654 * the information in `/proc/meminfo`.
1657 int utils_get_memory_total(size_t *value
)
1659 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);