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