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 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
|S_IWUSR
| S_IRGRP
| S_IROTH
);
234 PERROR("open file %s", filepath
);
239 fp
= fdopen(fd
, "w");
241 PERROR("fdopen file %s", filepath
);
247 ret
= fprintf(fp
, "%d\n", (int) pid
);
249 PERROR("fprintf file %s", filepath
);
254 DBG("'%d' written in file %s", (int) pid
, filepath
);
258 if (fp
&& fclose(fp
)) {
259 PERROR("fclose file %s", filepath
);
265 * Create lock file to the given path and filename.
266 * Returns the associated file descriptor, -1 on error.
269 int utils_create_lock_file(const char *filepath
)
277 memset(&lock
, 0, sizeof(lock
));
278 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
281 PERROR("open lock file %s", filepath
);
287 * Attempt to lock the file. If this fails, there is
288 * already a process using the same lock file running
289 * and we should exit.
291 lock
.l_whence
= SEEK_SET
;
292 lock
.l_type
= F_WRLCK
;
294 ret
= fcntl(fd
, F_SETLK
, &lock
);
296 PERROR("fcntl lock file");
297 ERR("Could not get lock file %s, another instance is running.",
300 PERROR("close lock file");
311 * Create directory using the given path and mode.
313 * On success, return 0 else a negative error code.
316 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
319 struct lttng_directory_handle
*handle
;
320 const struct lttng_credentials creds
= {
321 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
322 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
325 handle
= lttng_directory_handle_create(NULL
);
330 ret
= lttng_directory_handle_create_subdirectory_as_user(
332 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
334 lttng_directory_handle_put(handle
);
339 * Recursively create directory using the given path and mode, under the
340 * provided uid and gid.
342 * On success, return 0 else a negative error code.
345 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
348 struct lttng_directory_handle
*handle
;
349 const struct lttng_credentials creds
= {
350 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
351 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
354 handle
= lttng_directory_handle_create(NULL
);
359 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
361 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
363 lttng_directory_handle_put(handle
);
368 * out_stream_path is the output parameter.
370 * Return 0 on success or else a negative value.
373 int utils_stream_file_path(const char *path_name
, const char *file_name
,
374 uint64_t size
, uint64_t count
, const char *suffix
,
375 char *out_stream_path
, size_t stream_path_len
)
378 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
379 const char *path_separator
;
381 if (path_name
&& (path_name
[0] == '\0' ||
382 path_name
[strlen(path_name
) - 1] == '/')) {
385 path_separator
= "/";
388 path_name
= path_name
? : "";
389 suffix
= suffix
? : "";
391 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
393 assert(ret
> 0 && ret
< sizeof(count_str
));
396 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
397 path_name
, path_separator
, file_name
, count_str
,
399 if (ret
< 0 || ret
>= stream_path_len
) {
400 ERR("Truncation occurred while formatting stream path");
409 * Parse a string that represents a size in human readable format. It
410 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
412 * The suffix multiply the integer by:
417 * @param str The string to parse.
418 * @param size Pointer to a uint64_t that will be filled with the
421 * @return 0 on success, -1 on failure.
424 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
433 DBG("utils_parse_size_suffix: received a NULL string.");
438 /* strtoull will accept a negative number, but we don't want to. */
439 if (strchr(str
, '-') != NULL
) {
440 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
445 /* str_end will point to the \0 */
446 str_end
= str
+ strlen(str
);
448 base_size
= strtoull(str
, &num_end
, 0);
450 PERROR("utils_parse_size_suffix strtoull");
455 if (num_end
== str
) {
456 /* strtoull parsed nothing, not good. */
457 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
462 /* Check if a prefix is present. */
480 DBG("utils_parse_size_suffix: invalid suffix.");
485 /* Check for garbage after the valid input. */
486 if (num_end
!= str_end
) {
487 DBG("utils_parse_size_suffix: Garbage after size string.");
492 *size
= base_size
<< shift
;
494 /* Check for overflow */
495 if ((*size
>> shift
) != base_size
) {
496 DBG("utils_parse_size_suffix: oops, overflow detected.");
507 * Parse a string that represents a time in human readable format. It
508 * supports decimal integers suffixed by:
509 * "us" for microsecond,
510 * "ms" for millisecond,
515 * The suffix multiply the integer by:
522 * Note that unit-less numbers are assumed to be microseconds.
524 * @param str The string to parse, assumed to be NULL-terminated.
525 * @param time_us Pointer to a uint64_t that will be filled with the
526 * resulting time in microseconds.
528 * @return 0 on success, -1 on failure.
531 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
535 uint64_t multiplier
= 1;
540 DBG("utils_parse_time_suffix: received a NULL string.");
545 /* strtoull will accept a negative number, but we don't want to. */
546 if (strchr(str
, '-') != NULL
) {
547 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
552 /* str_end will point to the \0 */
553 str_end
= str
+ strlen(str
);
555 base_time
= strtoull(str
, &num_end
, 10);
557 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
562 if (num_end
== str
) {
563 /* strtoull parsed nothing, not good. */
564 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
569 /* Check if a prefix is present. */
575 * Skip the "us" if the string matches the "us" suffix,
576 * otherwise let the check for the end of the string handle
577 * the error reporting.
579 if (*(num_end
+ 1) == 's') {
584 if (*(num_end
+ 1) == 's') {
585 /* Millisecond (ms) */
586 multiplier
= USEC_PER_MSEC
;
591 multiplier
= USEC_PER_MINUTE
;
597 multiplier
= USEC_PER_SEC
;
602 multiplier
= USEC_PER_HOURS
;
608 DBG("utils_parse_time_suffix: invalid suffix.");
613 /* Check for garbage after the valid input. */
614 if (num_end
!= str_end
) {
615 DBG("utils_parse_time_suffix: Garbage after time string.");
620 *time_us
= base_time
* multiplier
;
622 /* Check for overflow */
623 if ((*time_us
/ multiplier
) != base_time
) {
624 DBG("utils_parse_time_suffix: oops, overflow detected.");
635 * fls: returns the position of the most significant bit.
636 * Returns 0 if no bit is set, else returns the position of the most
637 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
639 #if defined(__i386) || defined(__x86_64)
640 static inline unsigned int fls_u32(uint32_t x
)
648 : "=r" (r
) : "rm" (x
));
654 #if defined(__x86_64) && defined(__LP64__)
656 unsigned int fls_u64(uint64_t x
)
664 : "=r" (r
) : "rm" (x
));
671 static __attribute__((unused
))
672 unsigned int fls_u64(uint64_t x
)
679 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
683 if (!(x
& 0xFFFF000000000000ULL
)) {
687 if (!(x
& 0xFF00000000000000ULL
)) {
691 if (!(x
& 0xF000000000000000ULL
)) {
695 if (!(x
& 0xC000000000000000ULL
)) {
699 if (!(x
& 0x8000000000000000ULL
)) {
708 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
715 if (!(x
& 0xFFFF0000U
)) {
719 if (!(x
& 0xFF000000U
)) {
723 if (!(x
& 0xF0000000U
)) {
727 if (!(x
& 0xC0000000U
)) {
731 if (!(x
& 0x80000000U
)) {
740 * Return the minimum order for which x <= (1UL << order).
741 * Return -1 if x is 0.
744 int utils_get_count_order_u32(uint32_t x
)
750 return fls_u32(x
- 1);
754 * Return the minimum order for which x <= (1UL << order).
755 * Return -1 if x is 0.
758 int utils_get_count_order_u64(uint64_t x
)
764 return fls_u64(x
- 1);
768 * Obtain the value of LTTNG_HOME environment variable, if exists.
769 * Otherwise returns the value of HOME.
772 const char *utils_get_home_dir(void)
777 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
781 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
786 /* Fallback on the password file entry. */
787 pwd
= getpwuid(getuid());
793 DBG3("Home directory is '%s'", val
);
800 * Get user's home directory. Dynamically allocated, must be freed
804 char *utils_get_user_home_dir(uid_t uid
)
807 struct passwd
*result
;
808 char *home_dir
= NULL
;
813 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
818 buf
= zmalloc(buflen
);
823 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
824 if (ret
|| !result
) {
833 home_dir
= strdup(pwd
.pw_dir
);
840 * With the given format, fill dst with the time of len maximum siz.
842 * Return amount of bytes set in the buffer or else 0 on error.
845 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
854 /* Get date and time for session path */
856 timeinfo
= localtime(&rawtime
);
857 ret
= strftime(dst
, len
, format
, timeinfo
);
859 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
867 * Return 0 on success and set *gid to the group_ID matching the passed name.
868 * Else -1 if it cannot be found or an error occurred.
871 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
873 static volatile int warn_once
;
878 struct group
*result
;
879 struct lttng_dynamic_buffer buffer
;
881 /* Get the system limit, if it exists. */
882 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
886 len
= (size_t) sys_len
;
889 lttng_dynamic_buffer_init(&buffer
);
890 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
892 ERR("Failed to allocate group info buffer");
897 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
898 const size_t new_len
= 2 * buffer
.size
;
900 /* Buffer is not big enough, increase its size. */
901 if (new_len
< buffer
.size
) {
902 ERR("Group info buffer size overflow");
907 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
909 ERR("Failed to grow group info buffer to %zu bytes",
917 DBG("Could not find group file entry for group name '%s'",
920 PERROR("Failed to get group file entry for group name '%s'",
928 /* Group not found. */
934 *gid
= result
->gr_gid
;
938 if (ret
&& warn
&& !warn_once
) {
939 WARN("No tracing group detected");
942 lttng_dynamic_buffer_reset(&buffer
);
947 * Return a newly allocated option string. This string is to be used as the
948 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
949 * of elements in the long_options array. Returns NULL if the string's
953 char *utils_generate_optstring(const struct option
*long_options
,
957 size_t string_len
= opt_count
, str_pos
= 0;
961 * Compute the necessary string length. One letter per option, two when an
962 * argument is necessary, and a trailing NULL.
964 for (i
= 0; i
< opt_count
; i
++) {
965 string_len
+= long_options
[i
].has_arg
? 1 : 0;
968 optstring
= zmalloc(string_len
);
973 for (i
= 0; i
< opt_count
; i
++) {
974 if (!long_options
[i
].name
) {
975 /* Got to the trailing NULL element */
979 if (long_options
[i
].val
!= '\0') {
980 optstring
[str_pos
++] = (char) long_options
[i
].val
;
981 if (long_options
[i
].has_arg
) {
982 optstring
[str_pos
++] = ':';
992 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
993 * any file. Try to rmdir any empty directory within the hierarchy.
996 int utils_recursive_rmdir(const char *path
)
999 struct lttng_directory_handle
*handle
;
1001 handle
= lttng_directory_handle_create(NULL
);
1006 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1008 lttng_directory_handle_put(handle
);
1013 int utils_truncate_stream_file(int fd
, off_t length
)
1018 ret
= ftruncate(fd
, length
);
1020 PERROR("ftruncate");
1023 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1024 if (lseek_ret
< 0) {
1033 static const char *get_man_bin_path(void)
1035 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1038 return env_man_path
;
1041 return DEFAULT_MAN_BIN_PATH
;
1045 int utils_show_help(int section
, const char *page_name
,
1046 const char *help_msg
)
1048 char section_string
[8];
1049 const char *man_bin_path
= get_man_bin_path();
1053 printf("%s", help_msg
);
1057 /* Section integer -> section string */
1058 ret
= sprintf(section_string
, "%d", section
);
1059 assert(ret
> 0 && ret
< 8);
1062 * Execute man pager.
1064 * We provide -M to man here because LTTng-tools can
1065 * be installed outside /usr, in which case its man pages are
1066 * not located in the default /usr/share/man directory.
1068 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1069 section_string
, page_name
, NULL
);
1076 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1080 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1082 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1083 if (!proc_meminfo
) {
1084 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1090 * Read the contents of /proc/meminfo line by line to find the right
1093 while (!feof(proc_meminfo
)) {
1096 ret
= fscanf(proc_meminfo
,
1097 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1101 * fscanf() returning EOF can indicate EOF or an error.
1103 if (ferror(proc_meminfo
)) {
1104 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1109 if (ret
== 2 && strcmp(name
, field
) == 0) {
1111 * This number is displayed in kilo-bytes. Return the
1114 if (value_kb
> UINT64_MAX
/ 1024) {
1115 ERR("Overflow on kb to bytes conversion");
1119 *value
= value_kb
* 1024;
1124 /* Reached the end of the file without finding the right field. */
1128 fclose(proc_meminfo
);
1134 * Returns an estimate of the number of bytes of memory available based on the
1135 * the information in `/proc/meminfo`. The number returned by this function is
1139 int utils_get_memory_available(uint64_t *value
)
1141 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1145 * Returns the total size of the memory on the system in bytes based on the
1146 * the information in `/proc/meminfo`.
1149 int utils_get_memory_total(uint64_t *value
)
1151 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1155 int utils_change_working_directory(const char *path
)
1161 DBG("Changing working directory to \"%s\"", path
);
1164 PERROR("Failed to change working directory to \"%s\"", path
);
1168 /* Check for write access */
1169 if (access(path
, W_OK
)) {
1170 if (errno
== EACCES
) {
1172 * Do not treat this as an error since the permission
1173 * might change in the lifetime of the process
1175 DBG("Working directory \"%s\" is not writable", path
);
1177 PERROR("Failed to check if working directory \"%s\" is writable",
1187 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1189 struct passwd p
, *pres
;
1191 enum lttng_error_code ret_val
= LTTNG_OK
;
1195 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1197 buflen
= FALLBACK_USER_BUFLEN
;
1200 buf
= zmalloc(buflen
);
1202 ret_val
= LTTNG_ERR_NOMEM
;
1207 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1214 buf
= zmalloc(buflen
);
1216 ret_val
= LTTNG_ERR_NOMEM
;
1229 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1232 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1233 user_name
, (int64_t) *uid
);
1241 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1244 ret_val
= LTTNG_ERR_NOMEM
;
1252 enum lttng_error_code
utils_group_id_from_name(
1253 const char *group_name
, gid_t
*gid
)
1255 struct group g
, *gres
;
1257 enum lttng_error_code ret_val
= LTTNG_OK
;
1261 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1263 buflen
= FALLBACK_GROUP_BUFLEN
;
1266 buf
= zmalloc(buflen
);
1268 ret_val
= LTTNG_ERR_NOMEM
;
1273 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1280 buf
= zmalloc(buflen
);
1282 ret_val
= LTTNG_ERR_NOMEM
;
1295 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1298 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1299 group_name
, (int64_t) *gid
);
1307 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1310 ret_val
= LTTNG_ERR_NOMEM
;
1318 int utils_parse_unsigned_long_long(const char *str
,
1319 unsigned long long *value
)
1328 *value
= strtoull(str
, &endptr
, 10);
1330 /* Conversion failed. Out of range? */
1332 /* Don't print an error; allow the caller to log a better error. */
1333 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1339 /* Not the end of the string or empty string. */
1340 if (*endptr
|| endptr
== str
) {
1341 DBG("Failed to parse string as unsigned long long number: string = '%s'",