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