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