configure: enable -Wformat=2
[lttng-tools.git] / src / common / utils.cpp
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
a6bc4ca9 114 try_path_buf = (char *) zmalloc(LTTNG_PATH_MAX);
d7c23421
JG
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 151 /* Allocate memory for the resolved path. */
a6bc4ca9 152 resolved_path = (char *) 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
a6bc4ca9 233 next_slash = (const char *) memchr(curr_char, '/', path_last_char - curr_char);
4b223a67
FD
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 */
a6bc4ca9 274 prev_slash = (const char *) lttng_memrchr(path, '/', expanded_path_len);
4b223a67
FD
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 */
a6bc4ca9 332 absolute_path = (char *) 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
416char *utils_expand_path(const char *path)
417{
418 return _utils_expand_path(path, true);
419}
81b86775 420
4b223a67
FD
421char *utils_expand_path_keep_symlink(const char *path)
422{
423 return _utils_expand_path(path, false);
424}
81b86775
DG
425/*
426 * Create a pipe in dst.
427 */
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 */
450int utils_create_pipe_cloexec(int *dst)
451{
452 int ret, i;
453
454 if (dst == NULL) {
455 return -1;
456 }
457
458 ret = utils_create_pipe(dst);
459 if (ret < 0) {
460 goto error;
461 }
462
463 for (i = 0; i < 2; i++) {
464 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
465 if (ret < 0) {
466 PERROR("fcntl pipe cloexec");
467 goto error;
468 }
469 }
470
471error:
472 return ret;
473}
474
094f381c
MD
475/*
476 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
477 *
478 * Make sure the pipe opened by this function are closed at some point. Use
479 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
480 * support OSes other than Linux 2.6.23+.
481 */
094f381c
MD
482int utils_create_pipe_cloexec_nonblock(int *dst)
483{
484 int ret, i;
485
486 if (dst == NULL) {
487 return -1;
488 }
489
490 ret = utils_create_pipe(dst);
491 if (ret < 0) {
492 goto error;
493 }
494
495 for (i = 0; i < 2; i++) {
496 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
497 if (ret < 0) {
498 PERROR("fcntl pipe cloexec");
499 goto error;
500 }
501 /*
502 * Note: we override any flag that could have been
503 * previously set on the fd.
504 */
505 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
506 if (ret < 0) {
507 PERROR("fcntl pipe nonblock");
508 goto error;
509 }
510 }
511
512error:
513 return ret;
514}
515
81b86775
DG
516/*
517 * Close both read and write side of the pipe.
518 */
519void utils_close_pipe(int *src)
520{
521 int i, ret;
522
523 if (src == NULL) {
524 return;
525 }
526
527 for (i = 0; i < 2; i++) {
528 /* Safety check */
529 if (src[i] < 0) {
530 continue;
531 }
532
533 ret = close(src[i]);
534 if (ret) {
535 PERROR("close pipe");
536 }
11f8d2f7 537 src[i] = -1;
81b86775
DG
538 }
539}
a4b92340
DG
540
541/*
542 * Create a new string using two strings range.
543 */
544char *utils_strdupdelim(const char *begin, const char *end)
545{
546 char *str;
547
a6bc4ca9 548 str = (char *) zmalloc(end - begin + 1);
a4b92340
DG
549 if (str == NULL) {
550 PERROR("zmalloc strdupdelim");
551 goto error;
552 }
553
554 memcpy(str, begin, end - begin);
555 str[end - begin] = '\0';
556
557error:
558 return str;
559}
b662582b
DG
560
561/*
562 * Set CLOEXEC flag to the give file descriptor.
563 */
b662582b
DG
564int utils_set_fd_cloexec(int fd)
565{
566 int ret;
567
568 if (fd < 0) {
569 ret = -EINVAL;
570 goto end;
571 }
572
573 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
574 if (ret < 0) {
575 PERROR("fcntl cloexec");
576 ret = -errno;
577 }
578
579end:
580 return ret;
581}
35f90c40
DG
582
583/*
584 * Create pid file to the given path and filename.
585 */
35f90c40
DG
586int utils_create_pid_file(pid_t pid, const char *filepath)
587{
588 int ret;
589 FILE *fp;
590
a0377dfe 591 LTTNG_ASSERT(filepath);
35f90c40
DG
592
593 fp = fopen(filepath, "w");
594 if (fp == NULL) {
595 PERROR("open pid file %s", filepath);
596 ret = -1;
597 goto error;
598 }
599
d1f721c5 600 ret = fprintf(fp, "%d\n", (int) pid);
35f90c40
DG
601 if (ret < 0) {
602 PERROR("fprintf pid file");
e205d79b 603 goto error;
35f90c40
DG
604 }
605
e205d79b
MD
606 if (fclose(fp)) {
607 PERROR("fclose");
608 }
d1f721c5 609 DBG("Pid %d written in file %s", (int) pid, filepath);
e205d79b 610 ret = 0;
35f90c40
DG
611error:
612 return ret;
613}
2d851108 614
c9cb3e7d
JG
615/*
616 * Create lock file to the given path and filename.
617 * Returns the associated file descriptor, -1 on error.
618 */
c9cb3e7d
JG
619int utils_create_lock_file(const char *filepath)
620{
621 int ret;
622 int fd;
77e7fddf 623 struct flock lock;
c9cb3e7d 624
a0377dfe 625 LTTNG_ASSERT(filepath);
c9cb3e7d 626
77e7fddf
MJ
627 memset(&lock, 0, sizeof(lock));
628 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
629 S_IRGRP | S_IWGRP);
c9cb3e7d
JG
630 if (fd < 0) {
631 PERROR("open lock file %s", filepath);
e6576ba2 632 fd = -1;
c9cb3e7d
JG
633 goto error;
634 }
635
636 /*
637 * Attempt to lock the file. If this fails, there is
638 * already a process using the same lock file running
639 * and we should exit.
640 */
77e7fddf
MJ
641 lock.l_whence = SEEK_SET;
642 lock.l_type = F_WRLCK;
643
644 ret = fcntl(fd, F_SETLK, &lock);
645 if (ret == -1) {
646 PERROR("fcntl lock file");
208ff148 647 ERR("Could not get lock file %s, another instance is running.",
c9cb3e7d 648 filepath);
ffb0b851
JG
649 if (close(fd)) {
650 PERROR("close lock file");
651 }
c9cb3e7d
JG
652 fd = ret;
653 goto error;
654 }
655
656error:
657 return fd;
658}
659
2d851108 660/*
d77dded2 661 * Create directory using the given path and mode.
2d851108
DG
662 *
663 * On success, return 0 else a negative error code.
664 */
d77dded2
JG
665int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
666{
667 int ret;
cbf53d23 668 struct lttng_directory_handle *handle;
69e3a560 669 const struct lttng_credentials creds = {
a6bc4ca9
SM
670 .uid = LTTNG_OPTIONAL_INIT_VALUE((uid_t) uid),
671 .gid = LTTNG_OPTIONAL_INIT_VALUE((gid_t) gid),
18710679
JG
672 };
673
cbf53d23
JG
674 handle = lttng_directory_handle_create(NULL);
675 if (!handle) {
676 ret = -1;
fd774fc6
JG
677 goto end;
678 }
18710679 679 ret = lttng_directory_handle_create_subdirectory_as_user(
cbf53d23 680 handle, path, mode,
18710679 681 (uid >= 0 || gid >= 0) ? &creds : NULL);
fd774fc6 682end:
cbf53d23 683 lttng_directory_handle_put(handle);
2d851108
DG
684 return ret;
685}
fe4477ee 686
d77dded2
JG
687/*
688 * Recursively create directory using the given path and mode, under the
689 * provided uid and gid.
690 *
691 * On success, return 0 else a negative error code.
692 */
d77dded2
JG
693int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
694{
695 int ret;
cbf53d23 696 struct lttng_directory_handle *handle;
69e3a560 697 const struct lttng_credentials creds = {
a6bc4ca9
SM
698 .uid = LTTNG_OPTIONAL_INIT_VALUE((uid_t) uid),
699 .gid = LTTNG_OPTIONAL_INIT_VALUE((gid_t) gid),
18710679
JG
700 };
701
cbf53d23
JG
702 handle = lttng_directory_handle_create(NULL);
703 if (!handle) {
704 ret = -1;
fd774fc6
JG
705 goto end;
706 }
18710679 707 ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
cbf53d23 708 handle, path, mode,
18710679 709 (uid >= 0 || gid >= 0) ? &creds : NULL);
fd774fc6 710end:
cbf53d23 711 lttng_directory_handle_put(handle);
d77dded2
JG
712 return ret;
713}
714
fe4477ee 715/*
40804255 716 * out_stream_path is the output parameter.
fe4477ee
JD
717 *
718 * Return 0 on success or else a negative value.
719 */
40804255
JG
720int utils_stream_file_path(const char *path_name, const char *file_name,
721 uint64_t size, uint64_t count, const char *suffix,
722 char *out_stream_path, size_t stream_path_len)
fe4477ee 723{
7591bab1 724 int ret;
d6d89e4c 725 char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
40804255 726 const char *path_separator;
fe4477ee 727
d248f3c2
MD
728 if (path_name && (path_name[0] == '\0' ||
729 path_name[strlen(path_name) - 1] == '/')) {
40804255
JG
730 path_separator = "";
731 } else {
732 path_separator = "/";
fe4477ee
JD
733 }
734
40804255
JG
735 path_name = path_name ? : "";
736 suffix = suffix ? : "";
737 if (size > 0) {
738 ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
739 count);
a0377dfe 740 LTTNG_ASSERT(ret > 0 && ret < sizeof(count_str));
309167d2
JD
741 }
742
d6d89e4c 743 ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
40804255
JG
744 path_name, path_separator, file_name, count_str,
745 suffix);
746 if (ret < 0 || ret >= stream_path_len) {
747 ERR("Truncation occurred while formatting stream path");
748 ret = -1;
fe4477ee 749 } else {
40804255 750 ret = 0;
7591bab1 751 }
7591bab1
MD
752 return ret;
753}
754
70d0b120
SM
755/**
756 * Parse a string that represents a size in human readable format. It
5983a922 757 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
758 *
759 * The suffix multiply the integer by:
760 * 'k': 1024
761 * 'M': 1024^2
762 * 'G': 1024^3
763 *
764 * @param str The string to parse.
5983a922 765 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 766 * resulting size.
70d0b120
SM
767 *
768 * @return 0 on success, -1 on failure.
769 */
5983a922 770int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 771{
70d0b120 772 int ret;
5983a922 773 uint64_t base_size;
70d0b120 774 long shift = 0;
5983a922
SM
775 const char *str_end;
776 char *num_end;
70d0b120
SM
777
778 if (!str) {
5983a922 779 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
780 ret = -1;
781 goto end;
782 }
783
5983a922
SM
784 /* strtoull will accept a negative number, but we don't want to. */
785 if (strchr(str, '-') != NULL) {
786 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 787 ret = -1;
5983a922 788 goto end;
70d0b120
SM
789 }
790
5983a922
SM
791 /* str_end will point to the \0 */
792 str_end = str + strlen(str);
70d0b120 793 errno = 0;
5983a922 794 base_size = strtoull(str, &num_end, 0);
70d0b120 795 if (errno != 0) {
5983a922 796 PERROR("utils_parse_size_suffix strtoull");
70d0b120 797 ret = -1;
5983a922
SM
798 goto end;
799 }
800
801 if (num_end == str) {
802 /* strtoull parsed nothing, not good. */
803 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
804 ret = -1;
805 goto end;
806 }
807
808 /* Check if a prefix is present. */
809 switch (*num_end) {
810 case 'G':
811 shift = GIBI_LOG2;
812 num_end++;
813 break;
814 case 'M': /* */
815 shift = MEBI_LOG2;
816 num_end++;
817 break;
818 case 'K':
819 case 'k':
820 shift = KIBI_LOG2;
821 num_end++;
822 break;
823 case '\0':
824 break;
825 default:
826 DBG("utils_parse_size_suffix: invalid suffix.");
827 ret = -1;
828 goto end;
829 }
830
831 /* Check for garbage after the valid input. */
832 if (num_end != str_end) {
833 DBG("utils_parse_size_suffix: Garbage after size string.");
834 ret = -1;
835 goto end;
70d0b120
SM
836 }
837
838 *size = base_size << shift;
839
840 /* Check for overflow */
841 if ((*size >> shift) != base_size) {
5983a922 842 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 843 ret = -1;
5983a922 844 goto end;
70d0b120
SM
845 }
846
847 ret = 0;
70d0b120
SM
848end:
849 return ret;
850}
cfa9a5a2 851
7010c033
SM
852/**
853 * Parse a string that represents a time in human readable format. It
81684730
JR
854 * supports decimal integers suffixed by:
855 * "us" for microsecond,
856 * "ms" for millisecond,
857 * "s" for second,
858 * "m" for minute,
859 * "h" for hour
7010c033
SM
860 *
861 * The suffix multiply the integer by:
81684730
JR
862 * "us" : 1
863 * "ms" : 1000
864 * "s" : 1000000
865 * "m" : 60000000
866 * "h" : 3600000000
7010c033
SM
867 *
868 * Note that unit-less numbers are assumed to be microseconds.
869 *
870 * @param str The string to parse, assumed to be NULL-terminated.
871 * @param time_us Pointer to a uint64_t that will be filled with the
872 * resulting time in microseconds.
873 *
874 * @return 0 on success, -1 on failure.
875 */
7010c033
SM
876int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
877{
878 int ret;
879 uint64_t base_time;
81684730 880 uint64_t multiplier = 1;
7010c033
SM
881 const char *str_end;
882 char *num_end;
883
884 if (!str) {
885 DBG("utils_parse_time_suffix: received a NULL string.");
886 ret = -1;
887 goto end;
888 }
889
890 /* strtoull will accept a negative number, but we don't want to. */
891 if (strchr(str, '-') != NULL) {
892 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
893 ret = -1;
894 goto end;
895 }
896
897 /* str_end will point to the \0 */
898 str_end = str + strlen(str);
899 errno = 0;
900 base_time = strtoull(str, &num_end, 10);
901 if (errno != 0) {
902 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
903 ret = -1;
904 goto end;
905 }
906
907 if (num_end == str) {
908 /* strtoull parsed nothing, not good. */
909 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
910 ret = -1;
911 goto end;
912 }
913
914 /* Check if a prefix is present. */
915 switch (*num_end) {
916 case 'u':
81684730
JR
917 /*
918 * Microsecond (us)
919 *
920 * Skip the "us" if the string matches the "us" suffix,
921 * otherwise let the check for the end of the string handle
922 * the error reporting.
923 */
924 if (*(num_end + 1) == 's') {
925 num_end += 2;
926 }
7010c033
SM
927 break;
928 case 'm':
81684730
JR
929 if (*(num_end + 1) == 's') {
930 /* Millisecond (ms) */
931 multiplier = USEC_PER_MSEC;
932 /* Skip the 's' */
933 num_end++;
934 } else {
935 /* Minute (m) */
936 multiplier = USEC_PER_MINUTE;
937 }
938 num_end++;
7010c033
SM
939 break;
940 case 's':
81684730
JR
941 /* Second */
942 multiplier = USEC_PER_SEC;
943 num_end++;
944 break;
945 case 'h':
946 /* Hour */
947 multiplier = USEC_PER_HOURS;
7010c033
SM
948 num_end++;
949 break;
950 case '\0':
951 break;
952 default:
953 DBG("utils_parse_time_suffix: invalid suffix.");
954 ret = -1;
955 goto end;
956 }
957
958 /* Check for garbage after the valid input. */
959 if (num_end != str_end) {
960 DBG("utils_parse_time_suffix: Garbage after time string.");
961 ret = -1;
962 goto end;
963 }
964
965 *time_us = base_time * multiplier;
966
967 /* Check for overflow */
968 if ((*time_us / multiplier) != base_time) {
969 DBG("utils_parse_time_suffix: oops, overflow detected.");
970 ret = -1;
971 goto end;
972 }
973
974 ret = 0;
975end:
976 return ret;
977}
978
cfa9a5a2
DG
979/*
980 * fls: returns the position of the most significant bit.
981 * Returns 0 if no bit is set, else returns the position of the most
982 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
983 */
984#if defined(__i386) || defined(__x86_64)
985static inline unsigned int fls_u32(uint32_t x)
986{
987 int r;
988
989 asm("bsrl %1,%0\n\t"
990 "jnz 1f\n\t"
991 "movl $-1,%0\n\t"
992 "1:\n\t"
993 : "=r" (r) : "rm" (x));
994 return r + 1;
995}
996#define HAS_FLS_U32
997#endif
998
a1e4ab8b 999#if defined(__x86_64) && defined(__LP64__)
db5be0a3
JG
1000static inline
1001unsigned int fls_u64(uint64_t x)
1002{
1003 long r;
1004
1005 asm("bsrq %1,%0\n\t"
1006 "jnz 1f\n\t"
1007 "movq $-1,%0\n\t"
1008 "1:\n\t"
1009 : "=r" (r) : "rm" (x));
1010 return r + 1;
1011}
1012#define HAS_FLS_U64
1013#endif
1014
1015#ifndef HAS_FLS_U64
1016static __attribute__((unused))
1017unsigned int fls_u64(uint64_t x)
1018{
1019 unsigned int r = 64;
1020
1021 if (!x)
1022 return 0;
1023
1024 if (!(x & 0xFFFFFFFF00000000ULL)) {
1025 x <<= 32;
1026 r -= 32;
1027 }
1028 if (!(x & 0xFFFF000000000000ULL)) {
1029 x <<= 16;
1030 r -= 16;
1031 }
1032 if (!(x & 0xFF00000000000000ULL)) {
1033 x <<= 8;
1034 r -= 8;
1035 }
1036 if (!(x & 0xF000000000000000ULL)) {
1037 x <<= 4;
1038 r -= 4;
1039 }
1040 if (!(x & 0xC000000000000000ULL)) {
1041 x <<= 2;
1042 r -= 2;
1043 }
1044 if (!(x & 0x8000000000000000ULL)) {
1045 x <<= 1;
1046 r -= 1;
1047 }
1048 return r;
1049}
1050#endif
1051
cfa9a5a2
DG
1052#ifndef HAS_FLS_U32
1053static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1054{
1055 unsigned int r = 32;
1056
1057 if (!x) {
1058 return 0;
1059 }
1060 if (!(x & 0xFFFF0000U)) {
1061 x <<= 16;
1062 r -= 16;
1063 }
1064 if (!(x & 0xFF000000U)) {
1065 x <<= 8;
1066 r -= 8;
1067 }
1068 if (!(x & 0xF0000000U)) {
1069 x <<= 4;
1070 r -= 4;
1071 }
1072 if (!(x & 0xC0000000U)) {
1073 x <<= 2;
1074 r -= 2;
1075 }
1076 if (!(x & 0x80000000U)) {
1077 x <<= 1;
1078 r -= 1;
1079 }
1080 return r;
1081}
1082#endif
1083
1084/*
1085 * Return the minimum order for which x <= (1UL << order).
1086 * Return -1 if x is 0.
1087 */
cfa9a5a2
DG
1088int utils_get_count_order_u32(uint32_t x)
1089{
1090 if (!x) {
1091 return -1;
1092 }
1093
1094 return fls_u32(x - 1);
1095}
feb0f3e5 1096
db5be0a3
JG
1097/*
1098 * Return the minimum order for which x <= (1UL << order).
1099 * Return -1 if x is 0.
1100 */
db5be0a3
JG
1101int utils_get_count_order_u64(uint64_t x)
1102{
1103 if (!x) {
1104 return -1;
1105 }
1106
1107 return fls_u64(x - 1);
1108}
1109
feb0f3e5
AM
1110/**
1111 * Obtain the value of LTTNG_HOME environment variable, if exists.
1112 * Otherwise returns the value of HOME.
1113 */
4f00620d 1114const char *utils_get_home_dir(void)
feb0f3e5
AM
1115{
1116 char *val = NULL;
04135dbd
DG
1117 struct passwd *pwd;
1118
e8fa9fb0 1119 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
feb0f3e5 1120 if (val != NULL) {
04135dbd
DG
1121 goto end;
1122 }
e8fa9fb0 1123 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
04135dbd
DG
1124 if (val != NULL) {
1125 goto end;
feb0f3e5 1126 }
04135dbd
DG
1127
1128 /* Fallback on the password file entry. */
1129 pwd = getpwuid(getuid());
1130 if (!pwd) {
1131 goto end;
1132 }
1133 val = pwd->pw_dir;
1134
1135 DBG3("Home directory is '%s'", val);
1136
1137end:
1138 return val;
feb0f3e5 1139}
26fe5938 1140
fb198a11
JG
1141/**
1142 * Get user's home directory. Dynamically allocated, must be freed
1143 * by the caller.
1144 */
fb198a11
JG
1145char *utils_get_user_home_dir(uid_t uid)
1146{
1147 struct passwd pwd;
1148 struct passwd *result;
1149 char *home_dir = NULL;
1150 char *buf = NULL;
1151 long buflen;
1152 int ret;
1153
1154 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1155 if (buflen == -1) {
1156 goto end;
1157 }
1158retry:
a6bc4ca9 1159 buf = (char *) zmalloc(buflen);
fb198a11
JG
1160 if (!buf) {
1161 goto end;
1162 }
1163
1164 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1165 if (ret || !result) {
1166 if (ret == ERANGE) {
1167 free(buf);
1168 buflen *= 2;
1169 goto retry;
1170 }
1171 goto end;
1172 }
1173
1174 home_dir = strdup(pwd.pw_dir);
1175end:
1176 free(buf);
1177 return home_dir;
1178}
1179
26fe5938
DG
1180/*
1181 * With the given format, fill dst with the time of len maximum siz.
1182 *
1183 * Return amount of bytes set in the buffer or else 0 on error.
1184 */
26fe5938
DG
1185size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1186{
1187 size_t ret;
1188 time_t rawtime;
1189 struct tm *timeinfo;
1190
a0377dfe
FD
1191 LTTNG_ASSERT(format);
1192 LTTNG_ASSERT(dst);
26fe5938
DG
1193
1194 /* Get date and time for session path */
1195 time(&rawtime);
1196 timeinfo = localtime(&rawtime);
411b3154
SM
1197 DIAGNOSTIC_PUSH
1198 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
26fe5938 1199 ret = strftime(dst, len, format, timeinfo);
411b3154 1200 DIAGNOSTIC_POP
26fe5938 1201 if (ret == 0) {
68e6efdd 1202 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
1203 dst, len);
1204 }
1205
1206 return ret;
1207}
6c71277b
MD
1208
1209/*
28ab59d0
JR
1210 * Return 0 on success and set *gid to the group_ID matching the passed name.
1211 * Else -1 if it cannot be found or an error occurred.
6c71277b 1212 */
28ab59d0 1213int utils_get_group_id(const char *name, bool warn, gid_t *gid)
6c71277b 1214{
28ab59d0
JR
1215 static volatile int warn_once;
1216 int ret;
1217 long sys_len;
1218 size_t len;
1219 struct group grp;
1220 struct group *result;
1221 struct lttng_dynamic_buffer buffer;
1222
1223 /* Get the system limit, if it exists. */
1224 sys_len = sysconf(_SC_GETGR_R_SIZE_MAX);
1225 if (sys_len == -1) {
1226 len = 1024;
1227 } else {
1228 len = (size_t) sys_len;
1229 }
1230
1231 lttng_dynamic_buffer_init(&buffer);
1232 ret = lttng_dynamic_buffer_set_size(&buffer, len);
1233 if (ret) {
1234 ERR("Failed to allocate group info buffer");
1235 ret = -1;
1236 goto error;
1237 }
6c71277b 1238
28ab59d0
JR
1239 while ((ret = getgrnam_r(name, &grp, buffer.data, buffer.size, &result)) == ERANGE) {
1240 const size_t new_len = 2 * buffer.size;
6c71277b 1241
28ab59d0
JR
1242 /* Buffer is not big enough, increase its size. */
1243 if (new_len < buffer.size) {
1244 ERR("Group info buffer size overflow");
1245 ret = -1;
1246 goto error;
1247 }
1248
1249 ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
1250 if (ret) {
1251 ERR("Failed to grow group info buffer to %zu bytes",
1252 new_len);
1253 ret = -1;
1254 goto error;
6c71277b 1255 }
6c71277b 1256 }
28ab59d0 1257 if (ret) {
9120e619
JG
1258 if (ret == ESRCH) {
1259 DBG("Could not find group file entry for group name '%s'",
1260 name);
1261 } else {
1262 PERROR("Failed to get group file entry for group name '%s'",
1263 name);
1264 }
1265
28ab59d0
JR
1266 ret = -1;
1267 goto error;
1268 }
1269
1270 /* Group not found. */
1271 if (!result) {
1272 ret = -1;
1273 goto error;
1274 }
1275
1276 *gid = result->gr_gid;
1277 ret = 0;
1278
1279error:
1280 if (ret && warn && !warn_once) {
1281 WARN("No tracing group detected");
1282 warn_once = 1;
1283 }
1284 lttng_dynamic_buffer_reset(&buffer);
1285 return ret;
6c71277b 1286}
8db0dc00
JG
1287
1288/*
1289 * Return a newly allocated option string. This string is to be used as the
1290 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1291 * of elements in the long_options array. Returns NULL if the string's
1292 * allocation fails.
1293 */
8db0dc00
JG
1294char *utils_generate_optstring(const struct option *long_options,
1295 size_t opt_count)
1296{
1297 int i;
1298 size_t string_len = opt_count, str_pos = 0;
1299 char *optstring;
1300
1301 /*
1302 * Compute the necessary string length. One letter per option, two when an
1303 * argument is necessary, and a trailing NULL.
1304 */
1305 for (i = 0; i < opt_count; i++) {
1306 string_len += long_options[i].has_arg ? 1 : 0;
1307 }
1308
a6bc4ca9 1309 optstring = (char *) zmalloc(string_len);
8db0dc00
JG
1310 if (!optstring) {
1311 goto end;
1312 }
1313
1314 for (i = 0; i < opt_count; i++) {
1315 if (!long_options[i].name) {
1316 /* Got to the trailing NULL element */
1317 break;
1318 }
1319
a596dcb9
JG
1320 if (long_options[i].val != '\0') {
1321 optstring[str_pos++] = (char) long_options[i].val;
1322 if (long_options[i].has_arg) {
1323 optstring[str_pos++] = ':';
1324 }
8db0dc00
JG
1325 }
1326 }
1327
1328end:
1329 return optstring;
1330}
3d071855
MD
1331
1332/*
1333 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
9529ec1b 1334 * any file. Try to rmdir any empty directory within the hierarchy.
3d071855 1335 */
3d071855
MD
1336int utils_recursive_rmdir(const char *path)
1337{
93bed9fe 1338 int ret;
cbf53d23 1339 struct lttng_directory_handle *handle;
7a946beb 1340
cbf53d23
JG
1341 handle = lttng_directory_handle_create(NULL);
1342 if (!handle) {
1343 ret = -1;
93bed9fe 1344 goto end;
3d071855 1345 }
cbf53d23 1346 ret = lttng_directory_handle_remove_subdirectory(handle, path);
3d071855 1347end:
cbf53d23 1348 lttng_directory_handle_put(handle);
3d071855
MD
1349 return ret;
1350}
93ec662e 1351
93ec662e
JD
1352int utils_truncate_stream_file(int fd, off_t length)
1353{
1354 int ret;
a5df8828 1355 off_t lseek_ret;
93ec662e
JD
1356
1357 ret = ftruncate(fd, length);
1358 if (ret < 0) {
1359 PERROR("ftruncate");
1360 goto end;
1361 }
a5df8828
GL
1362 lseek_ret = lseek(fd, length, SEEK_SET);
1363 if (lseek_ret < 0) {
93ec662e 1364 PERROR("lseek");
a5df8828 1365 ret = -1;
93ec662e
JD
1366 goto end;
1367 }
93ec662e
JD
1368end:
1369 return ret;
1370}
4ba92f18
PP
1371
1372static const char *get_man_bin_path(void)
1373{
b7dce40d 1374 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
4ba92f18
PP
1375
1376 if (env_man_path) {
1377 return env_man_path;
1378 }
1379
1380 return DEFAULT_MAN_BIN_PATH;
1381}
1382
4fc83d94
PP
1383int utils_show_help(int section, const char *page_name,
1384 const char *help_msg)
4ba92f18
PP
1385{
1386 char section_string[8];
1387 const char *man_bin_path = get_man_bin_path();
4fc83d94
PP
1388 int ret = 0;
1389
1390 if (help_msg) {
1391 printf("%s", help_msg);
1392 goto end;
1393 }
4ba92f18
PP
1394
1395 /* Section integer -> section string */
1396 ret = sprintf(section_string, "%d", section);
a0377dfe 1397 LTTNG_ASSERT(ret > 0 && ret < 8);
4ba92f18
PP
1398
1399 /*
1400 * Execute man pager.
1401 *
b07e7ef0 1402 * We provide -M to man here because LTTng-tools can
4ba92f18
PP
1403 * be installed outside /usr, in which case its man pages are
1404 * not located in the default /usr/share/man directory.
1405 */
b07e7ef0 1406 ret = execlp(man_bin_path, "man", "-M", MANPATH,
4ba92f18 1407 section_string, page_name, NULL);
4fc83d94
PP
1408
1409end:
4ba92f18
PP
1410 return ret;
1411}
09b72f7a
FD
1412
1413static
1414int read_proc_meminfo_field(const char *field, size_t *value)
1415{
1416 int ret;
1417 FILE *proc_meminfo;
1418 char name[PROC_MEMINFO_FIELD_MAX_NAME_LEN] = {};
1419
1420 proc_meminfo = fopen(PROC_MEMINFO_PATH, "r");
1421 if (!proc_meminfo) {
1422 PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
1423 ret = -1;
1424 goto fopen_error;
1425 }
1426
1427 /*
1428 * Read the contents of /proc/meminfo line by line to find the right
1429 * field.
1430 */
1431 while (!feof(proc_meminfo)) {
1432 unsigned long value_kb;
1433
1434 ret = fscanf(proc_meminfo,
1435 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n",
1436 name, &value_kb);
1437 if (ret == EOF) {
1438 /*
1439 * fscanf() returning EOF can indicate EOF or an error.
1440 */
1441 if (ferror(proc_meminfo)) {
1442 PERROR("Failed to parse " PROC_MEMINFO_PATH);
1443 }
1444 break;
1445 }
1446
1447 if (ret == 2 && strcmp(name, field) == 0) {
1448 /*
1449 * This number is displayed in kilo-bytes. Return the
1450 * number of bytes.
1451 */
1452 *value = ((size_t) value_kb) * 1024;
1453 ret = 0;
1454 goto found;
1455 }
1456 }
1457 /* Reached the end of the file without finding the right field. */
1458 ret = -1;
1459
1460found:
1461 fclose(proc_meminfo);
1462fopen_error:
1463 return ret;
1464}
1465
1466/*
1467 * Returns an estimate of the number of bytes of memory available based on the
1468 * the information in `/proc/meminfo`. The number returned by this function is
1469 * a best guess.
1470 */
09b72f7a
FD
1471int utils_get_memory_available(size_t *value)
1472{
1473 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value);
1474}
1475
1476/*
1477 * Returns the total size of the memory on the system in bytes based on the
1478 * the information in `/proc/meminfo`.
1479 */
09b72f7a
FD
1480int utils_get_memory_total(size_t *value)
1481{
1482 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value);
1483}
ce9ee1fb 1484
ce9ee1fb
JR
1485int utils_change_working_directory(const char *path)
1486{
1487 int ret;
1488
a0377dfe 1489 LTTNG_ASSERT(path);
ce9ee1fb
JR
1490
1491 DBG("Changing working directory to \"%s\"", path);
1492 ret = chdir(path);
1493 if (ret) {
1494 PERROR("Failed to change working directory to \"%s\"", path);
1495 goto end;
1496 }
1497
1498 /* Check for write access */
1499 if (access(path, W_OK)) {
1500 if (errno == EACCES) {
1501 /*
1502 * Do not treat this as an error since the permission
1503 * might change in the lifetime of the process
1504 */
1505 DBG("Working directory \"%s\" is not writable", path);
1506 } else {
1507 PERROR("Failed to check if working directory \"%s\" is writable",
1508 path);
1509 }
1510 }
1511
1512end:
1513 return ret;
1514}
159b042f 1515
159b042f
JG
1516enum lttng_error_code utils_user_id_from_name(const char *user_name, uid_t *uid)
1517{
1518 struct passwd p, *pres;
1519 int ret;
1520 enum lttng_error_code ret_val = LTTNG_OK;
1521 char *buf = NULL;
1522 ssize_t buflen;
1523
1524 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1525 if (buflen < 0) {
1526 buflen = FALLBACK_USER_BUFLEN;
1527 }
1528
a6bc4ca9 1529 buf = (char *) zmalloc(buflen);
159b042f
JG
1530 if (!buf) {
1531 ret_val = LTTNG_ERR_NOMEM;
1532 goto end;
1533 }
1534
1535 for (;;) {
1536 ret = getpwnam_r(user_name, &p, buf, buflen, &pres);
1537 switch (ret) {
1538 case EINTR:
1539 continue;
1540 case ERANGE:
1541 buflen *= 2;
1542 free(buf);
a6bc4ca9 1543 buf = (char *) zmalloc(buflen);
159b042f
JG
1544 if (!buf) {
1545 ret_val = LTTNG_ERR_NOMEM;
1546 goto end;
1547 }
1548 continue;
1549 default:
1550 goto end_loop;
1551 }
1552 }
1553end_loop:
1554
1555 switch (ret) {
1556 case 0:
1557 if (pres == NULL) {
1558 ret_val = LTTNG_ERR_USER_NOT_FOUND;
1559 } else {
1560 *uid = p.pw_uid;
1561 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64,
1562 user_name, (int64_t) *uid);
1563 ret_val = LTTNG_OK;
1564 }
1565 break;
1566 case ENOENT:
1567 case ESRCH:
1568 case EBADF:
1569 case EPERM:
1570 ret_val = LTTNG_ERR_USER_NOT_FOUND;
1571 break;
1572 default:
1573 ret_val = LTTNG_ERR_NOMEM;
1574 }
1575end:
1576 free(buf);
1577 return ret_val;
1578}
1579
159b042f
JG
1580enum lttng_error_code utils_group_id_from_name(
1581 const char *group_name, gid_t *gid)
1582{
1583 struct group g, *gres;
1584 int ret;
1585 enum lttng_error_code ret_val = LTTNG_OK;
1586 char *buf = NULL;
1587 ssize_t buflen;
1588
1589 buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
1590 if (buflen < 0) {
1591 buflen = FALLBACK_GROUP_BUFLEN;
1592 }
1593
a6bc4ca9 1594 buf = (char *) zmalloc(buflen);
159b042f
JG
1595 if (!buf) {
1596 ret_val = LTTNG_ERR_NOMEM;
1597 goto end;
1598 }
1599
1600 for (;;) {
1601 ret = getgrnam_r(group_name, &g, buf, buflen, &gres);
1602 switch (ret) {
1603 case EINTR:
1604 continue;
1605 case ERANGE:
1606 buflen *= 2;
1607 free(buf);
a6bc4ca9 1608 buf = (char *) zmalloc(buflen);
159b042f
JG
1609 if (!buf) {
1610 ret_val = LTTNG_ERR_NOMEM;
1611 goto end;
1612 }
1613 continue;
1614 default:
1615 goto end_loop;
1616 }
1617 }
1618end_loop:
1619
1620 switch (ret) {
1621 case 0:
1622 if (gres == NULL) {
1623 ret_val = LTTNG_ERR_GROUP_NOT_FOUND;
1624 } else {
1625 *gid = g.gr_gid;
1626 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64,
1627 group_name, (int64_t) *gid);
1628 ret_val = LTTNG_OK;
1629 }
1630 break;
1631 case ENOENT:
1632 case ESRCH:
1633 case EBADF:
1634 case EPERM:
1635 ret_val = LTTNG_ERR_GROUP_NOT_FOUND;
1636 break;
1637 default:
1638 ret_val = LTTNG_ERR_NOMEM;
1639 }
1640end:
1641 free(buf);
1642 return ret_val;
1643}
240baf2b 1644
240baf2b
JR
1645int utils_parse_unsigned_long_long(const char *str,
1646 unsigned long long *value)
1647{
1648 int ret;
1649 char *endptr;
1650
a0377dfe
FD
1651 LTTNG_ASSERT(str);
1652 LTTNG_ASSERT(value);
240baf2b
JR
1653
1654 errno = 0;
1655 *value = strtoull(str, &endptr, 10);
1656
1657 /* Conversion failed. Out of range? */
1658 if (errno != 0) {
1659 /* Don't print an error; allow the caller to log a better error. */
1660 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1661 str, errno);
1662 ret = -1;
1663 goto end;
1664 }
1665
1666 /* Not the end of the string or empty string. */
1667 if (*endptr || endptr == str) {
1668 DBG("Failed to parse string as unsigned long long number: string = '%s'",
1669 str);
1670 ret = -1;
1671 goto end;
1672 }
1673
1674 ret = 0;
1675
1676end:
1677 return ret;
1678}
This page took 0.140642 seconds and 4 git commands to generate.