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 directory using the given path and mode.
270 * On success, return 0 else a negative error code.
273 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
276 struct lttng_directory_handle
*handle
;
277 const struct lttng_credentials creds
= {
282 handle
= lttng_directory_handle_create(NULL
);
287 ret
= lttng_directory_handle_create_subdirectory_as_user(
289 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
291 lttng_directory_handle_put(handle
);
296 * Recursively create directory using the given path and mode, under the
297 * provided uid and gid.
299 * On success, return 0 else a negative error code.
302 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
305 struct lttng_directory_handle
*handle
;
306 const struct lttng_credentials creds
= {
311 handle
= lttng_directory_handle_create(NULL
);
316 ret
= lttng_directory_handle_create_subdirectory_recursive_as_user(
318 (uid
>= 0 || gid
>= 0) ? &creds
: NULL
);
320 lttng_directory_handle_put(handle
);
325 * out_stream_path is the output parameter.
327 * Return 0 on success or else a negative value.
330 int utils_stream_file_path(const char *path_name
, const char *file_name
,
331 uint64_t size
, uint64_t count
, const char *suffix
,
332 char *out_stream_path
, size_t stream_path_len
)
335 char count_str
[MAX_INT_DEC_LEN(count
) + 1] = {};
336 const char *path_separator
;
338 if (path_name
&& (path_name
[0] == '\0' ||
339 path_name
[strlen(path_name
) - 1] == '/')) {
342 path_separator
= "/";
345 path_name
= path_name
? : "";
346 suffix
= suffix
? : "";
348 ret
= snprintf(count_str
, sizeof(count_str
), "_%" PRIu64
,
350 assert(ret
> 0 && ret
< sizeof(count_str
));
353 ret
= snprintf(out_stream_path
, stream_path_len
, "%s%s%s%s%s",
354 path_name
, path_separator
, file_name
, count_str
,
356 if (ret
< 0 || ret
>= stream_path_len
) {
357 ERR("Truncation occurred while formatting stream path");
366 * Parse a string that represents a size in human readable format. It
367 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
369 * The suffix multiply the integer by:
374 * @param str The string to parse.
375 * @param size Pointer to a uint64_t that will be filled with the
378 * @return 0 on success, -1 on failure.
381 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
390 DBG("utils_parse_size_suffix: received a NULL string.");
395 /* strtoull will accept a negative number, but we don't want to. */
396 if (strchr(str
, '-') != NULL
) {
397 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
402 /* str_end will point to the \0 */
403 str_end
= str
+ strlen(str
);
405 base_size
= strtoull(str
, &num_end
, 0);
407 PERROR("utils_parse_size_suffix strtoull");
412 if (num_end
== str
) {
413 /* strtoull parsed nothing, not good. */
414 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
419 /* Check if a prefix is present. */
437 DBG("utils_parse_size_suffix: invalid suffix.");
442 /* Check for garbage after the valid input. */
443 if (num_end
!= str_end
) {
444 DBG("utils_parse_size_suffix: Garbage after size string.");
449 *size
= base_size
<< shift
;
451 /* Check for overflow */
452 if ((*size
>> shift
) != base_size
) {
453 DBG("utils_parse_size_suffix: oops, overflow detected.");
464 * Parse a string that represents a time in human readable format. It
465 * supports decimal integers suffixed by:
466 * "us" for microsecond,
467 * "ms" for millisecond,
472 * The suffix multiply the integer by:
479 * Note that unit-less numbers are assumed to be microseconds.
481 * @param str The string to parse, assumed to be NULL-terminated.
482 * @param time_us Pointer to a uint64_t that will be filled with the
483 * resulting time in microseconds.
485 * @return 0 on success, -1 on failure.
488 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
492 uint64_t multiplier
= 1;
497 DBG("utils_parse_time_suffix: received a NULL string.");
502 /* strtoull will accept a negative number, but we don't want to. */
503 if (strchr(str
, '-') != NULL
) {
504 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
509 /* str_end will point to the \0 */
510 str_end
= str
+ strlen(str
);
512 base_time
= strtoull(str
, &num_end
, 10);
514 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
519 if (num_end
== str
) {
520 /* strtoull parsed nothing, not good. */
521 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
526 /* Check if a prefix is present. */
532 * Skip the "us" if the string matches the "us" suffix,
533 * otherwise let the check for the end of the string handle
534 * the error reporting.
536 if (*(num_end
+ 1) == 's') {
541 if (*(num_end
+ 1) == 's') {
542 /* Millisecond (ms) */
543 multiplier
= USEC_PER_MSEC
;
548 multiplier
= USEC_PER_MINUTE
;
554 multiplier
= USEC_PER_SEC
;
559 multiplier
= USEC_PER_HOURS
;
565 DBG("utils_parse_time_suffix: invalid suffix.");
570 /* Check for garbage after the valid input. */
571 if (num_end
!= str_end
) {
572 DBG("utils_parse_time_suffix: Garbage after time string.");
577 *time_us
= base_time
* multiplier
;
579 /* Check for overflow */
580 if ((*time_us
/ multiplier
) != base_time
) {
581 DBG("utils_parse_time_suffix: oops, overflow detected.");
592 * fls: returns the position of the most significant bit.
593 * Returns 0 if no bit is set, else returns the position of the most
594 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
596 #if defined(__i386) || defined(__x86_64)
597 static inline unsigned int fls_u32(uint32_t x
)
605 : "=r" (r
) : "rm" (x
));
611 #if defined(__x86_64) && defined(__LP64__)
613 unsigned int fls_u64(uint64_t x
)
621 : "=r" (r
) : "rm" (x
));
628 static __attribute__((unused
))
629 unsigned int fls_u64(uint64_t x
)
636 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
640 if (!(x
& 0xFFFF000000000000ULL
)) {
644 if (!(x
& 0xFF00000000000000ULL
)) {
648 if (!(x
& 0xF000000000000000ULL
)) {
652 if (!(x
& 0xC000000000000000ULL
)) {
656 if (!(x
& 0x8000000000000000ULL
)) {
665 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
672 if (!(x
& 0xFFFF0000U
)) {
676 if (!(x
& 0xFF000000U
)) {
680 if (!(x
& 0xF0000000U
)) {
684 if (!(x
& 0xC0000000U
)) {
688 if (!(x
& 0x80000000U
)) {
697 * Return the minimum order for which x <= (1UL << order).
698 * Return -1 if x is 0.
701 int utils_get_count_order_u32(uint32_t x
)
707 return fls_u32(x
- 1);
711 * Return the minimum order for which x <= (1UL << order).
712 * Return -1 if x is 0.
715 int utils_get_count_order_u64(uint64_t x
)
721 return fls_u64(x
- 1);
725 * Obtain the value of LTTNG_HOME environment variable, if exists.
726 * Otherwise returns the value of HOME.
729 const char *utils_get_home_dir(void)
734 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
738 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
743 /* Fallback on the password file entry. */
744 pwd
= getpwuid(getuid());
750 DBG3("Home directory is '%s'", val
);
757 * Get user's home directory. Dynamically allocated, must be freed
761 char *utils_get_user_home_dir(uid_t uid
)
764 struct passwd
*result
;
765 char *home_dir
= NULL
;
770 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
775 buf
= zmalloc(buflen
);
780 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
781 if (ret
|| !result
) {
790 home_dir
= strdup(pwd
.pw_dir
);
797 * With the given format, fill dst with the time of len maximum siz.
799 * Return amount of bytes set in the buffer or else 0 on error.
802 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
811 /* Get date and time for session path */
813 timeinfo
= localtime(&rawtime
);
814 ret
= strftime(dst
, len
, format
, timeinfo
);
816 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
824 * Return 0 on success and set *gid to the group_ID matching the passed name.
825 * Else -1 if it cannot be found or an error occurred.
828 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
830 static volatile int warn_once
;
835 struct group
*result
;
836 struct lttng_dynamic_buffer buffer
;
838 /* Get the system limit, if it exists. */
839 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
843 len
= (size_t) sys_len
;
846 lttng_dynamic_buffer_init(&buffer
);
847 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
849 ERR("Failed to allocate group info buffer");
854 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
855 const size_t new_len
= 2 * buffer
.size
;
857 /* Buffer is not big enough, increase its size. */
858 if (new_len
< buffer
.size
) {
859 ERR("Group info buffer size overflow");
864 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
866 ERR("Failed to grow group info buffer to %zu bytes",
874 DBG("Could not find group file entry for group name '%s'",
877 PERROR("Failed to get group file entry for group name '%s'",
885 /* Group not found. */
891 *gid
= result
->gr_gid
;
895 if (ret
&& warn
&& !warn_once
) {
896 WARN("No tracing group detected");
899 lttng_dynamic_buffer_reset(&buffer
);
904 * Return a newly allocated option string. This string is to be used as the
905 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
906 * of elements in the long_options array. Returns NULL if the string's
910 char *utils_generate_optstring(const struct option
*long_options
,
914 size_t string_len
= opt_count
, str_pos
= 0;
918 * Compute the necessary string length. One letter per option, two when an
919 * argument is necessary, and a trailing NULL.
921 for (i
= 0; i
< opt_count
; i
++) {
922 string_len
+= long_options
[i
].has_arg
? 1 : 0;
925 optstring
= zmalloc(string_len
);
930 for (i
= 0; i
< opt_count
; i
++) {
931 if (!long_options
[i
].name
) {
932 /* Got to the trailing NULL element */
936 if (long_options
[i
].val
!= '\0') {
937 optstring
[str_pos
++] = (char) long_options
[i
].val
;
938 if (long_options
[i
].has_arg
) {
939 optstring
[str_pos
++] = ':';
949 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
950 * any file. Try to rmdir any empty directory within the hierarchy.
953 int utils_recursive_rmdir(const char *path
)
956 struct lttng_directory_handle
*handle
;
958 handle
= lttng_directory_handle_create(NULL
);
963 ret
= lttng_directory_handle_remove_subdirectory(handle
, path
);
965 lttng_directory_handle_put(handle
);
970 int utils_truncate_stream_file(int fd
, off_t length
)
975 ret
= ftruncate(fd
, length
);
980 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
990 static const char *get_man_bin_path(void)
992 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
998 return DEFAULT_MAN_BIN_PATH
;
1002 int utils_show_help(int section
, const char *page_name
,
1003 const char *help_msg
)
1005 char section_string
[8];
1006 const char *man_bin_path
= get_man_bin_path();
1010 printf("%s", help_msg
);
1014 /* Section integer -> section string */
1015 ret
= sprintf(section_string
, "%d", section
);
1016 assert(ret
> 0 && ret
< 8);
1019 * Execute man pager.
1021 * We provide -M to man here because LTTng-tools can
1022 * be installed outside /usr, in which case its man pages are
1023 * not located in the default /usr/share/man directory.
1025 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1026 section_string
, page_name
, NULL
);
1033 int read_proc_meminfo_field(const char *field
, uint64_t *value
)
1037 char name
[PROC_MEMINFO_FIELD_MAX_NAME_LEN
] = {};
1039 proc_meminfo
= fopen(PROC_MEMINFO_PATH
, "r");
1040 if (!proc_meminfo
) {
1041 PERROR("Failed to fopen() " PROC_MEMINFO_PATH
);
1047 * Read the contents of /proc/meminfo line by line to find the right
1050 while (!feof(proc_meminfo
)) {
1053 ret
= fscanf(proc_meminfo
,
1054 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API
"s %" SCNu64
" kB\n",
1058 * fscanf() returning EOF can indicate EOF or an error.
1060 if (ferror(proc_meminfo
)) {
1061 PERROR("Failed to parse " PROC_MEMINFO_PATH
);
1066 if (ret
== 2 && strcmp(name
, field
) == 0) {
1068 * This number is displayed in kilo-bytes. Return the
1071 if (value_kb
> UINT64_MAX
/ 1024) {
1072 ERR("Overflow on kb to bytes conversion");
1076 *value
= value_kb
* 1024;
1081 /* Reached the end of the file without finding the right field. */
1085 fclose(proc_meminfo
);
1091 * Returns an estimate of the number of bytes of memory available based on the
1092 * the information in `/proc/meminfo`. The number returned by this function is
1096 int utils_get_memory_available(uint64_t *value
)
1098 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE
, value
);
1102 * Returns the total size of the memory on the system in bytes based on the
1103 * the information in `/proc/meminfo`.
1106 int utils_get_memory_total(uint64_t *value
)
1108 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE
, value
);
1112 int utils_change_working_directory(const char *path
)
1118 DBG("Changing working directory to \"%s\"", path
);
1121 PERROR("Failed to change working directory to \"%s\"", path
);
1125 /* Check for write access */
1126 if (access(path
, W_OK
)) {
1127 if (errno
== EACCES
) {
1129 * Do not treat this as an error since the permission
1130 * might change in the lifetime of the process
1132 DBG("Working directory \"%s\" is not writable", path
);
1134 PERROR("Failed to check if working directory \"%s\" is writable",
1144 enum lttng_error_code
utils_user_id_from_name(const char *user_name
, uid_t
*uid
)
1146 struct passwd p
, *pres
;
1148 enum lttng_error_code ret_val
= LTTNG_OK
;
1152 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1154 buflen
= FALLBACK_USER_BUFLEN
;
1157 buf
= zmalloc(buflen
);
1159 ret_val
= LTTNG_ERR_NOMEM
;
1164 ret
= getpwnam_r(user_name
, &p
, buf
, buflen
, &pres
);
1171 buf
= zmalloc(buflen
);
1173 ret_val
= LTTNG_ERR_NOMEM
;
1186 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1189 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64
,
1190 user_name
, (int64_t) *uid
);
1198 ret_val
= LTTNG_ERR_USER_NOT_FOUND
;
1201 ret_val
= LTTNG_ERR_NOMEM
;
1209 enum lttng_error_code
utils_group_id_from_name(
1210 const char *group_name
, gid_t
*gid
)
1212 struct group g
, *gres
;
1214 enum lttng_error_code ret_val
= LTTNG_OK
;
1218 buflen
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1220 buflen
= FALLBACK_GROUP_BUFLEN
;
1223 buf
= zmalloc(buflen
);
1225 ret_val
= LTTNG_ERR_NOMEM
;
1230 ret
= getgrnam_r(group_name
, &g
, buf
, buflen
, &gres
);
1237 buf
= zmalloc(buflen
);
1239 ret_val
= LTTNG_ERR_NOMEM
;
1252 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1255 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64
,
1256 group_name
, (int64_t) *gid
);
1264 ret_val
= LTTNG_ERR_GROUP_NOT_FOUND
;
1267 ret_val
= LTTNG_ERR_NOMEM
;