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
19 #include <sys/types.h>
22 #include <common/common.hpp>
23 #include <common/compat/directory-handle.hpp>
24 #include <common/compat/dirent.hpp>
25 #include <common/compat/getenv.hpp>
26 #include <common/compat/string.hpp>
27 #include <common/dynamic-buffer.hpp>
28 #include <common/readwrite.hpp>
29 #include <common/runas.hpp>
30 #include <common/string-utils/format.hpp>
31 #include <lttng/constant.h>
33 #include "defaults.hpp"
37 #define PROC_MEMINFO_PATH "/proc/meminfo"
38 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
39 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
41 /* The length of the longest field of `/proc/meminfo`. */
42 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
44 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
45 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
47 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
50 #define FALLBACK_USER_BUFLEN 16384
51 #define FALLBACK_GROUP_BUFLEN 16384
54 * Create a pipe in dst.
56 int utils_create_pipe(int *dst
)
66 PERROR("create pipe");
73 * Create pipe and set CLOEXEC flag to both fd.
75 * Make sure the pipe opened by this function are closed at some point. Use
78 int utils_create_pipe_cloexec(int *dst
)
86 ret
= utils_create_pipe(dst
);
91 for (i
= 0; i
< 2; i
++) {
92 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
94 PERROR("fcntl pipe cloexec");
104 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
106 * Make sure the pipe opened by this function are closed at some point. Use
107 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
108 * support OSes other than Linux 2.6.23+.
110 int utils_create_pipe_cloexec_nonblock(int *dst
)
118 ret
= utils_create_pipe(dst
);
123 for (i
= 0; i
< 2; i
++) {
124 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
126 PERROR("fcntl pipe cloexec");
130 * Note: we override any flag that could have been
131 * previously set on the fd.
133 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
135 PERROR("fcntl pipe nonblock");
145 * Close both read and write side of the pipe.
147 void utils_close_pipe(int *src
)
155 for (i
= 0; i
< 2; i
++) {
163 PERROR("close pipe");
170 * Create a new string using two strings range.
172 char *utils_strdupdelim(const char *begin
, const char *end
)
174 char *str
= zmalloc
<char>(end
- begin
+ 1);
177 PERROR("zmalloc strdupdelim");
181 memcpy(str
, begin
, end
- begin
);
182 str
[end
- begin
] = '\0';
189 * Set CLOEXEC flag to the give file descriptor.
191 int utils_set_fd_cloexec(int fd
)
200 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
202 PERROR("fcntl cloexec");
211 * Create pid file to the given path and filename.
213 int utils_create_pid_file(pid_t pid
, const char *filepath
)
218 LTTNG_ASSERT(filepath
);
220 fp
= fopen(filepath
, "w");
222 PERROR("open pid file %s", filepath
);
227 ret
= fprintf(fp
, "%d\n", (int) pid
);
229 PERROR("fprintf pid file");
236 DBG("Pid %d written in file %s", (int) pid
, filepath
);
243 * Create lock file to the given path and filename.
244 * Returns the associated file descriptor, -1 on error.
246 int utils_create_lock_file(const char *filepath
)
252 LTTNG_ASSERT(filepath
);
254 memset(&lock
, 0, sizeof(lock
));
255 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
258 PERROR("open lock file %s", filepath
);
264 * Attempt to lock the file. If this fails, there is
265 * already a process using the same lock file running
266 * and we should exit.
268 lock
.l_whence
= SEEK_SET
;
269 lock
.l_type
= F_WRLCK
;
271 ret
= fcntl(fd
, F_SETLK
, &lock
);
273 PERROR("fcntl lock file");
274 ERR("Could not get lock file %s, another instance is running.",
277 PERROR("close lock file");
288 * Create directory using the given path and mode.
290 * On success, return 0 else a negative error code.
292 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
295 struct lttng_directory_handle
*handle
;
296 const struct lttng_credentials creds
= {
297 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
298 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
301 handle
= lttng_directory_handle_create(NULL
);
306 ret
= lttng_directory_handle_create_subdirectory_as_user(
308 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
310 lttng_directory_handle_put(handle
);
315 * Recursively create directory using the given path and mode, under the
316 * provided uid and gid.
318 * On success, return 0 else a negative error code.
320 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
323 struct lttng_directory_handle
*handle
;
324 const struct lttng_credentials creds
= {
325 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
326 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
329 handle
= lttng_directory_handle_create(NULL
);
334 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
336 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
338 lttng_directory_handle_put(handle
);
343 * out_stream_path is the output parameter.
345 * Return 0 on success or else a negative value.
347 int utils_stream_file_path(const char *path_name
, const char *file_name
,
348 uint64_t size
, uint64_t count
, const char *suffix
,
349 char *out_stream_path
, size_t stream_path_len
)
352 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
353 const char *path_separator
;
355 if (path_name
&& (path_name
[0] == '\0' ||
356 path_name
[strlen(path_name
) - 1] == '/')) {
359 path_separator
= "/";
362 path_name
= path_name
? : "";
363 suffix
= suffix
? : "";
365 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
367 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
370 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
371 path_name
, path_separator
, file_name
, count_str
,
373 if (ret
< 0 || ret
>= stream_path_len
) {
374 ERR("Truncation occurred while formatting stream path");
383 * Parse a string that represents a size in human readable format. It
384 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
386 * The suffix multiply the integer by:
391 * @param str The string to parse.
392 * @param size Pointer to a uint64_t that will be filled with the
395 * @return 0 on success, -1 on failure.
397 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
406 DBG("utils_parse_size_suffix: received a NULL string.");
411 /* strtoull will accept a negative number, but we don't want to. */
412 if (strchr(str
, '-') != NULL
) {
413 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
418 /* str_end will point to the \0 */
419 str_end
= str
+ strlen(str
);
421 base_size
= strtoull(str
, &num_end
, 0);
423 PERROR("utils_parse_size_suffix strtoull");
428 if (num_end
== str
) {
429 /* strtoull parsed nothing, not good. */
430 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
435 /* Check if a prefix is present. */
453 DBG("utils_parse_size_suffix: invalid suffix.");
458 /* Check for garbage after the valid input. */
459 if (num_end
!= str_end
) {
460 DBG("utils_parse_size_suffix: Garbage after size string.");
465 *size
= base_size
<< shift
;
467 /* Check for overflow */
468 if ((*size
>> shift
) != base_size
) {
469 DBG("utils_parse_size_suffix: oops, overflow detected.");
480 * Parse a string that represents a time in human readable format. It
481 * supports decimal integers suffixed by:
482 * "us" for microsecond,
483 * "ms" for millisecond,
488 * The suffix multiply the integer by:
495 * Note that unit-less numbers are assumed to be microseconds.
497 * @param str The string to parse, assumed to be NULL-terminated.
498 * @param time_us Pointer to a uint64_t that will be filled with the
499 * resulting time in microseconds.
501 * @return 0 on success, -1 on failure.
503 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
507 uint64_t multiplier
= 1;
512 DBG("utils_parse_time_suffix: received a NULL string.");
517 /* strtoull will accept a negative number, but we don't want to. */
518 if (strchr(str
, '-') != NULL
) {
519 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
524 /* str_end will point to the \0 */
525 str_end
= str
+ strlen(str
);
527 base_time
= strtoull(str
, &num_end
, 10);
529 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
534 if (num_end
== str
) {
535 /* strtoull parsed nothing, not good. */
536 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
541 /* Check if a prefix is present. */
547 * Skip the "us" if the string matches the "us" suffix,
548 * otherwise let the check for the end of the string handle
549 * the error reporting.
551 if (*(num_end
+ 1) == 's') {
556 if (*(num_end
+ 1) == 's') {
557 /* Millisecond (ms) */
558 multiplier
= USEC_PER_MSEC
;
563 multiplier
= USEC_PER_MINUTE
;
569 multiplier
= USEC_PER_SEC
;
574 multiplier
= USEC_PER_HOURS
;
580 DBG("utils_parse_time_suffix: invalid suffix.");
585 /* Check for garbage after the valid input. */
586 if (num_end
!= str_end
) {
587 DBG("utils_parse_time_suffix: Garbage after time string.");
592 *time_us
= base_time
* multiplier
;
594 /* Check for overflow */
595 if ((*time_us
/ multiplier
) != base_time
) {
596 DBG("utils_parse_time_suffix: oops, overflow detected.");
607 * fls: returns the position of the most significant bit.
608 * Returns 0 if no bit is set, else returns the position of the most
609 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
611 #if defined(__i386) || defined(__x86_64)
612 static inline unsigned int fls_u32(uint32_t x
)
620 : "=r" (r
) : "rm" (x
));
626 #if defined(__x86_64) && defined(__LP64__)
628 unsigned int fls_u64(uint64_t x
)
636 : "=r" (r
) : "rm" (x
));
643 static __attribute__((unused
))
644 unsigned int fls_u64(uint64_t x
)
651 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
655 if (!(x
& 0xFFFF000000000000ULL
)) {
659 if (!(x
& 0xFF00000000000000ULL
)) {
663 if (!(x
& 0xF000000000000000ULL
)) {
667 if (!(x
& 0xC000000000000000ULL
)) {
671 if (!(x
& 0x8000000000000000ULL
)) {
680 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
687 if (!(x
& 0xFFFF0000U
)) {
691 if (!(x
& 0xFF000000U
)) {
695 if (!(x
& 0xF0000000U
)) {
699 if (!(x
& 0xC0000000U
)) {
703 if (!(x
& 0x80000000U
)) {
712 * Return the minimum order for which x <= (1UL << order).
713 * Return -1 if x is 0.
715 int utils_get_count_order_u32(uint32_t x
)
721 return fls_u32(x
- 1);
725 * Return the minimum order for which x <= (1UL << order).
726 * Return -1 if x is 0.
728 int utils_get_count_order_u64(uint64_t x
)
734 return fls_u64(x
- 1);
738 * Obtain the value of LTTNG_HOME environment variable, if exists.
739 * Otherwise returns the value of HOME.
741 const char *utils_get_home_dir(void)
746 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
750 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
755 /* Fallback on the password file entry. */
756 pwd
= getpwuid(getuid());
762 DBG3("Home directory is '%s'", val
);
769 * Get user's home directory. Dynamically allocated, must be freed
772 char *utils_get_user_home_dir(uid_t uid
)
775 struct passwd
*result
;
776 char *home_dir
= NULL
;
781 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
786 buf
= zmalloc
<char>(buflen
);
791 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
792 if (ret
|| !result
) {
801 home_dir
= strdup(pwd
.pw_dir
);
808 * With the given format, fill dst with the time of len maximum siz.
810 * Return amount of bytes set in the buffer or else 0 on error.
812 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
818 LTTNG_ASSERT(format
);
821 /* Get date and time for session path */
823 timeinfo
= localtime(&rawtime
);
825 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
826 ret
= strftime(dst
, len
, format
, timeinfo
);
829 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
837 * Return 0 on success and set *gid to the group_ID matching the passed name.
838 * Else -1 if it cannot be found or an error occurred.
840 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
842 static volatile int warn_once
;
847 struct group
*result
;
848 struct lttng_dynamic_buffer buffer
;
850 /* Get the system limit, if it exists. */
851 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
855 len
= (size_t) sys_len
;
858 lttng_dynamic_buffer_init(&buffer
);
859 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
861 ERR("Failed to allocate group info buffer");
866 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
867 const size_t new_len
= 2 * buffer
.size
;
869 /* Buffer is not big enough, increase its size. */
870 if (new_len
< buffer
.size
) {
871 ERR("Group info buffer size overflow");
876 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
878 ERR("Failed to grow group info buffer to %zu bytes",
886 DBG("Could not find group file entry for group name '%s'",
889 PERROR("Failed to get group file entry for group name '%s'",
897 /* Group not found. */
903 *gid
= result
->gr_gid
;
907 if (ret
&& warn
&& !warn_once
) {
908 WARN("No tracing group detected");
911 lttng_dynamic_buffer_reset(&buffer
);
916 * Return a newly allocated option string. This string is to be used as the
917 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
918 * of elements in the long_options array. Returns NULL if the string's
921 char *utils_generate_optstring(const struct option
*long_options
,
925 size_t string_len
= opt_count
, str_pos
= 0;
929 * Compute the necessary string length. One letter per option, two when an
930 * argument is necessary, and a trailing NULL.
932 for (i
= 0; i
< opt_count
; i
++) {
933 string_len
+= long_options
[i
].has_arg
? 1 : 0;
936 optstring
= zmalloc
<char>(string_len
);
941 for (i
= 0; i
< opt_count
; i
++) {
942 if (!long_options
[i
].name
) {
943 /* Got to the trailing NULL element */
947 if (long_options
[i
].val
!= '\0') {
948 optstring
[str_pos
++] = (char) long_options
[i
].val
;
949 if (long_options
[i
].has_arg
) {
950 optstring
[str_pos
++] = ':';
960 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
961 * any file. Try to rmdir any empty directory within the hierarchy.
963 int utils_recursive_rmdir(const char *path
)
966 struct lttng_directory_handle
*handle
;
968 handle
= lttng_directory_handle_create(NULL
);
973 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
975 lttng_directory_handle_put(handle
);
979 int utils_truncate_stream_file(int fd
, off_t length
)
984 ret
= ftruncate(fd
, length
);
989 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
999 static const char *get_man_bin_path(void)
1001 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1004 return env_man_path
;
1007 return DEFAULT_MAN_BIN_PATH
;
1010 int utils_show_help(int section
, const char *page_name
,
1011 const char *help_msg
)
1013 char section_string
[8];
1014 const char *man_bin_path
= get_man_bin_path();
1018 printf("%s", help_msg
);
1022 /* Section integer -> section string */
1023 ret
= sprintf(section_string
, "%d", section
);
1024 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1027 * Execute man pager.
1029 * We provide -M to man here because LTTng-tools can
1030 * be installed outside /usr, in which case its man pages are
1031 * not located in the default /usr/share/man directory.
1033 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1034 section_string
, page_name
, NULL
);
1041 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1045 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1047 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1048 if (!proc_meminfo
) {
1049 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1055 * Read the contents of /proc/meminfo line by line to find the right
1058 while (!feof(proc_meminfo
)) {
1061 ret
= fscanf(proc_meminfo
,
1062 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1066 * fscanf() returning EOF can indicate EOF or an error.
1068 if (ferror(proc_meminfo
)) {
1069 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1074 if (ret
== 2 && strcmp(name
, field
) == 0) {
1076 * This number is displayed in kilo-bytes. Return the
1079 if (value_kb
> UINT64_MAX
/ 1024) {
1080 ERR("Overflow on kb to bytes conversion");
1084 *value
= value_kb
* 1024;
1089 /* Reached the end of the file without finding the right field. */
1093 fclose(proc_meminfo
);
1099 * Returns an estimate of the number of bytes of memory available based on the
1100 * the information in `/proc/meminfo`. The number returned by this function is
1103 int utils_get_memory_available(uint64_t *value
)
1105 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1109 * Returns the total size of the memory on the system in bytes based on the
1110 * the information in `/proc/meminfo`.
1112 int utils_get_memory_total(uint64_t *value
)
1114 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1117 int utils_change_working_directory(const char *path
)
1123 DBG("Changing working directory to \"%s\"", path
);
1126 PERROR("Failed to change working directory to \"%s\"", path
);
1130 /* Check for write access */
1131 if (access(path
, W_OK
)) {
1132 if (errno
== EACCES
) {
1134 * Do not treat this as an error since the permission
1135 * might change in the lifetime of the process
1137 DBG("Working directory \"%s\" is not writable", path
);
1139 PERROR("Failed to check if working directory \"%s\" is writable",
1148 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1150 struct passwd p
, *pres
;
1152 enum lttng_error_code ret_val
= LTTNG_OK
;
1156 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1158 buflen
= FALLBACK_USER_BUFLEN
;
1161 buf
= zmalloc
<char>(buflen
);
1163 ret_val
= LTTNG_ERR_NOMEM
;
1168 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1175 buf
= zmalloc
<char>(buflen
);
1177 ret_val
= LTTNG_ERR_NOMEM
;
1190 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1193 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1194 user_name
, (int64_t) *uid
);
1202 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1205 ret_val
= LTTNG_ERR_NOMEM
;
1212 enum lttng_error_code
utils_group_id_from_name(
1213 const char *group_name
, gid_t
*gid
)
1215 struct group g
, *gres
;
1217 enum lttng_error_code ret_val
= LTTNG_OK
;
1221 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1223 buflen
= FALLBACK_GROUP_BUFLEN
;
1226 buf
= zmalloc
<char>(buflen
);
1228 ret_val
= LTTNG_ERR_NOMEM
;
1233 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1240 buf
= zmalloc
<char>(buflen
);
1242 ret_val
= LTTNG_ERR_NOMEM
;
1255 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1258 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1259 group_name
, (int64_t) *gid
);
1267 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1270 ret_val
= LTTNG_ERR_NOMEM
;
1277 int utils_parse_unsigned_long_long(const char *str
,
1278 unsigned long long *value
)
1284 LTTNG_ASSERT(value
);
1287 *value
= strtoull(str
, &endptr
, 10);
1289 /* Conversion failed. Out of range? */
1291 /* Don't print an error; allow the caller to log a better error. */
1292 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1298 /* Not the end of the string or empty string. */
1299 if (*endptr
|| endptr
== str
) {
1300 DBG("Failed to parse string as unsigned long long number: string = '%s'",