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