2 Copyright (c) 2010 Frank Lahm <franklahm@gmail.com>
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.
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.
17 * Netatalk utility functions
22 #endif /* HAVE_CONFIG_H */
29 #include <sys/types.h>
36 #include <atalk/adouble.h>
38 #include <atalk/afp.h>
39 #include <atalk/logger.h>
40 #include <atalk/vfs.h>
41 #include <atalk/util.h>
42 #include <atalk/unix.h>
43 #include <atalk/compat.h>
46 * @brief get cwd in static buffer
48 * @returns pointer to path or pointer to error messages on error
50 const char *getcwdpath(void)
52 static char cwd[MAXPATHLEN + 1];
55 if ((p = getcwd(cwd, MAXPATHLEN)) != NULL)
58 return strerror(errno);
62 * Make argument path absoulte
64 * @returns pointer to path or pointer to error messages on error
66 const char *abspath(const char *name)
68 static char buf[MAXPATHLEN + 1];
75 if ((p = getcwd(buf, MAXPATHLEN)) == NULL)
76 return strerror(errno);
82 strlcpy(buf + n, name, MAXPATHLEN - n);
87 * Takes a buffer with a path, strips slashs, returns basename
91 * "[/][dir/[...]]file"
93 * "[/][dir/[...]]dir/[/]"
94 * Result is "file" or "dir"
96 * @returns pointer to basename in path buffer, buffer is possibly modified
98 char *stripped_slashes_basename(char *p)
100 int i = strlen(p) - 1;
101 while (i > 0 && p[i] == '/')
103 return (strrchr(p, '/') ? strrchr(p, '/') + 1 : p);
107 * @brief symlink safe chdir replacement
109 * Only chdirs to dir if it doesn't contain symlinks.
111 * @returns 1 if a path element is a symlink, 0 otherwise, -1 on syserror
113 int lchdir(const char *dir)
115 char buf[MAXPATHLEN+1];
116 char cwd[MAXPATHLEN+1];
121 dir is a canonical path (without "../" "./" "//" )
126 if (getcwd(cwd, MAXPATHLEN) == NULL)
134 * chdir request | realpath result | ret
135 * (after getwcwd) | |
136 * =======================================
139 * /a/b/. | /c/d/e/f | 1
141 if (getcwd(buf, MAXPATHLEN) == NULL)
146 /* relative path requested,
149 for (; cwd[i]; i++) {
150 if (buf[i] != cwd[i])
161 for (i = 0; test[i]; i++) {
162 if (test[i] != dir[i]) {
181 * Store n random bytes an buf
183 void randombytes(void *buf, int n)
185 char *p = (char *)buf;
189 if ((fd = open("/dev/urandom", O_RDONLY)) != -1) {
190 /* generate from /dev/urandom */
191 if (read(fd, buf, n) != n) {
196 /* fd now != -1, so srandom wont be called below */
201 gettimeofday(&tv, NULL);
202 srandom((unsigned int)tv.tv_usec);
203 for (i=0 ; i < n ; i++)
204 p[i] = random() & 0xFF;