]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/unix.c
Add function basename_safe
[netatalk.git] / libatalk / util / unix.c
1 /*
2   Copyright (c) 2010 Frank Lahm <franklahm@gmail.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13 */
14
15 /*!
16  * @file
17  * Netatalk utility functions
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif /* HAVE_CONFIG_H */
23
24 #include <unistd.h>
25 #include <stdint.h>
26 #include <errno.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <dirent.h>
33 #include <sys/time.h>
34 #include <time.h>
35 #include <sys/wait.h>
36 #include <libgen.h>
37
38 #include <atalk/adouble.h>
39 #include <atalk/ea.h>
40 #include <atalk/afp.h>
41 #include <atalk/logger.h>
42 #include <atalk/vfs.h>
43 #include <atalk/util.h>
44 #include <atalk/unix.h>
45 #include <atalk/compat.h>
46 #include <atalk/errchk.h>
47
48 /* close all FDs >= a specified value */
49 static void closeall(int fd)
50 {
51     int fdlimit = sysconf(_SC_OPEN_MAX);
52
53     while (fd < fdlimit)
54         close(fd++);
55 }
56
57 /*!
58  * Run command in a child and wait for it to finish
59  */
60 int run_cmd(const char *cmd, char **cmd_argv)
61 {
62     EC_INIT;
63     pid_t pid, wpid;
64     sigset_t sigs, oldsigs;
65         int status = 0;
66
67     sigfillset(&sigs);
68     pthread_sigmask(SIG_SETMASK, &sigs, &oldsigs);
69
70     if ((pid = fork()) < 0) {
71         LOG(log_error, logtype_default, "run_cmd: fork: %s", strerror(errno));
72         return -1;
73     }
74
75     if (pid == 0) {
76         /* child */
77         closeall(3);
78         execvp("mv", cmd_argv);
79     }
80
81     /* parent */
82         while ((wpid = waitpid(pid, &status, 0)) < 0) {
83             if (errno == EINTR)
84             continue;
85             break;
86         }
87         if (wpid != pid) {
88             LOG(log_error, logtype_default, "waitpid(%d): %s", (int)pid, strerror(errno));
89         EC_FAIL;
90         }
91
92     if (WIFEXITED(status))
93         status = WEXITSTATUS(status);
94     else if (WIFSIGNALED(status))
95         status = WTERMSIG(status);
96
97     LOG(log_note, logtype_default, "run_cmd(\"%s\"): status: %d", cmd, status);
98
99 EC_CLEANUP:
100     if (status != 0)
101         ret = status;
102     pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
103     EC_EXIT;
104 }
105
106 /*!
107  * Daemonize
108  *
109  * Fork, exit parent, setsid(), optionally chdir("/"), optionally close all fds
110  *
111  * returns -1 on failure, but you can't do much except exit in that case
112  * since we may already have forked
113  */
114 int daemonize(int nochdir, int noclose)
115 {
116     switch (fork()) {
117     case 0:
118         break;
119     case -1:
120         return -1;
121     default:
122         _exit(0);
123     }
124
125     if (setsid() < 0)
126         return -1;
127
128     switch (fork()) {
129     case 0: 
130         break;
131     case -1:
132         return -1;
133     default:
134         _exit(0);
135     }
136
137     if (!nochdir)
138         chdir("/");
139
140     if (!noclose) {
141         closeall(0);
142         open("/dev/null",O_RDWR);
143         dup(0);
144         dup(0);
145     }
146
147     return 0;
148 }
149
150 static uid_t saved_uid = -1;
151
152 /*
153  * seteuid(0) and back, if either fails and panic != 0 we PANIC
154  */
155 void become_root(void)
156 {
157     if (getuid() == 0) {
158         saved_uid = geteuid();
159         if (seteuid(0) != 0)
160             AFP_PANIC("Can't seteuid(0)");
161     }
162 }
163
164 void unbecome_root(void)
165 {
166     if (getuid() == 0) {
167         if (saved_uid == -1 || seteuid(saved_uid) < 0)
168             AFP_PANIC("Can't seteuid back");
169         saved_uid = -1;
170     }
171 }
172
173 /*!
174  * @brief get cwd in static buffer
175  *
176  * @returns pointer to path or pointer to error messages on error
177  */
178 const char *getcwdpath(void)
179 {
180     static char cwd[MAXPATHLEN + 1];
181     char *p;
182
183     if ((p = getcwd(cwd, MAXPATHLEN)) != NULL)
184         return p;
185     else
186         return strerror(errno);
187 }
188
189 /*!
190  * @brief Request absolute path
191  *
192  * @returns Absolute filesystem path to object
193  */
194 const char *fullpathname(const char *name)
195 {
196     static char wd[MAXPATHLEN + 1];
197
198     if (name[0] == '/')
199         return name;
200
201     if (getcwd(wd , MAXPATHLEN)) {
202         strlcat(wd, "/", MAXPATHLEN);
203         strlcat(wd, name, MAXPATHLEN);
204     } else {
205         strlcpy(wd, name, MAXPATHLEN);
206     }
207
208     return wd;
209 }
210
211 /*!
212  * Takes a buffer with a path, strips slashs, returns basename
213  *
214  * @param p (rw) path
215  *        path may be
216  *          "[/][dir/[...]]file"
217  *        or
218  *          "[/][dir/[...]]dir/[/]"
219  *        Result is "file" or "dir" 
220  *
221  * @returns pointer to basename in path buffer, buffer is possibly modified
222  */
223 char *stripped_slashes_basename(char *p)
224 {
225     int i = strlen(p) - 1;
226     while (i > 0 && p[i] == '/')
227         p[i--] = 0;
228     return (strrchr(p, '/') ? strrchr(p, '/') + 1 : p);
229 }
230
231 /*!
232  * @brief symlink safe chdir replacement
233  *
234  * Only chdirs to dir if it doesn't contain symlinks.
235  *
236  * @returns 1 if a path element is a symlink, 0 otherwise, -1 on syserror
237  */
238 int lchdir(const char *dir)
239 {
240     char buf[MAXPATHLEN+1];
241     char cwd[MAXPATHLEN+1];
242     char *test;
243     int  i;
244
245     /*
246      dir is a canonical path (without "../" "./" "//" )
247      but may end with a / 
248     */
249     *cwd = 0;
250     if (*dir != '/') {
251         if (getcwd(cwd, MAXPATHLEN) == NULL)
252             return -1;
253     }
254     if (chdir(dir) != 0)
255         return -1;
256
257     /* 
258      * Cases:
259      * chdir request   | realpath result | ret
260      * (after getwcwd) |                 |
261      * =======================================
262      * /a/b/.          | /a/b            | 0
263      * /a/b/.          | /c              | 1
264      * /a/b/.          | /c/d/e/f        | 1
265      */
266     if (getcwd(buf, MAXPATHLEN) == NULL)
267         return 1;
268
269     i = 0;
270     if (*cwd) {
271         /* relative path requested, 
272          * Same directory?
273         */
274         for (; cwd[i]; i++) {
275             if (buf[i] != cwd[i])
276                 return 1;
277         }
278         if (buf[i]) {
279             if (buf[i] != '/')
280                 return 1;
281             i++;
282         }                    
283     }
284
285     test = &buf[i];    
286     for (i = 0; test[i]; i++) {
287         if (test[i] != dir[i]) {
288             return 1;
289         }
290     }
291     /* trailing '/' ? */
292     if (!dir[i])
293         return 0;
294
295     if (dir[i] != '/')
296         return 1;
297
298     i++;
299     if (dir[i])
300         return 1;
301
302     return 0;
303 }
304
305 /*!
306  * Store n random bytes an buf
307  */
308 void randombytes(void *buf, int n)
309 {
310     char *p = (char *)buf;
311     int fd, i;
312     struct timeval tv;
313
314     if ((fd = open("/dev/urandom", O_RDONLY)) != -1) {
315         /* generate from /dev/urandom */
316         if (read(fd, buf, n) != n) {
317             close(fd);
318             fd = -1;
319         } else {
320             close(fd);
321             /* fd now != -1, so srandom wont be called below */
322         }
323     }
324
325     if (fd == -1) {
326         gettimeofday(&tv, NULL);
327         srandom((unsigned int)tv.tv_usec);
328         for (i=0 ; i < n ; i++)
329             p[i] = random() & 0xFF;
330     }
331
332     return;
333 }
334
335 int gmem(gid_t gid, int ngroups, gid_t *groups)
336 {
337     int         i;
338
339     for ( i = 0; i < ngroups; i++ ) {
340         if ( groups[ i ] == gid ) {
341             return( 1 );
342         }
343     }
344     return( 0 );
345 }
346
347 /*
348  * realpath() replacement that always allocates storage for returned path
349  */
350 char *realpath_safe(const char *path)
351 {
352     char *resolved_path;
353
354 #ifdef REALPATH_TAKES_NULL
355     if ((resolved_path = realpath(path, NULL)) == NULL) {
356         LOG(log_error, logtype_afpd, "realpath() cannot resolve path \"%s\"", path);
357         return NULL;
358     }
359     return resolved_path;
360 #else
361     if ((resolved_path = malloc(MAXPATHLEN+1)) == NULL)
362         return NULL;
363     if (realpath(path, resolved_path) == NULL) {
364         free(resolved_path);
365         LOG(log_error, logtype_afpd, "realpath() cannot resolve path \"%s\"", path);
366         return NULL;
367     }
368     /* Safe some memory */
369     char *tmp;
370     if ((tmp = strdup(resolved_path)) == NULL) {
371         free(resolved_path);
372         return NULL;
373     }
374     free(resolved_path);
375     resolved_path = tmp;
376     return resolved_path;
377 #endif
378 }
379
380 /**
381  * Returns pointer to static buffer with basename of path
382  **/
383 const char *basename_safe(const char *path)
384 {
385     static char buf[MAXPATHLEN+1];
386     strlcpy(buf, path, MAXPATHLEN);
387     return basename(buf);
388 }