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
);
244 PERROR("Failed to close `%s` file descriptor while handling fdopen error", filepath
);
250 ret
= fprintf(fp
, "%d\n", (int) pid
);
252 PERROR("fprintf file %s", filepath
);
257 DBG("'%d' written in file %s", (int) pid
, filepath
);
261 if (fp
&& fclose(fp
)) {
262 PERROR("fclose file %s", filepath
);
268 * Create lock file to the given path and filename.
269 * Returns the associated file descriptor, -1 on error.
272 int utils_create_lock_file(const char *filepath
)
280 memset(&lock
, 0, sizeof(lock
));
281 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
284 PERROR("open lock file %s", filepath
);
290 * Attempt to lock the file. If this fails, there is
291 * already a process using the same lock file running
292 * and we should exit.
294 lock
.l_whence
= SEEK_SET
;
295 lock
.l_type
= F_WRLCK
;
297 ret
= fcntl(fd
, F_SETLK
, &lock
);
299 PERROR("fcntl lock file");
300 ERR("Could not get lock file %s, another instance is running.",
303 PERROR("close lock file");
314 * Create directory using the given path and mode.
316 * On success, return 0 else a negative error code.
319 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
322 struct lttng_directory_handle
*handle
;
323 const struct lttng_credentials creds
= {
324 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
325 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
328 handle
= lttng_directory_handle_create(NULL
);
333 ret
= lttng_directory_handle_create_subdirectory_as_user(
335 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
337 lttng_directory_handle_put(handle
);
342 * Recursively create directory using the given path and mode, under the
343 * provided uid and gid.
345 * On success, return 0 else a negative error code.
348 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
351 struct lttng_directory_handle
*handle
;
352 const struct lttng_credentials creds
= {
353 .uid
= LTTNG_OPTIONAL_INIT_VALUE(uid
),
354 .gid
= LTTNG_OPTIONAL_INIT_VALUE(gid
),
357 handle
= lttng_directory_handle_create(NULL
);
362 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
364 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
366 lttng_directory_handle_put(handle
);
371 * out_stream_path is the output parameter.
373 * Return 0 on success or else a negative value.
376 int utils_stream_file_path(const char *path_name
, const char *file_name
,
377 uint64_t size
, uint64_t count
, const char *suffix
,
378 char *out_stream_path
, size_t stream_path_len
)
381 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
382 const char *path_separator
;
384 if (path_name
&& (path_name
[0] == '\0' ||
385 path_name
[strlen(path_name
) - 1] == '/')) {
388 path_separator
= "/";
391 path_name
= path_name
? : "";
392 suffix
= suffix
? : "";
394 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
396 assert(ret
> 0 && ret
< sizeof(count_str
));
399 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
400 path_name
, path_separator
, file_name
, count_str
,
402 if (ret
< 0 || ret
>= stream_path_len
) {
403 ERR("Truncation occurred while formatting stream path");
412 * Parse a string that represents a size in human readable format. It
413 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
415 * The suffix multiply the integer by:
420 * @param str The string to parse.
421 * @param size Pointer to a uint64_t that will be filled with the
424 * @return 0 on success, -1 on failure.
427 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
436 DBG("utils_parse_size_suffix: received a NULL string.");
441 /* strtoull will accept a negative number, but we don't want to. */
442 if (strchr(str
, '-') != NULL
) {
443 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
448 /* str_end will point to the \0 */
449 str_end
= str
+ strlen(str
);
451 base_size
= strtoull(str
, &num_end
, 0);
453 PERROR("utils_parse_size_suffix strtoull");
458 if (num_end
== str
) {
459 /* strtoull parsed nothing, not good. */
460 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
465 /* Check if a prefix is present. */
483 DBG("utils_parse_size_suffix: invalid suffix.");
488 /* Check for garbage after the valid input. */
489 if (num_end
!= str_end
) {
490 DBG("utils_parse_size_suffix: Garbage after size string.");
495 *size
= base_size
<< shift
;
497 /* Check for overflow */
498 if ((*size
>> shift
) != base_size
) {
499 DBG("utils_parse_size_suffix: oops, overflow detected.");
510 * Parse a string that represents a time in human readable format. It
511 * supports decimal integers suffixed by:
512 * "us" for microsecond,
513 * "ms" for millisecond,
518 * The suffix multiply the integer by:
525 * Note that unit-less numbers are assumed to be microseconds.
527 * @param str The string to parse, assumed to be NULL-terminated.
528 * @param time_us Pointer to a uint64_t that will be filled with the
529 * resulting time in microseconds.
531 * @return 0 on success, -1 on failure.
534 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
538 uint64_t multiplier
= 1;
543 DBG("utils_parse_time_suffix: received a NULL string.");
548 /* strtoull will accept a negative number, but we don't want to. */
549 if (strchr(str
, '-') != NULL
) {
550 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
555 /* str_end will point to the \0 */
556 str_end
= str
+ strlen(str
);
558 base_time
= strtoull(str
, &num_end
, 10);
560 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
565 if (num_end
== str
) {
566 /* strtoull parsed nothing, not good. */
567 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
572 /* Check if a prefix is present. */
578 * Skip the "us" if the string matches the "us" suffix,
579 * otherwise let the check for the end of the string handle
580 * the error reporting.
582 if (*(num_end
+ 1) == 's') {
587 if (*(num_end
+ 1) == 's') {
588 /* Millisecond (ms) */
589 multiplier
= USEC_PER_MSEC
;
594 multiplier
= USEC_PER_MINUTE
;
600 multiplier
= USEC_PER_SEC
;
605 multiplier
= USEC_PER_HOURS
;
611 DBG("utils_parse_time_suffix: invalid suffix.");
616 /* Check for garbage after the valid input. */
617 if (num_end
!= str_end
) {
618 DBG("utils_parse_time_suffix: Garbage after time string.");
623 *time_us
= base_time
* multiplier
;
625 /* Check for overflow */
626 if ((*time_us
/ multiplier
) != base_time
) {
627 DBG("utils_parse_time_suffix: oops, overflow detected.");
638 * fls: returns the position of the most significant bit.
639 * Returns 0 if no bit is set, else returns the position of the most
640 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
642 #if defined(__i386) || defined(__x86_64)
643 static inline unsigned int fls_u32(uint32_t x
)
651 : "=r" (r
) : "rm" (x
));
657 #if defined(__x86_64) && defined(__LP64__)
659 unsigned int fls_u64(uint64_t x
)
667 : "=r" (r
) : "rm" (x
));
674 static __attribute__((unused
))
675 unsigned int fls_u64(uint64_t x
)
682 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
686 if (!(x
& 0xFFFF000000000000ULL
)) {
690 if (!(x
& 0xFF00000000000000ULL
)) {
694 if (!(x
& 0xF000000000000000ULL
)) {
698 if (!(x
& 0xC000000000000000ULL
)) {
702 if (!(x
& 0x8000000000000000ULL
)) {
711 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
718 if (!(x
& 0xFFFF0000U
)) {
722 if (!(x
& 0xFF000000U
)) {
726 if (!(x
& 0xF0000000U
)) {
730 if (!(x
& 0xC0000000U
)) {
734 if (!(x
& 0x80000000U
)) {
743 * Return the minimum order for which x <= (1UL << order).
744 * Return -1 if x is 0.
747 int utils_get_count_order_u32(uint32_t x
)
753 return fls_u32(x
- 1);
757 * Return the minimum order for which x <= (1UL << order).
758 * Return -1 if x is 0.
761 int utils_get_count_order_u64(uint64_t x
)
767 return fls_u64(x
- 1);
771 * Obtain the value of LTTNG_HOME environment variable, if exists.
772 * Otherwise returns the value of HOME.
775 const char *utils_get_home_dir(void)
780 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
784 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
789 /* Fallback on the password file entry. */
790 pwd
= getpwuid(getuid());
796 DBG3("Home directory is '%s'", val
);
803 * Get user's home directory. Dynamically allocated, must be freed
807 char *utils_get_user_home_dir(uid_t uid
)
810 struct passwd
*result
;
811 char *home_dir
= NULL
;
816 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
821 buf
= zmalloc(buflen
);
826 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
827 if (ret
|| !result
) {
836 home_dir
= strdup(pwd
.pw_dir
);
843 * With the given format, fill dst with the time of len maximum siz.
845 * Return amount of bytes set in the buffer or else 0 on error.
848 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
857 /* Get date and time for session path */
859 timeinfo
= localtime(&rawtime
);
860 ret
= strftime(dst
, len
, format
, timeinfo
);
862 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
870 * Return 0 on success and set *gid to the group_ID matching the passed name.
871 * Else -1 if it cannot be found or an error occurred.
874 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
876 static volatile int warn_once
;
881 struct group
*result
;
882 struct lttng_dynamic_buffer buffer
;
884 /* Get the system limit, if it exists. */
885 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
889 len
= (size_t) sys_len
;
892 lttng_dynamic_buffer_init(&buffer
);
893 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
895 ERR("Failed to allocate group info buffer");
900 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
901 const size_t new_len
= 2 * buffer
.size
;
903 /* Buffer is not big enough, increase its size. */
904 if (new_len
< buffer
.size
) {
905 ERR("Group info buffer size overflow");
910 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
912 ERR("Failed to grow group info buffer to %zu bytes",
920 DBG("Could not find group file entry for group name '%s'",
923 PERROR("Failed to get group file entry for group name '%s'",
931 /* Group not found. */
937 *gid
= result
->gr_gid
;
941 if (ret
&& warn
&& !warn_once
) {
942 WARN("No tracing group detected");
945 lttng_dynamic_buffer_reset(&buffer
);
950 * Return a newly allocated option string. This string is to be used as the
951 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
952 * of elements in the long_options array. Returns NULL if the string's
956 char *utils_generate_optstring(const struct option
*long_options
,
960 size_t string_len
= opt_count
, str_pos
= 0;
964 * Compute the necessary string length. One letter per option, two when an
965 * argument is necessary, and a trailing NULL.
967 for (i
= 0; i
< opt_count
; i
++) {
968 string_len
+= long_options
[i
].has_arg
? 1 : 0;
971 optstring
= zmalloc(string_len
);
976 for (i
= 0; i
< opt_count
; i
++) {
977 if (!long_options
[i
].name
) {
978 /* Got to the trailing NULL element */
982 if (long_options
[i
].val
!= '\0') {
983 optstring
[str_pos
++] = (char) long_options
[i
].val
;
984 if (long_options
[i
].has_arg
) {
985 optstring
[str_pos
++] = ':';
995 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
996 * any file. Try to rmdir any empty directory within the hierarchy.
999 int utils_recursive_rmdir(const char *path
)
1002 struct lttng_directory_handle
*handle
;
1004 handle
= lttng_directory_handle_create(NULL
);
1009 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
1011 lttng_directory_handle_put(handle
);
1016 int utils_truncate_stream_file(int fd
, off_t length
)
1021 ret
= ftruncate(fd
, length
);
1023 PERROR("ftruncate");
1026 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1027 if (lseek_ret
< 0) {
1036 static const char *get_man_bin_path(void)
1038 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1041 return env_man_path
;
1044 return DEFAULT_MAN_BIN_PATH
;
1048 int utils_show_help(int section
, const char *page_name
,
1049 const char *help_msg
)
1051 char section_string
[8];
1052 const char *man_bin_path
= get_man_bin_path();
1056 printf("%s", help_msg
);
1060 /* Section integer -> section string */
1061 ret
= sprintf(section_string
, "%d", section
);
1062 assert(ret
> 0 && ret
< 8);
1065 * Execute man pager.
1067 * We provide -M to man here because LTTng-tools can
1068 * be installed outside /usr, in which case its man pages are
1069 * not located in the default /usr/share/man directory.
1071 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1072 section_string
, page_name
, NULL
);
1079 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1083 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1085 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1086 if (!proc_meminfo
) {
1087 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1093 * Read the contents of /proc/meminfo line by line to find the right
1096 while (!feof(proc_meminfo
)) {
1099 ret
= fscanf(proc_meminfo
,
1100 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1104 * fscanf() returning EOF can indicate EOF or an error.
1106 if (ferror(proc_meminfo
)) {
1107 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1112 if (ret
== 2 && strcmp(name
, field
) == 0) {
1114 * This number is displayed in kilo-bytes. Return the
1117 if (value_kb
> UINT64_MAX
/ 1024) {
1118 ERR("Overflow on kb to bytes conversion");
1122 *value
= value_kb
* 1024;
1127 /* Reached the end of the file without finding the right field. */
1131 fclose(proc_meminfo
);
1137 * Returns an estimate of the number of bytes of memory available based on the
1138 * the information in `/proc/meminfo`. The number returned by this function is
1142 int utils_get_memory_available(uint64_t *value
)
1144 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1148 * Returns the total size of the memory on the system in bytes based on the
1149 * the information in `/proc/meminfo`.
1152 int utils_get_memory_total(uint64_t *value
)
1154 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1158 int utils_change_working_directory(const char *path
)
1164 DBG("Changing working directory to \"%s\"", path
);
1167 PERROR("Failed to change working directory to \"%s\"", path
);
1171 /* Check for write access */
1172 if (access(path
, W_OK
)) {
1173 if (errno
== EACCES
) {
1175 * Do not treat this as an error since the permission
1176 * might change in the lifetime of the process
1178 DBG("Working directory \"%s\" is not writable", path
);
1180 PERROR("Failed to check if working directory \"%s\" is writable",
1190 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1192 struct passwd p
, *pres
;
1194 enum lttng_error_code ret_val
= LTTNG_OK
;
1198 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1200 buflen
= FALLBACK_USER_BUFLEN
;
1203 buf
= zmalloc(buflen
);
1205 ret_val
= LTTNG_ERR_NOMEM
;
1210 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1217 buf
= zmalloc(buflen
);
1219 ret_val
= LTTNG_ERR_NOMEM
;
1232 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1235 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1236 user_name
, (int64_t) *uid
);
1244 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1247 ret_val
= LTTNG_ERR_NOMEM
;
1255 enum lttng_error_code
utils_group_id_from_name(
1256 const char *group_name
, gid_t
*gid
)
1258 struct group g
, *gres
;
1260 enum lttng_error_code ret_val
= LTTNG_OK
;
1264 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1266 buflen
= FALLBACK_GROUP_BUFLEN
;
1269 buf
= zmalloc(buflen
);
1271 ret_val
= LTTNG_ERR_NOMEM
;
1276 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1283 buf
= zmalloc(buflen
);
1285 ret_val
= LTTNG_ERR_NOMEM
;
1298 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1301 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1302 group_name
, (int64_t) *gid
);
1310 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1313 ret_val
= LTTNG_ERR_NOMEM
;
1321 int utils_parse_unsigned_long_long(const char *str
,
1322 unsigned long long *value
)
1331 *value
= strtoull(str
, &endptr
, 10);
1333 /* Conversion failed. Out of range? */
1335 /* Don't print an error; allow the caller to log a better error. */
1336 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1342 /* Not the end of the string or empty string. */
1343 if (*endptr
|| endptr
== str
) {
1344 DBG("Failed to parse string as unsigned long long number: string = '%s'",