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
9 #include "common/macros.h"
18 #include <sys/types.h>
26 #include <common/common.h>
27 #include <common/readwrite.h>
28 #include <common/runas.h>
29 #include <common/compat/getenv.h>
30 #include <common/compat/string.h>
31 #include <common/compat/dirent.h>
32 #include <common/compat/directory-handle.h>
33 #include <common/dynamic-buffer.h>
34 #include <common/string-utils/format.h>
35 #include <lttng/constant.h>
41 #define PROC_MEMINFO_PATH "/proc/meminfo"
42 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
43 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
45 /* The length of the longest field of `/proc/meminfo`. */
46 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
48 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
49 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
51 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
54 #define FALLBACK_USER_BUFLEN 16384
55 #define FALLBACK_GROUP_BUFLEN 16384
58 * Create a pipe in dst.
61 int utils_create_pipe(int *dst
)
71 PERROR("create pipe");
78 * Create pipe and set CLOEXEC flag to both fd.
80 * Make sure the pipe opened by this function are closed at some point. Use
84 int utils_create_pipe_cloexec(int *dst
)
92 ret
= utils_create_pipe(dst
);
97 for (i
= 0; i
< 2; i
++) {
98 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
100 PERROR("fcntl pipe cloexec");
110 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
112 * Make sure the pipe opened by this function are closed at some point. Use
113 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
114 * support OSes other than Linux 2.6.23+.
117 int utils_create_pipe_cloexec_nonblock(int *dst
)
125 ret
= utils_create_pipe(dst
);
130 for (i
= 0; i
< 2; i
++) {
131 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
133 PERROR("fcntl pipe cloexec");
137 * Note: we override any flag that could have been
138 * previously set on the fd.
140 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
142 PERROR("fcntl pipe nonblock");
152 * Close both read and write side of the pipe.
155 void utils_close_pipe(int *src
)
163 for (i
= 0; i
< 2; i
++) {
171 PERROR("close pipe");
178 * Create a new string using two strings range.
181 char *utils_strdupdelim(const char *begin
, const char *end
)
185 str
= zmalloc(end
- begin
+ 1);
187 PERROR("zmalloc strdupdelim");
191 memcpy(str
, begin
, end
- begin
);
192 str
[end
- begin
] = '\0';
199 * Set CLOEXEC flag to the give file descriptor.
202 int utils_set_fd_cloexec(int fd
)
211 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
213 PERROR("fcntl cloexec");
222 * Create pid file to the given path and filename.
225 int utils_create_pid_file(pid_t pid
, const char *filepath
)
232 fp
= fopen(filepath
, "w");
234 PERROR("open pid file %s", filepath
);
239 ret
= fprintf(fp
, "%d\n", (int) pid
);
241 PERROR("fprintf pid file");
248 DBG("Pid %d written in file %s", (int) pid
, filepath
);
255 * Create lock file to the given path and filename.
256 * Returns the associated file descriptor, -1 on error.
259 int utils_create_lock_file(const char *filepath
)
267 memset(&lock
, 0, sizeof(lock
));
268 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
271 PERROR("open lock file %s", filepath
);
277 * Attempt to lock the file. If this fails, there is
278 * already a process using the same lock file running
279 * and we should exit.
281 lock
.l_whence
= SEEK_SET
;
282 lock
.l_type
= F_WRLCK
;
284 ret
= fcntl(fd
, F_SETLK
, &lock
);
286 PERROR("fcntl lock file");
287 ERR("Could not get lock file %s, another instance is running.",
290 PERROR("close lock file");
301 * Create directory using the given path and mode.
303 * On success, return 0 else a negative error code.
306 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
309 struct lttng_directory_handle
*handle
;
310 const struct lttng_credentials creds
= {
315 handle
= lttng_directory_handle_create(NULL
);
320 ret
= lttng_directory_handle_create_subdirectory_as_user(
322 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
324 lttng_directory_handle_put(handle
);
329 * Recursively create directory using the given path and mode, under the
330 * provided uid and gid.
332 * On success, return 0 else a negative error code.
335 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
338 struct lttng_directory_handle
*handle
;
339 const struct lttng_credentials creds
= {
344 handle
= lttng_directory_handle_create(NULL
);
349 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
351 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
353 lttng_directory_handle_put(handle
);
358 * out_stream_path is the output parameter.
360 * Return 0 on success or else a negative value.
363 int utils_stream_file_path(const char *path_name
, const char *file_name
,
364 uint64_t size
, uint64_t count
, const char *suffix
,
365 char *out_stream_path
, size_t stream_path_len
)
368 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
369 const char *path_separator
;
371 if (path_name
&& (path_name
[0] == '\0' ||
372 path_name
[strlen(path_name
) - 1] == '/')) {
375 path_separator
= "/";
378 path_name
= path_name
? : "";
379 suffix
= suffix
? : "";
381 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
383 assert(ret
> 0 && ret
< sizeof(count_str
));
386 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
387 path_name
, path_separator
, file_name
, count_str
,
389 if (ret
< 0 || ret
>= stream_path_len
) {
390 ERR("Truncation occurred while formatting stream path");
399 * Parse a string that represents a size in human readable format. It
400 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
402 * The suffix multiply the integer by:
407 * @param str The string to parse.
408 * @param size Pointer to a uint64_t that will be filled with the
411 * @return 0 on success, -1 on failure.
414 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
423 DBG("utils_parse_size_suffix: received a NULL string.");
428 /* strtoull will accept a negative number, but we don't want to. */
429 if (strchr(str
, '-') != NULL
) {
430 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
435 /* str_end will point to the \0 */
436 str_end
= str
+ strlen(str
);
438 base_size
= strtoull(str
, &num_end
, 0);
440 PERROR("utils_parse_size_suffix strtoull");
445 if (num_end
== str
) {
446 /* strtoull parsed nothing, not good. */
447 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
452 /* Check if a prefix is present. */
470 DBG("utils_parse_size_suffix: invalid suffix.");
475 /* Check for garbage after the valid input. */
476 if (num_end
!= str_end
) {
477 DBG("utils_parse_size_suffix: Garbage after size string.");
482 *size
= base_size
<< shift
;
484 /* Check for overflow */
485 if ((*size
>> shift
) != base_size
) {
486 DBG("utils_parse_size_suffix: oops, overflow detected.");
497 * Parse a string that represents a time in human readable format. It
498 * supports decimal integers suffixed by:
499 * "us" for microsecond,
500 * "ms" for millisecond,
505 * The suffix multiply the integer by:
512 * Note that unit-less numbers are assumed to be microseconds.
514 * @param str The string to parse, assumed to be NULL-terminated.
515 * @param time_us Pointer to a uint64_t that will be filled with the
516 * resulting time in microseconds.
518 * @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
, '-') != NULL
) {
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
)
638 : "=r" (r
) : "rm" (x
));
644 #if defined(__x86_64) && defined(__LP64__)
646 unsigned int fls_u64(uint64_t x
)
654 : "=r" (r
) : "rm" (x
));
661 static __attribute__((unused
))
662 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.
734 int utils_get_count_order_u32(uint32_t x
)
740 return fls_u32(x
- 1);
744 * Return the minimum order for which x <= (1UL << order).
745 * Return -1 if x is 0.
748 int utils_get_count_order_u64(uint64_t x
)
754 return fls_u64(x
- 1);
758 * Obtain the value of LTTNG_HOME environment variable, if exists.
759 * Otherwise returns the value of HOME.
762 const char *utils_get_home_dir(void)
767 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
771 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
776 /* Fallback on the password file entry. */
777 pwd
= getpwuid(getuid());
783 DBG3("Home directory is '%s'", val
);
790 * Get user's home directory. Dynamically allocated, must be freed
794 char *utils_get_user_home_dir(uid_t uid
)
797 struct passwd
*result
;
798 char *home_dir
= NULL
;
803 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
808 buf
= zmalloc(buflen
);
813 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
814 if (ret
|| !result
) {
823 home_dir
= strdup(pwd
.pw_dir
);
830 * With the given format, fill dst with the time of len maximum siz.
832 * Return amount of bytes set in the buffer or else 0 on error.
835 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
844 /* Get date and time for session path */
846 timeinfo
= localtime(&rawtime
);
847 ret
= strftime(dst
, len
, format
, timeinfo
);
849 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
857 * Return 0 on success and set *gid to the group_ID matching the passed name.
858 * Else -1 if it cannot be found or an error occurred.
861 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
863 static volatile int warn_once
;
868 struct group
*result
;
869 struct lttng_dynamic_buffer buffer
;
871 /* Get the system limit, if it exists. */
872 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
876 len
= (size_t) sys_len
;
879 lttng_dynamic_buffer_init(&buffer
);
880 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
882 ERR("Failed to allocate group info buffer");
887 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
888 const size_t new_len
= 2 * buffer
.size
;
890 /* Buffer is not big enough, increase its size. */
891 if (new_len
< buffer
.size
) {
892 ERR("Group info buffer size overflow");
897 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
899 ERR("Failed to grow group info buffer to %zu bytes",
907 DBG("Could not find group file entry for group name '%s'",
910 PERROR("Failed to get group file entry for group name '%s'",
918 /* Group not found. */
924 *gid
= result
->gr_gid
;
928 if (ret
&& warn
&& !warn_once
) {
929 WARN("No tracing group detected");
932 lttng_dynamic_buffer_reset(&buffer
);
937 * Return a newly allocated option string. This string is to be used as the
938 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
939 * of elements in the long_options array. Returns NULL if the string's
943 char *utils_generate_optstring(const struct option
*long_options
,
947 size_t string_len
= opt_count
, str_pos
= 0;
951 * Compute the necessary string length. One letter per option, two when an
952 * argument is necessary, and a trailing NULL.
954 for (i
= 0; i
< opt_count
; i
++) {
955 string_len
+= long_options
[i
].has_arg
? 1 : 0;
958 optstring
= zmalloc(string_len
);
963 for (i
= 0; i
< opt_count
; i
++) {
964 if (!long_options
[i
].name
) {
965 /* Got to the trailing NULL element */
969 if (long_options
[i
].val
!= '\0') {
970 optstring
[str_pos
++] = (char) long_options
[i
].val
;
971 if (long_options
[i
].has_arg
) {
972 optstring
[str_pos
++] = ':';
982 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
983 * any file. Try to rmdir any empty directory within the hierarchy.
986 int utils_recursive_rmdir(const char *path
)
989 struct lttng_directory_handle
*handle
;
991 handle
= lttng_directory_handle_create(NULL
);
996 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
998 lttng_directory_handle_put(handle
);
1003 int utils_truncate_stream_file(int fd
, off_t length
)
1008 ret
= ftruncate(fd
, length
);
1010 PERROR("ftruncate");
1013 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1014 if (lseek_ret
< 0) {
1023 static const char *get_man_bin_path(void)
1025 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1028 return env_man_path
;
1031 return DEFAULT_MAN_BIN_PATH
;
1035 int utils_show_help(int section
, const char *page_name
,
1036 const char *help_msg
)
1038 char section_string
[8];
1039 const char *man_bin_path
= get_man_bin_path();
1043 printf("%s", help_msg
);
1047 /* Section integer -> section string */
1048 ret
= sprintf(section_string
, "%d", section
);
1049 assert(ret
> 0 && ret
< 8);
1052 * Execute man pager.
1054 * We provide -M to man here because LTTng-tools can
1055 * be installed outside /usr, in which case its man pages are
1056 * not located in the default /usr/share/man directory.
1058 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1059 section_string
, page_name
, NULL
);
1066 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1070 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1072 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1073 if (!proc_meminfo
) {
1074 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1080 * Read the contents of /proc/meminfo line by line to find the right
1083 while (!feof(proc_meminfo
)) {
1086 ret
= fscanf(proc_meminfo
,
1087 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1091 * fscanf() returning EOF can indicate EOF or an error.
1093 if (ferror(proc_meminfo
)) {
1094 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1099 if (ret
== 2 && strcmp(name
, field
) == 0) {
1101 * This number is displayed in kilo-bytes. Return the
1104 if (value_kb
> UINT64_MAX
/ 1024) {
1105 ERR("Overflow on kb to bytes conversion");
1109 *value
= value_kb
* 1024;
1114 /* Reached the end of the file without finding the right field. */
1118 fclose(proc_meminfo
);
1124 * Returns an estimate of the number of bytes of memory available based on the
1125 * the information in `/proc/meminfo`. The number returned by this function is
1129 int utils_get_memory_available(uint64_t *value
)
1131 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1135 * Returns the total size of the memory on the system in bytes based on the
1136 * the information in `/proc/meminfo`.
1139 int utils_get_memory_total(uint64_t *value
)
1141 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1145 int utils_change_working_directory(const char *path
)
1151 DBG("Changing working directory to \"%s\"", path
);
1154 PERROR("Failed to change working directory to \"%s\"", path
);
1158 /* Check for write access */
1159 if (access(path
, W_OK
)) {
1160 if (errno
== EACCES
) {
1162 * Do not treat this as an error since the permission
1163 * might change in the lifetime of the process
1165 DBG("Working directory \"%s\" is not writable", path
);
1167 PERROR("Failed to check if working directory \"%s\" is writable",
1177 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1179 struct passwd p
, *pres
;
1181 enum lttng_error_code ret_val
= LTTNG_OK
;
1185 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1187 buflen
= FALLBACK_USER_BUFLEN
;
1190 buf
= zmalloc(buflen
);
1192 ret_val
= LTTNG_ERR_NOMEM
;
1197 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1204 buf
= zmalloc(buflen
);
1206 ret_val
= LTTNG_ERR_NOMEM
;
1219 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1222 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1223 user_name
, (int64_t) *uid
);
1231 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1234 ret_val
= LTTNG_ERR_NOMEM
;
1242 enum lttng_error_code
utils_group_id_from_name(
1243 const char *group_name
, gid_t
*gid
)
1245 struct group g
, *gres
;
1247 enum lttng_error_code ret_val
= LTTNG_OK
;
1251 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1253 buflen
= FALLBACK_GROUP_BUFLEN
;
1256 buf
= zmalloc(buflen
);
1258 ret_val
= LTTNG_ERR_NOMEM
;
1263 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1270 buf
= zmalloc(buflen
);
1272 ret_val
= LTTNG_ERR_NOMEM
;
1285 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1288 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1289 group_name
, (int64_t) *gid
);
1297 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1300 ret_val
= LTTNG_ERR_NOMEM
;