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 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
|S_IWUSR
| S_IRGRP
| S_IROTH
);
222 PERROR("open file %s", filepath
);
227 fp
= fdopen(fd
, "w");
229 PERROR("fdopen file %s", filepath
);
232 PERROR("Failed to close `%s` file descriptor while handling fdopen error", filepath
);
238 ret
= fprintf(fp
, "%d\n", (int) pid
);
240 PERROR("fprintf file %s", filepath
);
245 DBG("'%d' written in file %s", (int) pid
, filepath
);
249 if (fp
&& fclose(fp
)) {
250 PERROR("fclose file %s", filepath
);
256 * Create lock file to the given path and filename.
257 * Returns the associated file descriptor, -1 on error.
259 int utils_create_lock_file(const char *filepath
)
265 LTTNG_ASSERT(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.
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(NULL
);
319 ret
= lttng_directory_handle_create_subdirectory_as_user(
321 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
323 lttng_directory_handle_put(handle
);
328 * Recursively create directory using the given path and mode, under the
329 * provided uid and gid.
331 * On success, return 0 else a negative error code.
333 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
336 struct lttng_directory_handle
*handle
;
337 const struct lttng_credentials creds
= {
338 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
339 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
342 handle
= lttng_directory_handle_create(NULL
);
347 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
349 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
351 lttng_directory_handle_put(handle
);
356 * out_stream_path is the output parameter.
358 * Return 0 on success or else a negative value.
360 int utils_stream_file_path(const char *path_name
, const char *file_name
,
361 uint64_t size
, uint64_t count
, const char *suffix
,
362 char *out_stream_path
, size_t stream_path_len
)
365 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
366 const char *path_separator
;
368 if (path_name
&& (path_name
[0] == '\0' ||
369 path_name
[strlen(path_name
) - 1] == '/')) {
372 path_separator
= "/";
375 path_name
= path_name
? : "";
376 suffix
= suffix
? : "";
378 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
380 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
383 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
384 path_name
, path_separator
, file_name
, count_str
,
386 if (ret
< 0 || ret
>= stream_path_len
) {
387 ERR("Truncation occurred while formatting stream path");
396 * Parse a string that represents a size in human readable format. It
397 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
399 * The suffix multiply the integer by:
404 * @param str The string to parse.
405 * @param size Pointer to a uint64_t that will be filled with the
408 * @return 0 on success, -1 on failure.
410 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
419 DBG("utils_parse_size_suffix: received a NULL string.");
424 /* strtoull will accept a negative number, but we don't want to. */
425 if (strchr(str
, '-') != NULL
) {
426 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
431 /* str_end will point to the \0 */
432 str_end
= str
+ strlen(str
);
434 base_size
= strtoull(str
, &num_end
, 0);
436 PERROR("utils_parse_size_suffix strtoull");
441 if (num_end
== str
) {
442 /* strtoull parsed nothing, not good. */
443 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
448 /* Check if a prefix is present. */
466 DBG("utils_parse_size_suffix: invalid suffix.");
471 /* Check for garbage after the valid input. */
472 if (num_end
!= str_end
) {
473 DBG("utils_parse_size_suffix: Garbage after size string.");
478 *size
= base_size
<< shift
;
480 /* Check for overflow */
481 if ((*size
>> shift
) != base_size
) {
482 DBG("utils_parse_size_suffix: oops, overflow detected.");
493 * Parse a string that represents a time in human readable format. It
494 * supports decimal integers suffixed by:
495 * "us" for microsecond,
496 * "ms" for millisecond,
501 * The suffix multiply the integer by:
508 * Note that unit-less numbers are assumed to be microseconds.
510 * @param str The string to parse, assumed to be NULL-terminated.
511 * @param time_us Pointer to a uint64_t that will be filled with the
512 * resulting time in microseconds.
514 * @return 0 on success, -1 on failure.
516 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
520 uint64_t multiplier
= 1;
525 DBG("utils_parse_time_suffix: received a NULL string.");
530 /* strtoull will accept a negative number, but we don't want to. */
531 if (strchr(str
, '-') != NULL
) {
532 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
537 /* str_end will point to the \0 */
538 str_end
= str
+ strlen(str
);
540 base_time
= strtoull(str
, &num_end
, 10);
542 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
547 if (num_end
== str
) {
548 /* strtoull parsed nothing, not good. */
549 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
554 /* Check if a prefix is present. */
560 * Skip the "us" if the string matches the "us" suffix,
561 * otherwise let the check for the end of the string handle
562 * the error reporting.
564 if (*(num_end
+ 1) == 's') {
569 if (*(num_end
+ 1) == 's') {
570 /* Millisecond (ms) */
571 multiplier
= USEC_PER_MSEC
;
576 multiplier
= USEC_PER_MINUTE
;
582 multiplier
= USEC_PER_SEC
;
587 multiplier
= USEC_PER_HOURS
;
593 DBG("utils_parse_time_suffix: invalid suffix.");
598 /* Check for garbage after the valid input. */
599 if (num_end
!= str_end
) {
600 DBG("utils_parse_time_suffix: Garbage after time string.");
605 *time_us
= base_time
* multiplier
;
607 /* Check for overflow */
608 if ((*time_us
/ multiplier
) != base_time
) {
609 DBG("utils_parse_time_suffix: oops, overflow detected.");
620 * fls: returns the position of the most significant bit.
621 * Returns 0 if no bit is set, else returns the position of the most
622 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
624 #if defined(__i386) || defined(__x86_64)
625 static inline unsigned int fls_u32(uint32_t x
)
633 : "=r" (r
) : "rm" (x
));
639 #if defined(__x86_64) && defined(__LP64__)
641 unsigned int fls_u64(uint64_t x
)
649 : "=r" (r
) : "rm" (x
));
656 static __attribute__((unused
))
657 unsigned int fls_u64(uint64_t x
)
664 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
668 if (!(x
& 0xFFFF000000000000ULL
)) {
672 if (!(x
& 0xFF00000000000000ULL
)) {
676 if (!(x
& 0xF000000000000000ULL
)) {
680 if (!(x
& 0xC000000000000000ULL
)) {
684 if (!(x
& 0x8000000000000000ULL
)) {
693 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
700 if (!(x
& 0xFFFF0000U
)) {
704 if (!(x
& 0xFF000000U
)) {
708 if (!(x
& 0xF0000000U
)) {
712 if (!(x
& 0xC0000000U
)) {
716 if (!(x
& 0x80000000U
)) {
725 * Return the minimum order for which x <= (1UL << order).
726 * Return -1 if x is 0.
728 int utils_get_count_order_u32(uint32_t x
)
734 return fls_u32(x
- 1);
738 * Return the minimum order for which x <= (1UL << order).
739 * Return -1 if x is 0.
741 int utils_get_count_order_u64(uint64_t x
)
747 return fls_u64(x
- 1);
751 * Obtain the value of LTTNG_HOME environment variable, if exists.
752 * Otherwise returns the value of HOME.
754 const char *utils_get_home_dir(void)
759 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
763 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
768 /* Fallback on the password file entry. */
769 pwd
= getpwuid(getuid());
775 DBG3("Home directory is '%s'", val
);
782 * Get user's home directory. Dynamically allocated, must be freed
785 char *utils_get_user_home_dir(uid_t uid
)
788 struct passwd
*result
;
789 char *home_dir
= NULL
;
794 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
799 buf
= zmalloc
<char>(buflen
);
804 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
805 if (ret
|| !result
) {
814 home_dir
= strdup(pwd
.pw_dir
);
821 * With the given format, fill dst with the time of len maximum siz.
823 * Return amount of bytes set in the buffer or else 0 on error.
825 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
831 LTTNG_ASSERT(format
);
834 /* Get date and time for session path */
836 timeinfo
= localtime(&rawtime
);
838 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
839 ret
= strftime(dst
, len
, format
, timeinfo
);
842 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
850 * Return 0 on success and set *gid to the group_ID matching the passed name.
851 * Else -1 if it cannot be found or an error occurred.
853 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
855 static volatile int warn_once
;
860 struct group
*result
;
861 struct lttng_dynamic_buffer buffer
;
863 /* Get the system limit, if it exists. */
864 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
868 len
= (size_t) sys_len
;
871 lttng_dynamic_buffer_init(&buffer
);
872 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
874 ERR("Failed to allocate group info buffer");
879 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
880 const size_t new_len
= 2 * buffer
.size
;
882 /* Buffer is not big enough, increase its size. */
883 if (new_len
< buffer
.size
) {
884 ERR("Group info buffer size overflow");
889 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
891 ERR("Failed to grow group info buffer to %zu bytes",
899 DBG("Could not find group file entry for group name '%s'",
902 PERROR("Failed to get group file entry for group name '%s'",
910 /* Group not found. */
916 *gid
= result
->gr_gid
;
920 if (ret
&& warn
&& !warn_once
) {
921 WARN("No tracing group detected");
924 lttng_dynamic_buffer_reset(&buffer
);
929 * Return a newly allocated option string. This string is to be used as the
930 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
931 * of elements in the long_options array. Returns NULL if the string's
934 char *utils_generate_optstring(const struct option
*long_options
,
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(NULL
);
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(void)
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
,
1024 const char *help_msg
)
1026 char section_string
[8];
1027 const char *man_bin_path
= get_man_bin_path();
1031 printf("%s", help_msg
);
1035 /* Section integer -> section string */
1036 ret
= sprintf(section_string
, "%d", section
);
1037 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1040 * Execute man pager.
1042 * We provide -M to man here because LTTng-tools can
1043 * be installed outside /usr, in which case its man pages are
1044 * not located in the default /usr/share/man directory.
1046 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1047 section_string
, page_name
, NULL
);
1054 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1058 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1060 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1061 if (!proc_meminfo
) {
1062 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1068 * Read the contents of /proc/meminfo line by line to find the right
1071 while (!feof(proc_meminfo
)) {
1074 ret
= fscanf(proc_meminfo
,
1075 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1079 * fscanf() returning EOF can indicate EOF or an error.
1081 if (ferror(proc_meminfo
)) {
1082 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1087 if (ret
== 2 && strcmp(name
, field
) == 0) {
1089 * This number is displayed in kilo-bytes. Return the
1092 if (value_kb
> UINT64_MAX
/ 1024) {
1093 ERR("Overflow on kb to bytes conversion");
1097 *value
= value_kb
* 1024;
1102 /* Reached the end of the file without finding the right field. */
1106 fclose(proc_meminfo
);
1112 * Returns an estimate of the number of bytes of memory available based on the
1113 * the information in `/proc/meminfo`. The number returned by this function is
1116 int utils_get_memory_available(uint64_t *value
)
1118 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1122 * Returns the total size of the memory on the system in bytes based on the
1123 * the information in `/proc/meminfo`.
1125 int utils_get_memory_total(uint64_t *value
)
1127 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1130 int utils_change_working_directory(const char *path
)
1136 DBG("Changing working directory to \"%s\"", path
);
1139 PERROR("Failed to change working directory to \"%s\"", path
);
1143 /* Check for write access */
1144 if (access(path
, W_OK
)) {
1145 if (errno
== EACCES
) {
1147 * Do not treat this as an error since the permission
1148 * might change in the lifetime of the process
1150 DBG("Working directory \"%s\" is not writable", path
);
1152 PERROR("Failed to check if working directory \"%s\" is writable",
1161 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1163 struct passwd p
, *pres
;
1165 enum lttng_error_code ret_val
= LTTNG_OK
;
1169 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1171 buflen
= FALLBACK_USER_BUFLEN
;
1174 buf
= zmalloc
<char>(buflen
);
1176 ret_val
= LTTNG_ERR_NOMEM
;
1181 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1188 buf
= zmalloc
<char>(buflen
);
1190 ret_val
= LTTNG_ERR_NOMEM
;
1203 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1206 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1207 user_name
, (int64_t) *uid
);
1215 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1218 ret_val
= LTTNG_ERR_NOMEM
;
1225 enum lttng_error_code
utils_group_id_from_name(
1226 const char *group_name
, gid_t
*gid
)
1228 struct group g
, *gres
;
1230 enum lttng_error_code ret_val
= LTTNG_OK
;
1234 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1236 buflen
= FALLBACK_GROUP_BUFLEN
;
1239 buf
= zmalloc
<char>(buflen
);
1241 ret_val
= LTTNG_ERR_NOMEM
;
1246 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1253 buf
= zmalloc
<char>(buflen
);
1255 ret_val
= LTTNG_ERR_NOMEM
;
1268 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1271 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1272 group_name
, (int64_t) *gid
);
1280 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1283 ret_val
= LTTNG_ERR_NOMEM
;
1290 int utils_parse_unsigned_long_long(const char *str
,
1291 unsigned long long *value
)
1297 LTTNG_ASSERT(value
);
1300 *value
= strtoull(str
, &endptr
, 10);
1302 /* Conversion failed. Out of range? */
1304 /* Don't print an error; allow the caller to log a better error. */
1305 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1311 /* Not the end of the string or empty string. */
1312 if (*endptr
|| endptr
== str
) {
1313 DBG("Failed to parse string as unsigned long long number: string = '%s'",