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.
28 #include <sys/types.h>
35 #include <common/common.h>
36 #include <common/runas.h>
42 * Return a partial realpath(3) of the path even if the full path does not
43 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
44 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
45 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
46 * point directory does not exist.
47 * In case resolved_path is NULL, the string returned was allocated in the
48 * function and thus need to be freed by the caller. The size argument allows
49 * to specify the size of the resolved_path argument if given, or the size to
53 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
55 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
56 const char *next
, *prev
, *end
;
64 * Identify the end of the path, we don't want to treat the
65 * last char if it is a '/', we will just keep it on the side
66 * to be added at the end, and return a value coherent with
67 * the path given as argument
69 end
= path
+ strlen(path
);
70 if (*(end
-1) == '/') {
74 /* Initiate the values of the pointers before looping */
77 /* Only to ensure try_path is not NULL to enter the while */
78 try_path
= (char *)next
;
80 /* Resolve the canonical path of the first part of the path */
81 while (try_path
!= NULL
&& next
!= end
) {
83 * If there is not any '/' left, we want to try with
86 next
= strpbrk(next
+ 1, "/");
91 /* Cut the part we will be trying to resolve */
92 cut_path
= strndup(path
, next
- path
);
94 /* Try to resolve this part */
95 try_path
= realpath((char *)cut_path
, NULL
);
96 if (try_path
== NULL
) {
98 * There was an error, we just want to be assured it
99 * is linked to an unexistent directory, if it's another
100 * reason, we spawn an error
104 /* Ignore the error */
107 PERROR("realpath (partial_realpath)");
112 /* Save the place we are before trying the next step */
114 try_path_prev
= try_path
;
118 /* Free the allocated memory */
122 /* Allocate memory for the resolved path if necessary */
123 if (resolved_path
== NULL
) {
124 resolved_path
= zmalloc(size
);
125 if (resolved_path
== NULL
) {
126 PERROR("zmalloc resolved path");
132 * If we were able to solve at least partially the path, we can concatenate
133 * what worked and what didn't work
135 if (try_path_prev
!= NULL
) {
136 /* If we risk to concatenate two '/', we remove one of them */
137 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
138 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
142 * Duplicate the memory used by prev in case resolved_path and
143 * path are pointers for the same memory space
145 cut_path
= strdup(prev
);
147 /* Concatenate the strings */
148 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
150 /* Free the allocated memory */
154 * Else, we just copy the path in our resolved_path to
158 strncpy(resolved_path
, path
, size
);
161 /* Then we return the 'partially' resolved path */
162 return resolved_path
;
170 * Make a full resolution of the given path even if it doesn't exist.
171 * This function uses the utils_partial_realpath function to resolve
172 * symlinks and relatives paths at the start of the string, and
173 * implements functionnalities to resolve the './' and '../' strings
174 * in the middle of a path. This function is only necessary because
175 * realpath(3) does not accept to resolve unexistent paths.
176 * The returned string was allocated in the function, it is thus of
177 * the responsibility of the caller to free this memory.
180 char *utils_expand_path(const char *path
)
182 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
184 int is_dot
, is_dotdot
;
191 /* Allocate memory for the absolute_path */
192 absolute_path
= zmalloc(PATH_MAX
);
193 if (absolute_path
== NULL
) {
194 PERROR("zmalloc expand path");
199 * If the path is not already absolute nor explicitly relative,
200 * consider we're in the current directory
202 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
203 strncmp(path
, "../", 3) != 0) {
204 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
205 /* Else, we just copy the path */
207 strncpy(absolute_path
, path
, PATH_MAX
);
210 /* Resolve partially our path */
211 absolute_path
= utils_partial_realpath(absolute_path
,
212 absolute_path
, PATH_MAX
);
214 /* As long as we find '/./' in the working_path string */
215 while ((next
= strstr(absolute_path
, "/./"))) {
217 /* We prepare the start_path not containing it */
218 start_path
= strndup(absolute_path
, next
- absolute_path
);
220 /* And we concatenate it with the part after this string */
221 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
226 /* As long as we find '/../' in the working_path string */
227 while ((next
= strstr(absolute_path
, "/../"))) {
228 /* We find the last level of directory */
229 previous
= absolute_path
;
230 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
231 previous
= slash
+ 1;
234 /* Then we prepare the start_path not containing it */
235 start_path
= strndup(absolute_path
, previous
- absolute_path
);
237 /* And we concatenate it with the part after the '/../' */
238 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
240 /* We can free the memory used for the start path*/
243 /* Then we verify for symlinks using partial_realpath */
244 absolute_path
= utils_partial_realpath(absolute_path
,
245 absolute_path
, PATH_MAX
);
248 /* Identify the last token */
249 last_token
= strrchr(absolute_path
, '/');
251 /* Verify that this token is not a relative path */
252 is_dotdot
= (strcmp(last_token
, "/..") == 0);
253 is_dot
= (strcmp(last_token
, "/.") == 0);
255 /* If it is, take action */
256 if (is_dot
|| is_dotdot
) {
257 /* For both, remove this token */
260 /* If it was a reference to parent directory, go back one more time */
262 last_token
= strrchr(absolute_path
, '/');
264 /* If there was only one level left, we keep the first '/' */
265 if (last_token
== absolute_path
) {
273 return absolute_path
;
281 * Create a pipe in dst.
284 int utils_create_pipe(int *dst
)
294 PERROR("create pipe");
301 * Create pipe and set CLOEXEC flag to both fd.
303 * Make sure the pipe opened by this function are closed at some point. Use
304 * utils_close_pipe().
307 int utils_create_pipe_cloexec(int *dst
)
315 ret
= utils_create_pipe(dst
);
320 for (i
= 0; i
< 2; i
++) {
321 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
323 PERROR("fcntl pipe cloexec");
333 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
335 * Make sure the pipe opened by this function are closed at some point. Use
336 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
337 * support OSes other than Linux 2.6.23+.
340 int utils_create_pipe_cloexec_nonblock(int *dst
)
348 ret
= utils_create_pipe(dst
);
353 for (i
= 0; i
< 2; i
++) {
354 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
356 PERROR("fcntl pipe cloexec");
360 * Note: we override any flag that could have been
361 * previously set on the fd.
363 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
365 PERROR("fcntl pipe nonblock");
375 * Close both read and write side of the pipe.
378 void utils_close_pipe(int *src
)
386 for (i
= 0; i
< 2; i
++) {
394 PERROR("close pipe");
400 * Create a new string using two strings range.
403 char *utils_strdupdelim(const char *begin
, const char *end
)
407 str
= zmalloc(end
- begin
+ 1);
409 PERROR("zmalloc strdupdelim");
413 memcpy(str
, begin
, end
- begin
);
414 str
[end
- begin
] = '\0';
421 * Set CLOEXEC flag to the give file descriptor.
424 int utils_set_fd_cloexec(int fd
)
433 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
435 PERROR("fcntl cloexec");
444 * Create pid file to the given path and filename.
447 int utils_create_pid_file(pid_t pid
, const char *filepath
)
454 fp
= fopen(filepath
, "w");
456 PERROR("open pid file %s", filepath
);
461 ret
= fprintf(fp
, "%d\n", pid
);
463 PERROR("fprintf pid file");
467 DBG("Pid %d written in file %s", pid
, filepath
);
473 * Create lock file to the given path and filename.
474 * Returns the associated file descriptor, -1 on error.
477 int utils_create_lock_file(const char *filepath
)
484 fd
= open(filepath
, O_CREAT
,
485 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
487 PERROR("open lock file %s", filepath
);
493 * Attempt to lock the file. If this fails, there is
494 * already a process using the same lock file running
495 * and we should exit.
497 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
499 WARN("Could not get lock file %s, another instance is running.",
511 * Recursively create directory using the given path and mode.
513 * On success, return 0 else a negative error code.
516 int utils_mkdir_recursive(const char *path
, mode_t mode
)
518 char *p
, tmp
[PATH_MAX
];
524 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
526 PERROR("snprintf mkdir");
531 if (tmp
[len
- 1] == '/') {
535 for (p
= tmp
+ 1; *p
; p
++) {
538 if (tmp
[strlen(tmp
) - 1] == '.' &&
539 tmp
[strlen(tmp
) - 2] == '.' &&
540 tmp
[strlen(tmp
) - 3] == '/') {
541 ERR("Using '/../' is not permitted in the trace path (%s)",
546 ret
= mkdir(tmp
, mode
);
548 if (errno
!= EEXIST
) {
549 PERROR("mkdir recursive");
558 ret
= mkdir(tmp
, mode
);
560 if (errno
!= EEXIST
) {
561 PERROR("mkdir recursive last piece");
573 * Create the stream tracefile on disk.
575 * Return 0 on success or else a negative value.
578 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
579 uint64_t count
, int uid
, int gid
, char *suffix
)
581 int ret
, out_fd
, flags
, mode
;
582 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
588 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
589 path_name
, file_name
);
591 PERROR("snprintf create output file");
595 /* Setup extra string if suffix or/and a count is needed. */
596 if (size
> 0 && suffix
) {
597 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
598 } else if (size
> 0) {
599 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
601 ret
= asprintf(&extra
, "%s", suffix
);
604 PERROR("Allocating extra string to name");
609 * If we split the trace in multiple files, we have to add the count at the
610 * end of the tracefile name
613 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
615 PERROR("Allocating path name with extra string");
616 goto error_free_suffix
;
618 path
= path_name_suffix
;
623 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
624 /* Open with 660 mode */
625 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
627 if (uid
< 0 || gid
< 0) {
628 out_fd
= open(path
, flags
, mode
);
630 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
633 PERROR("open stream path %s", path
);
639 free(path_name_suffix
);
647 * Change the output tracefile according to the given size and count The
648 * new_count pointer is set during this operation.
650 * From the consumer, the stream lock MUST be held before calling this function
651 * because we are modifying the stream status.
653 * Return 0 on success or else a negative value.
656 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
657 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
667 PERROR("Closing tracefile");
672 *new_count
= (*new_count
+ 1) % count
;
677 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
693 * Parse a string that represents a size in human readable format. It
694 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
696 * The suffix multiply the integer by:
701 * @param str The string to parse.
702 * @param size Pointer to a uint64_t that will be filled with the
705 * @return 0 on success, -1 on failure.
708 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
717 DBG("utils_parse_size_suffix: received a NULL string.");
722 /* strtoull will accept a negative number, but we don't want to. */
723 if (strchr(str
, '-') != NULL
) {
724 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
729 /* str_end will point to the \0 */
730 str_end
= str
+ strlen(str
);
732 base_size
= strtoull(str
, &num_end
, 0);
734 PERROR("utils_parse_size_suffix strtoull");
739 if (num_end
== str
) {
740 /* strtoull parsed nothing, not good. */
741 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
746 /* Check if a prefix is present. */
764 DBG("utils_parse_size_suffix: invalid suffix.");
769 /* Check for garbage after the valid input. */
770 if (num_end
!= str_end
) {
771 DBG("utils_parse_size_suffix: Garbage after size string.");
776 *size
= base_size
<< shift
;
778 /* Check for overflow */
779 if ((*size
>> shift
) != base_size
) {
780 DBG("utils_parse_size_suffix: oops, overflow detected.");
791 * fls: returns the position of the most significant bit.
792 * Returns 0 if no bit is set, else returns the position of the most
793 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
795 #if defined(__i386) || defined(__x86_64)
796 static inline unsigned int fls_u32(uint32_t x
)
804 : "=r" (r
) : "rm" (x
));
811 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
818 if (!(x
& 0xFFFF0000U
)) {
822 if (!(x
& 0xFF000000U
)) {
826 if (!(x
& 0xF0000000U
)) {
830 if (!(x
& 0xC0000000U
)) {
834 if (!(x
& 0x80000000U
)) {
843 * Return the minimum order for which x <= (1UL << order).
844 * Return -1 if x is 0.
847 int utils_get_count_order_u32(uint32_t x
)
853 return fls_u32(x
- 1);
857 * Obtain the value of LTTNG_HOME environment variable, if exists.
858 * Otherwise returns the value of HOME.
861 char *utils_get_home_dir(void)
866 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
870 val
= getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
875 /* Fallback on the password file entry. */
876 pwd
= getpwuid(getuid());
882 DBG3("Home directory is '%s'", val
);
889 * Get user's home directory. Dynamically allocated, must be freed
893 char *utils_get_user_home_dir(uid_t uid
)
896 struct passwd
*result
;
897 char *home_dir
= NULL
;
902 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
907 buf
= zmalloc(buflen
);
912 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
913 if (ret
|| !result
) {
922 home_dir
= strdup(pwd
.pw_dir
);
929 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
930 * Otherwise returns NULL.
933 char *utils_get_kmod_probes_list(void)
935 return getenv(DEFAULT_LTTNG_KMOD_PROBES
);
939 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
940 * exists. Otherwise returns NULL.
943 char *utils_get_extra_kmod_probes_list(void)
945 return getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
949 * With the given format, fill dst with the time of len maximum siz.
951 * Return amount of bytes set in the buffer or else 0 on error.
954 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
963 /* Get date and time for session path */
965 timeinfo
= localtime(&rawtime
);
966 ret
= strftime(dst
, len
, format
, timeinfo
);
968 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
976 * Return the group ID matching name, else 0 if it cannot be found.
979 gid_t
utils_get_group_id(const char *name
)
983 grp
= getgrnam(name
);
985 static volatile int warn_once
;
988 WARN("No tracing group detected");
997 * Return a newly allocated option string. This string is to be used as the
998 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
999 * of elements in the long_options array. Returns NULL if the string's
1003 char *utils_generate_optstring(const struct option
*long_options
,
1007 size_t string_len
= opt_count
, str_pos
= 0;
1011 * Compute the necessary string length. One letter per option, two when an
1012 * argument is necessary, and a trailing NULL.
1014 for (i
= 0; i
< opt_count
; i
++) {
1015 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1018 optstring
= zmalloc(string_len
);
1023 for (i
= 0; i
< opt_count
; i
++) {
1024 if (!long_options
[i
].name
) {
1025 /* Got to the trailing NULL element */
1029 optstring
[str_pos
++] = (char)long_options
[i
].val
;
1030 if (long_options
[i
].has_arg
) {
1031 optstring
[str_pos
++] = ':';