]> arthur.barton.de Git - netatalk.git/blob - bin/ad/ad_util.c
Rename cfrombstring to cfrombstr and msic
[netatalk.git] / bin / ad / 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 <atalk/bstrlib.h>
54 #include <atalk/bstradd.h>
55 #include <atalk/util.h>
56 #include "ad.h"
57
58 #define cp_pct(x, y)((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
59
60 /* Memory strategy threshold, in pages: if physmem is larger then this, use a 
61  * large buffer */
62 #define PHYSPAGES_THRESHOLD (32*1024)
63
64 /* Maximum buffer size in bytes - do not allow it to grow larger than this */
65 #define BUFSIZE_MAX (2*1024*1024)
66
67 /* Small (default) buffer size in bytes. It's inefficient for this to be
68  * smaller than MAXPHYS */
69 #define MAXPHYS (64 * 1024)
70 #define BUFSIZE_SMALL (MAXPHYS)
71
72 int log_verbose;             /* Logging flag */
73
74 void _log(enum logtype lt, char *fmt, ...)
75 {
76     int len;
77     static char logbuffer[1024];
78     va_list args;
79
80     if ( (lt == STD) || (log_verbose == 1)) {
81         va_start(args, fmt);
82         len = vsnprintf(logbuffer, 1023, fmt, args);
83         va_end(args);
84         logbuffer[1023] = 0;
85
86         printf("%s\n", logbuffer);
87     }
88 }
89
90 int newvol(const char *path, afpvol_t *vol)
91 {
92     //    char *pathdup;
93     
94     memset(vol, 0, sizeof(afpvol_t));
95
96     //    pathdup = strdup(path);
97     //    vol->dirname = strdup(dirname(pathdup));
98     //    free(pathdup);
99     
100     //    pathdup = strdup(path);
101     //    vol->basename = strdup(basename(pathdup));
102     //    free(pathdup);
103
104     loadvolinfo((char *)path, &vol->volinfo);
105
106     return 0;
107 }
108
109 void freevol(afpvol_t *vol)
110 {
111 #if 0
112     if (vol->dirname) {
113         free(vol->dirname);
114         vol->dirname = NULL;
115     }
116     if (vol->basename) {
117         free(vol->basename);
118         vol->basename = NULL;
119     }
120 #endif
121 }
122
123 /*
124   Taken form afpd/desktop.c
125 */
126 char *utompath(const struct volinfo *volinfo, char *upath)
127 {
128     static char  mpath[ MAXPATHLEN + 2]; /* for convert_charset dest_len parameter +2 */
129     char         *m, *u;
130     uint16_t     flags = CONV_IGNORE | CONV_UNESCAPEHEX;
131     size_t       outlen;
132
133     if (!upath)
134         return NULL;
135
136     m = mpath;
137     u = upath;
138     outlen = strlen(upath);
139
140     if ((volinfo->v_casefold & AFPVOL_UTOMUPPER))
141         flags |= CONV_TOUPPER;
142     else if ((volinfo->v_casefold & AFPVOL_UTOMLOWER))
143         flags |= CONV_TOLOWER;
144
145     if ((volinfo->v_flags & AFPVOL_EILSEQ)) {
146         flags |= CONV__EILSEQ;
147     }
148
149     /* convert charsets */
150     if ((size_t)-1 == ( outlen = convert_charset(volinfo->v_volcharset,
151                                                  CH_UTF8_MAC,
152                                                  volinfo->v_maccharset,
153                                                  u, outlen, mpath, MAXPATHLEN, &flags)) ) {
154         SLOG("Conversion from %s to %s for %s failed.",
155             volinfo->v_volcodepage, volinfo->v_maccodepage, u);
156         return NULL;
157     }
158
159     return(m);
160 }
161
162 /*
163  * path might be:
164  * (a) relative:
165  *     "dir/subdir" with cwd: "/afp_volume/topdir"
166  * (b) absolute:
167  *     "/afp_volume/dir/subdir"
168  */
169 static const char *relative_path_for_volume(const char *path, const char *volpath)
170 {
171     static char buf[MAXPATHLEN+1];
172     bstring fpath;
173
174     /* Make path absolute by concetanating for case (a) */
175     if (path[0] != '/') {
176         fpath = bfromcstr(getcwdpath());
177         if (fpath->data[fpath->slen - 1] != '/')
178             bcatcstr(fpath, "/");
179         bcatcstr(fpath, path);
180         if (fpath->data[fpath->slen - 1] == '/')
181             bdelete(fpath, fpath->slen - 1, 1);
182     } else {
183         fpath = bfromcstr(path);
184         if (fpath->data[fpath->slen - 1] == '/')
185             bdelete(fpath, fpath->slen - 1, 1);
186
187     }
188
189     return NULL;
190 }
191
192 /*!
193  * ResolvesCNID of a given paths
194  *
195  * path might be:
196  * (a) relative:
197  *     "dir/subdir" with cwd: "/afp_volume/topdir"
198  * (b) absolute:
199  *     "/afp_volume/dir/subdir"
200  *
201  * 1) in case a) concatenate both paths
202  * 3) strip volume root
203  * 4) start recursive CNID search with
204  *    a) DID:2, "topdir"
205  *    b) DID:2, "dir"
206  * 5) ...until we have the CNID for
207  *    a) "/afp_volume/topdir/dir"
208  *    b) "/afp_volume/dir" (no recursion required)
209  */
210 cnid_t cnid_for_path(const struct volinfo *vi,
211                      const struct vol *vol,
212                      const char *path)
213 {
214
215     return 0;
216 }
217
218 int ftw_copy_file(const struct FTW *entp,
219               const char *spath,
220               const struct stat *sp,
221               int dne)
222 {
223     static char *buf = NULL;
224     static size_t bufsize;
225     ssize_t wcount;
226     size_t wresid;
227     off_t wtotal;
228     int ch, checkch, from_fd = 0, rcount, rval, to_fd = 0;
229     char *bufp;
230     char *p;
231
232     if ((from_fd = open(spath, O_RDONLY, 0)) == -1) {
233         SLOG("%s: %s", spath, strerror(errno));
234         return (1);
235     }
236
237     /*
238      * If the file exists and we're interactive, verify with the user.
239      * If the file DNE, set the mode to be the from file, minus setuid
240      * bits, modified by the umask; arguably wrong, but it makes copying
241      * executables work right and it's been that way forever.  (The
242      * other choice is 666 or'ed with the execute bits on the from file
243      * modified by the umask.)
244      */
245     if (!dne) {
246 #define YESNO "(y/n [n]) "
247         if (nflag) {
248             if (vflag)
249                 printf("%s not overwritten\n", to.p_path);
250             (void)close(from_fd);
251             return (0);
252         } else if (iflag) {
253             (void)fprintf(stderr, "overwrite %s? %s", 
254                           to.p_path, YESNO);
255             checkch = ch = getchar();
256             while (ch != '\n' && ch != EOF)
257                 ch = getchar();
258             if (checkch != 'y' && checkch != 'Y') {
259                 (void)close(from_fd);
260                 (void)fprintf(stderr, "not overwritten\n");
261                 return (1);
262             }
263         }
264         
265         if (fflag) {
266             /* remove existing destination file name, 
267              * create a new file  */
268             (void)unlink(to.p_path);
269             if (!lflag)
270                 to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
271                              sp->st_mode & ~(S_ISUID | S_ISGID));
272         } else {
273             if (!lflag)
274                 /* overwrite existing destination file name */
275                 to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
276         }
277     } else {
278         if (!lflag)
279             to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
280                          sp->st_mode & ~(S_ISUID | S_ISGID));
281     }
282     
283     if (to_fd == -1) {
284         SLOG("%s: %s", to.p_path, strerror(errno));
285         (void)close(from_fd);
286         return (1);
287     }
288
289     rval = 0;
290
291     if (!lflag) {
292         /*
293          * Mmap and write if less than 8M (the limit is so we don't totally
294          * trash memory on big files.  This is really a minor hack, but it
295          * wins some CPU back.
296          * Some filesystems, such as smbnetfs, don't support mmap,
297          * so this is a best-effort attempt.
298          */
299
300         if (S_ISREG(sp->st_mode) && sp->st_size > 0 &&
301             sp->st_size <= 8 * 1024 * 1024 &&
302             (p = mmap(NULL, (size_t)sp->st_size, PROT_READ,
303                       MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) {
304             wtotal = 0;
305             for (bufp = p, wresid = sp->st_size; ;
306                  bufp += wcount, wresid -= (size_t)wcount) {
307                 wcount = write(to_fd, bufp, wresid);
308                 if (wcount <= 0)
309                     break;
310                 wtotal += wcount;
311                 if (wcount >= (ssize_t)wresid)
312                     break;
313             }
314             if (wcount != (ssize_t)wresid) {
315                 SLOG("%s: %s", to.p_path, strerror(errno));
316                 rval = 1;
317             }
318             /* Some systems don't unmap on close(2). */
319             if (munmap(p, sp->st_size) < 0) {
320                 SLOG("%s: %s", spath, strerror(errno));
321                 rval = 1;
322             }
323         } else {
324             if (buf == NULL) {
325                 /*
326                  * Note that buf and bufsize are static. If
327                  * malloc() fails, it will fail at the start
328                  * and not copy only some files. 
329                  */ 
330                 if (sysconf(_SC_PHYS_PAGES) > 
331                     PHYSPAGES_THRESHOLD)
332                     bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
333                 else
334                     bufsize = BUFSIZE_SMALL;
335                 buf = malloc(bufsize);
336                 if (buf == NULL)
337                     ERROR("Not enough memory");
338
339             }
340             wtotal = 0;
341             while ((rcount = read(from_fd, buf, bufsize)) > 0) {
342                 for (bufp = buf, wresid = rcount; ;
343                      bufp += wcount, wresid -= wcount) {
344                     wcount = write(to_fd, bufp, wresid);
345                     if (wcount <= 0)
346                         break;
347                     wtotal += wcount;
348                     if (wcount >= (ssize_t)wresid)
349                         break;
350                 }
351                 if (wcount != (ssize_t)wresid) {
352                     SLOG("%s: %s", to.p_path, strerror(errno));
353                     rval = 1;
354                     break;
355                 }
356             }
357             if (rcount < 0) {
358                 SLOG("%s: %s", spath, strerror(errno));
359                 rval = 1;
360             }
361         }
362     } else {
363         if (link(spath, to.p_path)) {
364             SLOG("%s", to.p_path);
365             rval = 1;
366         }
367     }
368     
369     /*
370      * Don't remove the target even after an error.  The target might
371      * not be a regular file, or its attributes might be important,
372      * or its contents might be irreplaceable.  It would only be safe
373      * to remove it if we created it and its length is 0.
374      */
375
376     if (!lflag) {
377         if (pflag && setfile(sp, to_fd))
378             rval = 1;
379         if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
380             rval = 1;
381         if (close(to_fd)) {
382             SLOG("%s: %s", to.p_path, strerror(errno));
383             rval = 1;
384         }
385     }
386
387     (void)close(from_fd);
388
389     return (rval);
390 }
391
392 int copy_link(const struct FTW *p,
393               const char *spath,
394               const struct stat *sstp,
395               int exists)
396 {
397     int len;
398     char llink[PATH_MAX];
399
400     if ((len = readlink(spath, llink, sizeof(llink) - 1)) == -1) {
401         SLOG("readlink: %s: %s", spath, strerror(errno));
402         return (1);
403     }
404     llink[len] = '\0';
405     if (exists && unlink(to.p_path)) {
406         SLOG("unlink: %s: %s", to.p_path, strerror(errno));
407         return (1);
408     }
409     if (symlink(llink, to.p_path)) {
410         SLOG("symlink: %s: %s", llink, strerror(errno));
411         return (1);
412     }
413     return (pflag ? setfile(sstp, -1) : 0);
414 }
415
416 int setfile(const struct stat *fs, int fd)
417 {
418     static struct timeval tv[2];
419     struct stat ts;
420     int rval, gotstat, islink, fdval;
421     mode_t mode;
422
423     rval = 0;
424     fdval = fd != -1;
425     islink = !fdval && S_ISLNK(fs->st_mode);
426     mode = fs->st_mode & (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
427
428     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atim);
429     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtim);
430     if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
431         SLOG("%sutimes: %s", islink ? "l" : "", to.p_path);
432         rval = 1;
433     }
434     if (fdval ? fstat(fd, &ts) :
435         (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
436         gotstat = 0;
437     else {
438         gotstat = 1;
439         ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
440             S_IRWXU | S_IRWXG | S_IRWXO;
441     }
442     /*
443      * Changing the ownership probably won't succeed, unless we're root
444      * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
445      * the mode; current BSD behavior is to remove all setuid bits on
446      * chown.  If chown fails, lose setuid/setgid bits.
447      */
448     if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
449         if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
450             (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
451              chown(to.p_path, fs->st_uid, fs->st_gid))) {
452             if (errno != EPERM) {
453                 SLOG("chown: %s: %s", to.p_path, strerror(errno));
454                 rval = 1;
455             }
456             mode &= ~(S_ISUID | S_ISGID);
457         }
458
459     if (!gotstat || mode != ts.st_mode)
460         if (fdval ? fchmod(fd, mode) : chmod(to.p_path, mode)) {
461             SLOG("chmod: %s: %s", to.p_path, strerror(errno));
462             rval = 1;
463         }
464
465 #ifdef HAVE_ST_FLAGS
466     if (!gotstat || fs->st_flags != ts.st_flags)
467         if (fdval ?
468             fchflags(fd, fs->st_flags) :
469             (islink ? lchflags(to.p_path, fs->st_flags) :
470              chflags(to.p_path, fs->st_flags))) {
471             SLOG("chflags: %s: %s", to.p_path, strerror(errno));
472             rval = 1;
473         }
474 #endif
475
476     return (rval);
477 }
478
479 int preserve_fd_acls(int source_fd, int dest_fd)
480 {
481 #if 0
482     acl_t acl;
483     acl_type_t acl_type;
484     int acl_supported = 0, ret, trivial;
485
486     ret = fpathconf(source_fd, _PC_ACL_NFS4);
487     if (ret > 0 ) {
488         acl_supported = 1;
489         acl_type = ACL_TYPE_NFS4;
490     } else if (ret < 0 && errno != EINVAL) {
491         warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", to.p_path);
492         return (1);
493     }
494     if (acl_supported == 0) {
495         ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
496         if (ret > 0 ) {
497             acl_supported = 1;
498             acl_type = ACL_TYPE_ACCESS;
499         } else if (ret < 0 && errno != EINVAL) {
500             warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
501                  to.p_path);
502             return (1);
503         }
504     }
505     if (acl_supported == 0)
506         return (0);
507
508     acl = acl_get_fd_np(source_fd, acl_type);
509     if (acl == NULL) {
510         warn("failed to get acl entries while setting %s", to.p_path);
511         return (1);
512     }
513     if (acl_is_trivial_np(acl, &trivial)) {
514         warn("acl_is_trivial() failed for %s", to.p_path);
515         acl_free(acl);
516         return (1);
517     }
518     if (trivial) {
519         acl_free(acl);
520         return (0);
521     }
522     if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
523         warn("failed to set acl entries for %s", to.p_path);
524         acl_free(acl);
525         return (1);
526     }
527     acl_free(acl);
528 #endif
529     return (0);
530 }
531
532 int preserve_dir_acls(const struct stat *fs, char *source_dir, char *dest_dir)
533 {
534 #if 0
535     acl_t (*aclgetf)(const char *, acl_type_t);
536     int (*aclsetf)(const char *, acl_type_t, acl_t);
537     struct acl *aclp;
538     acl_t acl;
539     acl_type_t acl_type;
540     int acl_supported = 0, ret, trivial;
541
542     ret = pathconf(source_dir, _PC_ACL_NFS4);
543     if (ret > 0) {
544         acl_supported = 1;
545         acl_type = ACL_TYPE_NFS4;
546     } else if (ret < 0 && errno != EINVAL) {
547         warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", source_dir);
548         return (1);
549     }
550     if (acl_supported == 0) {
551         ret = pathconf(source_dir, _PC_ACL_EXTENDED);
552         if (ret > 0) {
553             acl_supported = 1;
554             acl_type = ACL_TYPE_ACCESS;
555         } else if (ret < 0 && errno != EINVAL) {
556             warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
557                  source_dir);
558             return (1);
559         }
560     }
561     if (acl_supported == 0)
562         return (0);
563
564     /*
565      * If the file is a link we will not follow it
566      */
567     if (S_ISLNK(fs->st_mode)) {
568         aclgetf = acl_get_link_np;
569         aclsetf = acl_set_link_np;
570     } else {
571         aclgetf = acl_get_file;
572         aclsetf = acl_set_file;
573     }
574     if (acl_type == ACL_TYPE_ACCESS) {
575         /*
576          * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
577          * size ACL will be returned. So it is not safe to simply
578          * check the pointer to see if the default ACL is present.
579          */
580         acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
581         if (acl == NULL) {
582             warn("failed to get default acl entries on %s",
583                  source_dir);
584             return (1);
585         }
586         aclp = &acl->ats_acl;
587         if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
588                                           ACL_TYPE_DEFAULT, acl) < 0) {
589             warn("failed to set default acl entries on %s",
590                  dest_dir);
591             acl_free(acl);
592             return (1);
593         }
594         acl_free(acl);
595     }
596     acl = aclgetf(source_dir, acl_type);
597     if (acl == NULL) {
598         warn("failed to get acl entries on %s", source_dir);
599         return (1);
600     }
601     if (acl_is_trivial_np(acl, &trivial)) {
602         warn("acl_is_trivial() failed on %s", source_dir);
603         acl_free(acl);
604         return (1);
605     }
606     if (trivial) {
607         acl_free(acl);
608         return (0);
609     }
610     if (aclsetf(dest_dir, acl_type, acl) < 0) {
611         warn("failed to set acl entries on %s", dest_dir);
612         acl_free(acl);
613         return (1);
614     }
615     acl_free(acl);
616 #endif
617     return (0);
618 }