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>
45 * @brief get cwd in static buffer
47 * @returns pointer to path or pointer to error messages on error
49 const char *getcwdpath(void)
51 static char cwd[MAXPATHLEN + 1];
54 if ((p = getcwd(cwd, MAXPATHLEN)) != NULL)
57 return strerror(errno);
61 * Make argument path absoulte
63 * @returns pointer to path or pointer to error messages on error
65 const char *abspath(const char *name)
67 static char buf[MAXPATHLEN + 1];
74 if ((p = getcwd(buf, MAXPATHLEN)) == NULL)
75 return strerror(errno);
81 strlcpy(buf + n, name, MAXPATHLEN - n);
86 * Takes a buffer with a path, strips slashs, returns basename
90 * "[/][dir/[...]]file"
92 * "[/][dir/[...]]dir/[/]"
93 * Result is "file" or "dir"
95 * @returns pointer to basename in path buffer, buffer is possibly modified
97 char *stripped_slashes_basename(char *p)
99 int i = strlen(p) - 1;
100 while (i > 0 && p[i] == '/')
102 return (strrchr(p, '/') ? strrchr(p, '/') + 1 : p);
106 * @brief symlink safe chdir replacement
108 * Only chdirs to dir if it doesn't contain symlinks.
110 * @returns 1 if a path element is a symlink, 0 otherwise, -1 on syserror
112 int lchdir(const char *dir)
114 char buf[MAXPATHLEN+1];
115 char cwd[MAXPATHLEN+1];
120 dir is a canonical path (without "../" "./" "//" )
125 if (getcwd(cwd, MAXPATHLEN) == NULL)
133 * chdir request | realpath result | ret
134 * (after getwcwd) | |
135 * =======================================
138 * /a/b/. | /c/d/e/f | 1
140 if (getcwd(buf, MAXPATHLEN) == NULL)
145 /* relative path requested,
148 for (; cwd[i]; i++) {
149 if (buf[i] != cwd[i])
160 for (i = 0; test[i]; i++) {
161 if (test[i] != dir[i]) {
180 * Store n random bytes an buf
182 void randombytes(void *buf, int n)
184 char *p = (char *)buf;
188 if ((fd = open("/dev/urandom", O_RDONLY)) != -1) {
189 /* generate from /dev/urandom */
190 if (read(fd, buf, n) != n) {
195 /* fd now != -1, so srandom wont be called below */
200 gettimeofday(&tv, NULL);
201 srandom((unsigned int)tv.tv_usec);
202 for (i=0 ; i < n ; i++)
203 p[i] = random() & 0xFF;