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