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"
17 #include <sys/types.h>
25 #include <common/common.h>
26 #include <common/readwrite.h>
27 #include <common/runas.h>
28 #include <common/compat/getenv.h>
29 #include <common/compat/string.h>
30 #include <common/compat/dirent.h>
31 #include <common/compat/directory-handle.h>
32 #include <common/dynamic-buffer.h>
33 #include <common/string-utils/format.h>
34 #include <lttng/constant.h>
40 #define PROC_MEMINFO_PATH "/proc/meminfo"
41 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
42 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
44 /* The length of the longest field of `/proc/meminfo`. */
45 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
47 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
48 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
50 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
53 #define FALLBACK_USER_BUFLEN 16384
54 #define FALLBACK_GROUP_BUFLEN 16384
57 * Create a pipe in dst.
60 int utils_create_pipe(int *dst
)
70 PERROR("create pipe");
77 * Create pipe and set CLOEXEC flag to both fd.
79 * Make sure the pipe opened by this function are closed at some point. Use
83 int utils_create_pipe_cloexec(int *dst
)
91 ret
= utils_create_pipe(dst
);
96 for (i
= 0; i
< 2; i
++) {
97 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
99 PERROR("fcntl pipe cloexec");
109 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
111 * Make sure the pipe opened by this function are closed at some point. Use
112 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
113 * support OSes other than Linux 2.6.23+.
116 int utils_create_pipe_cloexec_nonblock(int *dst
)
124 ret
= utils_create_pipe(dst
);
129 for (i
= 0; i
< 2; i
++) {
130 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
132 PERROR("fcntl pipe cloexec");
136 * Note: we override any flag that could have been
137 * previously set on the fd.
139 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
141 PERROR("fcntl pipe nonblock");
151 * Close both read and write side of the pipe.
154 void utils_close_pipe(int *src
)
162 for (i
= 0; i
< 2; i
++) {
170 PERROR("close pipe");
177 * Create a new string using two strings range.
180 char *utils_strdupdelim(const char *begin
, const char *end
)
184 str
= zmalloc(end
- begin
+ 1);
186 PERROR("zmalloc strdupdelim");
190 memcpy(str
, begin
, end
- begin
);
191 str
[end
- begin
] = '\0';
198 * Set CLOEXEC flag to the give file descriptor.
201 int utils_set_fd_cloexec(int fd
)
210 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
212 PERROR("fcntl cloexec");
221 * Create pid file to the given path and filename.
224 int utils_create_pid_file(pid_t pid
, const char *filepath
)
231 fp
= fopen(filepath
, "w");
233 PERROR("open pid file %s", filepath
);
238 ret
= fprintf(fp
, "%d\n", (int) pid
);
240 PERROR("fprintf pid file");
247 DBG("Pid %d written in file %s", (int) pid
, filepath
);
254 * Create lock file to the given path and filename.
255 * Returns the associated file descriptor, -1 on error.
258 int utils_create_lock_file(const char *filepath
)
266 memset(&lock
, 0, sizeof(lock
));
267 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
270 PERROR("open lock file %s", filepath
);
276 * Attempt to lock the file. If this fails, there is
277 * already a process using the same lock file running
278 * and we should exit.
280 lock
.l_whence
= SEEK_SET
;
281 lock
.l_type
= F_WRLCK
;
283 ret
= fcntl(fd
, F_SETLK
, &lock
);
285 PERROR("fcntl lock file");
286 ERR("Could not get lock file %s, another instance is running.",
289 PERROR("close lock file");
300 * Create directory using the given path and mode.
302 * 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
),
311 .gid
= LTTNG_OPTIONAL_INIT_VALUE(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.
334 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
337 struct lttng_directory_handle
*handle
;
338 const struct lttng_credentials creds
= {
339 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
340 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
343 handle
= lttng_directory_handle_create(NULL
);
348 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
350 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
352 lttng_directory_handle_put(handle
);
357 * out_stream_path is the output parameter.
359 * Return 0 on success or else a negative value.
362 int utils_stream_file_path(const char *path_name
, const char *file_name
,
363 uint64_t size
, uint64_t count
, const char *suffix
,
364 char *out_stream_path
, size_t stream_path_len
)
367 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
368 const char *path_separator
;
370 if (path_name
&& (path_name
[0] == '\0' ||
371 path_name
[strlen(path_name
) - 1] == '/')) {
374 path_separator
= "/";
377 path_name
= path_name
? : "";
378 suffix
= suffix
? : "";
380 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
382 assert(ret
> 0 && ret
< sizeof(count_str
));
385 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
386 path_name
, path_separator
, file_name
, count_str
,
388 if (ret
< 0 || ret
>= stream_path_len
) {
389 ERR("Truncation occurred while formatting stream path");
398 * Parse a string that represents a size in human readable format. It
399 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
401 * The suffix multiply the integer by:
406 * @param str The string to parse.
407 * @param size Pointer to a uint64_t that will be filled with the
410 * @return 0 on success, -1 on failure.
413 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
422 DBG("utils_parse_size_suffix: received a NULL string.");
427 /* strtoull will accept a negative number, but we don't want to. */
428 if (strchr(str
, '-') != NULL
) {
429 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
434 /* str_end will point to the \0 */
435 str_end
= str
+ strlen(str
);
437 base_size
= strtoull(str
, &num_end
, 0);
439 PERROR("utils_parse_size_suffix strtoull");
444 if (num_end
== str
) {
445 /* strtoull parsed nothing, not good. */
446 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
451 /* Check if a prefix is present. */
469 DBG("utils_parse_size_suffix: invalid suffix.");
474 /* Check for garbage after the valid input. */
475 if (num_end
!= str_end
) {
476 DBG("utils_parse_size_suffix: Garbage after size string.");
481 *size
= base_size
<< shift
;
483 /* Check for overflow */
484 if ((*size
>> shift
) != base_size
) {
485 DBG("utils_parse_size_suffix: oops, overflow detected.");
496 * Parse a string that represents a time in human readable format. It
497 * supports decimal integers suffixed by:
498 * "us" for microsecond,
499 * "ms" for millisecond,
504 * The suffix multiply the integer by:
511 * Note that unit-less numbers are assumed to be microseconds.
513 * @param str The string to parse, assumed to be NULL-terminated.
514 * @param time_us Pointer to a uint64_t that will be filled with the
515 * resulting time in microseconds.
517 * @return 0 on success, -1 on failure.
520 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
524 uint64_t multiplier
= 1;
529 DBG("utils_parse_time_suffix: received a NULL string.");
534 /* strtoull will accept a negative number, but we don't want to. */
535 if (strchr(str
, '-') != NULL
) {
536 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
541 /* str_end will point to the \0 */
542 str_end
= str
+ strlen(str
);
544 base_time
= strtoull(str
, &num_end
, 10);
546 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
551 if (num_end
== str
) {
552 /* strtoull parsed nothing, not good. */
553 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
558 /* Check if a prefix is present. */
564 * Skip the "us" if the string matches the "us" suffix,
565 * otherwise let the check for the end of the string handle
566 * the error reporting.
568 if (*(num_end
+ 1) == 's') {
573 if (*(num_end
+ 1) == 's') {
574 /* Millisecond (ms) */
575 multiplier
= USEC_PER_MSEC
;
580 multiplier
= USEC_PER_MINUTE
;
586 multiplier
= USEC_PER_SEC
;
591 multiplier
= USEC_PER_HOURS
;
597 DBG("utils_parse_time_suffix: invalid suffix.");
602 /* Check for garbage after the valid input. */
603 if (num_end
!= str_end
) {
604 DBG("utils_parse_time_suffix: Garbage after time string.");
609 *time_us
= base_time
* multiplier
;
611 /* Check for overflow */
612 if ((*time_us
/ multiplier
) != base_time
) {
613 DBG("utils_parse_time_suffix: oops, overflow detected.");
624 * fls: returns the position of the most significant bit.
625 * Returns 0 if no bit is set, else returns the position of the most
626 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
628 #if defined(__i386) || defined(__x86_64)
629 static inline unsigned int fls_u32(uint32_t x
)
637 : "=r" (r
) : "rm" (x
));
643 #if defined(__x86_64) && defined(__LP64__)
645 unsigned int fls_u64(uint64_t x
)
653 : "=r" (r
) : "rm" (x
));
660 static __attribute__((unused
))
661 unsigned int fls_u64(uint64_t x
)
668 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
672 if (!(x
& 0xFFFF000000000000ULL
)) {
676 if (!(x
& 0xFF00000000000000ULL
)) {
680 if (!(x
& 0xF000000000000000ULL
)) {
684 if (!(x
& 0xC000000000000000ULL
)) {
688 if (!(x
& 0x8000000000000000ULL
)) {
697 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
704 if (!(x
& 0xFFFF0000U
)) {
708 if (!(x
& 0xFF000000U
)) {
712 if (!(x
& 0xF0000000U
)) {
716 if (!(x
& 0xC0000000U
)) {
720 if (!(x
& 0x80000000U
)) {
729 * Return the minimum order for which x <= (1UL << order).
730 * Return -1 if x is 0.
733 int utils_get_count_order_u32(uint32_t x
)
739 return fls_u32(x
- 1);
743 * Return the minimum order for which x <= (1UL << order).
744 * Return -1 if x is 0.
747 int utils_get_count_order_u64(uint64_t x
)
753 return fls_u64(x
- 1);
757 * Obtain the value of LTTNG_HOME environment variable, if exists.
758 * Otherwise returns the value of HOME.
761 const char *utils_get_home_dir(void)
766 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
770 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
775 /* Fallback on the password file entry. */
776 pwd
= getpwuid(getuid());
782 DBG3("Home directory is '%s'", val
);
789 * Get user's home directory. Dynamically allocated, must be freed
793 char *utils_get_user_home_dir(uid_t uid
)
796 struct passwd
*result
;
797 char *home_dir
= NULL
;
802 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
807 buf
= zmalloc(buflen
);
812 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
813 if (ret
|| !result
) {
822 home_dir
= strdup(pwd
.pw_dir
);
829 * With the given format, fill dst with the time of len maximum siz.
831 * Return amount of bytes set in the buffer or else 0 on error.
834 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
843 /* Get date and time for session path */
845 timeinfo
= localtime(&rawtime
);
846 ret
= strftime(dst
, len
, format
, timeinfo
);
848 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
856 * Return 0 on success and set *gid to the group_ID matching the passed name.
857 * Else -1 if it cannot be found or an error occurred.
860 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
862 static volatile int warn_once
;
867 struct group
*result
;
868 struct lttng_dynamic_buffer buffer
;
870 /* Get the system limit, if it exists. */
871 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
875 len
= (size_t) sys_len
;
878 lttng_dynamic_buffer_init(&buffer
);
879 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
881 ERR("Failed to allocate group info buffer");
886 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
887 const size_t new_len
= 2 * buffer
.size
;
889 /* Buffer is not big enough, increase its size. */
890 if (new_len
< buffer
.size
) {
891 ERR("Group info buffer size overflow");
896 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
898 ERR("Failed to grow group info buffer to %zu bytes",
906 DBG("Could not find group file entry for group name '%s'",
909 PERROR("Failed to get group file entry for group name '%s'",
917 /* Group not found. */
923 *gid
= result
->gr_gid
;
927 if (ret
&& warn
&& !warn_once
) {
928 WARN("No tracing group detected");
931 lttng_dynamic_buffer_reset(&buffer
);
936 * Return a newly allocated option string. This string is to be used as the
937 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
938 * of elements in the long_options array. Returns NULL if the string's
942 char *utils_generate_optstring(const struct option
*long_options
,
946 size_t string_len
= opt_count
, str_pos
= 0;
950 * Compute the necessary string length. One letter per option, two when an
951 * argument is necessary, and a trailing NULL.
953 for (i
= 0; i
< opt_count
; i
++) {
954 string_len
+= long_options
[i
].has_arg
? 1 : 0;
957 optstring
= zmalloc(string_len
);
962 for (i
= 0; i
< opt_count
; i
++) {
963 if (!long_options
[i
].name
) {
964 /* Got to the trailing NULL element */
968 if (long_options
[i
].val
!= '\0') {
969 optstring
[str_pos
++] = (char) long_options
[i
].val
;
970 if (long_options
[i
].has_arg
) {
971 optstring
[str_pos
++] = ':';
981 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
982 * any file. Try to rmdir any empty directory within the hierarchy.
985 int utils_recursive_rmdir(const char *path
)
988 struct lttng_directory_handle
*handle
;
990 handle
= lttng_directory_handle_create(NULL
);
995 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
997 lttng_directory_handle_put(handle
);
1002 int utils_truncate_stream_file(int fd
, off_t length
)
1007 ret
= ftruncate(fd
, length
);
1009 PERROR("ftruncate");
1012 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1013 if (lseek_ret
< 0) {
1022 static const char *get_man_bin_path(void)
1024 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1027 return env_man_path
;
1030 return DEFAULT_MAN_BIN_PATH
;
1034 int utils_show_help(int section
, const char *page_name
,
1035 const char *help_msg
)
1037 char section_string
[8];
1038 const char *man_bin_path
= get_man_bin_path();
1042 printf("%s", help_msg
);
1046 /* Section integer -> section string */
1047 ret
= sprintf(section_string
, "%d", section
);
1048 assert(ret
> 0 && ret
< 8);
1051 * Execute man pager.
1053 * We provide -M to man here because LTTng-tools can
1054 * be installed outside /usr, in which case its man pages are
1055 * not located in the default /usr/share/man directory.
1057 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1058 section_string
, page_name
, NULL
);
1065 int read_proc_meminfo_field(const char *field
, size_t *value
)
1069 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1071 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1072 if (!proc_meminfo
) {
1073 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1079 * Read the contents of /proc/meminfo line by line to find the right
1082 while (!feof(proc_meminfo
)) {
1083 unsigned long value_kb
;
1085 ret
= fscanf(proc_meminfo
,
1086 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %lu kB\n",
1090 * fscanf() returning EOF can indicate EOF or an error.
1092 if (ferror(proc_meminfo
)) {
1093 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1098 if (ret
== 2 && strcmp(name
, field
) == 0) {
1100 * This number is displayed in kilo-bytes. Return the
1103 *value
= ((size_t) value_kb
) * 1024;
1108 /* Reached the end of the file without finding the right field. */
1112 fclose(proc_meminfo
);
1118 * Returns an estimate of the number of bytes of memory available based on the
1119 * the information in `/proc/meminfo`. The number returned by this function is
1123 int utils_get_memory_available(size_t *value
)
1125 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1129 * Returns the total size of the memory on the system in bytes based on the
1130 * the information in `/proc/meminfo`.
1133 int utils_get_memory_total(size_t *value
)
1135 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1139 int utils_change_working_directory(const char *path
)
1145 DBG("Changing working directory to \"%s\"", path
);
1148 PERROR("Failed to change working directory to \"%s\"", path
);
1152 /* Check for write access */
1153 if (access(path
, W_OK
)) {
1154 if (errno
== EACCES
) {
1156 * Do not treat this as an error since the permission
1157 * might change in the lifetime of the process
1159 DBG("Working directory \"%s\" is not writable", path
);
1161 PERROR("Failed to check if working directory \"%s\" is writable",
1171 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1173 struct passwd p
, *pres
;
1175 enum lttng_error_code ret_val
= LTTNG_OK
;
1179 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1181 buflen
= FALLBACK_USER_BUFLEN
;
1184 buf
= zmalloc(buflen
);
1186 ret_val
= LTTNG_ERR_NOMEM
;
1191 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1198 buf
= zmalloc(buflen
);
1200 ret_val
= LTTNG_ERR_NOMEM
;
1213 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1216 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1217 user_name
, (int64_t) *uid
);
1225 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1228 ret_val
= LTTNG_ERR_NOMEM
;
1236 enum lttng_error_code
utils_group_id_from_name(
1237 const char *group_name
, gid_t
*gid
)
1239 struct group g
, *gres
;
1241 enum lttng_error_code ret_val
= LTTNG_OK
;
1245 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1247 buflen
= FALLBACK_GROUP_BUFLEN
;
1250 buf
= zmalloc(buflen
);
1252 ret_val
= LTTNG_ERR_NOMEM
;
1257 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1264 buf
= zmalloc(buflen
);
1266 ret_val
= LTTNG_ERR_NOMEM
;
1279 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1282 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1283 group_name
, (int64_t) *gid
);
1291 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1294 ret_val
= LTTNG_ERR_NOMEM
;
1302 int utils_parse_unsigned_long_long(const char *str
,
1303 unsigned long long *value
)
1312 *value
= strtoull(str
, &endptr
, 10);
1314 /* Conversion failed. Out of range? */
1316 /* Don't print an error; allow the caller to log a better error. */
1317 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1323 /* Not the end of the string or empty string. */
1324 if (*endptr
|| endptr
== str
) {
1325 DBG("Failed to parse string as unsigned long long number: string = '%s'",