Add utils_expand_path_keep_symlink fonction
[lttng-tools.git] / src / common / utils.c
CommitLineData
81b86775
DG
1/*
2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
66495845 3 * Copyright (C) 2013 - Raphaël Beamonte <raphael.beamonte@gmail.com>
8db0dc00 4 * Copyright (C) 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
81b86775
DG
5 *
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.
9 *
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
13 * more details.
14 *
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.
18 */
19
6c1c0768 20#define _LGPL_SOURCE
35f90c40 21#include <assert.h>
81b86775
DG
22#include <ctype.h>
23#include <fcntl.h>
24#include <limits.h>
25#include <stdlib.h>
2d851108 26#include <sys/stat.h>
0c7bcad5 27#include <sys/types.h>
2d851108 28#include <unistd.h>
fe4477ee 29#include <inttypes.h>
6c71277b 30#include <grp.h>
fb198a11 31#include <pwd.h>
c9cb3e7d 32#include <sys/file.h>
a98e236e 33#include <unistd.h>
81b86775
DG
34
35#include <common/common.h>
fe4477ee 36#include <common/runas.h>
e8fa9fb0 37#include <common/compat/getenv.h>
f5436bfc 38#include <common/compat/string.h>
5a2451c9 39#include <common/compat/dirent.h>
d7c23421 40#include <lttng/constant.h>
81b86775
DG
41
42#include "utils.h"
feb0f3e5 43#include "defaults.h"
81b86775 44
5154230f
RB
45/*
46 * Return a partial realpath(3) of the path even if the full path does not
47 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
48 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
49 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
50 * point directory does not exist.
51 * In case resolved_path is NULL, the string returned was allocated in the
52 * function and thus need to be freed by the caller. The size argument allows
53 * to specify the size of the resolved_path argument if given, or the size to
54 * allocate.
55 */
56LTTNG_HIDDEN
57char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
58{
9482daac 59 char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
5154230f
RB
60 const char *next, *prev, *end;
61
62 /* Safety net */
63 if (path == NULL) {
64 goto error;
65 }
66
67 /*
68 * Identify the end of the path, we don't want to treat the
69 * last char if it is a '/', we will just keep it on the side
70 * to be added at the end, and return a value coherent with
71 * the path given as argument
72 */
73 end = path + strlen(path);
74 if (*(end-1) == '/') {
75 end--;
76 }
77
78 /* Initiate the values of the pointers before looping */
79 next = path;
80 prev = next;
81 /* Only to ensure try_path is not NULL to enter the while */
82 try_path = (char *)next;
83
84 /* Resolve the canonical path of the first part of the path */
85 while (try_path != NULL && next != end) {
d7c23421
JG
86 char *try_path_buf = NULL;
87
5154230f
RB
88 /*
89 * If there is not any '/' left, we want to try with
90 * the full path
91 */
92 next = strpbrk(next + 1, "/");
93 if (next == NULL) {
94 next = end;
95 }
96
97 /* Cut the part we will be trying to resolve */
f5436bfc 98 cut_path = lttng_strndup(path, next - path);
d9dbcf5e 99 if (cut_path == NULL) {
f5436bfc 100 PERROR("lttng_strndup");
d9dbcf5e
MD
101 goto error;
102 }
5154230f 103
d7c23421
JG
104 try_path_buf = zmalloc(LTTNG_PATH_MAX);
105 if (!try_path_buf) {
106 PERROR("zmalloc");
107 goto error;
108 }
109
5154230f 110 /* Try to resolve this part */
f3472d9a 111 try_path = realpath((char *) cut_path, try_path_buf);
5154230f 112 if (try_path == NULL) {
d7c23421 113 free(try_path_buf);
5154230f
RB
114 /*
115 * There was an error, we just want to be assured it
116 * is linked to an unexistent directory, if it's another
117 * reason, we spawn an error
118 */
119 switch (errno) {
120 case ENOENT:
121 /* Ignore the error */
122 break;
123 default:
124 PERROR("realpath (partial_realpath)");
125 goto error;
126 break;
127 }
128 } else {
129 /* Save the place we are before trying the next step */
d7c23421 130 try_path_buf = NULL;
5154230f
RB
131 free(try_path_prev);
132 try_path_prev = try_path;
133 prev = next;
134 }
135
136 /* Free the allocated memory */
137 free(cut_path);
c14cc491 138 cut_path = NULL;
494a8e99 139 }
5154230f
RB
140
141 /* Allocate memory for the resolved path if necessary */
142 if (resolved_path == NULL) {
143 resolved_path = zmalloc(size);
144 if (resolved_path == NULL) {
145 PERROR("zmalloc resolved path");
146 goto error;
147 }
148 }
149
150 /*
151 * If we were able to solve at least partially the path, we can concatenate
152 * what worked and what didn't work
153 */
154 if (try_path_prev != NULL) {
155 /* If we risk to concatenate two '/', we remove one of them */
156 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
157 try_path_prev[strlen(try_path_prev) - 1] = '\0';
158 }
159
160 /*
161 * Duplicate the memory used by prev in case resolved_path and
162 * path are pointers for the same memory space
163 */
164 cut_path = strdup(prev);
d9dbcf5e
MD
165 if (cut_path == NULL) {
166 PERROR("strdup");
167 goto error;
168 }
5154230f
RB
169
170 /* Concatenate the strings */
171 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
172
173 /* Free the allocated memory */
174 free(cut_path);
175 free(try_path_prev);
494a8e99
JG
176 cut_path = NULL;
177 try_path_prev = NULL;
5154230f
RB
178 /*
179 * Else, we just copy the path in our resolved_path to
180 * return it as is
181 */
182 } else {
183 strncpy(resolved_path, path, size);
184 }
185
186 /* Then we return the 'partially' resolved path */
187 return resolved_path;
188
189error:
190 free(resolved_path);
9482daac 191 free(cut_path);
b86d5f3f 192 free(try_path);
32bd4678
MJ
193 if (try_path_prev != try_path) {
194 free(try_path_prev);
195 }
5154230f
RB
196 return NULL;
197}
198
4b223a67
FD
199static
200char *expand_double_slashes_dot_and_dotdot(char *path)
201{
202 size_t expanded_path_len, path_len;
203 const char *curr_char, *path_last_char, *next_slash, *prev_slash;
204
205 path_len = strlen(path);
206 path_last_char = &path[path_len];
207
208 if (path_len == 0) {
209 path = NULL;
210 goto error;
211 }
212
213 expanded_path_len = 0;
214
215 /* We iterate over the provided path to expand the "//", "../" and "./" */
216 for (curr_char = path; curr_char <= path_last_char; curr_char = next_slash + 1) {
217 /* Find the next forward slash. */
218 size_t curr_token_len;
219
220 if (curr_char == path_last_char) {
221 expanded_path_len++;
222 break;
223 }
224
225 next_slash = memchr(curr_char, '/', path_last_char - curr_char);
226 if (next_slash == NULL) {
227 /* Reached the end of the provided path. */
228 next_slash = path_last_char;
229 }
230
231 /* Compute how long is the previous token. */
232 curr_token_len = next_slash - curr_char;
233 switch(curr_token_len) {
234 case 0:
235 /*
236 * The pointer has not move meaning that curr_char is
237 * pointing to a slash. It that case there is no token
238 * to copy, so continue the iteration to find the next
239 * token
240 */
241 continue;
242 case 1:
243 /*
244 * The pointer moved 1 character. Check if that
245 * character is a dot ('.'), if it is: omit it, else
246 * copy the token to the normalized path.
247 */
248 if (curr_char[0] == '.') {
249 continue;
250 }
251 break;
252 case 2:
253 /*
254 * The pointer moved 2 characters. Check if these
255 * characters are double dots ('..'). If that is the
256 * case, we need to remove the last token of the
257 * normalized path.
258 */
259 if (curr_char[0] == '.' && curr_char[1] == '.') {
260 /*
261 * Find the previous path component by
262 * using the memrchr function to find the
263 * previous forward slash and substract that
264 * len to the resulting path.
265 */
266 prev_slash = lttng_memrchr(path, '/', expanded_path_len);
267 /*
268 * If prev_slash is NULL, we reached the
269 * beginning of the path. We can't go back any
270 * further.
271 */
272 if (prev_slash != NULL) {
273 expanded_path_len = prev_slash - path;
274 }
275 continue;
276 }
277 break;
278 default:
279 break;
280 }
281
282 /*
283 * Copy the current token which is neither a '.' nor a '..'.
284 */
285 path[expanded_path_len++] = '/';
286 memcpy(&path[expanded_path_len], curr_char, curr_token_len);
287 expanded_path_len += curr_token_len;
288 }
289
290 if (expanded_path_len == 0) {
291 path[expanded_path_len++] = '/';
292 }
293
294 path[expanded_path_len] = '\0';
295
296error:
297 return path;
298}
299
81b86775 300/*
3d229795
RB
301 * Make a full resolution of the given path even if it doesn't exist.
302 * This function uses the utils_partial_realpath function to resolve
303 * symlinks and relatives paths at the start of the string, and
304 * implements functionnalities to resolve the './' and '../' strings
305 * in the middle of a path. This function is only necessary because
306 * realpath(3) does not accept to resolve unexistent paths.
307 * The returned string was allocated in the function, it is thus of
308 * the responsibility of the caller to free this memory.
81b86775 309 */
90e535ef 310LTTNG_HIDDEN
4b223a67 311char *_utils_expand_path(const char *path, bool keep_symlink)
81b86775 312{
4b223a67 313 char *absolute_path = NULL;
5de083f4
RB
314 char *last_token;
315 int is_dot, is_dotdot;
81b86775
DG
316
317 /* Safety net */
318 if (path == NULL) {
319 goto error;
320 }
321
3d229795
RB
322 /* Allocate memory for the absolute_path */
323 absolute_path = zmalloc(PATH_MAX);
324 if (absolute_path == NULL) {
81b86775
DG
325 PERROR("zmalloc expand path");
326 goto error;
327 }
328
4b223a67 329 if (path[0] == '/') {
3d229795 330 strncpy(absolute_path, path, PATH_MAX);
4b223a67
FD
331 } else {
332 /*
333 * This is a relative path. We need to get the present working
334 * directory and start the path walk from there.
335 */
336 char current_working_dir[PATH_MAX];
337 char *cwd_ret;
338 cwd_ret = getcwd(current_working_dir, sizeof(current_working_dir));
339 if (!cwd_ret) {
340 absolute_path = NULL;
d9dbcf5e
MD
341 goto error;
342 }
4b223a67
FD
343 /*
344 * Get the number of character in the CWD and allocate an array
345 * to can hold it and the path provided by the caller.
346 */
347 snprintf(absolute_path, PATH_MAX, "%s/%s", current_working_dir, path);
3d229795 348 }
116f95d9 349
4b223a67
FD
350 if (keep_symlink) {
351 /* Resolve partially our path */
3d229795
RB
352 absolute_path = utils_partial_realpath(absolute_path,
353 absolute_path, PATH_MAX);
116f95d9 354 }
81b86775 355
4b223a67
FD
356 absolute_path = expand_double_slashes_dot_and_dotdot(absolute_path);
357 if (!absolute_path) {
358 goto error;
359 }
360
5de083f4
RB
361 /* Identify the last token */
362 last_token = strrchr(absolute_path, '/');
363
364 /* Verify that this token is not a relative path */
365 is_dotdot = (strcmp(last_token, "/..") == 0);
366 is_dot = (strcmp(last_token, "/.") == 0);
367
368 /* If it is, take action */
369 if (is_dot || is_dotdot) {
370 /* For both, remove this token */
371 *last_token = '\0';
372
373 /* If it was a reference to parent directory, go back one more time */
374 if (is_dotdot) {
375 last_token = strrchr(absolute_path, '/');
376
377 /* If there was only one level left, we keep the first '/' */
378 if (last_token == absolute_path) {
379 last_token++;
380 }
381
382 *last_token = '\0';
383 }
384 }
385
3d229795 386 return absolute_path;
81b86775
DG
387
388error:
3d229795 389 free(absolute_path);
81b86775
DG
390 return NULL;
391}
4b223a67
FD
392LTTNG_HIDDEN
393char *utils_expand_path(const char *path)
394{
395 return _utils_expand_path(path, true);
396}
81b86775 397
4b223a67
FD
398LTTNG_HIDDEN
399char *utils_expand_path_keep_symlink(const char *path)
400{
401 return _utils_expand_path(path, false);
402}
81b86775
DG
403/*
404 * Create a pipe in dst.
405 */
90e535ef 406LTTNG_HIDDEN
81b86775
DG
407int utils_create_pipe(int *dst)
408{
409 int ret;
410
411 if (dst == NULL) {
412 return -1;
413 }
414
415 ret = pipe(dst);
416 if (ret < 0) {
417 PERROR("create pipe");
418 }
419
420 return ret;
421}
422
423/*
424 * Create pipe and set CLOEXEC flag to both fd.
425 *
426 * Make sure the pipe opened by this function are closed at some point. Use
427 * utils_close_pipe().
428 */
90e535ef 429LTTNG_HIDDEN
81b86775
DG
430int utils_create_pipe_cloexec(int *dst)
431{
432 int ret, i;
433
434 if (dst == NULL) {
435 return -1;
436 }
437
438 ret = utils_create_pipe(dst);
439 if (ret < 0) {
440 goto error;
441 }
442
443 for (i = 0; i < 2; i++) {
444 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
445 if (ret < 0) {
446 PERROR("fcntl pipe cloexec");
447 goto error;
448 }
449 }
450
451error:
452 return ret;
453}
454
094f381c
MD
455/*
456 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
457 *
458 * Make sure the pipe opened by this function are closed at some point. Use
459 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
460 * support OSes other than Linux 2.6.23+.
461 */
462LTTNG_HIDDEN
463int utils_create_pipe_cloexec_nonblock(int *dst)
464{
465 int ret, i;
466
467 if (dst == NULL) {
468 return -1;
469 }
470
471 ret = utils_create_pipe(dst);
472 if (ret < 0) {
473 goto error;
474 }
475
476 for (i = 0; i < 2; i++) {
477 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
478 if (ret < 0) {
479 PERROR("fcntl pipe cloexec");
480 goto error;
481 }
482 /*
483 * Note: we override any flag that could have been
484 * previously set on the fd.
485 */
486 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
487 if (ret < 0) {
488 PERROR("fcntl pipe nonblock");
489 goto error;
490 }
491 }
492
493error:
494 return ret;
495}
496
81b86775
DG
497/*
498 * Close both read and write side of the pipe.
499 */
90e535ef 500LTTNG_HIDDEN
81b86775
DG
501void utils_close_pipe(int *src)
502{
503 int i, ret;
504
505 if (src == NULL) {
506 return;
507 }
508
509 for (i = 0; i < 2; i++) {
510 /* Safety check */
511 if (src[i] < 0) {
512 continue;
513 }
514
515 ret = close(src[i]);
516 if (ret) {
517 PERROR("close pipe");
518 }
519 }
520}
a4b92340
DG
521
522/*
523 * Create a new string using two strings range.
524 */
90e535ef 525LTTNG_HIDDEN
a4b92340
DG
526char *utils_strdupdelim(const char *begin, const char *end)
527{
528 char *str;
529
530 str = zmalloc(end - begin + 1);
531 if (str == NULL) {
532 PERROR("zmalloc strdupdelim");
533 goto error;
534 }
535
536 memcpy(str, begin, end - begin);
537 str[end - begin] = '\0';
538
539error:
540 return str;
541}
b662582b
DG
542
543/*
544 * Set CLOEXEC flag to the give file descriptor.
545 */
90e535ef 546LTTNG_HIDDEN
b662582b
DG
547int utils_set_fd_cloexec(int fd)
548{
549 int ret;
550
551 if (fd < 0) {
552 ret = -EINVAL;
553 goto end;
554 }
555
556 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
557 if (ret < 0) {
558 PERROR("fcntl cloexec");
559 ret = -errno;
560 }
561
562end:
563 return ret;
564}
35f90c40
DG
565
566/*
567 * Create pid file to the given path and filename.
568 */
90e535ef 569LTTNG_HIDDEN
35f90c40
DG
570int utils_create_pid_file(pid_t pid, const char *filepath)
571{
572 int ret;
573 FILE *fp;
574
575 assert(filepath);
576
577 fp = fopen(filepath, "w");
578 if (fp == NULL) {
579 PERROR("open pid file %s", filepath);
580 ret = -1;
581 goto error;
582 }
583
d1f721c5 584 ret = fprintf(fp, "%d\n", (int) pid);
35f90c40
DG
585 if (ret < 0) {
586 PERROR("fprintf pid file");
e205d79b 587 goto error;
35f90c40
DG
588 }
589
e205d79b
MD
590 if (fclose(fp)) {
591 PERROR("fclose");
592 }
d1f721c5 593 DBG("Pid %d written in file %s", (int) pid, filepath);
e205d79b 594 ret = 0;
35f90c40
DG
595error:
596 return ret;
597}
2d851108 598
c9cb3e7d
JG
599/*
600 * Create lock file to the given path and filename.
601 * Returns the associated file descriptor, -1 on error.
602 */
603LTTNG_HIDDEN
604int utils_create_lock_file(const char *filepath)
605{
606 int ret;
607 int fd;
77e7fddf 608 struct flock lock;
c9cb3e7d
JG
609
610 assert(filepath);
611
77e7fddf
MJ
612 memset(&lock, 0, sizeof(lock));
613 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
614 S_IRGRP | S_IWGRP);
c9cb3e7d
JG
615 if (fd < 0) {
616 PERROR("open lock file %s", filepath);
e6576ba2 617 fd = -1;
c9cb3e7d
JG
618 goto error;
619 }
620
621 /*
622 * Attempt to lock the file. If this fails, there is
623 * already a process using the same lock file running
624 * and we should exit.
625 */
77e7fddf
MJ
626 lock.l_whence = SEEK_SET;
627 lock.l_type = F_WRLCK;
628
629 ret = fcntl(fd, F_SETLK, &lock);
630 if (ret == -1) {
631 PERROR("fcntl lock file");
208ff148 632 ERR("Could not get lock file %s, another instance is running.",
c9cb3e7d 633 filepath);
ffb0b851
JG
634 if (close(fd)) {
635 PERROR("close lock file");
636 }
c9cb3e7d
JG
637 fd = ret;
638 goto error;
639 }
640
641error:
642 return fd;
643}
644
a98e236e
JG
645/*
646 * On some filesystems (e.g. nfs), mkdir will validate access rights before
647 * checking for the existence of the path element. This means that on a setup
648 * where "/home/" is a mounted NFS share, and running as an unpriviledged user,
649 * recursively creating a path of the form "/home/my_user/trace/" will fail with
650 * EACCES on mkdir("/home", ...).
651 *
652 * Performing a stat(...) on the path to check for existence allows us to
653 * work around this behaviour.
654 */
655static
656int mkdir_check_exists(const char *path, mode_t mode)
657{
658 int ret = 0;
659 struct stat st;
660
661 ret = stat(path, &st);
662 if (ret == 0) {
663 if (S_ISDIR(st.st_mode)) {
664 /* Directory exists, skip. */
665 goto end;
666 } else {
667 /* Exists, but is not a directory. */
668 errno = ENOTDIR;
669 ret = -1;
670 goto end;
671 }
672 }
673
674 /*
675 * Let mkdir handle other errors as the caller expects mkdir
676 * semantics.
677 */
678 ret = mkdir(path, mode);
679end:
680 return ret;
681}
682
2d851108 683/*
d77dded2 684 * Create directory using the given path and mode.
2d851108
DG
685 *
686 * On success, return 0 else a negative error code.
687 */
90e535ef 688LTTNG_HIDDEN
d77dded2
JG
689int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
690{
691 int ret;
692
693 if (uid < 0 || gid < 0) {
a98e236e 694 ret = mkdir_check_exists(path, mode);
d77dded2
JG
695 } else {
696 ret = run_as_mkdir(path, mode, uid, gid);
697 }
698 if (ret < 0) {
699 if (errno != EEXIST) {
700 PERROR("mkdir %s, uid %d, gid %d", path ? path : "NULL",
701 uid, gid);
702 } else {
703 ret = 0;
704 }
705 }
706
707 return ret;
708}
709
710/*
711 * Internal version of mkdir_recursive. Runs as the current user.
712 * Don't call directly; use utils_mkdir_recursive().
713 *
714 * This function is ominously marked as "unsafe" since it should only
715 * be called by a caller that has transitioned to the uid and gid under which
716 * the directory creation should occur.
717 */
718LTTNG_HIDDEN
719int _utils_mkdir_recursive_unsafe(const char *path, mode_t mode)
2d851108
DG
720{
721 char *p, tmp[PATH_MAX];
2d851108
DG
722 size_t len;
723 int ret;
724
725 assert(path);
726
727 ret = snprintf(tmp, sizeof(tmp), "%s", path);
728 if (ret < 0) {
729 PERROR("snprintf mkdir");
730 goto error;
731 }
732
733 len = ret;
734 if (tmp[len - 1] == '/') {
735 tmp[len - 1] = 0;
736 }
737
738 for (p = tmp + 1; *p; p++) {
739 if (*p == '/') {
740 *p = 0;
741 if (tmp[strlen(tmp) - 1] == '.' &&
742 tmp[strlen(tmp) - 2] == '.' &&
743 tmp[strlen(tmp) - 3] == '/') {
744 ERR("Using '/../' is not permitted in the trace path (%s)",
745 tmp);
746 ret = -1;
747 goto error;
748 }
a98e236e 749 ret = mkdir_check_exists(tmp, mode);
2d851108 750 if (ret < 0) {
a98e236e 751 if (errno != EACCES) {
0c7bcad5
MD
752 PERROR("mkdir recursive");
753 ret = -errno;
754 goto error;
2d851108
DG
755 }
756 }
757 *p = '/';
758 }
759 }
760
a98e236e 761 ret = mkdir_check_exists(tmp, mode);
2d851108 762 if (ret < 0) {
a98e236e
JG
763 PERROR("mkdir recursive last element");
764 ret = -errno;
2d851108
DG
765 }
766
767error:
768 return ret;
769}
fe4477ee 770
d77dded2
JG
771/*
772 * Recursively create directory using the given path and mode, under the
773 * provided uid and gid.
774 *
775 * On success, return 0 else a negative error code.
776 */
777LTTNG_HIDDEN
778int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
779{
780 int ret;
781
782 if (uid < 0 || gid < 0) {
783 /* Run as current user. */
784 ret = _utils_mkdir_recursive_unsafe(path, mode);
785 } else {
786 ret = run_as_mkdir_recursive(path, mode, uid, gid);
787 }
788 if (ret < 0) {
789 PERROR("mkdir %s, uid %d, gid %d", path ? path : "NULL",
790 uid, gid);
791 }
792
793 return ret;
794}
795
fe4477ee 796/*
d77dded2 797 * path is the output parameter. It needs to be PATH_MAX len.
fe4477ee
JD
798 *
799 * Return 0 on success or else a negative value.
800 */
7591bab1
MD
801static int utils_stream_file_name(char *path,
802 const char *path_name, const char *file_name,
803 uint64_t size, uint64_t count,
804 const char *suffix)
fe4477ee 805{
7591bab1
MD
806 int ret;
807 char full_path[PATH_MAX];
808 char *path_name_suffix = NULL;
309167d2 809 char *extra = NULL;
fe4477ee 810
fe4477ee
JD
811 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
812 path_name, file_name);
813 if (ret < 0) {
814 PERROR("snprintf create output file");
815 goto error;
816 }
817
309167d2
JD
818 /* Setup extra string if suffix or/and a count is needed. */
819 if (size > 0 && suffix) {
820 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
821 } else if (size > 0) {
822 ret = asprintf(&extra, "_%" PRIu64, count);
823 } else if (suffix) {
824 ret = asprintf(&extra, "%s", suffix);
825 }
826 if (ret < 0) {
827 PERROR("Allocating extra string to name");
828 goto error;
829 }
830
fe4477ee 831 /*
7591bab1
MD
832 * If we split the trace in multiple files, we have to add the count at
833 * the end of the tracefile name.
fe4477ee 834 */
309167d2
JD
835 if (extra) {
836 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
fe4477ee 837 if (ret < 0) {
309167d2
JD
838 PERROR("Allocating path name with extra string");
839 goto error_free_suffix;
fe4477ee 840 }
7591bab1
MD
841 strncpy(path, path_name_suffix, PATH_MAX - 1);
842 path[PATH_MAX - 1] = '\0';
fe4477ee 843 } else {
072ede59
JG
844 ret = lttng_strncpy(path, full_path, PATH_MAX);
845 if (ret) {
846 ERR("Failed to copy stream file name");
847 goto error_free_suffix;
848 }
7591bab1
MD
849 }
850 path[PATH_MAX - 1] = '\0';
851 ret = 0;
852
853 free(path_name_suffix);
854error_free_suffix:
855 free(extra);
856error:
857 return ret;
858}
859
860/*
861 * Create the stream file on disk.
862 *
863 * Return 0 on success or else a negative value.
864 */
865LTTNG_HIDDEN
866int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
867 uint64_t count, int uid, int gid, char *suffix)
868{
869 int ret, flags, mode;
870 char path[PATH_MAX];
871
872 ret = utils_stream_file_name(path, path_name, file_name,
873 size, count, suffix);
874 if (ret < 0) {
875 goto error;
fe4477ee
JD
876 }
877
d3ecc550
JD
878 /*
879 * With the session rotation feature on the relay, we might need to seek
880 * and truncate a tracefile, so we need read and write access.
881 */
882 flags = O_RDWR | O_CREAT | O_TRUNC;
0f907de1 883 /* Open with 660 mode */
be96a7d1
DG
884 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
885
886 if (uid < 0 || gid < 0) {
7591bab1 887 ret = open(path, flags, mode);
be96a7d1 888 } else {
7591bab1 889 ret = run_as_open(path, flags, mode, uid, gid);
be96a7d1 890 }
7591bab1 891 if (ret < 0) {
fe4477ee 892 PERROR("open stream path %s", path);
fe4477ee 893 }
7591bab1
MD
894error:
895 return ret;
896}
fe4477ee 897
7591bab1
MD
898/*
899 * Unlink the stream tracefile from disk.
900 *
901 * Return 0 on success or else a negative value.
902 */
903LTTNG_HIDDEN
904int utils_unlink_stream_file(const char *path_name, char *file_name, uint64_t size,
905 uint64_t count, int uid, int gid, char *suffix)
906{
907 int ret;
908 char path[PATH_MAX];
909
910 ret = utils_stream_file_name(path, path_name, file_name,
911 size, count, suffix);
912 if (ret < 0) {
913 goto error;
914 }
915 if (uid < 0 || gid < 0) {
916 ret = unlink(path);
917 } else {
918 ret = run_as_unlink(path, uid, gid);
7591bab1
MD
919 }
920 if (ret < 0) {
921 goto error;
922 }
fe4477ee 923error:
7591bab1 924 DBG("utils_unlink_stream_file %s returns %d", path, ret);
fe4477ee
JD
925 return ret;
926}
927
928/*
929 * Change the output tracefile according to the given size and count The
930 * new_count pointer is set during this operation.
931 *
932 * From the consumer, the stream lock MUST be held before calling this function
933 * because we are modifying the stream status.
934 *
935 * Return 0 on success or else a negative value.
936 */
bc182241 937LTTNG_HIDDEN
fe4477ee 938int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
309167d2
JD
939 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
940 int *stream_fd)
fe4477ee
JD
941{
942 int ret;
943
309167d2
JD
944 assert(stream_fd);
945
fe4477ee
JD
946 ret = close(out_fd);
947 if (ret < 0) {
948 PERROR("Closing tracefile");
949 goto error;
950 }
b5b0c181 951 *stream_fd = -1;
fe4477ee
JD
952
953 if (count > 0) {
7591bab1
MD
954 /*
955 * In tracefile rotation, for the relay daemon we need
956 * to unlink the old file if present, because it may
957 * still be open in reading by the live thread, and we
958 * need to ensure that we do not overwrite the content
959 * between get_index and get_packet. Since we have no
960 * way to verify integrity of the data content compared
961 * to the associated index, we need to ensure the reader
962 * has exclusive access to the file content, and that
963 * the open of the data file is performed in get_index.
964 * Unlinking the old file rather than overwriting it
965 * achieves this.
966 */
93ec662e
JD
967 if (new_count) {
968 *new_count = (*new_count + 1) % count;
969 }
970 ret = utils_unlink_stream_file(path_name, file_name, size,
971 new_count ? *new_count : 0, uid, gid, 0);
7591bab1
MD
972 if (ret < 0 && errno != ENOENT) {
973 goto error;
974 }
fe4477ee 975 } else {
93ec662e
JD
976 if (new_count) {
977 (*new_count)++;
978 }
fe4477ee
JD
979 }
980
93ec662e
JD
981 ret = utils_create_stream_file(path_name, file_name, size,
982 new_count ? *new_count : 0, uid, gid, 0);
309167d2
JD
983 if (ret < 0) {
984 goto error;
985 }
986 *stream_fd = ret;
987
988 /* Success. */
989 ret = 0;
990
fe4477ee
JD
991error:
992 return ret;
993}
70d0b120 994
70d0b120
SM
995
996/**
997 * Parse a string that represents a size in human readable format. It
5983a922 998 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
999 *
1000 * The suffix multiply the integer by:
1001 * 'k': 1024
1002 * 'M': 1024^2
1003 * 'G': 1024^3
1004 *
1005 * @param str The string to parse.
5983a922 1006 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 1007 * resulting size.
70d0b120
SM
1008 *
1009 * @return 0 on success, -1 on failure.
1010 */
00a52467 1011LTTNG_HIDDEN
5983a922 1012int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 1013{
70d0b120 1014 int ret;
5983a922 1015 uint64_t base_size;
70d0b120 1016 long shift = 0;
5983a922
SM
1017 const char *str_end;
1018 char *num_end;
70d0b120
SM
1019
1020 if (!str) {
5983a922 1021 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
1022 ret = -1;
1023 goto end;
1024 }
1025
5983a922
SM
1026 /* strtoull will accept a negative number, but we don't want to. */
1027 if (strchr(str, '-') != NULL) {
1028 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 1029 ret = -1;
5983a922 1030 goto end;
70d0b120
SM
1031 }
1032
5983a922
SM
1033 /* str_end will point to the \0 */
1034 str_end = str + strlen(str);
70d0b120 1035 errno = 0;
5983a922 1036 base_size = strtoull(str, &num_end, 0);
70d0b120 1037 if (errno != 0) {
5983a922 1038 PERROR("utils_parse_size_suffix strtoull");
70d0b120 1039 ret = -1;
5983a922
SM
1040 goto end;
1041 }
1042
1043 if (num_end == str) {
1044 /* strtoull parsed nothing, not good. */
1045 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
1046 ret = -1;
1047 goto end;
1048 }
1049
1050 /* Check if a prefix is present. */
1051 switch (*num_end) {
1052 case 'G':
1053 shift = GIBI_LOG2;
1054 num_end++;
1055 break;
1056 case 'M': /* */
1057 shift = MEBI_LOG2;
1058 num_end++;
1059 break;
1060 case 'K':
1061 case 'k':
1062 shift = KIBI_LOG2;
1063 num_end++;
1064 break;
1065 case '\0':
1066 break;
1067 default:
1068 DBG("utils_parse_size_suffix: invalid suffix.");
1069 ret = -1;
1070 goto end;
1071 }
1072
1073 /* Check for garbage after the valid input. */
1074 if (num_end != str_end) {
1075 DBG("utils_parse_size_suffix: Garbage after size string.");
1076 ret = -1;
1077 goto end;
70d0b120
SM
1078 }
1079
1080 *size = base_size << shift;
1081
1082 /* Check for overflow */
1083 if ((*size >> shift) != base_size) {
5983a922 1084 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 1085 ret = -1;
5983a922 1086 goto end;
70d0b120
SM
1087 }
1088
1089 ret = 0;
70d0b120
SM
1090end:
1091 return ret;
1092}
cfa9a5a2 1093
7010c033
SM
1094/**
1095 * Parse a string that represents a time in human readable format. It
1096 * supports decimal integers suffixed by 's', 'u', 'm', 'us', and 'ms'.
1097 *
1098 * The suffix multiply the integer by:
1099 * 'u'/'us': 1
1100 * 'm'/'ms': 1000
1101 * 's': 1000000
1102 *
1103 * Note that unit-less numbers are assumed to be microseconds.
1104 *
1105 * @param str The string to parse, assumed to be NULL-terminated.
1106 * @param time_us Pointer to a uint64_t that will be filled with the
1107 * resulting time in microseconds.
1108 *
1109 * @return 0 on success, -1 on failure.
1110 */
1111LTTNG_HIDDEN
1112int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
1113{
1114 int ret;
1115 uint64_t base_time;
1116 long multiplier = 1;
1117 const char *str_end;
1118 char *num_end;
1119
1120 if (!str) {
1121 DBG("utils_parse_time_suffix: received a NULL string.");
1122 ret = -1;
1123 goto end;
1124 }
1125
1126 /* strtoull will accept a negative number, but we don't want to. */
1127 if (strchr(str, '-') != NULL) {
1128 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1129 ret = -1;
1130 goto end;
1131 }
1132
1133 /* str_end will point to the \0 */
1134 str_end = str + strlen(str);
1135 errno = 0;
1136 base_time = strtoull(str, &num_end, 10);
1137 if (errno != 0) {
1138 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
1139 ret = -1;
1140 goto end;
1141 }
1142
1143 if (num_end == str) {
1144 /* strtoull parsed nothing, not good. */
1145 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1146 ret = -1;
1147 goto end;
1148 }
1149
1150 /* Check if a prefix is present. */
1151 switch (*num_end) {
1152 case 'u':
1153 multiplier = 1;
1154 /* Skip another letter in the 'us' case. */
1155 num_end += (*(num_end + 1) == 's') ? 2 : 1;
1156 break;
1157 case 'm':
1158 multiplier = 1000;
1159 /* Skip another letter in the 'ms' case. */
1160 num_end += (*(num_end + 1) == 's') ? 2 : 1;
1161 break;
1162 case 's':
1163 multiplier = 1000000;
1164 num_end++;
1165 break;
1166 case '\0':
1167 break;
1168 default:
1169 DBG("utils_parse_time_suffix: invalid suffix.");
1170 ret = -1;
1171 goto end;
1172 }
1173
1174 /* Check for garbage after the valid input. */
1175 if (num_end != str_end) {
1176 DBG("utils_parse_time_suffix: Garbage after time string.");
1177 ret = -1;
1178 goto end;
1179 }
1180
1181 *time_us = base_time * multiplier;
1182
1183 /* Check for overflow */
1184 if ((*time_us / multiplier) != base_time) {
1185 DBG("utils_parse_time_suffix: oops, overflow detected.");
1186 ret = -1;
1187 goto end;
1188 }
1189
1190 ret = 0;
1191end:
1192 return ret;
1193}
1194
cfa9a5a2
DG
1195/*
1196 * fls: returns the position of the most significant bit.
1197 * Returns 0 if no bit is set, else returns the position of the most
1198 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1199 */
1200#if defined(__i386) || defined(__x86_64)
1201static inline unsigned int fls_u32(uint32_t x)
1202{
1203 int r;
1204
1205 asm("bsrl %1,%0\n\t"
1206 "jnz 1f\n\t"
1207 "movl $-1,%0\n\t"
1208 "1:\n\t"
1209 : "=r" (r) : "rm" (x));
1210 return r + 1;
1211}
1212#define HAS_FLS_U32
1213#endif
1214
db5be0a3
JG
1215#if defined(__x86_64)
1216static inline
1217unsigned int fls_u64(uint64_t x)
1218{
1219 long r;
1220
1221 asm("bsrq %1,%0\n\t"
1222 "jnz 1f\n\t"
1223 "movq $-1,%0\n\t"
1224 "1:\n\t"
1225 : "=r" (r) : "rm" (x));
1226 return r + 1;
1227}
1228#define HAS_FLS_U64
1229#endif
1230
1231#ifndef HAS_FLS_U64
1232static __attribute__((unused))
1233unsigned int fls_u64(uint64_t x)
1234{
1235 unsigned int r = 64;
1236
1237 if (!x)
1238 return 0;
1239
1240 if (!(x & 0xFFFFFFFF00000000ULL)) {
1241 x <<= 32;
1242 r -= 32;
1243 }
1244 if (!(x & 0xFFFF000000000000ULL)) {
1245 x <<= 16;
1246 r -= 16;
1247 }
1248 if (!(x & 0xFF00000000000000ULL)) {
1249 x <<= 8;
1250 r -= 8;
1251 }
1252 if (!(x & 0xF000000000000000ULL)) {
1253 x <<= 4;
1254 r -= 4;
1255 }
1256 if (!(x & 0xC000000000000000ULL)) {
1257 x <<= 2;
1258 r -= 2;
1259 }
1260 if (!(x & 0x8000000000000000ULL)) {
1261 x <<= 1;
1262 r -= 1;
1263 }
1264 return r;
1265}
1266#endif
1267
cfa9a5a2
DG
1268#ifndef HAS_FLS_U32
1269static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1270{
1271 unsigned int r = 32;
1272
1273 if (!x) {
1274 return 0;
1275 }
1276 if (!(x & 0xFFFF0000U)) {
1277 x <<= 16;
1278 r -= 16;
1279 }
1280 if (!(x & 0xFF000000U)) {
1281 x <<= 8;
1282 r -= 8;
1283 }
1284 if (!(x & 0xF0000000U)) {
1285 x <<= 4;
1286 r -= 4;
1287 }
1288 if (!(x & 0xC0000000U)) {
1289 x <<= 2;
1290 r -= 2;
1291 }
1292 if (!(x & 0x80000000U)) {
1293 x <<= 1;
1294 r -= 1;
1295 }
1296 return r;
1297}
1298#endif
1299
1300/*
1301 * Return the minimum order for which x <= (1UL << order).
1302 * Return -1 if x is 0.
1303 */
1304LTTNG_HIDDEN
1305int utils_get_count_order_u32(uint32_t x)
1306{
1307 if (!x) {
1308 return -1;
1309 }
1310
1311 return fls_u32(x - 1);
1312}
feb0f3e5 1313
db5be0a3
JG
1314/*
1315 * Return the minimum order for which x <= (1UL << order).
1316 * Return -1 if x is 0.
1317 */
1318LTTNG_HIDDEN
1319int utils_get_count_order_u64(uint64_t x)
1320{
1321 if (!x) {
1322 return -1;
1323 }
1324
1325 return fls_u64(x - 1);
1326}
1327
feb0f3e5
AM
1328/**
1329 * Obtain the value of LTTNG_HOME environment variable, if exists.
1330 * Otherwise returns the value of HOME.
1331 */
00a52467 1332LTTNG_HIDDEN
feb0f3e5
AM
1333char *utils_get_home_dir(void)
1334{
1335 char *val = NULL;
04135dbd
DG
1336 struct passwd *pwd;
1337
e8fa9fb0 1338 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
feb0f3e5 1339 if (val != NULL) {
04135dbd
DG
1340 goto end;
1341 }
e8fa9fb0 1342 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
04135dbd
DG
1343 if (val != NULL) {
1344 goto end;
feb0f3e5 1345 }
04135dbd
DG
1346
1347 /* Fallback on the password file entry. */
1348 pwd = getpwuid(getuid());
1349 if (!pwd) {
1350 goto end;
1351 }
1352 val = pwd->pw_dir;
1353
1354 DBG3("Home directory is '%s'", val);
1355
1356end:
1357 return val;
feb0f3e5 1358}
26fe5938 1359
fb198a11
JG
1360/**
1361 * Get user's home directory. Dynamically allocated, must be freed
1362 * by the caller.
1363 */
1364LTTNG_HIDDEN
1365char *utils_get_user_home_dir(uid_t uid)
1366{
1367 struct passwd pwd;
1368 struct passwd *result;
1369 char *home_dir = NULL;
1370 char *buf = NULL;
1371 long buflen;
1372 int ret;
1373
1374 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1375 if (buflen == -1) {
1376 goto end;
1377 }
1378retry:
1379 buf = zmalloc(buflen);
1380 if (!buf) {
1381 goto end;
1382 }
1383
1384 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1385 if (ret || !result) {
1386 if (ret == ERANGE) {
1387 free(buf);
1388 buflen *= 2;
1389 goto retry;
1390 }
1391 goto end;
1392 }
1393
1394 home_dir = strdup(pwd.pw_dir);
1395end:
1396 free(buf);
1397 return home_dir;
1398}
1399
26fe5938
DG
1400/*
1401 * With the given format, fill dst with the time of len maximum siz.
1402 *
1403 * Return amount of bytes set in the buffer or else 0 on error.
1404 */
1405LTTNG_HIDDEN
1406size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1407{
1408 size_t ret;
1409 time_t rawtime;
1410 struct tm *timeinfo;
1411
1412 assert(format);
1413 assert(dst);
1414
1415 /* Get date and time for session path */
1416 time(&rawtime);
1417 timeinfo = localtime(&rawtime);
1418 ret = strftime(dst, len, format, timeinfo);
1419 if (ret == 0) {
68e6efdd 1420 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
1421 dst, len);
1422 }
1423
1424 return ret;
1425}
6c71277b
MD
1426
1427/*
1428 * Return the group ID matching name, else 0 if it cannot be found.
1429 */
1430LTTNG_HIDDEN
1431gid_t utils_get_group_id(const char *name)
1432{
1433 struct group *grp;
1434
1435 grp = getgrnam(name);
1436 if (!grp) {
1437 static volatile int warn_once;
1438
1439 if (!warn_once) {
1440 WARN("No tracing group detected");
1441 warn_once = 1;
1442 }
1443 return 0;
1444 }
1445 return grp->gr_gid;
1446}
8db0dc00
JG
1447
1448/*
1449 * Return a newly allocated option string. This string is to be used as the
1450 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1451 * of elements in the long_options array. Returns NULL if the string's
1452 * allocation fails.
1453 */
1454LTTNG_HIDDEN
1455char *utils_generate_optstring(const struct option *long_options,
1456 size_t opt_count)
1457{
1458 int i;
1459 size_t string_len = opt_count, str_pos = 0;
1460 char *optstring;
1461
1462 /*
1463 * Compute the necessary string length. One letter per option, two when an
1464 * argument is necessary, and a trailing NULL.
1465 */
1466 for (i = 0; i < opt_count; i++) {
1467 string_len += long_options[i].has_arg ? 1 : 0;
1468 }
1469
1470 optstring = zmalloc(string_len);
1471 if (!optstring) {
1472 goto end;
1473 }
1474
1475 for (i = 0; i < opt_count; i++) {
1476 if (!long_options[i].name) {
1477 /* Got to the trailing NULL element */
1478 break;
1479 }
1480
a596dcb9
JG
1481 if (long_options[i].val != '\0') {
1482 optstring[str_pos++] = (char) long_options[i].val;
1483 if (long_options[i].has_arg) {
1484 optstring[str_pos++] = ':';
1485 }
8db0dc00
JG
1486 }
1487 }
1488
1489end:
1490 return optstring;
1491}
3d071855
MD
1492
1493/*
1494 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
9529ec1b 1495 * any file. Try to rmdir any empty directory within the hierarchy.
3d071855
MD
1496 */
1497LTTNG_HIDDEN
1498int utils_recursive_rmdir(const char *path)
1499{
1500 DIR *dir;
7a946beb 1501 size_t path_len;
9529ec1b 1502 int dir_fd, ret = 0, closeret, is_empty = 1;
3d071855
MD
1503 struct dirent *entry;
1504
1505 /* Open directory */
1506 dir = opendir(path);
1507 if (!dir) {
1508 PERROR("Cannot open '%s' path", path);
1509 return -1;
1510 }
5a2451c9 1511 dir_fd = lttng_dirfd(dir);
3d071855 1512 if (dir_fd < 0) {
5a2451c9 1513 PERROR("lttng_dirfd");
3d071855
MD
1514 return -1;
1515 }
1516
7a946beb 1517 path_len = strlen(path);
3d071855 1518 while ((entry = readdir(dir))) {
7a946beb
MJ
1519 struct stat st;
1520 size_t name_len;
1521 char filename[PATH_MAX];
1522
3763af87
JG
1523 if (!strcmp(entry->d_name, ".")
1524 || !strcmp(entry->d_name, "..")) {
1525 continue;
1526 }
1527
7a946beb
MJ
1528 name_len = strlen(entry->d_name);
1529 if (path_len + name_len + 2 > sizeof(filename)) {
1530 ERR("Failed to remove file: path name too long (%s/%s)",
1531 path, entry->d_name);
1532 continue;
1533 }
1534 if (snprintf(filename, sizeof(filename), "%s/%s",
1535 path, entry->d_name) < 0) {
1536 ERR("Failed to format path.");
1537 continue;
1538 }
1539
1540 if (stat(filename, &st)) {
1541 PERROR("stat");
1542 continue;
1543 }
1544
1545 if (S_ISDIR(st.st_mode)) {
3d071855
MD
1546 char subpath[PATH_MAX];
1547
1548 strncpy(subpath, path, PATH_MAX);
1549 subpath[PATH_MAX - 1] = '\0';
1550 strncat(subpath, "/",
1551 PATH_MAX - strlen(subpath) - 1);
1552 strncat(subpath, entry->d_name,
1553 PATH_MAX - strlen(subpath) - 1);
9529ec1b
MD
1554 if (utils_recursive_rmdir(subpath)) {
1555 is_empty = 0;
3d071855 1556 }
7a946beb 1557 } else if (S_ISREG(st.st_mode)) {
9529ec1b 1558 is_empty = 0;
7a946beb 1559 } else {
3d071855
MD
1560 ret = -EINVAL;
1561 goto end;
1562 }
1563 }
1564end:
1565 closeret = closedir(dir);
1566 if (closeret) {
1567 PERROR("closedir");
1568 }
9529ec1b 1569 if (is_empty) {
3d071855
MD
1570 DBG3("Attempting rmdir %s", path);
1571 ret = rmdir(path);
1572 }
1573 return ret;
1574}
93ec662e
JD
1575
1576LTTNG_HIDDEN
1577int utils_truncate_stream_file(int fd, off_t length)
1578{
1579 int ret;
a5df8828 1580 off_t lseek_ret;
93ec662e
JD
1581
1582 ret = ftruncate(fd, length);
1583 if (ret < 0) {
1584 PERROR("ftruncate");
1585 goto end;
1586 }
a5df8828
GL
1587 lseek_ret = lseek(fd, length, SEEK_SET);
1588 if (lseek_ret < 0) {
93ec662e 1589 PERROR("lseek");
a5df8828 1590 ret = -1;
93ec662e
JD
1591 goto end;
1592 }
93ec662e
JD
1593end:
1594 return ret;
1595}
4ba92f18
PP
1596
1597static const char *get_man_bin_path(void)
1598{
b7dce40d 1599 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
4ba92f18
PP
1600
1601 if (env_man_path) {
1602 return env_man_path;
1603 }
1604
1605 return DEFAULT_MAN_BIN_PATH;
1606}
1607
1608LTTNG_HIDDEN
4fc83d94
PP
1609int utils_show_help(int section, const char *page_name,
1610 const char *help_msg)
4ba92f18
PP
1611{
1612 char section_string[8];
1613 const char *man_bin_path = get_man_bin_path();
4fc83d94
PP
1614 int ret = 0;
1615
1616 if (help_msg) {
1617 printf("%s", help_msg);
1618 goto end;
1619 }
4ba92f18
PP
1620
1621 /* Section integer -> section string */
1622 ret = sprintf(section_string, "%d", section);
1623 assert(ret > 0 && ret < 8);
1624
1625 /*
1626 * Execute man pager.
1627 *
b07e7ef0 1628 * We provide -M to man here because LTTng-tools can
4ba92f18
PP
1629 * be installed outside /usr, in which case its man pages are
1630 * not located in the default /usr/share/man directory.
1631 */
b07e7ef0 1632 ret = execlp(man_bin_path, "man", "-M", MANPATH,
4ba92f18 1633 section_string, page_name, NULL);
4fc83d94
PP
1634
1635end:
4ba92f18
PP
1636 return ret;
1637}
This page took 0.132366 seconds and 5 git commands to generate.