Fix: consumer handling of metadata for relayd
[lttng-tools.git] / src / common / utils.c
CommitLineData
81b86775
DG
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
35f90c40 19#include <assert.h>
81b86775
DG
20#include <ctype.h>
21#include <fcntl.h>
22#include <limits.h>
23#include <stdlib.h>
24#include <string.h>
2d851108 25#include <sys/stat.h>
0c7bcad5 26#include <sys/types.h>
2d851108 27#include <unistd.h>
fe4477ee 28#include <inttypes.h>
70d0b120 29#include <regex.h>
81b86775
DG
30
31#include <common/common.h>
fe4477ee 32#include <common/runas.h>
81b86775
DG
33
34#include "utils.h"
feb0f3e5 35#include "defaults.h"
81b86775
DG
36
37/*
38 * Return the realpath(3) of the path even if the last directory token does not
39 * exist. For example, with /tmp/test1/test2, if test2/ does not exist but the
40 * /tmp/test1 does, the real path is returned. In normal time, realpath(3)
41 * fails if the end point directory does not exist.
42 */
90e535ef 43LTTNG_HIDDEN
81b86775
DG
44char *utils_expand_path(const char *path)
45{
46 const char *end_path = path;
47 char *next, *cut_path = NULL, *expanded_path = NULL;
48
49 /* Safety net */
50 if (path == NULL) {
51 goto error;
52 }
53
54 /* Find last token delimited by '/' */
55 while ((next = strpbrk(end_path + 1, "/"))) {
56 end_path = next;
57 }
58
59 /* Cut last token from original path */
60 cut_path = strndup(path, end_path - path);
61
62 expanded_path = zmalloc(PATH_MAX);
63 if (expanded_path == NULL) {
64 PERROR("zmalloc expand path");
65 goto error;
66 }
67
68 expanded_path = realpath((char *)cut_path, expanded_path);
69 if (expanded_path == NULL) {
70 switch (errno) {
71 case ENOENT:
72 ERR("%s: No such file or directory", cut_path);
73 break;
74 default:
75 PERROR("realpath utils expand path");
76 break;
77 }
78 goto error;
79 }
80
81 /* Add end part to expanded path */
c30ce0b3 82 strncat(expanded_path, end_path, PATH_MAX - strlen(expanded_path) - 1);
81b86775
DG
83
84 free(cut_path);
85 return expanded_path;
86
87error:
88 free(expanded_path);
89 free(cut_path);
90 return NULL;
91}
92
93/*
94 * Create a pipe in dst.
95 */
90e535ef 96LTTNG_HIDDEN
81b86775
DG
97int utils_create_pipe(int *dst)
98{
99 int ret;
100
101 if (dst == NULL) {
102 return -1;
103 }
104
105 ret = pipe(dst);
106 if (ret < 0) {
107 PERROR("create pipe");
108 }
109
110 return ret;
111}
112
113/*
114 * Create pipe and set CLOEXEC flag to both fd.
115 *
116 * Make sure the pipe opened by this function are closed at some point. Use
117 * utils_close_pipe().
118 */
90e535ef 119LTTNG_HIDDEN
81b86775
DG
120int utils_create_pipe_cloexec(int *dst)
121{
122 int ret, i;
123
124 if (dst == NULL) {
125 return -1;
126 }
127
128 ret = utils_create_pipe(dst);
129 if (ret < 0) {
130 goto error;
131 }
132
133 for (i = 0; i < 2; i++) {
134 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
135 if (ret < 0) {
136 PERROR("fcntl pipe cloexec");
137 goto error;
138 }
139 }
140
141error:
142 return ret;
143}
144
145/*
146 * Close both read and write side of the pipe.
147 */
90e535ef 148LTTNG_HIDDEN
81b86775
DG
149void utils_close_pipe(int *src)
150{
151 int i, ret;
152
153 if (src == NULL) {
154 return;
155 }
156
157 for (i = 0; i < 2; i++) {
158 /* Safety check */
159 if (src[i] < 0) {
160 continue;
161 }
162
163 ret = close(src[i]);
164 if (ret) {
165 PERROR("close pipe");
166 }
167 }
168}
a4b92340
DG
169
170/*
171 * Create a new string using two strings range.
172 */
90e535ef 173LTTNG_HIDDEN
a4b92340
DG
174char *utils_strdupdelim(const char *begin, const char *end)
175{
176 char *str;
177
178 str = zmalloc(end - begin + 1);
179 if (str == NULL) {
180 PERROR("zmalloc strdupdelim");
181 goto error;
182 }
183
184 memcpy(str, begin, end - begin);
185 str[end - begin] = '\0';
186
187error:
188 return str;
189}
b662582b
DG
190
191/*
192 * Set CLOEXEC flag to the give file descriptor.
193 */
90e535ef 194LTTNG_HIDDEN
b662582b
DG
195int utils_set_fd_cloexec(int fd)
196{
197 int ret;
198
199 if (fd < 0) {
200 ret = -EINVAL;
201 goto end;
202 }
203
204 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
205 if (ret < 0) {
206 PERROR("fcntl cloexec");
207 ret = -errno;
208 }
209
210end:
211 return ret;
212}
35f90c40
DG
213
214/*
215 * Create pid file to the given path and filename.
216 */
90e535ef 217LTTNG_HIDDEN
35f90c40
DG
218int utils_create_pid_file(pid_t pid, const char *filepath)
219{
220 int ret;
221 FILE *fp;
222
223 assert(filepath);
224
225 fp = fopen(filepath, "w");
226 if (fp == NULL) {
227 PERROR("open pid file %s", filepath);
228 ret = -1;
229 goto error;
230 }
231
232 ret = fprintf(fp, "%d\n", pid);
233 if (ret < 0) {
234 PERROR("fprintf pid file");
235 }
236
237 fclose(fp);
238 DBG("Pid %d written in file %s", pid, filepath);
239error:
240 return ret;
241}
2d851108
DG
242
243/*
244 * Recursively create directory using the given path and mode.
245 *
246 * On success, return 0 else a negative error code.
247 */
90e535ef 248LTTNG_HIDDEN
2d851108
DG
249int utils_mkdir_recursive(const char *path, mode_t mode)
250{
251 char *p, tmp[PATH_MAX];
2d851108
DG
252 size_t len;
253 int ret;
254
255 assert(path);
256
257 ret = snprintf(tmp, sizeof(tmp), "%s", path);
258 if (ret < 0) {
259 PERROR("snprintf mkdir");
260 goto error;
261 }
262
263 len = ret;
264 if (tmp[len - 1] == '/') {
265 tmp[len - 1] = 0;
266 }
267
268 for (p = tmp + 1; *p; p++) {
269 if (*p == '/') {
270 *p = 0;
271 if (tmp[strlen(tmp) - 1] == '.' &&
272 tmp[strlen(tmp) - 2] == '.' &&
273 tmp[strlen(tmp) - 3] == '/') {
274 ERR("Using '/../' is not permitted in the trace path (%s)",
275 tmp);
276 ret = -1;
277 goto error;
278 }
0c7bcad5 279 ret = mkdir(tmp, mode);
2d851108 280 if (ret < 0) {
0c7bcad5
MD
281 if (errno != EEXIST) {
282 PERROR("mkdir recursive");
283 ret = -errno;
284 goto error;
2d851108
DG
285 }
286 }
287 *p = '/';
288 }
289 }
290
291 ret = mkdir(tmp, mode);
292 if (ret < 0) {
293 if (errno != EEXIST) {
294 PERROR("mkdir recursive last piece");
295 ret = -errno;
296 } else {
297 ret = 0;
298 }
299 }
300
301error:
302 return ret;
303}
fe4477ee
JD
304
305/*
306 * Create the stream tracefile on disk.
307 *
308 * Return 0 on success or else a negative value.
309 */
bc182241 310LTTNG_HIDDEN
07b86b52 311int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
fe4477ee
JD
312 uint64_t count, int uid, int gid)
313{
be96a7d1 314 int ret, out_fd, flags, mode;
fe4477ee
JD
315 char full_path[PATH_MAX], *path_name_id = NULL, *path;
316
317 assert(path_name);
318 assert(file_name);
319
320 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
321 path_name, file_name);
322 if (ret < 0) {
323 PERROR("snprintf create output file");
324 goto error;
325 }
326
327 /*
328 * If we split the trace in multiple files, we have to add the count at the
329 * end of the tracefile name
330 */
331 if (size > 0) {
332 ret = asprintf(&path_name_id, "%s_%" PRIu64, full_path, count);
333 if (ret < 0) {
334 PERROR("Allocating path name ID");
335 goto error;
336 }
337 path = path_name_id;
338 } else {
339 path = full_path;
340 }
341
be96a7d1 342 flags = O_WRONLY | O_CREAT | O_TRUNC;
0f907de1 343 /* Open with 660 mode */
be96a7d1
DG
344 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
345
346 if (uid < 0 || gid < 0) {
347 out_fd = open(path, flags, mode);
348 } else {
349 out_fd = run_as_open(path, flags, mode, uid, gid);
350 }
fe4477ee
JD
351 if (out_fd < 0) {
352 PERROR("open stream path %s", path);
353 goto error_open;
354 }
355 ret = out_fd;
356
357error_open:
358 free(path_name_id);
359error:
360 return ret;
361}
362
363/*
364 * Change the output tracefile according to the given size and count The
365 * new_count pointer is set during this operation.
366 *
367 * From the consumer, the stream lock MUST be held before calling this function
368 * because we are modifying the stream status.
369 *
370 * Return 0 on success or else a negative value.
371 */
bc182241 372LTTNG_HIDDEN
fe4477ee
JD
373int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
374 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count)
375{
376 int ret;
377
378 ret = close(out_fd);
379 if (ret < 0) {
380 PERROR("Closing tracefile");
381 goto error;
382 }
383
384 if (count > 0) {
385 *new_count = (*new_count + 1) % count;
386 } else {
387 (*new_count)++;
388 }
389
390 return utils_create_stream_file(path_name, file_name, size, *new_count,
391 uid, gid);
392error:
393 return ret;
394}
70d0b120
SM
395
396/**
397 * Prints the error message corresponding to a regex error code.
398 *
399 * @param errcode The error code.
400 * @param regex The regex object that produced the error code.
401 */
402static void regex_print_error(int errcode, regex_t *regex)
403{
404 /* Get length of error message and allocate accordingly */
405 size_t length;
406 char *buffer;
407
408 assert(regex != NULL);
409
410 length = regerror(errcode, regex, NULL, 0);
411 if (length == 0) {
412 ERR("regerror returned a length of 0");
413 return;
414 }
415
416 buffer = zmalloc(length);
417 if (!buffer) {
418 ERR("regex_print_error: zmalloc failed");
419 return;
420 }
421
422 /* Get and print error message */
423 regerror(errcode, regex, buffer, length);
424 ERR("regex error: %s\n", buffer);
425 free(buffer);
426
427}
428
429/**
430 * Parse a string that represents a size in human readable format. It
431 * supports decimal integers suffixed by 'k', 'M' or 'G'.
432 *
433 * The suffix multiply the integer by:
434 * 'k': 1024
435 * 'M': 1024^2
436 * 'G': 1024^3
437 *
438 * @param str The string to parse.
439 * @param size Pointer to a size_t that will be filled with the
cfa9a5a2 440 * resulting size.
70d0b120
SM
441 *
442 * @return 0 on success, -1 on failure.
443 */
444int utils_parse_size_suffix(char *str, uint64_t *size)
445{
446 regex_t regex;
447 int ret;
448 const int nmatch = 3;
449 regmatch_t suffix_match, matches[nmatch];
450 unsigned long long base_size;
451 long shift = 0;
452
453 if (!str) {
454 return 0;
455 }
456
457 /* Compile regex */
458 ret = regcomp(&regex, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
459 if (ret != 0) {
460 regex_print_error(ret, &regex);
461 ret = -1;
462 goto end;
463 }
464
465 /* Match regex */
466 ret = regexec(&regex, str, nmatch, matches, 0);
467 if (ret != 0) {
468 ret = -1;
469 goto free;
470 }
471
472 /* There is a match ! */
473 errno = 0;
474 base_size = strtoull(str, NULL, 0);
475 if (errno != 0) {
476 PERROR("strtoull");
477 ret = -1;
478 goto free;
479 }
480
481 /* Check if there is a suffix */
482 suffix_match = matches[2];
483 if (suffix_match.rm_eo - suffix_match.rm_so == 1) {
484 switch (*(str + suffix_match.rm_so)) {
485 case 'K':
486 case 'k':
487 shift = KIBI_LOG2;
488 break;
489 case 'M':
490 shift = MEBI_LOG2;
491 break;
492 case 'G':
493 shift = GIBI_LOG2;
494 break;
495 default:
496 ERR("parse_human_size: invalid suffix");
497 ret = -1;
498 goto free;
499 }
500 }
501
502 *size = base_size << shift;
503
504 /* Check for overflow */
505 if ((*size >> shift) != base_size) {
506 ERR("parse_size_suffix: oops, overflow detected.");
507 ret = -1;
508 goto free;
509 }
510
511 ret = 0;
512
513free:
514 regfree(&regex);
515end:
516 return ret;
517}
cfa9a5a2
DG
518
519/*
520 * fls: returns the position of the most significant bit.
521 * Returns 0 if no bit is set, else returns the position of the most
522 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
523 */
524#if defined(__i386) || defined(__x86_64)
525static inline unsigned int fls_u32(uint32_t x)
526{
527 int r;
528
529 asm("bsrl %1,%0\n\t"
530 "jnz 1f\n\t"
531 "movl $-1,%0\n\t"
532 "1:\n\t"
533 : "=r" (r) : "rm" (x));
534 return r + 1;
535}
536#define HAS_FLS_U32
537#endif
538
539#ifndef HAS_FLS_U32
540static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
541{
542 unsigned int r = 32;
543
544 if (!x) {
545 return 0;
546 }
547 if (!(x & 0xFFFF0000U)) {
548 x <<= 16;
549 r -= 16;
550 }
551 if (!(x & 0xFF000000U)) {
552 x <<= 8;
553 r -= 8;
554 }
555 if (!(x & 0xF0000000U)) {
556 x <<= 4;
557 r -= 4;
558 }
559 if (!(x & 0xC0000000U)) {
560 x <<= 2;
561 r -= 2;
562 }
563 if (!(x & 0x80000000U)) {
564 x <<= 1;
565 r -= 1;
566 }
567 return r;
568}
569#endif
570
571/*
572 * Return the minimum order for which x <= (1UL << order).
573 * Return -1 if x is 0.
574 */
575LTTNG_HIDDEN
576int utils_get_count_order_u32(uint32_t x)
577{
578 if (!x) {
579 return -1;
580 }
581
582 return fls_u32(x - 1);
583}
feb0f3e5
AM
584
585/**
586 * Obtain the value of LTTNG_HOME environment variable, if exists.
587 * Otherwise returns the value of HOME.
588 */
589char *utils_get_home_dir(void)
590{
591 char *val = NULL;
592 val = getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
593 if (val != NULL) {
594 return val;
595 }
596 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
597}
This page took 0.053784 seconds and 5 git commands to generate.