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 * Takes a buffer with a path, strips slashs, returns basename
65 * "[/][dir/[...]]file"
67 * "[/][dir/[...]]dir/[/]"
68 * Result is "file" or "dir"
70 * @returns pointer to basename in path buffer, buffer is possibly modified
72 char *stripped_slashes_basename(char *p)
74 int i = strlen(p) - 1;
75 while (i > 0 && p[i] == '/')
77 return (strrchr(p, '/') ? strrchr(p, '/') + 1 : p);
81 * @brief symlink safe chdir replacement
83 * Only chdirs to dir if it doesn't contain symlinks.
85 * @returns 1 if a path element is a symlink, 0 otherwise, -1 on syserror
87 int lchdir(const char *dir)
89 char buf[MAXPATHLEN+1];
90 char cwd[MAXPATHLEN+1];
95 dir is a canonical path (without "../" "./" "//" )
100 if (getcwd(cwd, MAXPATHLEN) == NULL)
108 * chdir request | realpath result | ret
109 * (after getwcwd) | |
110 * =======================================
113 * /a/b/. | /c/d/e/f | 1
115 if (getcwd(buf, MAXPATHLEN) == NULL)
120 /* relative path requested,
123 for (; cwd[i]; i++) {
124 if (buf[i] != cwd[i])
135 for (i = 0; test[i]; i++) {
136 if (test[i] != dir[i]) {
155 * Store n random bytes an buf
157 void randombytes(void *buf, int n)
159 char *p = (char *)buf;
163 if ((fd = open("/dev/urandom", O_RDONLY)) != -1) {
164 /* generate from /dev/urandom */
165 if (read(fd, buf, n) != n) {
170 /* fd now != -1, so srandom wont be called below */
175 gettimeofday(&tv, NULL);
176 srandom((unsigned int)tv.tv_usec);
177 for (i=0 ; i < n ; i++)
178 p[i] = random() & 0xFF;