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 directory using the given path and mode.
260 * On success, return 0 else a negative error code.
262 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
265 struct lttng_directory_handle
*handle
;
266 const struct lttng_credentials creds
= {
267 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
268 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
271 handle
= lttng_directory_handle_create(nullptr);
276 ret
= lttng_directory_handle_create_subdirectory_as_user(
277 handle
, path
, mode
, (uid
>= 0 || gid
>= 0) ? &creds
: nullptr);
279 lttng_directory_handle_put(handle
);
284 * Recursively create directory using the given path and mode, under the
285 * provided uid and gid.
287 * On success, return 0 else a negative error code.
289 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
292 struct lttng_directory_handle
*handle
;
293 const struct lttng_credentials creds
= {
294 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
295 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
298 handle
= lttng_directory_handle_create(nullptr);
303 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
304 handle
, path
, mode
, (uid
>= 0 || gid
>= 0) ? &creds
: nullptr);
306 lttng_directory_handle_put(handle
);
311 * out_stream_path is the output parameter.
313 * Return 0 on success or else a negative value.
315 int utils_stream_file_path(const char *path_name
,
316 const char *file_name
,
320 char *out_stream_path
,
321 size_t stream_path_len
)
324 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
325 const char *path_separator
;
327 if (path_name
&& (path_name
[0] == '\0' || path_name
[strlen(path_name
) - 1] == '/')) {
330 path_separator
= "/";
333 path_name
= path_name
?: "";
334 suffix
= suffix
?: "";
336 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
, count
);
337 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
340 ret
= snprintf(out_stream_path
,
348 if (ret
< 0 || ret
>= stream_path_len
) {
349 ERR("Truncation occurred while formatting stream path");
358 * Parse a string that represents a size in human readable format. It
359 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
361 * The suffix multiply the integer by:
366 * @param str The string to parse.
367 * @param size Pointer to a uint64_t that will be filled with the
370 * @return 0 on success, -1 on failure.
372 int utils_parse_size_suffix(const char *const str
, uint64_t *const size
)
381 DBG("utils_parse_size_suffix: received a NULL string.");
386 /* strtoull will accept a negative number, but we don't want to. */
387 if (strchr(str
, '-') != nullptr) {
388 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
393 /* str_end will point to the \0 */
394 str_end
= str
+ strlen(str
);
396 base_size
= strtoull(str
, &num_end
, 0);
398 PERROR("utils_parse_size_suffix strtoull");
403 if (num_end
== str
) {
404 /* strtoull parsed nothing, not good. */
405 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
410 /* Check if a prefix is present. */
428 DBG("utils_parse_size_suffix: invalid suffix.");
433 /* Check for garbage after the valid input. */
434 if (num_end
!= str_end
) {
435 DBG("utils_parse_size_suffix: Garbage after size string.");
440 *size
= base_size
<< shift
;
442 /* Check for overflow */
443 if ((*size
>> shift
) != base_size
) {
444 DBG("utils_parse_size_suffix: oops, overflow detected.");
455 * Parse a string that represents a time in human readable format. It
456 * supports decimal integers suffixed by:
457 * "us" for microsecond,
458 * "ms" for millisecond,
463 * The suffix multiply the integer by:
470 * Note that unit-less numbers are assumed to be microseconds.
472 * @param str The string to parse, assumed to be NULL-terminated.
473 * @param time_us Pointer to a uint64_t that will be filled with the
474 * resulting time in microseconds.
476 * @return 0 on success, -1 on failure.
478 int utils_parse_time_suffix(char const *const str
, uint64_t *const time_us
)
482 uint64_t multiplier
= 1;
487 DBG("utils_parse_time_suffix: received a NULL string.");
492 /* strtoull will accept a negative number, but we don't want to. */
493 if (strchr(str
, '-') != nullptr) {
494 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
499 /* str_end will point to the \0 */
500 str_end
= str
+ strlen(str
);
502 base_time
= strtoull(str
, &num_end
, 10);
504 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
509 if (num_end
== str
) {
510 /* strtoull parsed nothing, not good. */
511 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
516 /* Check if a prefix is present. */
522 * Skip the "us" if the string matches the "us" suffix,
523 * otherwise let the check for the end of the string handle
524 * the error reporting.
526 if (*(num_end
+ 1) == 's') {
531 if (*(num_end
+ 1) == 's') {
532 /* Millisecond (ms) */
533 multiplier
= USEC_PER_MSEC
;
538 multiplier
= USEC_PER_MINUTE
;
544 multiplier
= USEC_PER_SEC
;
549 multiplier
= USEC_PER_HOURS
;
555 DBG("utils_parse_time_suffix: invalid suffix.");
560 /* Check for garbage after the valid input. */
561 if (num_end
!= str_end
) {
562 DBG("utils_parse_time_suffix: Garbage after time string.");
567 *time_us
= base_time
* multiplier
;
569 /* Check for overflow */
570 if ((*time_us
/ multiplier
) != base_time
) {
571 DBG("utils_parse_time_suffix: oops, overflow detected.");
582 * fls: returns the position of the most significant bit.
583 * Returns 0 if no bit is set, else returns the position of the most
584 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
586 #if defined(__i386) || defined(__x86_64)
587 static inline unsigned int fls_u32(uint32_t x
)
602 #if defined(__x86_64) && defined(__LP64__)
603 static inline unsigned int fls_u64(uint64_t x
)
619 static __attribute__((unused
)) unsigned int fls_u64(uint64_t x
)
626 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
630 if (!(x
& 0xFFFF000000000000ULL
)) {
634 if (!(x
& 0xFF00000000000000ULL
)) {
638 if (!(x
& 0xF000000000000000ULL
)) {
642 if (!(x
& 0xC000000000000000ULL
)) {
646 if (!(x
& 0x8000000000000000ULL
)) {
655 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
662 if (!(x
& 0xFFFF0000U
)) {
666 if (!(x
& 0xFF000000U
)) {
670 if (!(x
& 0xF0000000U
)) {
674 if (!(x
& 0xC0000000U
)) {
678 if (!(x
& 0x80000000U
)) {
687 * Return the minimum order for which x <= (1UL << order).
688 * Return -1 if x is 0.
690 int utils_get_count_order_u32(uint32_t x
)
696 return fls_u32(x
- 1);
700 * Return the minimum order for which x <= (1UL << order).
701 * Return -1 if x is 0.
703 int utils_get_count_order_u64(uint64_t x
)
709 return fls_u64(x
- 1);
713 * Obtain the value of LTTNG_HOME environment variable, if exists.
714 * Otherwise returns the value of HOME.
716 const char *utils_get_home_dir()
721 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
722 if (val
!= nullptr) {
725 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
726 if (val
!= nullptr) {
730 /* Fallback on the password file entry. */
731 pwd
= getpwuid(getuid());
737 DBG3("Home directory is '%s'", val
);
744 * Get user's home directory. Dynamically allocated, must be freed
747 char *utils_get_user_home_dir(uid_t uid
)
750 struct passwd
*result
;
751 char *home_dir
= nullptr;
756 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
761 buf
= zmalloc
<char>(buflen
);
766 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
767 if (ret
|| !result
) {
776 home_dir
= strdup(pwd
.pw_dir
);
783 * With the given format, fill dst with the time of len maximum siz.
785 * Return amount of bytes set in the buffer or else 0 on error.
787 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
793 LTTNG_ASSERT(format
);
796 /* Get date and time for session path */
798 timeinfo
= localtime(&rawtime
);
800 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
801 ret
= strftime(dst
, len
, format
, timeinfo
);
804 ERR("Unable to strftime with format %s at dst %p of len %zu", format
, dst
, len
);
811 * Return 0 on success and set *gid to the group_ID matching the passed name.
812 * Else -1 if it cannot be found or an error occurred.
814 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
816 static volatile int warn_once
;
821 struct group
*result
;
822 struct lttng_dynamic_buffer buffer
;
824 /* Get the system limit, if it exists. */
825 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
829 len
= (size_t) sys_len
;
832 lttng_dynamic_buffer_init(&buffer
);
833 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
835 ERR("Failed to allocate group info buffer");
840 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
841 const size_t new_len
= 2 * buffer
.size
;
843 /* Buffer is not big enough, increase its size. */
844 if (new_len
< buffer
.size
) {
845 ERR("Group info buffer size overflow");
850 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
852 ERR("Failed to grow group info buffer to %zu bytes", new_len
);
859 DBG("Could not find group file entry for group name '%s'", name
);
861 PERROR("Failed to get group file entry for group name '%s'", name
);
868 /* Group not found. */
874 *gid
= result
->gr_gid
;
878 if (ret
&& warn
&& !warn_once
) {
879 WARN("No tracing group detected");
882 lttng_dynamic_buffer_reset(&buffer
);
887 * Return a newly allocated option string. This string is to be used as the
888 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
889 * of elements in the long_options array. Returns NULL if the string's
892 char *utils_generate_optstring(const struct option
*long_options
, size_t opt_count
)
895 size_t string_len
= opt_count
, str_pos
= 0;
899 * Compute the necessary string length. One letter per option, two when an
900 * argument is necessary, and a trailing NULL.
902 for (i
= 0; i
< opt_count
; i
++) {
903 string_len
+= long_options
[i
].has_arg
? 1 : 0;
906 optstring
= zmalloc
<char>(string_len
);
911 for (i
= 0; i
< opt_count
; i
++) {
912 if (!long_options
[i
].name
) {
913 /* Got to the trailing NULL element */
917 if (long_options
[i
].val
!= '\0') {
918 optstring
[str_pos
++] = (char) long_options
[i
].val
;
919 if (long_options
[i
].has_arg
) {
920 optstring
[str_pos
++] = ':';
930 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
931 * any file. Try to rmdir any empty directory within the hierarchy.
933 int utils_recursive_rmdir(const char *path
)
936 struct lttng_directory_handle
*handle
;
938 handle
= lttng_directory_handle_create(nullptr);
943 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
945 lttng_directory_handle_put(handle
);
949 int utils_truncate_stream_file(int fd
, off_t length
)
954 ret
= ftruncate(fd
, length
);
959 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
969 static const char *get_man_bin_path()
971 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
977 return DEFAULT_MAN_BIN_PATH
;
980 static const char *get_manpath()
982 char *manpath
= lttng_secure_getenv(DEFAULT_MANPATH
);
988 /* As defined during configuration. */
992 int utils_show_help(int section
, const char *page_name
, const char *help_msg
)
994 char section_string
[8];
995 const char *man_bin_path
= get_man_bin_path();
996 const char *manpath
= get_manpath();
1000 printf("%s", help_msg
);
1004 /* Section integer -> section string */
1005 ret
= snprintf(section_string
, sizeof(section_string
), "%d", section
);
1006 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1009 * Execute man pager.
1011 * We provide -M to man here because LTTng-tools can
1012 * be installed outside /usr, in which case its man pages are
1013 * not located in the default /usr/share/man directory.
1015 ret
= execlp(man_bin_path
, "man", "-M", manpath
, section_string
, page_name
, NULL
);
1021 static int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1025 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1027 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1028 if (!proc_meminfo
) {
1029 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1035 * Read the contents of /proc/meminfo line by line to find the right
1038 while (!feof(proc_meminfo
)) {
1041 ret
= fscanf(proc_meminfo
,
1042 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1047 * fscanf() returning EOF can indicate EOF or an error.
1049 if (ferror(proc_meminfo
)) {
1050 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1055 if (ret
== 2 && strcmp(name
, field
) == 0) {
1057 * This number is displayed in kilo-bytes. Return the
1060 if (value_kb
> UINT64_MAX
/ 1024) {
1061 ERR("Overflow on kb to bytes conversion");
1065 *value
= value_kb
* 1024;
1070 /* Reached the end of the file without finding the right field. */
1074 fclose(proc_meminfo
);
1080 * Returns an estimate of the number of bytes of memory available based on the
1081 * the information in `/proc/meminfo`. The number returned by this function is
1084 int utils_get_memory_available(uint64_t *value
)
1086 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1090 * Returns the total size of the memory on the system in bytes based on the
1091 * the information in `/proc/meminfo`.
1093 int utils_get_memory_total(uint64_t *value
)
1095 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1098 int utils_change_working_directory(const char *path
)
1104 DBG("Changing working directory to \"%s\"", path
);
1107 PERROR("Failed to change working directory to \"%s\"", path
);
1111 /* Check for write access */
1112 if (access(path
, W_OK
)) {
1113 if (errno
== EACCES
) {
1115 * Do not treat this as an error since the permission
1116 * might change in the lifetime of the process
1118 DBG("Working directory \"%s\" is not writable", path
);
1120 PERROR("Failed to check if working directory \"%s\" is writable", path
);
1128 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1130 struct passwd p
, *pres
;
1132 enum lttng_error_code ret_val
= LTTNG_OK
;
1133 char *buf
= nullptr;
1136 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1138 buflen
= FALLBACK_USER_BUFLEN
;
1141 buf
= zmalloc
<char>(buflen
);
1143 ret_val
= LTTNG_ERR_NOMEM
;
1148 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1155 buf
= zmalloc
<char>(buflen
);
1157 ret_val
= LTTNG_ERR_NOMEM
;
1169 if (pres
== nullptr) {
1170 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1173 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1183 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1186 ret_val
= LTTNG_ERR_NOMEM
;
1193 enum lttng_error_code
utils_group_id_from_name(const char *group_name
, gid_t
*gid
)
1195 struct group g
, *gres
;
1197 enum lttng_error_code ret_val
= LTTNG_OK
;
1198 char *buf
= nullptr;
1201 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1203 buflen
= FALLBACK_GROUP_BUFLEN
;
1206 buf
= zmalloc
<char>(buflen
);
1208 ret_val
= LTTNG_ERR_NOMEM
;
1213 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1220 buf
= zmalloc
<char>(buflen
);
1222 ret_val
= LTTNG_ERR_NOMEM
;
1234 if (gres
== nullptr) {
1235 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1238 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1248 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1251 ret_val
= LTTNG_ERR_NOMEM
;
1258 int utils_parse_unsigned_long_long(const char *str
, unsigned long long *value
)
1264 LTTNG_ASSERT(value
);
1267 *value
= strtoull(str
, &endptr
, 10);
1269 /* Conversion failed. Out of range? */
1271 /* Don't print an error; allow the caller to log a better error. */
1272 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1279 /* Not the end of the string or empty string. */
1280 if (*endptr
|| endptr
== str
) {
1281 DBG("Failed to parse string as unsigned long long number: string = '%s'", str
);