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