]> arthur.barton.de Git - netatalk.git/blob - bin/cnid/ad_util.c
Use own ftw func in ad cp
[netatalk.git] / bin / cnid / ad_util.c
1 /* 
2  * Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
3  * Copyright (c) 1991, 1993, 1994
4  * The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.   
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif /* HAVE_CONFIG_H */
34
35 #include <sys/types.h>
36 #include <sys/acl.h>
37 #include <sys/param.h>
38 #include <sys/stat.h>
39 #include <sys/mman.h>
40
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <sysexits.h>
47 #include <unistd.h>
48 #include <stdarg.h>
49 #include <string.h>
50
51 #include <atalk/cnid.h>
52 #include <atalk/volinfo.h>
53 #include "ad.h"
54
55 #define cp_pct(x, y)((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
56
57 /* Memory strategy threshold, in pages: if physmem is larger then this, use a 
58  * large buffer */
59 #define PHYSPAGES_THRESHOLD (32*1024)
60
61 /* Maximum buffer size in bytes - do not allow it to grow larger than this */
62 #define BUFSIZE_MAX (2*1024*1024)
63
64 /* Small (default) buffer size in bytes. It's inefficient for this to be
65  * smaller than MAXPHYS */
66 #define MAXPHYS (64 * 1024)
67 #define BUFSIZE_SMALL (MAXPHYS)
68
69 int log_verbose;             /* Logging flag */
70
71 void _log(enum logtype lt, char *fmt, ...)
72 {
73     int len;
74     static char logbuffer[1024];
75     va_list args;
76
77     if ( (lt == STD) || (log_verbose == 1)) {
78         va_start(args, fmt);
79         len = vsnprintf(logbuffer, 1023, fmt, args);
80         va_end(args);
81         logbuffer[1023] = 0;
82
83         printf("%s\n", logbuffer);
84     }
85 }
86
87 int newvol(const char *path, afpvol_t *vol)
88 {
89     //    char *pathdup;
90     
91     memset(vol, 0, sizeof(afpvol_t));
92
93     //    pathdup = strdup(path);
94     //    vol->dirname = strdup(dirname(pathdup));
95     //    free(pathdup);
96     
97     //    pathdup = strdup(path);
98     //    vol->basename = strdup(basename(pathdup));
99     //    free(pathdup);
100
101     loadvolinfo((char *)path, &vol->volinfo);
102
103     return 0;
104 }
105
106 void freevol(afpvol_t *vol)
107 {
108 #if 0
109     if (vol->dirname) {
110         free(vol->dirname);
111         vol->dirname = NULL;
112     }
113     if (vol->basename) {
114         free(vol->basename);
115         vol->basename = NULL;
116     }
117 #endif
118 }
119
120 /*
121   Taken form afpd/desktop.c
122 */
123 char *utompath(const struct volinfo *volinfo, char *upath)
124 {
125     static char  mpath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
126     char         *m, *u;
127     uint16_t     flags = CONV_IGNORE | CONV_UNESCAPEHEX;
128     size_t       outlen;
129
130     if (!upath)
131         return NULL;
132
133     m = mpath;
134     u = upath;
135     outlen = strlen(upath);
136
137     if ((volinfo->v_casefold & AFPVOL_UTOMUPPER))
138         flags |= CONV_TOUPPER;
139     else if ((volinfo->v_casefold & AFPVOL_UTOMLOWER))
140         flags |= CONV_TOLOWER;
141
142     if ((volinfo->v_flags & AFPVOL_EILSEQ)) {
143         flags |= CONV__EILSEQ;
144     }
145
146     /* convert charsets */
147     if ((size_t)-1 == ( outlen = convert_charset(volinfo->v_volcharset,
148                                                  CH_UTF8_MAC,
149                                                  volinfo->v_maccharset,
150                                                  u, outlen, mpath, MAXPATHLEN, &flags)) ) {
151         SLOG("Conversion from %s to %s for %s failed.",
152             volinfo->v_volcodepage, volinfo->v_maccodepage, u);
153         return NULL;
154     }
155
156     return(m);
157 }
158
159 /*!
160  * Resolves CNID of a given paths parent directory
161  *
162  * path might be:
163  * (a) relative:
164  *     "dir/subdir" with cwd: "/afp_volume/topdir"
165  * (b) absolute:
166  *     "/afp_volume/dir/subdir"
167  *
168  * 1) in case a) concatenate both paths
169  * 2) strip last element
170  * 3) strip volume root
171  * 4) start recursive CNID search with
172  *    a) DID:2, "topdir"
173  *    b) DID:2, "dir"
174  * 5) ...until we have the CNID for
175  *    a) "/afp_volume/topdir/dir"
176  *    b) "/afp_volume/dir" (no recursion required)
177  */
178 cnid_t get_parent_cnid_for_path(const struct volinfo *vi,
179                                 const struct vol *vol,
180                                 const char *path)
181 {
182
183     return 0;
184 }
185
186 int ftw_copy_file(const struct FTW *entp,
187               const char *spath,
188               const struct stat *sp,
189               int dne)
190 {
191     static char *buf = NULL;
192     static size_t bufsize;
193     ssize_t wcount;
194     size_t wresid;
195     off_t wtotal;
196     int ch, checkch, from_fd = 0, rcount, rval, to_fd = 0;
197     char *bufp;
198     char *p;
199
200     if ((from_fd = open(spath, O_RDONLY, 0)) == -1) {
201         SLOG("%s: %s", spath, strerror(errno));
202         return (1);
203     }
204
205     /*
206      * If the file exists and we're interactive, verify with the user.
207      * If the file DNE, set the mode to be the from file, minus setuid
208      * bits, modified by the umask; arguably wrong, but it makes copying
209      * executables work right and it's been that way forever.  (The
210      * other choice is 666 or'ed with the execute bits on the from file
211      * modified by the umask.)
212      */
213     if (!dne) {
214 #define YESNO "(y/n [n]) "
215         if (nflag) {
216             if (vflag)
217                 printf("%s not overwritten\n", to.p_path);
218             (void)close(from_fd);
219             return (0);
220         } else if (iflag) {
221             (void)fprintf(stderr, "overwrite %s? %s", 
222                           to.p_path, YESNO);
223             checkch = ch = getchar();
224             while (ch != '\n' && ch != EOF)
225                 ch = getchar();
226             if (checkch != 'y' && checkch != 'Y') {
227                 (void)close(from_fd);
228                 (void)fprintf(stderr, "not overwritten\n");
229                 return (1);
230             }
231         }
232         
233         if (fflag) {
234             /* remove existing destination file name, 
235              * create a new file  */
236             (void)unlink(to.p_path);
237             if (!lflag)
238                 to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
239                              sp->st_mode & ~(S_ISUID | S_ISGID));
240         } else {
241             if (!lflag)
242                 /* overwrite existing destination file name */
243                 to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
244         }
245     } else {
246         if (!lflag)
247             to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
248                          sp->st_mode & ~(S_ISUID | S_ISGID));
249     }
250     
251     if (to_fd == -1) {
252         SLOG("%s: %s", to.p_path, strerror(errno));
253         (void)close(from_fd);
254         return (1);
255     }
256
257     rval = 0;
258
259     if (!lflag) {
260         /*
261          * Mmap and write if less than 8M (the limit is so we don't totally
262          * trash memory on big files.  This is really a minor hack, but it
263          * wins some CPU back.
264          * Some filesystems, such as smbnetfs, don't support mmap,
265          * so this is a best-effort attempt.
266          */
267
268         if (S_ISREG(sp->st_mode) && sp->st_size > 0 &&
269             sp->st_size <= 8 * 1024 * 1024 &&
270             (p = mmap(NULL, (size_t)sp->st_size, PROT_READ,
271                       MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) {
272             wtotal = 0;
273             for (bufp = p, wresid = sp->st_size; ;
274                  bufp += wcount, wresid -= (size_t)wcount) {
275                 wcount = write(to_fd, bufp, wresid);
276                 if (wcount <= 0)
277                     break;
278                 wtotal += wcount;
279                 if (wcount >= (ssize_t)wresid)
280                     break;
281             }
282             if (wcount != (ssize_t)wresid) {
283                 SLOG("%s: %s", to.p_path, strerror(errno));
284                 rval = 1;
285             }
286             /* Some systems don't unmap on close(2). */
287             if (munmap(p, sp->st_size) < 0) {
288                 SLOG("%s: %s", spath, strerror(errno));
289                 rval = 1;
290             }
291         } else {
292             if (buf == NULL) {
293                 /*
294                  * Note that buf and bufsize are static. If
295                  * malloc() fails, it will fail at the start
296                  * and not copy only some files. 
297                  */ 
298                 if (sysconf(_SC_PHYS_PAGES) > 
299                     PHYSPAGES_THRESHOLD)
300                     bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
301                 else
302                     bufsize = BUFSIZE_SMALL;
303                 buf = malloc(bufsize);
304                 if (buf == NULL)
305                     ERROR("Not enough memory");
306
307             }
308             wtotal = 0;
309             while ((rcount = read(from_fd, buf, bufsize)) > 0) {
310                 for (bufp = buf, wresid = rcount; ;
311                      bufp += wcount, wresid -= wcount) {
312                     wcount = write(to_fd, bufp, wresid);
313                     if (wcount <= 0)
314                         break;
315                     wtotal += wcount;
316                     if (wcount >= (ssize_t)wresid)
317                         break;
318                 }
319                 if (wcount != (ssize_t)wresid) {
320                     SLOG("%s: %s", to.p_path, strerror(errno));
321                     rval = 1;
322                     break;
323                 }
324             }
325             if (rcount < 0) {
326                 SLOG("%s: %s", spath, strerror(errno));
327                 rval = 1;
328             }
329         }
330     } else {
331         if (link(spath, to.p_path)) {
332             SLOG("%s", to.p_path);
333             rval = 1;
334         }
335     }
336     
337     /*
338      * Don't remove the target even after an error.  The target might
339      * not be a regular file, or its attributes might be important,
340      * or its contents might be irreplaceable.  It would only be safe
341      * to remove it if we created it and its length is 0.
342      */
343
344     if (!lflag) {
345         if (pflag && setfile(sp, to_fd))
346             rval = 1;
347         if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
348             rval = 1;
349         if (close(to_fd)) {
350             SLOG("%s: %s", to.p_path, strerror(errno));
351             rval = 1;
352         }
353     }
354
355     (void)close(from_fd);
356
357     return (rval);
358 }
359
360 int copy_link(const struct FTW *p,
361               const char *spath,
362               const struct stat *sstp,
363               int exists)
364 {
365     int len;
366     char llink[PATH_MAX];
367
368     if ((len = readlink(spath, llink, sizeof(llink) - 1)) == -1) {
369         SLOG("readlink: %s: %s", spath, strerror(errno));
370         return (1);
371     }
372     llink[len] = '\0';
373     if (exists && unlink(to.p_path)) {
374         SLOG("unlink: %s: %s", to.p_path, strerror(errno));
375         return (1);
376     }
377     if (symlink(llink, to.p_path)) {
378         SLOG("symlink: %s: %s", llink, strerror(errno));
379         return (1);
380     }
381     return (pflag ? setfile(sstp, -1) : 0);
382 }
383
384 int setfile(const struct stat *fs, int fd)
385 {
386     static struct timeval tv[2];
387     struct stat ts;
388     int rval, gotstat, islink, fdval;
389     mode_t mode;
390
391     rval = 0;
392     fdval = fd != -1;
393     islink = !fdval && S_ISLNK(fs->st_mode);
394     mode = fs->st_mode & (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
395
396     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atim);
397     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtim);
398     if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
399         SLOG("%sutimes: %s", islink ? "l" : "", to.p_path);
400         rval = 1;
401     }
402     if (fdval ? fstat(fd, &ts) :
403         (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
404         gotstat = 0;
405     else {
406         gotstat = 1;
407         ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
408             S_IRWXU | S_IRWXG | S_IRWXO;
409     }
410     /*
411      * Changing the ownership probably won't succeed, unless we're root
412      * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
413      * the mode; current BSD behavior is to remove all setuid bits on
414      * chown.  If chown fails, lose setuid/setgid bits.
415      */
416     if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
417         if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
418             (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
419              chown(to.p_path, fs->st_uid, fs->st_gid))) {
420             if (errno != EPERM) {
421                 SLOG("chown: %s: %s", to.p_path, strerror(errno));
422                 rval = 1;
423             }
424             mode &= ~(S_ISUID | S_ISGID);
425         }
426
427     if (!gotstat || mode != ts.st_mode)
428         if (fdval ? fchmod(fd, mode) : chmod(to.p_path, mode)) {
429             SLOG("chmod: %s: %s", to.p_path, strerror(errno));
430             rval = 1;
431         }
432
433 #ifdef HAVE_ST_FLAGS
434     if (!gotstat || fs->st_flags != ts.st_flags)
435         if (fdval ?
436             fchflags(fd, fs->st_flags) :
437             (islink ? lchflags(to.p_path, fs->st_flags) :
438              chflags(to.p_path, fs->st_flags))) {
439             SLOG("chflags: %s: %s", to.p_path, strerror(errno));
440             rval = 1;
441         }
442 #endif
443
444     return (rval);
445 }
446
447 int preserve_fd_acls(int source_fd, int dest_fd)
448 {
449 #if 0
450     acl_t acl;
451     acl_type_t acl_type;
452     int acl_supported = 0, ret, trivial;
453
454     ret = fpathconf(source_fd, _PC_ACL_NFS4);
455     if (ret > 0 ) {
456         acl_supported = 1;
457         acl_type = ACL_TYPE_NFS4;
458     } else if (ret < 0 && errno != EINVAL) {
459         warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", to.p_path);
460         return (1);
461     }
462     if (acl_supported == 0) {
463         ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
464         if (ret > 0 ) {
465             acl_supported = 1;
466             acl_type = ACL_TYPE_ACCESS;
467         } else if (ret < 0 && errno != EINVAL) {
468             warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
469                  to.p_path);
470             return (1);
471         }
472     }
473     if (acl_supported == 0)
474         return (0);
475
476     acl = acl_get_fd_np(source_fd, acl_type);
477     if (acl == NULL) {
478         warn("failed to get acl entries while setting %s", to.p_path);
479         return (1);
480     }
481     if (acl_is_trivial_np(acl, &trivial)) {
482         warn("acl_is_trivial() failed for %s", to.p_path);
483         acl_free(acl);
484         return (1);
485     }
486     if (trivial) {
487         acl_free(acl);
488         return (0);
489     }
490     if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
491         warn("failed to set acl entries for %s", to.p_path);
492         acl_free(acl);
493         return (1);
494     }
495     acl_free(acl);
496 #endif
497     return (0);
498 }
499
500 int preserve_dir_acls(const struct stat *fs, char *source_dir, char *dest_dir)
501 {
502 #if 0
503     acl_t (*aclgetf)(const char *, acl_type_t);
504     int (*aclsetf)(const char *, acl_type_t, acl_t);
505     struct acl *aclp;
506     acl_t acl;
507     acl_type_t acl_type;
508     int acl_supported = 0, ret, trivial;
509
510     ret = pathconf(source_dir, _PC_ACL_NFS4);
511     if (ret > 0) {
512         acl_supported = 1;
513         acl_type = ACL_TYPE_NFS4;
514     } else if (ret < 0 && errno != EINVAL) {
515         warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", source_dir);
516         return (1);
517     }
518     if (acl_supported == 0) {
519         ret = pathconf(source_dir, _PC_ACL_EXTENDED);
520         if (ret > 0) {
521             acl_supported = 1;
522             acl_type = ACL_TYPE_ACCESS;
523         } else if (ret < 0 && errno != EINVAL) {
524             warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
525                  source_dir);
526             return (1);
527         }
528     }
529     if (acl_supported == 0)
530         return (0);
531
532     /*
533      * If the file is a link we will not follow it
534      */
535     if (S_ISLNK(fs->st_mode)) {
536         aclgetf = acl_get_link_np;
537         aclsetf = acl_set_link_np;
538     } else {
539         aclgetf = acl_get_file;
540         aclsetf = acl_set_file;
541     }
542     if (acl_type == ACL_TYPE_ACCESS) {
543         /*
544          * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
545          * size ACL will be returned. So it is not safe to simply
546          * check the pointer to see if the default ACL is present.
547          */
548         acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
549         if (acl == NULL) {
550             warn("failed to get default acl entries on %s",
551                  source_dir);
552             return (1);
553         }
554         aclp = &acl->ats_acl;
555         if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
556                                           ACL_TYPE_DEFAULT, acl) < 0) {
557             warn("failed to set default acl entries on %s",
558                  dest_dir);
559             acl_free(acl);
560             return (1);
561         }
562         acl_free(acl);
563     }
564     acl = aclgetf(source_dir, acl_type);
565     if (acl == NULL) {
566         warn("failed to get acl entries on %s", source_dir);
567         return (1);
568     }
569     if (acl_is_trivial_np(acl, &trivial)) {
570         warn("acl_is_trivial() failed on %s", source_dir);
571         acl_free(acl);
572         return (1);
573     }
574     if (trivial) {
575         acl_free(acl);
576         return (0);
577     }
578     if (aclsetf(dest_dir, acl_type, acl) < 0) {
579         warn("failed to set acl entries on %s", dest_dir);
580         acl_free(acl);
581         return (1);
582     }
583     acl_free(acl);
584 #endif
585     return (0);
586 }