Merge branch 'master' of ssh://git.lttng.org/home/git/lttng-tools
[lttng-tools.git] / ltt-sessiond / utils.c
1 /*
2 * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca>
3 * Copyright (C) 2011 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; only version 2
8 * of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 */
19
20 #define _GNU_SOURCE
21 #include <errno.h>
22 #include <limits.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29
30 #include "utils.h"
31
32 /*
33 * get_home_dir
34 *
35 * Return pointer to home directory path using the env variable HOME.
36 * No home, NULL is returned.
37 */
38 const char *get_home_dir(void)
39 {
40 return ((const char *) getenv("HOME"));
41 }
42
43 /*
44 * mkdir_recursive
45 *
46 * Create recursively directory using the FULL path.
47 */
48 int mkdir_recursive(const char *path, mode_t mode, uid_t uid, gid_t gid)
49 {
50 int ret;
51 char *p, tmp[PATH_MAX];
52 size_t len;
53 mode_t old_umask;
54
55 ret = snprintf(tmp, sizeof(tmp), "%s", path);
56 if (ret < 0) {
57 perror("snprintf mkdir");
58 goto error;
59 }
60
61 len = ret;
62 if (tmp[len - 1] == '/') {
63 tmp[len - 1] = 0;
64 }
65
66 old_umask = umask(0);
67 for (p = tmp + 1; *p; p++) {
68 if (*p == '/') {
69 *p = 0;
70 ret = mkdir(tmp, mode);
71 if (ret < 0) {
72 if (!(errno == EEXIST)) {
73 perror("mkdir recursive");
74 ret = -errno;
75 goto umask_error;
76 }
77 } else if (ret == 0) {
78 /*
79 * We created the directory. Set its
80 * ownership to the user/group
81 * specified.
82 */
83 ret = chown(tmp, uid, gid);
84 if (ret < 0) {
85 perror("chown in mkdir recursive");
86 ret = -errno;
87 goto umask_error;
88 }
89 }
90 *p = '/';
91 }
92 }
93
94 ret = mkdir(tmp, mode);
95 if (ret < 0) {
96 ret = -errno;
97 } else if (ret == 0) {
98 /*
99 * We created the directory. Set its ownership to the
100 * user/group specified.
101 */
102 ret = chown(tmp, uid, gid);
103 if (ret < 0) {
104 perror("chown in mkdir recursive");
105 ret = -errno;
106 goto umask_error;
107 }
108 }
109
110 umask_error:
111 umask(old_umask);
112 error:
113 return ret;
114 }
This page took 0.031815 seconds and 5 git commands to generate.