2 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 * SPDX-License-Identifier: LGPL-2.1-only
10 #include "defaults.hpp"
14 #include <common/common.hpp>
15 #include <common/compat/directory-handle.hpp>
16 #include <common/compat/dirent.hpp>
17 #include <common/compat/getenv.hpp>
18 #include <common/compat/string.hpp>
19 #include <common/dynamic-buffer.hpp>
20 #include <common/readwrite.hpp>
21 #include <common/runas.hpp>
22 #include <common/string-utils/format.hpp>
24 #include <lttng/constant.h>
35 #include <sys/types.h>
38 #define PROC_MEMINFO_PATH "/proc/meminfo"
39 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
40 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
42 /* The lnullptrh of the longest field of `/proc/meminfo`. */
43 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
45 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
46 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
48 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
51 #define FALLBACK_USER_BUFLEN 16384
52 #define FALLBACK_GROUP_BUFLEN 16384
55 * Create a pipe in dst.
57 int utils_create_pipe(int *dst
)
67 PERROR("create pipe");
74 * Create pipe and set CLOEXEC flag to both fd.
76 * Make sure the pipe opened by this function are closed at some point. Use
79 int utils_create_pipe_cloexec(int *dst
)
87 ret
= utils_create_pipe(dst
);
92 for (i
= 0; i
< 2; i
++) {
93 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
95 PERROR("fcntl pipe cloexec");
105 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
107 * Make sure the pipe opened by this function are closed at some point. Use
108 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
109 * support OSes other than Linux 2.6.23+.
111 int utils_create_pipe_cloexec_nonblock(int *dst
)
115 if (dst
== nullptr) {
119 ret
= utils_create_pipe(dst
);
124 for (i
= 0; i
< 2; i
++) {
125 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
127 PERROR("fcntl pipe cloexec");
131 * Note: we override any flag that could have been
132 * previously set on the fd.
134 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
136 PERROR("fcntl pipe nonblock");
146 * Close both read and write side of the pipe.
148 void utils_close_pipe(int *src
)
152 if (src
== nullptr) {
156 for (i
= 0; i
< 2; i
++) {
164 PERROR("close pipe");
171 * Create a new string using two strings range.
173 char *utils_strdupdelim(const char *begin
, const char *end
)
175 char *str
= zmalloc
<char>(end
- begin
+ 1);
177 if (str
== nullptr) {
178 PERROR("zmalloc strdupdelim");
182 memcpy(str
, begin
, end
- begin
);
183 str
[end
- begin
] = '\0';
190 * Set CLOEXEC flag to the give file descriptor.
192 int utils_set_fd_cloexec(int fd
)
201 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
203 PERROR("fcntl cloexec");
212 * Create pid file to the given path and filename.
214 int utils_create_pid_file(pid_t pid
, const char *filepath
)
219 LTTNG_ASSERT(filepath
);
221 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
);
223 PERROR("open file %s", filepath
);
228 fp
= fdopen(fd
, "w");
230 PERROR("fdopen file %s", filepath
);
233 PERROR("Failed to close `%s` file descriptor while handling fdopen error",
240 ret
= fprintf(fp
, "%d\n", (int) pid
);
242 PERROR("fprintf file %s", filepath
);
247 DBG("'%d' written in file %s", (int) pid
, filepath
);
251 if (fp
&& fclose(fp
)) {
252 PERROR("fclose file %s", filepath
);
258 * Create lock file to the given path and filename.
259 * Returns the associated file descriptor, -1 on error.
261 int utils_create_lock_file(const char *filepath
)
267 LTTNG_ASSERT(filepath
);
269 memset(&lock
, 0, sizeof(lock
));
270 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
272 PERROR("open lock file %s", filepath
);
278 * Attempt to lock the file. If this fails, there is
279 * already a process using the same lock file running
280 * and we should exit.
282 lock
.l_whence
= SEEK_SET
;
283 lock
.l_type
= F_WRLCK
;
285 ret
= fcntl(fd
, F_SETLK
, &lock
);
287 PERROR("fcntl lock file");
288 ERR("Could not get lock file %s, another instance is running.", filepath
);
290 PERROR("close lock file");
301 * Create directory using the given path and mode.
303 * On success, return 0 else a negative error code.
305 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
308 struct lttng_directory_handle
*handle
;
309 const struct lttng_credentials creds
= {
310 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
311 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
314 handle
= lttng_directory_handle_create(nullptr);
319 ret
= lttng_directory_handle_create_subdirectory_as_user(
320 handle
, path
, mode
, (uid
>= 0 || gid
>= 0) ? &creds
: nullptr);
322 lttng_directory_handle_put(handle
);
327 * Recursively create directory using the given path and mode, under the
328 * provided uid and gid.
330 * On success, return 0 else a negative error code.
332 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
335 struct lttng_directory_handle
*handle
;
336 const struct lttng_credentials creds
= {
337 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
338 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
341 handle
= lttng_directory_handle_create(nullptr);
346 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
347 handle
, path
, mode
, (uid
>= 0 || gid
>= 0) ? &creds
: nullptr);
349 lttng_directory_handle_put(handle
);
354 * out_stream_path is the output parameter.
356 * Return 0 on success or else a negative value.
358 int utils_stream_file_path(const char *path_name
,
359 const char *file_name
,
363 char *out_stream_path
,
364 size_t stream_path_len
)
367 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
368 const char *path_separator
;
370 if (path_name
&& (path_name
[0] == '\0' || path_name
[strlen(path_name
) - 1] == '/')) {
373 path_separator
= "/";
376 path_name
= path_name
?: "";
377 suffix
= suffix
?: "";
379 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
, count
);
380 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
383 ret
= snprintf(out_stream_path
,
391 if (ret
< 0 || ret
>= stream_path_len
) {
392 ERR("Truncation occurred while formatting stream path");
401 * Parse a string that represents a size in human readable format. It
402 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
404 * The suffix multiply the integer by:
409 * @param str The string to parse.
410 * @param size Pointer to a uint64_t that will be filled with the
413 * @return 0 on success, -1 on failure.
415 int utils_parse_size_suffix(const char *const str
, uint64_t *const size
)
424 DBG("utils_parse_size_suffix: received a NULL string.");
429 /* strtoull will accept a negative number, but we don't want to. */
430 if (strchr(str
, '-') != nullptr) {
431 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
436 /* str_end will point to the \0 */
437 str_end
= str
+ strlen(str
);
439 base_size
= strtoull(str
, &num_end
, 0);
441 PERROR("utils_parse_size_suffix strtoull");
446 if (num_end
== str
) {
447 /* strtoull parsed nothing, not good. */
448 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
453 /* Check if a prefix is present. */
471 DBG("utils_parse_size_suffix: invalid suffix.");
476 /* Check for garbage after the valid input. */
477 if (num_end
!= str_end
) {
478 DBG("utils_parse_size_suffix: Garbage after size string.");
483 *size
= base_size
<< shift
;
485 /* Check for overflow */
486 if ((*size
>> shift
) != base_size
) {
487 DBG("utils_parse_size_suffix: oops, overflow detected.");
498 * Parse a string that represents a time in human readable format. It
499 * supports decimal integers suffixed by:
500 * "us" for microsecond,
501 * "ms" for millisecond,
506 * The suffix multiply the integer by:
513 * Note that unit-less numbers are assumed to be microseconds.
515 * @param str The string to parse, assumed to be NULL-terminated.
516 * @param time_us Pointer to a uint64_t that will be filled with the
517 * resulting time in microseconds.
519 * @return 0 on success, -1 on failure.
521 int utils_parse_time_suffix(char const *const str
, uint64_t *const time_us
)
525 uint64_t multiplier
= 1;
530 DBG("utils_parse_time_suffix: received a NULL string.");
535 /* strtoull will accept a negative number, but we don't want to. */
536 if (strchr(str
, '-') != nullptr) {
537 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
542 /* str_end will point to the \0 */
543 str_end
= str
+ strlen(str
);
545 base_time
= strtoull(str
, &num_end
, 10);
547 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
552 if (num_end
== str
) {
553 /* strtoull parsed nothing, not good. */
554 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
559 /* Check if a prefix is present. */
565 * Skip the "us" if the string matches the "us" suffix,
566 * otherwise let the check for the end of the string handle
567 * the error reporting.
569 if (*(num_end
+ 1) == 's') {
574 if (*(num_end
+ 1) == 's') {
575 /* Millisecond (ms) */
576 multiplier
= USEC_PER_MSEC
;
581 multiplier
= USEC_PER_MINUTE
;
587 multiplier
= USEC_PER_SEC
;
592 multiplier
= USEC_PER_HOURS
;
598 DBG("utils_parse_time_suffix: invalid suffix.");
603 /* Check for garbage after the valid input. */
604 if (num_end
!= str_end
) {
605 DBG("utils_parse_time_suffix: Garbage after time string.");
610 *time_us
= base_time
* multiplier
;
612 /* Check for overflow */
613 if ((*time_us
/ multiplier
) != base_time
) {
614 DBG("utils_parse_time_suffix: oops, overflow detected.");
625 * fls: returns the position of the most significant bit.
626 * Returns 0 if no bit is set, else returns the position of the most
627 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
629 #if defined(__i386) || defined(__x86_64)
630 static inline unsigned int fls_u32(uint32_t x
)
645 #if defined(__x86_64) && defined(__LP64__)
646 static inline unsigned int fls_u64(uint64_t x
)
662 static __attribute__((unused
)) unsigned int fls_u64(uint64_t x
)
669 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
673 if (!(x
& 0xFFFF000000000000ULL
)) {
677 if (!(x
& 0xFF00000000000000ULL
)) {
681 if (!(x
& 0xF000000000000000ULL
)) {
685 if (!(x
& 0xC000000000000000ULL
)) {
689 if (!(x
& 0x8000000000000000ULL
)) {
698 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
705 if (!(x
& 0xFFFF0000U
)) {
709 if (!(x
& 0xFF000000U
)) {
713 if (!(x
& 0xF0000000U
)) {
717 if (!(x
& 0xC0000000U
)) {
721 if (!(x
& 0x80000000U
)) {
730 * Return the minimum order for which x <= (1UL << order).
731 * Return -1 if x is 0.
733 int utils_get_count_order_u32(uint32_t x
)
739 return fls_u32(x
- 1);
743 * Return the minimum order for which x <= (1UL << order).
744 * Return -1 if x is 0.
746 int utils_get_count_order_u64(uint64_t x
)
752 return fls_u64(x
- 1);
756 * Obtain the value of LTTNG_HOME environment variable, if exists.
757 * Otherwise returns the value of HOME.
759 const char *utils_get_home_dir()
764 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
765 if (val
!= nullptr) {
768 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
769 if (val
!= nullptr) {
773 /* Fallback on the password file entry. */
774 pwd
= getpwuid(getuid());
780 DBG3("Home directory is '%s'", val
);
787 * Get user's home directory. Dynamically allocated, must be freed
790 char *utils_get_user_home_dir(uid_t uid
)
793 struct passwd
*result
;
794 char *home_dir
= nullptr;
799 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
804 buf
= zmalloc
<char>(buflen
);
809 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
810 if (ret
|| !result
) {
819 home_dir
= strdup(pwd
.pw_dir
);
826 * With the given format, fill dst with the time of len maximum siz.
828 * Return amount of bytes set in the buffer or else 0 on error.
830 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
836 LTTNG_ASSERT(format
);
839 /* Get date and time for session path */
841 timeinfo
= localtime(&rawtime
);
843 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
844 ret
= strftime(dst
, len
, format
, timeinfo
);
847 ERR("Unable to strftime with format %s at dst %p of len %zu", format
, dst
, len
);
854 * Return 0 on success and set *gid to the group_ID matching the passed name.
855 * Else -1 if it cannot be found or an error occurred.
857 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
859 static volatile int warn_once
;
864 struct group
*result
;
865 struct lttng_dynamic_buffer buffer
;
867 /* Get the system limit, if it exists. */
868 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
872 len
= (size_t) sys_len
;
875 lttng_dynamic_buffer_init(&buffer
);
876 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
878 ERR("Failed to allocate group info buffer");
883 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
884 const size_t new_len
= 2 * buffer
.size
;
886 /* Buffer is not big enough, increase its size. */
887 if (new_len
< buffer
.size
) {
888 ERR("Group info buffer size overflow");
893 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
895 ERR("Failed to grow group info buffer to %zu bytes", new_len
);
902 DBG("Could not find group file entry for group name '%s'", name
);
904 PERROR("Failed to get group file entry for group name '%s'", name
);
911 /* Group not found. */
917 *gid
= result
->gr_gid
;
921 if (ret
&& warn
&& !warn_once
) {
922 WARN("No tracing group detected");
925 lttng_dynamic_buffer_reset(&buffer
);
930 * Return a newly allocated option string. This string is to be used as the
931 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
932 * of elements in the long_options array. Returns NULL if the string's
935 char *utils_generate_optstring(const struct option
*long_options
, size_t opt_count
)
938 size_t string_len
= opt_count
, str_pos
= 0;
942 * Compute the necessary string length. One letter per option, two when an
943 * argument is necessary, and a trailing NULL.
945 for (i
= 0; i
< opt_count
; i
++) {
946 string_len
+= long_options
[i
].has_arg
? 1 : 0;
949 optstring
= zmalloc
<char>(string_len
);
954 for (i
= 0; i
< opt_count
; i
++) {
955 if (!long_options
[i
].name
) {
956 /* Got to the trailing NULL element */
960 if (long_options
[i
].val
!= '\0') {
961 optstring
[str_pos
++] = (char) long_options
[i
].val
;
962 if (long_options
[i
].has_arg
) {
963 optstring
[str_pos
++] = ':';
973 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
974 * any file. Try to rmdir any empty directory within the hierarchy.
976 int utils_recursive_rmdir(const char *path
)
979 struct lttng_directory_handle
*handle
;
981 handle
= lttng_directory_handle_create(nullptr);
986 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
988 lttng_directory_handle_put(handle
);
992 int utils_truncate_stream_file(int fd
, off_t length
)
997 ret
= ftruncate(fd
, length
);
1002 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1003 if (lseek_ret
< 0) {
1012 static const char *get_man_bin_path()
1014 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1017 return env_man_path
;
1020 return DEFAULT_MAN_BIN_PATH
;
1023 int utils_show_help(int section
, const char *page_name
, const char *help_msg
)
1025 char section_string
[8];
1026 const char *man_bin_path
= get_man_bin_path();
1030 printf("%s", help_msg
);
1034 /* Section integer -> section string */
1035 ret
= snprintf(section_string
, sizeof(section_string
), "%d", section
);
1036 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1039 * Execute man pager.
1041 * We provide -M to man here because LTTng-tools can
1042 * be installed outside /usr, in which case its man pages are
1043 * not located in the default /usr/share/man directory.
1045 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
, section_string
, page_name
, NULL
);
1051 static int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1055 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1057 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1058 if (!proc_meminfo
) {
1059 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1065 * Read the contents of /proc/meminfo line by line to find the right
1068 while (!feof(proc_meminfo
)) {
1071 ret
= fscanf(proc_meminfo
,
1072 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1077 * fscanf() returning EOF can indicate EOF or an error.
1079 if (ferror(proc_meminfo
)) {
1080 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1085 if (ret
== 2 && strcmp(name
, field
) == 0) {
1087 * This number is displayed in kilo-bytes. Return the
1090 if (value_kb
> UINT64_MAX
/ 1024) {
1091 ERR("Overflow on kb to bytes conversion");
1095 *value
= value_kb
* 1024;
1100 /* Reached the end of the file without finding the right field. */
1104 fclose(proc_meminfo
);
1110 * Returns an estimate of the number of bytes of memory available based on the
1111 * the information in `/proc/meminfo`. The number returned by this function is
1114 int utils_get_memory_available(uint64_t *value
)
1116 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1120 * Returns the total size of the memory on the system in bytes based on the
1121 * the information in `/proc/meminfo`.
1123 int utils_get_memory_total(uint64_t *value
)
1125 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1128 int utils_change_working_directory(const char *path
)
1134 DBG("Changing working directory to \"%s\"", path
);
1137 PERROR("Failed to change working directory to \"%s\"", path
);
1141 /* Check for write access */
1142 if (access(path
, W_OK
)) {
1143 if (errno
== EACCES
) {
1145 * Do not treat this as an error since the permission
1146 * might change in the lifetime of the process
1148 DBG("Working directory \"%s\" is not writable", path
);
1150 PERROR("Failed to check if working directory \"%s\" is writable", path
);
1158 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1160 struct passwd p
, *pres
;
1162 enum lttng_error_code ret_val
= LTTNG_OK
;
1163 char *buf
= nullptr;
1166 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1168 buflen
= FALLBACK_USER_BUFLEN
;
1171 buf
= zmalloc
<char>(buflen
);
1173 ret_val
= LTTNG_ERR_NOMEM
;
1178 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1185 buf
= zmalloc
<char>(buflen
);
1187 ret_val
= LTTNG_ERR_NOMEM
;
1199 if (pres
== nullptr) {
1200 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1203 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1213 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1216 ret_val
= LTTNG_ERR_NOMEM
;
1223 enum lttng_error_code
utils_group_id_from_name(const char *group_name
, gid_t
*gid
)
1225 struct group g
, *gres
;
1227 enum lttng_error_code ret_val
= LTTNG_OK
;
1228 char *buf
= nullptr;
1231 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1233 buflen
= FALLBACK_GROUP_BUFLEN
;
1236 buf
= zmalloc
<char>(buflen
);
1238 ret_val
= LTTNG_ERR_NOMEM
;
1243 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1250 buf
= zmalloc
<char>(buflen
);
1252 ret_val
= LTTNG_ERR_NOMEM
;
1264 if (gres
== nullptr) {
1265 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1268 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1278 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1281 ret_val
= LTTNG_ERR_NOMEM
;
1288 int utils_parse_unsigned_long_long(const char *str
, unsigned long long *value
)
1294 LTTNG_ASSERT(value
);
1297 *value
= strtoull(str
, &endptr
, 10);
1299 /* Conversion failed. Out of range? */
1301 /* Don't print an error; allow the caller to log a better error. */
1302 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1309 /* Not the end of the string or empty string. */
1310 if (*endptr
|| endptr
== str
) {
1311 DBG("Failed to parse string as unsigned long long number: string = '%s'", str
);