2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 - Raphaël Beamonte <raphael.beamonte@gmail.com>
4 * Copyright (C) 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License, version 2 only, as
8 * published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 #include <sys/types.h>
36 #include <common/common.h>
37 #include <common/runas.h>
38 #include <common/compat/getenv.h>
44 * Return a partial realpath(3) of the path even if the full path does not
45 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
46 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
47 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
48 * point directory does not exist.
49 * In case resolved_path is NULL, the string returned was allocated in the
50 * function and thus need to be freed by the caller. The size argument allows
51 * to specify the size of the resolved_path argument if given, or the size to
55 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
57 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
58 const char *next
, *prev
, *end
;
66 * Identify the end of the path, we don't want to treat the
67 * last char if it is a '/', we will just keep it on the side
68 * to be added at the end, and return a value coherent with
69 * the path given as argument
71 end
= path
+ strlen(path
);
72 if (*(end
-1) == '/') {
76 /* Initiate the values of the pointers before looping */
79 /* Only to ensure try_path is not NULL to enter the while */
80 try_path
= (char *)next
;
82 /* Resolve the canonical path of the first part of the path */
83 while (try_path
!= NULL
&& next
!= end
) {
85 * If there is not any '/' left, we want to try with
88 next
= strpbrk(next
+ 1, "/");
93 /* Cut the part we will be trying to resolve */
94 cut_path
= strndup(path
, next
- path
);
95 if (cut_path
== NULL
) {
100 /* Try to resolve this part */
101 try_path
= realpath((char *)cut_path
, NULL
);
102 if (try_path
== NULL
) {
104 * There was an error, we just want to be assured it
105 * is linked to an unexistent directory, if it's another
106 * reason, we spawn an error
110 /* Ignore the error */
113 PERROR("realpath (partial_realpath)");
118 /* Save the place we are before trying the next step */
120 try_path_prev
= try_path
;
124 /* Free the allocated memory */
128 /* Allocate memory for the resolved path if necessary */
129 if (resolved_path
== NULL
) {
130 resolved_path
= zmalloc(size
);
131 if (resolved_path
== NULL
) {
132 PERROR("zmalloc resolved path");
138 * If we were able to solve at least partially the path, we can concatenate
139 * what worked and what didn't work
141 if (try_path_prev
!= NULL
) {
142 /* If we risk to concatenate two '/', we remove one of them */
143 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
144 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
148 * Duplicate the memory used by prev in case resolved_path and
149 * path are pointers for the same memory space
151 cut_path
= strdup(prev
);
152 if (cut_path
== NULL
) {
157 /* Concatenate the strings */
158 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
160 /* Free the allocated memory */
164 * Else, we just copy the path in our resolved_path to
168 strncpy(resolved_path
, path
, size
);
171 /* Then we return the 'partially' resolved path */
172 return resolved_path
;
180 * Make a full resolution of the given path even if it doesn't exist.
181 * This function uses the utils_partial_realpath function to resolve
182 * symlinks and relatives paths at the start of the string, and
183 * implements functionnalities to resolve the './' and '../' strings
184 * in the middle of a path. This function is only necessary because
185 * realpath(3) does not accept to resolve unexistent paths.
186 * The returned string was allocated in the function, it is thus of
187 * the responsibility of the caller to free this memory.
190 char *utils_expand_path(const char *path
)
192 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
194 int is_dot
, is_dotdot
;
201 /* Allocate memory for the absolute_path */
202 absolute_path
= zmalloc(PATH_MAX
);
203 if (absolute_path
== NULL
) {
204 PERROR("zmalloc expand path");
209 * If the path is not already absolute nor explicitly relative,
210 * consider we're in the current directory
212 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
213 strncmp(path
, "../", 3) != 0) {
214 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
215 /* Else, we just copy the path */
217 strncpy(absolute_path
, path
, PATH_MAX
);
220 /* Resolve partially our path */
221 absolute_path
= utils_partial_realpath(absolute_path
,
222 absolute_path
, PATH_MAX
);
224 /* As long as we find '/./' in the working_path string */
225 while ((next
= strstr(absolute_path
, "/./"))) {
227 /* We prepare the start_path not containing it */
228 start_path
= strndup(absolute_path
, next
- absolute_path
);
233 /* And we concatenate it with the part after this string */
234 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
239 /* As long as we find '/../' in the working_path string */
240 while ((next
= strstr(absolute_path
, "/../"))) {
241 /* We find the last level of directory */
242 previous
= absolute_path
;
243 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
244 previous
= slash
+ 1;
247 /* Then we prepare the start_path not containing it */
248 start_path
= strndup(absolute_path
, previous
- absolute_path
);
254 /* And we concatenate it with the part after the '/../' */
255 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
257 /* We can free the memory used for the start path*/
260 /* Then we verify for symlinks using partial_realpath */
261 absolute_path
= utils_partial_realpath(absolute_path
,
262 absolute_path
, PATH_MAX
);
265 /* Identify the last token */
266 last_token
= strrchr(absolute_path
, '/');
268 /* Verify that this token is not a relative path */
269 is_dotdot
= (strcmp(last_token
, "/..") == 0);
270 is_dot
= (strcmp(last_token
, "/.") == 0);
272 /* If it is, take action */
273 if (is_dot
|| is_dotdot
) {
274 /* For both, remove this token */
277 /* If it was a reference to parent directory, go back one more time */
279 last_token
= strrchr(absolute_path
, '/');
281 /* If there was only one level left, we keep the first '/' */
282 if (last_token
== absolute_path
) {
290 return absolute_path
;
298 * Create a pipe in dst.
301 int utils_create_pipe(int *dst
)
311 PERROR("create pipe");
318 * Create pipe and set CLOEXEC flag to both fd.
320 * Make sure the pipe opened by this function are closed at some point. Use
321 * utils_close_pipe().
324 int utils_create_pipe_cloexec(int *dst
)
332 ret
= utils_create_pipe(dst
);
337 for (i
= 0; i
< 2; i
++) {
338 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
340 PERROR("fcntl pipe cloexec");
350 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
352 * Make sure the pipe opened by this function are closed at some point. Use
353 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
354 * support OSes other than Linux 2.6.23+.
357 int utils_create_pipe_cloexec_nonblock(int *dst
)
365 ret
= utils_create_pipe(dst
);
370 for (i
= 0; i
< 2; i
++) {
371 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
373 PERROR("fcntl pipe cloexec");
377 * Note: we override any flag that could have been
378 * previously set on the fd.
380 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
382 PERROR("fcntl pipe nonblock");
392 * Close both read and write side of the pipe.
395 void utils_close_pipe(int *src
)
403 for (i
= 0; i
< 2; i
++) {
411 PERROR("close pipe");
417 * Create a new string using two strings range.
420 char *utils_strdupdelim(const char *begin
, const char *end
)
424 str
= zmalloc(end
- begin
+ 1);
426 PERROR("zmalloc strdupdelim");
430 memcpy(str
, begin
, end
- begin
);
431 str
[end
- begin
] = '\0';
438 * Set CLOEXEC flag to the give file descriptor.
441 int utils_set_fd_cloexec(int fd
)
450 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
452 PERROR("fcntl cloexec");
461 * Create pid file to the given path and filename.
464 int utils_create_pid_file(pid_t pid
, const char *filepath
)
471 fp
= fopen(filepath
, "w");
473 PERROR("open pid file %s", filepath
);
478 ret
= fprintf(fp
, "%d\n", pid
);
480 PERROR("fprintf pid file");
487 DBG("Pid %d written in file %s", pid
, filepath
);
494 * Create lock file to the given path and filename.
495 * Returns the associated file descriptor, -1 on error.
498 int utils_create_lock_file(const char *filepath
)
505 fd
= open(filepath
, O_CREAT
,
506 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
508 PERROR("open lock file %s", filepath
);
514 * Attempt to lock the file. If this fails, there is
515 * already a process using the same lock file running
516 * and we should exit.
518 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
520 ERR("Could not get lock file %s, another instance is running.",
523 PERROR("close lock file");
534 * Recursively create directory using the given path and mode.
536 * On success, return 0 else a negative error code.
539 int utils_mkdir_recursive(const char *path
, mode_t mode
)
541 char *p
, tmp
[PATH_MAX
];
547 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
549 PERROR("snprintf mkdir");
554 if (tmp
[len
- 1] == '/') {
558 for (p
= tmp
+ 1; *p
; p
++) {
561 if (tmp
[strlen(tmp
) - 1] == '.' &&
562 tmp
[strlen(tmp
) - 2] == '.' &&
563 tmp
[strlen(tmp
) - 3] == '/') {
564 ERR("Using '/../' is not permitted in the trace path (%s)",
569 ret
= mkdir(tmp
, mode
);
571 if (errno
!= EEXIST
) {
572 PERROR("mkdir recursive");
581 ret
= mkdir(tmp
, mode
);
583 if (errno
!= EEXIST
) {
584 PERROR("mkdir recursive last piece");
596 * Create the stream tracefile on disk.
598 * Return 0 on success or else a negative value.
601 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
602 uint64_t count
, int uid
, int gid
, char *suffix
)
604 int ret
, out_fd
, flags
, mode
;
605 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
611 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
612 path_name
, file_name
);
614 PERROR("snprintf create output file");
618 /* Setup extra string if suffix or/and a count is needed. */
619 if (size
> 0 && suffix
) {
620 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
621 } else if (size
> 0) {
622 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
624 ret
= asprintf(&extra
, "%s", suffix
);
627 PERROR("Allocating extra string to name");
632 * If we split the trace in multiple files, we have to add the count at the
633 * end of the tracefile name
636 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
638 PERROR("Allocating path name with extra string");
639 goto error_free_suffix
;
641 path
= path_name_suffix
;
646 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
647 /* Open with 660 mode */
648 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
650 if (uid
< 0 || gid
< 0) {
651 out_fd
= open(path
, flags
, mode
);
653 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
656 PERROR("open stream path %s", path
);
662 free(path_name_suffix
);
670 * Change the output tracefile according to the given size and count The
671 * new_count pointer is set during this operation.
673 * From the consumer, the stream lock MUST be held before calling this function
674 * because we are modifying the stream status.
676 * Return 0 on success or else a negative value.
679 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
680 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
690 PERROR("Closing tracefile");
695 *new_count
= (*new_count
+ 1) % count
;
700 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
716 * Parse a string that represents a size in human readable format. It
717 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
719 * The suffix multiply the integer by:
724 * @param str The string to parse.
725 * @param size Pointer to a uint64_t that will be filled with the
728 * @return 0 on success, -1 on failure.
731 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
740 DBG("utils_parse_size_suffix: received a NULL string.");
745 /* strtoull will accept a negative number, but we don't want to. */
746 if (strchr(str
, '-') != NULL
) {
747 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
752 /* str_end will point to the \0 */
753 str_end
= str
+ strlen(str
);
755 base_size
= strtoull(str
, &num_end
, 0);
757 PERROR("utils_parse_size_suffix strtoull");
762 if (num_end
== str
) {
763 /* strtoull parsed nothing, not good. */
764 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
769 /* Check if a prefix is present. */
787 DBG("utils_parse_size_suffix: invalid suffix.");
792 /* Check for garbage after the valid input. */
793 if (num_end
!= str_end
) {
794 DBG("utils_parse_size_suffix: Garbage after size string.");
799 *size
= base_size
<< shift
;
801 /* Check for overflow */
802 if ((*size
>> shift
) != base_size
) {
803 DBG("utils_parse_size_suffix: oops, overflow detected.");
814 * fls: returns the position of the most significant bit.
815 * Returns 0 if no bit is set, else returns the position of the most
816 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
818 #if defined(__i386) || defined(__x86_64)
819 static inline unsigned int fls_u32(uint32_t x
)
827 : "=r" (r
) : "rm" (x
));
834 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
841 if (!(x
& 0xFFFF0000U
)) {
845 if (!(x
& 0xFF000000U
)) {
849 if (!(x
& 0xF0000000U
)) {
853 if (!(x
& 0xC0000000U
)) {
857 if (!(x
& 0x80000000U
)) {
866 * Return the minimum order for which x <= (1UL << order).
867 * Return -1 if x is 0.
870 int utils_get_count_order_u32(uint32_t x
)
876 return fls_u32(x
- 1);
880 * Obtain the value of LTTNG_HOME environment variable, if exists.
881 * Otherwise returns the value of HOME.
884 char *utils_get_home_dir(void)
889 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
893 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
898 /* Fallback on the password file entry. */
899 pwd
= getpwuid(getuid());
905 DBG3("Home directory is '%s'", val
);
912 * Get user's home directory. Dynamically allocated, must be freed
916 char *utils_get_user_home_dir(uid_t uid
)
919 struct passwd
*result
;
920 char *home_dir
= NULL
;
925 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
930 buf
= zmalloc(buflen
);
935 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
936 if (ret
|| !result
) {
945 home_dir
= strdup(pwd
.pw_dir
);
952 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
953 * Otherwise returns NULL.
956 char *utils_get_kmod_probes_list(void)
958 return lttng_secure_getenv(DEFAULT_LTTNG_KMOD_PROBES
);
962 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
963 * exists. Otherwise returns NULL.
966 char *utils_get_extra_kmod_probes_list(void)
968 return lttng_secure_getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
972 * With the given format, fill dst with the time of len maximum siz.
974 * Return amount of bytes set in the buffer or else 0 on error.
977 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
986 /* Get date and time for session path */
988 timeinfo
= localtime(&rawtime
);
989 ret
= strftime(dst
, len
, format
, timeinfo
);
991 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
999 * Return the group ID matching name, else 0 if it cannot be found.
1002 gid_t
utils_get_group_id(const char *name
)
1006 grp
= getgrnam(name
);
1008 static volatile int warn_once
;
1011 WARN("No tracing group detected");
1020 * Return a newly allocated option string. This string is to be used as the
1021 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1022 * of elements in the long_options array. Returns NULL if the string's
1026 char *utils_generate_optstring(const struct option
*long_options
,
1030 size_t string_len
= opt_count
, str_pos
= 0;
1034 * Compute the necessary string length. One letter per option, two when an
1035 * argument is necessary, and a trailing NULL.
1037 for (i
= 0; i
< opt_count
; i
++) {
1038 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1041 optstring
= zmalloc(string_len
);
1046 for (i
= 0; i
< opt_count
; i
++) {
1047 if (!long_options
[i
].name
) {
1048 /* Got to the trailing NULL element */
1052 optstring
[str_pos
++] = (char)long_options
[i
].val
;
1053 if (long_options
[i
].has_arg
) {
1054 optstring
[str_pos
++] = ':';