6938a5ae52f6cac2e12465b37e3caafe8ae61d23
[lttng-tools.git] / src / common / utils.c
1 /*
2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License, version 2 only, as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11 * more details.
12 *
13 * You should have received a copy of the GNU General Public License along with
14 * this program; if not, write to the Free Software Foundation, Inc., 51
15 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 */
17
18 #define _GNU_SOURCE
19 #include <assert.h>
20 #include <ctype.h>
21 #include <fcntl.h>
22 #include <limits.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 #include <inttypes.h>
29 #include <regex.h>
30 #include <grp.h>
31
32 #include <common/common.h>
33 #include <common/runas.h>
34
35 #include "utils.h"
36 #include "defaults.h"
37
38 /*
39 * Resolve the './' and '../' strings in the middle of a path using
40 * our very own way to do it, so that it works even if the directory
41 * does not exist
42 */
43 LTTNG_HIDDEN
44 char *utils_resolve_relative(const char *path)
45 {
46 char *next, *previous, *slash, *start_path, *absolute_path = NULL;
47
48 /* Safety net */
49 if (path == NULL) {
50 goto error;
51 }
52
53 /* Allocate memory for the absolute path */
54 absolute_path = zmalloc(PATH_MAX);
55 if (absolute_path == NULL) {
56 PERROR("zmalloc expand path");
57 goto error;
58 }
59
60 /* Copy the path in the absolute path */
61 strncpy(absolute_path, path, PATH_MAX);
62
63 /* As long as we find '/./' in the path string */
64 while ((next = strstr(absolute_path, "/./"))) {
65
66 /* We prepare the start_path not containing it */
67 start_path = strndup(absolute_path, next - absolute_path);
68
69 /* And we concatenate it with the part after this string */
70 snprintf(absolute_path, PATH_MAX, "%s%s", start_path, next + 2);
71
72 free(start_path);
73 }
74
75 /* As long as we find '/../' in the path string */
76 while ((next = strstr(absolute_path, "/../"))) {
77 /* If the path starts with '/../', there's a problem */
78 if (next == absolute_path) {
79 ERR("%s: Path cannot be resolved", path);
80 goto error;
81 }
82
83 /* We find the last level of directory */
84 previous = absolute_path;
85 while ((slash = strpbrk(previous + 1, "/")) && slash != next) {
86 previous = slash;
87 }
88
89 /* Then we prepare the start_path not containing it */
90 start_path = strndup(absolute_path, previous - absolute_path);
91
92 /* And we concatenate it with the part after the '/../' */
93 snprintf(absolute_path, PATH_MAX, "%s%s", start_path, next + 3);
94
95 free(start_path);
96 }
97
98 return absolute_path;
99
100 error:
101 free(absolute_path);
102 return NULL;
103 }
104
105
106 /*
107 * Return the realpath(3) of the path even if the last directory token does not
108 * exist. For example, with /tmp/test1/test2, if test2/ does not exist but the
109 * /tmp/test1 does, the real path is returned. In normal time, realpath(3)
110 * fails if the end point directory does not exist.
111 */
112 LTTNG_HIDDEN
113 char *utils_expand_path(const char *path)
114 {
115 const char *end_path = NULL;
116 char *next, *cut_path = NULL, *expanded_path = NULL;
117
118 /* Safety net */
119 if (path == NULL) {
120 goto error;
121 }
122
123 /* Allocate memory for the expanded path */
124 expanded_path = zmalloc(PATH_MAX);
125 if (expanded_path == NULL) {
126 PERROR("zmalloc expand path");
127 goto error;
128 }
129
130 /* If given path is already absolute */
131 if (*path == '/') {
132 strncpy(expanded_path, path, PATH_MAX);
133 /* Else, we have some work to do */
134 } else {
135 /* Pointer to the last char of the path */
136 const char *last_char = path + strlen(path) - 1;
137
138 end_path = path;
139
140 /* Split part that will be resolved by realpath (relative path from
141 * current directory using ./ or ../ only) and part that could not
142 * (directory names)
143 */
144 while ((next = strpbrk(end_path, "/")) && (next != last_char)) {
145 end_path = next + 1;
146 if (strncmp(end_path, "./", 2) != 0 &&
147 strncmp(end_path, "../", 3) != 0) {
148 break;
149 }
150 }
151
152 /* If this is the end of the string, and we still can resolve it */
153 if (strncmp(end_path, "..\0", 3) == 0 ||
154 strncmp(end_path, ".\0", 2) == 0) {
155 end_path += strlen(end_path);
156 }
157
158 /* If the end part is the whole path, we are in the current dir */
159 if (end_path == path) {
160 cut_path = strdup(".");
161 /* Else, cut the resolvable part from original path */
162 } else {
163 cut_path = strndup(path, end_path - path);
164 }
165
166 /* Resolve the canonical path of the first part of the path */
167 expanded_path = realpath((char *)cut_path, expanded_path);
168 if (expanded_path == NULL) {
169 switch (errno) {
170 case ENOENT:
171 ERR("%s: No such file or directory", cut_path);
172 break;
173 default:
174 PERROR("realpath utils expand path");
175 break;
176 }
177 goto error;
178 }
179
180 /* Add end part to expanded path if not empty */
181 if (*end_path != 0) {
182 strncat(expanded_path, "/", PATH_MAX - strlen(expanded_path) - 1);
183 strncat(expanded_path, end_path,
184 PATH_MAX - strlen(expanded_path) - 1);
185 }
186 }
187
188 /* Resolve the internal './' and '../' strings */
189 next = utils_resolve_relative(expanded_path);
190 if (next == NULL) {
191 goto error;
192 }
193
194 free(expanded_path);
195 free(cut_path);
196 return next;
197
198 error:
199 free(expanded_path);
200 free(cut_path);
201 return NULL;
202 }
203
204 /*
205 * Create a pipe in dst.
206 */
207 LTTNG_HIDDEN
208 int utils_create_pipe(int *dst)
209 {
210 int ret;
211
212 if (dst == NULL) {
213 return -1;
214 }
215
216 ret = pipe(dst);
217 if (ret < 0) {
218 PERROR("create pipe");
219 }
220
221 return ret;
222 }
223
224 /*
225 * Create pipe and set CLOEXEC flag to both fd.
226 *
227 * Make sure the pipe opened by this function are closed at some point. Use
228 * utils_close_pipe().
229 */
230 LTTNG_HIDDEN
231 int utils_create_pipe_cloexec(int *dst)
232 {
233 int ret, i;
234
235 if (dst == NULL) {
236 return -1;
237 }
238
239 ret = utils_create_pipe(dst);
240 if (ret < 0) {
241 goto error;
242 }
243
244 for (i = 0; i < 2; i++) {
245 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
246 if (ret < 0) {
247 PERROR("fcntl pipe cloexec");
248 goto error;
249 }
250 }
251
252 error:
253 return ret;
254 }
255
256 /*
257 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
258 *
259 * Make sure the pipe opened by this function are closed at some point. Use
260 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
261 * support OSes other than Linux 2.6.23+.
262 */
263 LTTNG_HIDDEN
264 int utils_create_pipe_cloexec_nonblock(int *dst)
265 {
266 int ret, i;
267
268 if (dst == NULL) {
269 return -1;
270 }
271
272 ret = utils_create_pipe(dst);
273 if (ret < 0) {
274 goto error;
275 }
276
277 for (i = 0; i < 2; i++) {
278 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
279 if (ret < 0) {
280 PERROR("fcntl pipe cloexec");
281 goto error;
282 }
283 /*
284 * Note: we override any flag that could have been
285 * previously set on the fd.
286 */
287 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
288 if (ret < 0) {
289 PERROR("fcntl pipe nonblock");
290 goto error;
291 }
292 }
293
294 error:
295 return ret;
296 }
297
298 /*
299 * Close both read and write side of the pipe.
300 */
301 LTTNG_HIDDEN
302 void utils_close_pipe(int *src)
303 {
304 int i, ret;
305
306 if (src == NULL) {
307 return;
308 }
309
310 for (i = 0; i < 2; i++) {
311 /* Safety check */
312 if (src[i] < 0) {
313 continue;
314 }
315
316 ret = close(src[i]);
317 if (ret) {
318 PERROR("close pipe");
319 }
320 }
321 }
322
323 /*
324 * Create a new string using two strings range.
325 */
326 LTTNG_HIDDEN
327 char *utils_strdupdelim(const char *begin, const char *end)
328 {
329 char *str;
330
331 str = zmalloc(end - begin + 1);
332 if (str == NULL) {
333 PERROR("zmalloc strdupdelim");
334 goto error;
335 }
336
337 memcpy(str, begin, end - begin);
338 str[end - begin] = '\0';
339
340 error:
341 return str;
342 }
343
344 /*
345 * Set CLOEXEC flag to the give file descriptor.
346 */
347 LTTNG_HIDDEN
348 int utils_set_fd_cloexec(int fd)
349 {
350 int ret;
351
352 if (fd < 0) {
353 ret = -EINVAL;
354 goto end;
355 }
356
357 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
358 if (ret < 0) {
359 PERROR("fcntl cloexec");
360 ret = -errno;
361 }
362
363 end:
364 return ret;
365 }
366
367 /*
368 * Create pid file to the given path and filename.
369 */
370 LTTNG_HIDDEN
371 int utils_create_pid_file(pid_t pid, const char *filepath)
372 {
373 int ret;
374 FILE *fp;
375
376 assert(filepath);
377
378 fp = fopen(filepath, "w");
379 if (fp == NULL) {
380 PERROR("open pid file %s", filepath);
381 ret = -1;
382 goto error;
383 }
384
385 ret = fprintf(fp, "%d\n", pid);
386 if (ret < 0) {
387 PERROR("fprintf pid file");
388 }
389
390 fclose(fp);
391 DBG("Pid %d written in file %s", pid, filepath);
392 error:
393 return ret;
394 }
395
396 /*
397 * Recursively create directory using the given path and mode.
398 *
399 * On success, return 0 else a negative error code.
400 */
401 LTTNG_HIDDEN
402 int utils_mkdir_recursive(const char *path, mode_t mode)
403 {
404 char *p, tmp[PATH_MAX];
405 size_t len;
406 int ret;
407
408 assert(path);
409
410 ret = snprintf(tmp, sizeof(tmp), "%s", path);
411 if (ret < 0) {
412 PERROR("snprintf mkdir");
413 goto error;
414 }
415
416 len = ret;
417 if (tmp[len - 1] == '/') {
418 tmp[len - 1] = 0;
419 }
420
421 for (p = tmp + 1; *p; p++) {
422 if (*p == '/') {
423 *p = 0;
424 if (tmp[strlen(tmp) - 1] == '.' &&
425 tmp[strlen(tmp) - 2] == '.' &&
426 tmp[strlen(tmp) - 3] == '/') {
427 ERR("Using '/../' is not permitted in the trace path (%s)",
428 tmp);
429 ret = -1;
430 goto error;
431 }
432 ret = mkdir(tmp, mode);
433 if (ret < 0) {
434 if (errno != EEXIST) {
435 PERROR("mkdir recursive");
436 ret = -errno;
437 goto error;
438 }
439 }
440 *p = '/';
441 }
442 }
443
444 ret = mkdir(tmp, mode);
445 if (ret < 0) {
446 if (errno != EEXIST) {
447 PERROR("mkdir recursive last piece");
448 ret = -errno;
449 } else {
450 ret = 0;
451 }
452 }
453
454 error:
455 return ret;
456 }
457
458 /*
459 * Create the stream tracefile on disk.
460 *
461 * Return 0 on success or else a negative value.
462 */
463 LTTNG_HIDDEN
464 int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
465 uint64_t count, int uid, int gid, char *suffix)
466 {
467 int ret, out_fd, flags, mode;
468 char full_path[PATH_MAX], *path_name_suffix = NULL, *path;
469 char *extra = NULL;
470
471 assert(path_name);
472 assert(file_name);
473
474 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
475 path_name, file_name);
476 if (ret < 0) {
477 PERROR("snprintf create output file");
478 goto error;
479 }
480
481 /* Setup extra string if suffix or/and a count is needed. */
482 if (size > 0 && suffix) {
483 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
484 } else if (size > 0) {
485 ret = asprintf(&extra, "_%" PRIu64, count);
486 } else if (suffix) {
487 ret = asprintf(&extra, "%s", suffix);
488 }
489 if (ret < 0) {
490 PERROR("Allocating extra string to name");
491 goto error;
492 }
493
494 /*
495 * If we split the trace in multiple files, we have to add the count at the
496 * end of the tracefile name
497 */
498 if (extra) {
499 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
500 if (ret < 0) {
501 PERROR("Allocating path name with extra string");
502 goto error_free_suffix;
503 }
504 path = path_name_suffix;
505 } else {
506 path = full_path;
507 }
508
509 flags = O_WRONLY | O_CREAT | O_TRUNC;
510 /* Open with 660 mode */
511 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
512
513 if (uid < 0 || gid < 0) {
514 out_fd = open(path, flags, mode);
515 } else {
516 out_fd = run_as_open(path, flags, mode, uid, gid);
517 }
518 if (out_fd < 0) {
519 PERROR("open stream path %s", path);
520 goto error_open;
521 }
522 ret = out_fd;
523
524 error_open:
525 free(path_name_suffix);
526 error_free_suffix:
527 free(extra);
528 error:
529 return ret;
530 }
531
532 /*
533 * Change the output tracefile according to the given size and count The
534 * new_count pointer is set during this operation.
535 *
536 * From the consumer, the stream lock MUST be held before calling this function
537 * because we are modifying the stream status.
538 *
539 * Return 0 on success or else a negative value.
540 */
541 LTTNG_HIDDEN
542 int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
543 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
544 int *stream_fd)
545 {
546 int ret;
547
548 assert(new_count);
549 assert(stream_fd);
550
551 ret = close(out_fd);
552 if (ret < 0) {
553 PERROR("Closing tracefile");
554 goto error;
555 }
556
557 if (count > 0) {
558 *new_count = (*new_count + 1) % count;
559 } else {
560 (*new_count)++;
561 }
562
563 ret = utils_create_stream_file(path_name, file_name, size, *new_count,
564 uid, gid, 0);
565 if (ret < 0) {
566 goto error;
567 }
568 *stream_fd = ret;
569
570 /* Success. */
571 ret = 0;
572
573 error:
574 return ret;
575 }
576
577 /**
578 * Prints the error message corresponding to a regex error code.
579 *
580 * @param errcode The error code.
581 * @param regex The regex object that produced the error code.
582 */
583 static void regex_print_error(int errcode, regex_t *regex)
584 {
585 /* Get length of error message and allocate accordingly */
586 size_t length;
587 char *buffer;
588
589 assert(regex != NULL);
590
591 length = regerror(errcode, regex, NULL, 0);
592 if (length == 0) {
593 ERR("regerror returned a length of 0");
594 return;
595 }
596
597 buffer = zmalloc(length);
598 if (!buffer) {
599 ERR("regex_print_error: zmalloc failed");
600 return;
601 }
602
603 /* Get and print error message */
604 regerror(errcode, regex, buffer, length);
605 ERR("regex error: %s\n", buffer);
606 free(buffer);
607
608 }
609
610 /**
611 * Parse a string that represents a size in human readable format. It
612 * supports decimal integers suffixed by 'k', 'M' or 'G'.
613 *
614 * The suffix multiply the integer by:
615 * 'k': 1024
616 * 'M': 1024^2
617 * 'G': 1024^3
618 *
619 * @param str The string to parse.
620 * @param size Pointer to a size_t that will be filled with the
621 * resulting size.
622 *
623 * @return 0 on success, -1 on failure.
624 */
625 LTTNG_HIDDEN
626 int utils_parse_size_suffix(char *str, uint64_t *size)
627 {
628 regex_t regex;
629 int ret;
630 const int nmatch = 3;
631 regmatch_t suffix_match, matches[nmatch];
632 unsigned long long base_size;
633 long shift = 0;
634
635 if (!str) {
636 return 0;
637 }
638
639 /* Compile regex */
640 ret = regcomp(&regex, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
641 if (ret != 0) {
642 regex_print_error(ret, &regex);
643 ret = -1;
644 goto end;
645 }
646
647 /* Match regex */
648 ret = regexec(&regex, str, nmatch, matches, 0);
649 if (ret != 0) {
650 ret = -1;
651 goto free;
652 }
653
654 /* There is a match ! */
655 errno = 0;
656 base_size = strtoull(str, NULL, 0);
657 if (errno != 0) {
658 PERROR("strtoull");
659 ret = -1;
660 goto free;
661 }
662
663 /* Check if there is a suffix */
664 suffix_match = matches[2];
665 if (suffix_match.rm_eo - suffix_match.rm_so == 1) {
666 switch (*(str + suffix_match.rm_so)) {
667 case 'K':
668 case 'k':
669 shift = KIBI_LOG2;
670 break;
671 case 'M':
672 shift = MEBI_LOG2;
673 break;
674 case 'G':
675 shift = GIBI_LOG2;
676 break;
677 default:
678 ERR("parse_human_size: invalid suffix");
679 ret = -1;
680 goto free;
681 }
682 }
683
684 *size = base_size << shift;
685
686 /* Check for overflow */
687 if ((*size >> shift) != base_size) {
688 ERR("parse_size_suffix: oops, overflow detected.");
689 ret = -1;
690 goto free;
691 }
692
693 ret = 0;
694
695 free:
696 regfree(&regex);
697 end:
698 return ret;
699 }
700
701 /*
702 * fls: returns the position of the most significant bit.
703 * Returns 0 if no bit is set, else returns the position of the most
704 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
705 */
706 #if defined(__i386) || defined(__x86_64)
707 static inline unsigned int fls_u32(uint32_t x)
708 {
709 int r;
710
711 asm("bsrl %1,%0\n\t"
712 "jnz 1f\n\t"
713 "movl $-1,%0\n\t"
714 "1:\n\t"
715 : "=r" (r) : "rm" (x));
716 return r + 1;
717 }
718 #define HAS_FLS_U32
719 #endif
720
721 #ifndef HAS_FLS_U32
722 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
723 {
724 unsigned int r = 32;
725
726 if (!x) {
727 return 0;
728 }
729 if (!(x & 0xFFFF0000U)) {
730 x <<= 16;
731 r -= 16;
732 }
733 if (!(x & 0xFF000000U)) {
734 x <<= 8;
735 r -= 8;
736 }
737 if (!(x & 0xF0000000U)) {
738 x <<= 4;
739 r -= 4;
740 }
741 if (!(x & 0xC0000000U)) {
742 x <<= 2;
743 r -= 2;
744 }
745 if (!(x & 0x80000000U)) {
746 x <<= 1;
747 r -= 1;
748 }
749 return r;
750 }
751 #endif
752
753 /*
754 * Return the minimum order for which x <= (1UL << order).
755 * Return -1 if x is 0.
756 */
757 LTTNG_HIDDEN
758 int utils_get_count_order_u32(uint32_t x)
759 {
760 if (!x) {
761 return -1;
762 }
763
764 return fls_u32(x - 1);
765 }
766
767 /**
768 * Obtain the value of LTTNG_HOME environment variable, if exists.
769 * Otherwise returns the value of HOME.
770 */
771 LTTNG_HIDDEN
772 char *utils_get_home_dir(void)
773 {
774 char *val = NULL;
775 val = getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
776 if (val != NULL) {
777 return val;
778 }
779 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
780 }
781
782 /*
783 * With the given format, fill dst with the time of len maximum siz.
784 *
785 * Return amount of bytes set in the buffer or else 0 on error.
786 */
787 LTTNG_HIDDEN
788 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
789 {
790 size_t ret;
791 time_t rawtime;
792 struct tm *timeinfo;
793
794 assert(format);
795 assert(dst);
796
797 /* Get date and time for session path */
798 time(&rawtime);
799 timeinfo = localtime(&rawtime);
800 ret = strftime(dst, len, format, timeinfo);
801 if (ret == 0) {
802 ERR("Unable to strftime with format %s at dst %p of len %lu", format,
803 dst, len);
804 }
805
806 return ret;
807 }
808
809 /*
810 * Return the group ID matching name, else 0 if it cannot be found.
811 */
812 LTTNG_HIDDEN
813 gid_t utils_get_group_id(const char *name)
814 {
815 struct group *grp;
816
817 grp = getgrnam(name);
818 if (!grp) {
819 static volatile int warn_once;
820
821 if (!warn_once) {
822 WARN("No tracing group detected");
823 warn_once = 1;
824 }
825 return 0;
826 }
827 return grp->gr_gid;
828 }
This page took 0.070095 seconds and 3 git commands to generate.