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
);
235 ret
= fprintf(fp
, "%d\n", (int) pid
);
237 PERROR("fprintf file %s", filepath
);
242 DBG("'%d' written in file %s", (int) pid
, filepath
);
246 if (fp
&& fclose(fp
)) {
247 PERROR("fclose file %s", filepath
);
253 * Create lock file to the given path and filename.
254 * Returns the associated file descriptor, -1 on error.
256 int utils_create_lock_file(const char *filepath
)
262 LTTNG_ASSERT(filepath
);
264 memset(&lock
, 0, sizeof(lock
));
265 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
268 PERROR("open lock file %s", filepath
);
274 * Attempt to lock the file. If this fails, there is
275 * already a process using the same lock file running
276 * and we should exit.
278 lock
.l_whence
= SEEK_SET
;
279 lock
.l_type
= F_WRLCK
;
281 ret
= fcntl(fd
, F_SETLK
, &lock
);
283 PERROR("fcntl lock file");
284 ERR("Could not get lock file %s, another instance is running.",
287 PERROR("close lock file");
298 * Create directory using the given path and mode.
300 * On success, return 0 else a negative error code.
302 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
305 struct lttng_directory_handle
*handle
;
306 const struct lttng_credentials creds
= {
307 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
308 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
311 handle
= lttng_directory_handle_create(NULL
);
316 ret
= lttng_directory_handle_create_subdirectory_as_user(
318 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
320 lttng_directory_handle_put(handle
);
325 * Recursively create directory using the given path and mode, under the
326 * provided uid and gid.
328 * On success, return 0 else a negative error code.
330 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
333 struct lttng_directory_handle
*handle
;
334 const struct lttng_credentials creds
= {
335 .uid
= LTTNG_OPTIONAL_INIT_VALUE((uid_t
) uid
),
336 .gid
= LTTNG_OPTIONAL_INIT_VALUE((gid_t
) gid
),
339 handle
= lttng_directory_handle_create(NULL
);
344 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
346 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
348 lttng_directory_handle_put(handle
);
353 * out_stream_path is the output parameter.
355 * Return 0 on success or else a negative value.
357 int utils_stream_file_path(const char *path_name
, const char *file_name
,
358 uint64_t size
, uint64_t count
, const char *suffix
,
359 char *out_stream_path
, size_t stream_path_len
)
362 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
363 const char *path_separator
;
365 if (path_name
&& (path_name
[0] == '\0' ||
366 path_name
[strlen(path_name
) - 1] == '/')) {
369 path_separator
= "/";
372 path_name
= path_name
? : "";
373 suffix
= suffix
? : "";
375 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
377 LTTNG_ASSERT(ret
> 0 && ret
< sizeof(count_str
));
380 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
381 path_name
, path_separator
, file_name
, count_str
,
383 if (ret
< 0 || ret
>= stream_path_len
) {
384 ERR("Truncation occurred while formatting stream path");
393 * Parse a string that represents a size in human readable format. It
394 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
396 * The suffix multiply the integer by:
401 * @param str The string to parse.
402 * @param size Pointer to a uint64_t that will be filled with the
405 * @return 0 on success, -1 on failure.
407 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
416 DBG("utils_parse_size_suffix: received a NULL string.");
421 /* strtoull will accept a negative number, but we don't want to. */
422 if (strchr(str
, '-') != NULL
) {
423 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
428 /* str_end will point to the \0 */
429 str_end
= str
+ strlen(str
);
431 base_size
= strtoull(str
, &num_end
, 0);
433 PERROR("utils_parse_size_suffix strtoull");
438 if (num_end
== str
) {
439 /* strtoull parsed nothing, not good. */
440 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
445 /* Check if a prefix is present. */
463 DBG("utils_parse_size_suffix: invalid suffix.");
468 /* Check for garbage after the valid input. */
469 if (num_end
!= str_end
) {
470 DBG("utils_parse_size_suffix: Garbage after size string.");
475 *size
= base_size
<< shift
;
477 /* Check for overflow */
478 if ((*size
>> shift
) != base_size
) {
479 DBG("utils_parse_size_suffix: oops, overflow detected.");
490 * Parse a string that represents a time in human readable format. It
491 * supports decimal integers suffixed by:
492 * "us" for microsecond,
493 * "ms" for millisecond,
498 * The suffix multiply the integer by:
505 * Note that unit-less numbers are assumed to be microseconds.
507 * @param str The string to parse, assumed to be NULL-terminated.
508 * @param time_us Pointer to a uint64_t that will be filled with the
509 * resulting time in microseconds.
511 * @return 0 on success, -1 on failure.
513 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
517 uint64_t multiplier
= 1;
522 DBG("utils_parse_time_suffix: received a NULL string.");
527 /* strtoull will accept a negative number, but we don't want to. */
528 if (strchr(str
, '-') != NULL
) {
529 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
534 /* str_end will point to the \0 */
535 str_end
= str
+ strlen(str
);
537 base_time
= strtoull(str
, &num_end
, 10);
539 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
544 if (num_end
== str
) {
545 /* strtoull parsed nothing, not good. */
546 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
551 /* Check if a prefix is present. */
557 * Skip the "us" if the string matches the "us" suffix,
558 * otherwise let the check for the end of the string handle
559 * the error reporting.
561 if (*(num_end
+ 1) == 's') {
566 if (*(num_end
+ 1) == 's') {
567 /* Millisecond (ms) */
568 multiplier
= USEC_PER_MSEC
;
573 multiplier
= USEC_PER_MINUTE
;
579 multiplier
= USEC_PER_SEC
;
584 multiplier
= USEC_PER_HOURS
;
590 DBG("utils_parse_time_suffix: invalid suffix.");
595 /* Check for garbage after the valid input. */
596 if (num_end
!= str_end
) {
597 DBG("utils_parse_time_suffix: Garbage after time string.");
602 *time_us
= base_time
* multiplier
;
604 /* Check for overflow */
605 if ((*time_us
/ multiplier
) != base_time
) {
606 DBG("utils_parse_time_suffix: oops, overflow detected.");
617 * fls: returns the position of the most significant bit.
618 * Returns 0 if no bit is set, else returns the position of the most
619 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
621 #if defined(__i386) || defined(__x86_64)
622 static inline unsigned int fls_u32(uint32_t x
)
630 : "=r" (r
) : "rm" (x
));
636 #if defined(__x86_64) && defined(__LP64__)
638 unsigned int fls_u64(uint64_t x
)
646 : "=r" (r
) : "rm" (x
));
653 static __attribute__((unused
))
654 unsigned int fls_u64(uint64_t x
)
661 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
665 if (!(x
& 0xFFFF000000000000ULL
)) {
669 if (!(x
& 0xFF00000000000000ULL
)) {
673 if (!(x
& 0xF000000000000000ULL
)) {
677 if (!(x
& 0xC000000000000000ULL
)) {
681 if (!(x
& 0x8000000000000000ULL
)) {
690 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
697 if (!(x
& 0xFFFF0000U
)) {
701 if (!(x
& 0xFF000000U
)) {
705 if (!(x
& 0xF0000000U
)) {
709 if (!(x
& 0xC0000000U
)) {
713 if (!(x
& 0x80000000U
)) {
722 * Return the minimum order for which x <= (1UL << order).
723 * Return -1 if x is 0.
725 int utils_get_count_order_u32(uint32_t x
)
731 return fls_u32(x
- 1);
735 * Return the minimum order for which x <= (1UL << order).
736 * Return -1 if x is 0.
738 int utils_get_count_order_u64(uint64_t x
)
744 return fls_u64(x
- 1);
748 * Obtain the value of LTTNG_HOME environment variable, if exists.
749 * Otherwise returns the value of HOME.
751 const char *utils_get_home_dir(void)
756 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
760 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
765 /* Fallback on the password file entry. */
766 pwd
= getpwuid(getuid());
772 DBG3("Home directory is '%s'", val
);
779 * Get user's home directory. Dynamically allocated, must be freed
782 char *utils_get_user_home_dir(uid_t uid
)
785 struct passwd
*result
;
786 char *home_dir
= NULL
;
791 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
796 buf
= zmalloc
<char>(buflen
);
801 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
802 if (ret
|| !result
) {
811 home_dir
= strdup(pwd
.pw_dir
);
818 * With the given format, fill dst with the time of len maximum siz.
820 * Return amount of bytes set in the buffer or else 0 on error.
822 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
828 LTTNG_ASSERT(format
);
831 /* Get date and time for session path */
833 timeinfo
= localtime(&rawtime
);
835 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
836 ret
= strftime(dst
, len
, format
, timeinfo
);
839 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
847 * Return 0 on success and set *gid to the group_ID matching the passed name.
848 * Else -1 if it cannot be found or an error occurred.
850 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
852 static volatile int warn_once
;
857 struct group
*result
;
858 struct lttng_dynamic_buffer buffer
;
860 /* Get the system limit, if it exists. */
861 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
865 len
= (size_t) sys_len
;
868 lttng_dynamic_buffer_init(&buffer
);
869 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
871 ERR("Failed to allocate group info buffer");
876 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
877 const size_t new_len
= 2 * buffer
.size
;
879 /* Buffer is not big enough, increase its size. */
880 if (new_len
< buffer
.size
) {
881 ERR("Group info buffer size overflow");
886 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
888 ERR("Failed to grow group info buffer to %zu bytes",
896 DBG("Could not find group file entry for group name '%s'",
899 PERROR("Failed to get group file entry for group name '%s'",
907 /* Group not found. */
913 *gid
= result
->gr_gid
;
917 if (ret
&& warn
&& !warn_once
) {
918 WARN("No tracing group detected");
921 lttng_dynamic_buffer_reset(&buffer
);
926 * Return a newly allocated option string. This string is to be used as the
927 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
928 * of elements in the long_options array. Returns NULL if the string's
931 char *utils_generate_optstring(const struct option
*long_options
,
935 size_t string_len
= opt_count
, str_pos
= 0;
939 * Compute the necessary string length. One letter per option, two when an
940 * argument is necessary, and a trailing NULL.
942 for (i
= 0; i
< opt_count
; i
++) {
943 string_len
+= long_options
[i
].has_arg
? 1 : 0;
946 optstring
= zmalloc
<char>(string_len
);
951 for (i
= 0; i
< opt_count
; i
++) {
952 if (!long_options
[i
].name
) {
953 /* Got to the trailing NULL element */
957 if (long_options
[i
].val
!= '\0') {
958 optstring
[str_pos
++] = (char) long_options
[i
].val
;
959 if (long_options
[i
].has_arg
) {
960 optstring
[str_pos
++] = ':';
970 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
971 * any file. Try to rmdir any empty directory within the hierarchy.
973 int utils_recursive_rmdir(const char *path
)
976 struct lttng_directory_handle
*handle
;
978 handle
= lttng_directory_handle_create(NULL
);
983 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
985 lttng_directory_handle_put(handle
);
989 int utils_truncate_stream_file(int fd
, off_t length
)
994 ret
= ftruncate(fd
, length
);
999 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1000 if (lseek_ret
< 0) {
1009 static const char *get_man_bin_path(void)
1011 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1014 return env_man_path
;
1017 return DEFAULT_MAN_BIN_PATH
;
1020 int utils_show_help(int section
, const char *page_name
,
1021 const char *help_msg
)
1023 char section_string
[8];
1024 const char *man_bin_path
= get_man_bin_path();
1028 printf("%s", help_msg
);
1032 /* Section integer -> section string */
1033 ret
= sprintf(section_string
, "%d", section
);
1034 LTTNG_ASSERT(ret
> 0 && ret
< 8);
1037 * Execute man pager.
1039 * We provide -M to man here because LTTng-tools can
1040 * be installed outside /usr, in which case its man pages are
1041 * not located in the default /usr/share/man directory.
1043 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1044 section_string
, page_name
, NULL
);
1051 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1055 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1057 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1058 if (!proc_meminfo
) {
1059 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1065 * Read the contents of /proc/meminfo line by line to find the right
1068 while (!feof(proc_meminfo
)) {
1071 ret
= fscanf(proc_meminfo
,
1072 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1076 * fscanf() returning EOF can indicate EOF or an error.
1078 if (ferror(proc_meminfo
)) {
1079 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1084 if (ret
== 2 && strcmp(name
, field
) == 0) {
1086 * This number is displayed in kilo-bytes. Return the
1089 if (value_kb
> UINT64_MAX
/ 1024) {
1090 ERR("Overflow on kb to bytes conversion");
1094 *value
= value_kb
* 1024;
1099 /* Reached the end of the file without finding the right field. */
1103 fclose(proc_meminfo
);
1109 * Returns an estimate of the number of bytes of memory available based on the
1110 * the information in `/proc/meminfo`. The number returned by this function is
1113 int utils_get_memory_available(uint64_t *value
)
1115 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1119 * Returns the total size of the memory on the system in bytes based on the
1120 * the information in `/proc/meminfo`.
1122 int utils_get_memory_total(uint64_t *value
)
1124 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1127 int utils_change_working_directory(const char *path
)
1133 DBG("Changing working directory to \"%s\"", path
);
1136 PERROR("Failed to change working directory to \"%s\"", path
);
1140 /* Check for write access */
1141 if (access(path
, W_OK
)) {
1142 if (errno
== EACCES
) {
1144 * Do not treat this as an error since the permission
1145 * might change in the lifetime of the process
1147 DBG("Working directory \"%s\" is not writable", path
);
1149 PERROR("Failed to check if working directory \"%s\" is writable",
1158 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1160 struct passwd p
, *pres
;
1162 enum lttng_error_code ret_val
= LTTNG_OK
;
1166 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1168 buflen
= FALLBACK_USER_BUFLEN
;
1171 buf
= zmalloc
<char>(buflen
);
1173 ret_val
= LTTNG_ERR_NOMEM
;
1178 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1185 buf
= zmalloc
<char>(buflen
);
1187 ret_val
= LTTNG_ERR_NOMEM
;
1200 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1203 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1204 user_name
, (int64_t) *uid
);
1212 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1215 ret_val
= LTTNG_ERR_NOMEM
;
1222 enum lttng_error_code
utils_group_id_from_name(
1223 const char *group_name
, gid_t
*gid
)
1225 struct group g
, *gres
;
1227 enum lttng_error_code ret_val
= LTTNG_OK
;
1231 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1233 buflen
= FALLBACK_GROUP_BUFLEN
;
1236 buf
= zmalloc
<char>(buflen
);
1238 ret_val
= LTTNG_ERR_NOMEM
;
1243 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1250 buf
= zmalloc
<char>(buflen
);
1252 ret_val
= LTTNG_ERR_NOMEM
;
1265 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1268 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1269 group_name
, (int64_t) *gid
);
1277 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1280 ret_val
= LTTNG_ERR_NOMEM
;
1287 int utils_parse_unsigned_long_long(const char *str
,
1288 unsigned long long *value
)
1294 LTTNG_ASSERT(value
);
1297 *value
= strtoull(str
, &endptr
, 10);
1299 /* Conversion failed. Out of range? */
1301 /* Don't print an error; allow the caller to log a better error. */
1302 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1308 /* Not the end of the string or empty string. */
1309 if (*endptr
|| endptr
== str
) {
1310 DBG("Failed to parse string as unsigned long long number: string = '%s'",