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