]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
Use blocksize and dirs for calculating used size
[netatalk.git] / etc / afpd / volume.c
1 /*
2  * Copyright (c) 1990,1993 Regents of The University of Michigan.
3  * All Rights Reserved.  See COPYRIGHT.
4  */
5
6 #ifdef HAVE_CONFIG_H
7 #include "config.h"
8 #endif /* HAVE_CONFIG_H */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13 #include <pwd.h>
14 #include <grp.h>
15 #include <utime.h>
16 #include <errno.h>
17 #ifdef HAVE_STRINGS_H
18 #include <strings.h>
19 #endif
20 /* STDC check */
21 #if STDC_HEADERS
22 #include <string.h>
23 #else /* STDC_HEADERS */
24 #ifndef HAVE_STRCHR
25 #define strchr index
26 #define strrchr index
27 #endif /* HAVE_STRCHR */
28 char *strchr (), *strrchr ();
29 #ifndef HAVE_MEMCPY
30 #define memcpy(d,s,n) bcopy ((s), (d), (n))
31 #define memmove(d,s,n) bcopy ((s), (d), (n))
32 #endif /* ! HAVE_MEMCPY */
33 #endif /* STDC_HEADERS */
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <inttypes.h>
39
40 #include <atalk/asp.h>
41 #include <atalk/dsi.h>
42 #include <atalk/adouble.h>
43 #include <atalk/afp.h>
44 #include <atalk/util.h>
45 #include <atalk/volinfo.h>
46 #include <atalk/logger.h>
47 #include <atalk/vfs.h>
48 #include <atalk/uuid.h>
49 #include <atalk/bstrlib.h>
50 #include <atalk/bstradd.h>
51 #include <atalk/ftw.h>
52
53 #ifdef CNID_DB
54 #include <atalk/cnid.h>
55 #endif /* CNID_DB*/
56
57 #include "globals.h"
58 #include "directory.h"
59 #include "file.h"
60 #include "volume.h"
61 #include "unix.h"
62 #include "mangle.h"
63 #include "fork.h"
64 #include "hash.h"
65 #include "acls.h"
66
67 extern int afprun(int root, char *cmd, int *outfd);
68
69 #ifndef MIN
70 #define MIN(a, b) ((a) < (b) ? (a) : (b))
71 #endif /* ! MIN */
72
73 #ifndef NO_LARGE_VOL_SUPPORT
74 #if BYTE_ORDER == BIG_ENDIAN
75 #define hton64(x)       (x)
76 #define ntoh64(x)       (x)
77 #else /* BYTE_ORDER == BIG_ENDIAN */
78 #define hton64(x)       ((u_int64_t) (htonl(((x) >> 32) & 0xffffffffLL)) | \
79                          (u_int64_t) ((htonl(x) & 0xffffffffLL) << 32))
80 #define ntoh64(x)       (hton64(x))
81 #endif /* BYTE_ORDER == BIG_ENDIAN */
82 #endif /* ! NO_LARGE_VOL_SUPPORT */
83
84 #ifndef UUID_PRINTABLE_STRING_LENGTH
85 #define UUID_PRINTABLE_STRING_LENGTH 37
86 #endif
87
88 /* Globals */
89 struct vol *current_vol;        /* last volume from getvolbyvid() */
90
91 static struct vol *Volumes = NULL;
92 static u_int16_t    lastvid = 0;
93 static char     *Trash = "\02\024Network Trash Folder";
94
95 static struct extmap    *Extmap = NULL, *Defextmap = NULL;
96 static int              Extmap_cnt;
97 static void             free_extmap(void);
98
99 #define VOLOPT_ALLOW      0  /* user allow list */
100 #define VOLOPT_DENY       1  /* user deny list */
101 #define VOLOPT_RWLIST     2  /* user rw list */
102 #define VOLOPT_ROLIST     3  /* user ro list */
103 #define VOLOPT_PASSWORD   4  /* volume password */
104 #define VOLOPT_CASEFOLD   5  /* character case mangling */
105 #define VOLOPT_FLAGS      6  /* various flags */
106 #define VOLOPT_DBPATH     7  /* path to database */
107 #define VOLOPT_LIMITSIZE  8  /* Limit the size of the volume */
108 /* Usable slot: 9 */
109 #define VOLOPT_VETO          10  /* list of veto filespec */
110 #define VOLOPT_PREEXEC       11  /* preexec command */
111 #define VOLOPT_ROOTPREEXEC   12  /* root preexec command */
112 #define VOLOPT_POSTEXEC      13  /* postexec command */
113 #define VOLOPT_ROOTPOSTEXEC  14  /* root postexec command */
114 #define VOLOPT_ENCODING      15  /* mac encoding (pre OSX)*/
115 #define VOLOPT_MACCHARSET    16
116 #define VOLOPT_CNIDSCHEME    17
117 #define VOLOPT_ADOUBLE       18  /* adouble version */
118
119 #ifdef FORCE_UIDGID
120 #warning UIDGID
121 #include "uid.h"
122
123 #define VOLOPT_FORCEUID      19  /* force uid for username x */
124 #define VOLOPT_FORCEGID      20  /* force gid for group x */
125 #endif /* FORCE_UIDGID */
126
127 #define VOLOPT_UMASK         21
128 #define VOLOPT_ALLOWED_HOSTS 22
129 #define VOLOPT_DENIED_HOSTS  23
130 #define VOLOPT_DPERM         24  /* dperm default directories perms */
131 #define VOLOPT_FPERM         25  /* fperm default files perms */
132 #define VOLOPT_DFLTPERM      26  /* perm */
133 #define VOLOPT_EA_VFS        27  /* Extended Attributes vfs indirection */
134 #define VOLOPT_CNIDSERVER    28  /* CNID Server ip address*/
135 #define VOLOPT_CNIDPORT      30  /* CNID server tcp port */
136
137 #define VOLOPT_MAX           31  /* <== IMPORTANT !!!!!! */
138 #define VOLOPT_NUM           (VOLOPT_MAX + 1)
139
140 #define VOLPASSLEN  8
141 #define VOLOPT_DEFAULT     ":DEFAULT:"
142 #define VOLOPT_DEFAULT_LEN 9
143
144 struct vol_option {
145     char *c_value;
146     int i_value;
147 };
148
149 typedef struct _special_folder {
150     const char *name;
151     int precreate;
152     mode_t mode;
153     int hide;
154 } _special_folder;
155
156 static const _special_folder special_folders[] = {
157     {"Network Trash Folder",     1,  0777,  1},
158     {"Temporary Items",          1,  0777,  1},
159     {".AppleDesktop",            1,  0777,  0},
160 #if 0
161     {"TheFindByContentFolder",   0,     0,  1},
162     {"TheVolumeSettingsFolder",  0,     0,  1},
163 #endif
164     {NULL, 0, 0, 0}};
165
166 /* Forward declarations */
167 static void handle_special_folders (const struct vol *);
168 static void deletevol(struct vol *vol);
169 static void volume_free(struct vol *vol);
170 static void check_ea_sys_support(struct vol *vol);
171 static char *get_vol_uuid(const AFPObj *obj, const char *volname);
172 static int readvolfile(AFPObj *obj, struct afp_volume_name *p1,char *p2, int user, struct passwd *pwent);
173
174 static void volfree(struct vol_option *options, const struct vol_option *save)
175 {
176     int i;
177
178     if (save) {
179         for (i = 0; i < VOLOPT_MAX; i++) {
180             if (options[i].c_value && (options[i].c_value != save[i].c_value))
181                 free(options[i].c_value);
182         }
183     } else {
184         for (i = 0; i < VOLOPT_MAX; i++) {
185             if (options[i].c_value)
186                 free(options[i].c_value);
187         }
188     }
189 }
190
191
192 #define is_var(a, b) (strncmp((a), (b), 2) == 0)
193
194 /*
195  * Handle variable substitutions. here's what we understand:
196  * $b   -> basename of path
197  * $c   -> client ip/appletalk address
198  * $d   -> volume pathname on server
199  * $f   -> full name (whatever's in the gecos field)
200  * $g   -> group
201  * $h   -> hostname
202  * $i   -> client ip/appletalk address without port
203  * $s   -> server name (hostname if it doesn't exist)
204  * $u   -> username (guest is usually nobody)
205  * $v   -> volume name or basename if null
206  * $z   -> zone (may not exist)
207  * $$   -> $
208  *
209  * This get's called from readvolfile with
210  * path = NULL, volname = NULL for xlating the volumes path
211  * path = path, volname = NULL for xlating the volumes name
212  * ... and from volumes options parsing code when xlating eg dbpath with
213  * path = path, volname = volname
214  *
215  * Using this information we can reject xlation of any variable depeninding on a login
216  * context which is not given in the afp master, where we must evaluate this whole stuff
217  * too for the Zeroconf announcements.
218  */
219 static char *volxlate(AFPObj *obj,
220                       char *dest,
221                       size_t destlen,
222                       char *src,
223                       struct passwd *pwd,
224                       char *path,
225                       char *volname)
226 {
227     char *p, *r;
228     const char *q;
229     int len;
230     char *ret;
231     int afpmaster = 0;
232     int xlatevolname = 0;
233
234     if (parent_or_child == 0)
235         afpmaster = 1;
236
237     if (path && !volname)
238         /* cf above */
239         xlatevolname = 1;
240
241     if (!src) {
242         return NULL;
243     }
244     if (!dest) {
245         dest = calloc(destlen +1, 1);
246     }
247     ret = dest;
248     if (!ret) {
249         return NULL;
250     }
251     strlcpy(dest, src, destlen +1);
252     if ((p = strchr(src, '$')) == NULL) /* nothing to do */
253         return ret;
254
255     /* first part of the path. just forward to the next variable. */
256     len = MIN((size_t)(p - src), destlen);
257     if (len > 0) {
258         destlen -= len;
259         dest += len;
260     }
261
262     while (p && destlen > 0) {
263         /* now figure out what the variable is */
264         q = NULL;
265         if (is_var(p, "$b")) {
266             if (afpmaster && xlatevolname)
267                 return NULL;
268             if (path) {
269                 if ((q = strrchr(path, '/')) == NULL)
270                     q = path;
271                 else if (*(q + 1) != '\0')
272                     q++;
273             }
274         } else if (is_var(p, "$c")) {
275             if (afpmaster && xlatevolname)
276                 return NULL;
277             if (obj->proto == AFPPROTO_ASP) {
278                 ASP asp = obj->handle;
279
280                 len = sprintf(dest, "%u.%u", ntohs(asp->asp_sat.sat_addr.s_net),
281                               asp->asp_sat.sat_addr.s_node);
282                 dest += len;
283                 destlen -= len;
284
285             } else if (obj->proto == AFPPROTO_DSI) {
286                 DSI *dsi = obj->handle;
287                 len = sprintf(dest, "%s:%u",
288                               getip_string((struct sockaddr *)&dsi->client),
289                               getip_port((struct sockaddr *)&dsi->client));
290                 dest += len;
291                 destlen -= len;
292             }
293         } else if (is_var(p, "$d")) {
294             if (afpmaster && xlatevolname)
295                 return NULL;
296             q = path;
297         } else if (pwd && is_var(p, "$f")) {
298             if (afpmaster && xlatevolname)
299                 return NULL;
300             if ((r = strchr(pwd->pw_gecos, ',')))
301                 *r = '\0';
302             q = pwd->pw_gecos;
303         } else if (pwd && is_var(p, "$g")) {
304             if (afpmaster && xlatevolname)
305                 return NULL;
306             struct group *grp = getgrgid(pwd->pw_gid);
307             if (grp)
308                 q = grp->gr_name;
309         } else if (is_var(p, "$h")) {
310             q = obj->options.hostname;
311         } else if (is_var(p, "$i")) {
312             if (afpmaster && xlatevolname)
313                 return NULL;
314             if (obj->proto == AFPPROTO_ASP) {
315                 ASP asp = obj->handle;
316
317                 len = sprintf(dest, "%u", ntohs(asp->asp_sat.sat_addr.s_net));
318                 dest += len;
319                 destlen -= len;
320
321             } else if (obj->proto == AFPPROTO_DSI) {
322                 DSI *dsi = obj->handle;
323                 q = getip_string((struct sockaddr *)&dsi->client);
324             }
325         } else if (is_var(p, "$s")) {
326             if (obj->Obj)
327                 q = obj->Obj;
328             else if (obj->options.server) {
329                 q = obj->options.server;
330             } else
331                 q = obj->options.hostname;
332         } else if (obj->username && is_var(p, "$u")) {
333             if (afpmaster && xlatevolname)
334                 return NULL;
335             char* sep = NULL;
336             if ( obj->options.ntseparator && (sep = strchr(obj->username, obj->options.ntseparator[0])) != NULL)
337                 q = sep+1;
338             else
339                 q = obj->username;
340         } else if (is_var(p, "$v")) {
341             if (afpmaster && xlatevolname)
342                 return NULL;
343             if (volname) {
344                 q = volname;
345             }
346             else if (path) {
347                 if ((q = strrchr(path, '/')) == NULL)
348                     q = path;
349                 else if (*(q + 1) != '\0')
350                     q++;
351             }
352         } else if (is_var(p, "$z")) {
353             q = obj->Zone;
354         } else if (is_var(p, "$$")) {
355             q = "$";
356         } else
357             q = p;
358
359         /* copy the stuff over. if we don't understand something that we
360          * should, just skip it over. */
361         if (q) {
362             len = MIN(p == q ? 2 : strlen(q), destlen);
363             strncpy(dest, q, len);
364             dest += len;
365             destlen -= len;
366         }
367
368         /* stuff up to next $ */
369         src = p + 2;
370         p = strchr(src, '$');
371         len = p ? MIN((size_t)(p - src), destlen) : destlen;
372         if (len > 0) {
373             strncpy(dest, src, len);
374             dest += len;
375             destlen -= len;
376         }
377     }
378     return ret;
379 }
380
381 /* to make sure that val is valid, make sure to select an opt that
382    includes val */
383 static int optionok(const char *buf, const char *opt, const char *val)
384 {
385     if (!strstr(buf,opt))
386         return 0;
387     if (!val[1])
388         return 0;
389     return 1;
390 }
391
392
393 /* -------------------- */
394 static void setoption(struct vol_option *options, struct vol_option *save, int opt, const char *val)
395 {
396     if (options[opt].c_value && (!save || options[opt].c_value != save[opt].c_value))
397         free(options[opt].c_value);
398     options[opt].c_value = strdup(val + 1);
399 }
400
401 /* ------------------------------------------
402    handle all the options. tmp can't be NULL. */
403 static void volset(struct vol_option *options, struct vol_option *save,
404                    char *volname, int vlen,
405                    const char *tmp)
406 {
407     char *val;
408
409     val = strchr(tmp, ':');
410     if (!val) {
411         /* we'll assume it's a volume name. */
412         strncpy(volname, tmp, vlen);
413         volname[vlen] = 0;
414         return;
415     }
416 #if 0
417     LOG(log_debug, logtype_afpd, "Parsing volset %s", val);
418 #endif
419     if (optionok(tmp, "allow:", val)) {
420         setoption(options, save, VOLOPT_ALLOW, val);
421
422     } else if (optionok(tmp, "deny:", val)) {
423         setoption(options, save, VOLOPT_DENY, val);
424
425     } else if (optionok(tmp, "rwlist:", val)) {
426         setoption(options, save, VOLOPT_RWLIST, val);
427
428     } else if (optionok(tmp, "rolist:", val)) {
429         setoption(options, save, VOLOPT_ROLIST, val);
430
431     } else if (optionok(tmp, "codepage:", val)) {
432         LOG (log_error, logtype_afpd, "The old codepage system has been removed. Please make sure to read the documentation !!!!");
433         /* Make sure we don't screw anything */
434         exit (EXITERR_CONF);
435     } else if (optionok(tmp, "volcharset:", val)) {
436         setoption(options, save, VOLOPT_ENCODING, val);
437     } else if (optionok(tmp, "maccharset:", val)) {
438         setoption(options, save, VOLOPT_MACCHARSET, val);
439     } else if (optionok(tmp, "veto:", val)) {
440         setoption(options, save, VOLOPT_VETO, val);
441     } else if (optionok(tmp, "cnidscheme:", val)) {
442         setoption(options, save, VOLOPT_CNIDSCHEME, val);
443     } else if (optionok(tmp, "casefold:", val)) {
444         if (strcasecmp(val + 1, "tolower") == 0)
445             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMLOWER;
446         else if (strcasecmp(val + 1, "toupper") == 0)
447             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMUPPER;
448         else if (strcasecmp(val + 1, "xlatelower") == 0)
449             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UUPPERMLOWER;
450         else if (strcasecmp(val + 1, "xlateupper") == 0)
451             options[VOLOPT_CASEFOLD].i_value = AFPVOL_ULOWERMUPPER;
452     } else if (optionok(tmp, "adouble:", val)) {
453         if (strcasecmp(val + 1, "v1") == 0)
454             options[VOLOPT_ADOUBLE].i_value = AD_VERSION1;
455 #if AD_VERSION == AD_VERSION2
456         else if (strcasecmp(val + 1, "v2") == 0)
457             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2;
458         else if (strcasecmp(val + 1, "osx") == 0)
459             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2_OSX;
460         else if (strcasecmp(val + 1, "sfm") == 0)
461             options[VOLOPT_ADOUBLE].i_value = AD_VERSION1_SFM;
462 #endif
463     } else if (optionok(tmp, "options:", val)) {
464         char *p;
465
466         if ((p = strtok(val + 1, ",")) == NULL) /* nothing */
467             return;
468
469         while (p) {
470             if (strcasecmp(p, "prodos") == 0)
471                 options[VOLOPT_FLAGS].i_value |= AFPVOL_A2VOL;
472             else if (strcasecmp(p, "mswindows") == 0) {
473                 options[VOLOPT_FLAGS].i_value |= AFPVOL_MSWINDOWS | AFPVOL_USEDOTS;
474             } else if (strcasecmp(p, "crlf") == 0)
475                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CRLF;
476             else if (strcasecmp(p, "noadouble") == 0)
477                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOADOUBLE;
478             else if (strcasecmp(p, "ro") == 0)
479                 options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
480             else if (strcasecmp(p, "nohex") == 0)
481                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOHEX;
482             else if (strcasecmp(p, "usedots") == 0)
483                 options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS;
484             else if (strcasecmp(p, "invisibledots") == 0)
485                 options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS | AFPVOL_INV_DOTS;
486             else if (strcasecmp(p, "limitsize") == 0)
487                 options[VOLOPT_FLAGS].i_value |= AFPVOL_LIMITSIZE;
488             /* support for either "dropbox" or "dropkludge" */
489             else if (strcasecmp(p, "dropbox") == 0)
490                 options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
491             else if (strcasecmp(p, "dropkludge") == 0)
492                 options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
493             else if (strcasecmp(p, "nofileid") == 0)
494                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOFILEID;
495             else if (strcasecmp(p, "nostat") == 0)
496                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOSTAT;
497             else if (strcasecmp(p, "preexec_close") == 0)
498                 options[VOLOPT_PREEXEC].i_value = 1;
499             else if (strcasecmp(p, "root_preexec_close") == 0)
500                 options[VOLOPT_ROOTPREEXEC].i_value = 1;
501             else if (strcasecmp(p, "upriv") == 0)
502                 options[VOLOPT_FLAGS].i_value |= AFPVOL_UNIX_PRIV;
503             else if (strcasecmp(p, "nodev") == 0)
504                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NODEV;
505             else if (strcasecmp(p, "caseinsensitive") == 0)
506                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CASEINSEN;
507             else if (strcasecmp(p, "illegalseq") == 0)
508                 options[VOLOPT_FLAGS].i_value |= AFPVOL_EILSEQ;
509             else if (strcasecmp(p, "nocnidcache") == 0)
510                 options[VOLOPT_FLAGS].i_value &= ~AFPVOL_CACHE;
511             else if (strcasecmp(p, "tm") == 0)
512                 options[VOLOPT_FLAGS].i_value |= AFPVOL_TM;
513             else if (strcasecmp(p, "searchdb") == 0)
514                 options[VOLOPT_FLAGS].i_value |= AFPVOL_SEARCHDB;
515 /* Found this in branch dir-rewrite, maybe we want to use it sometimes */
516 #if 0
517             else if (strcasecmp(p, "cdrom") == 0)
518                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CDROM | AFPVOL_RO;
519 #endif
520             p = strtok(NULL, ",");
521         }
522
523     } else if (optionok(tmp, "cnidserver:", val)) {
524         setoption(options, save, VOLOPT_CNIDSERVER, val);
525
526         char *p = strrchr(val + 1, ':');
527         if (p) {
528             *p = 0;
529             setoption(options, save, VOLOPT_CNIDPORT, p);
530         }
531
532         LOG(log_debug, logtype_afpd, "CNID Server for volume '%s': %s:%s",
533             volname, val + 1, p ? p + 1 : Cnid_port);
534
535     } else if (optionok(tmp, "dbpath:", val)) {
536         setoption(options, save, VOLOPT_DBPATH, val);
537
538     } else if (optionok(tmp, "umask:", val)) {
539         options[VOLOPT_UMASK].i_value = (int)strtol(val +1, NULL, 8);
540     } else if (optionok(tmp, "dperm:", val)) {
541         options[VOLOPT_DPERM].i_value = (int)strtol(val+1, NULL, 8);
542     } else if (optionok(tmp, "fperm:", val)) {
543         options[VOLOPT_FPERM].i_value = (int)strtol(val+1, NULL, 8);
544     } else if (optionok(tmp, "perm:", val)) {
545         options[VOLOPT_DFLTPERM].i_value = (int)strtol(val+1, NULL, 8);
546     } else if (optionok(tmp, "password:", val)) {
547         setoption(options, save, VOLOPT_PASSWORD, val);
548
549 #ifdef FORCE_UIDGID
550
551         /* this code allows forced uid/gid per volume settings */
552     } else if (optionok(tmp, "forceuid:", val)) {
553         setoption(options, save, VOLOPT_FORCEUID, val);
554     } else if (optionok(tmp, "forcegid:", val)) {
555         setoption(options, save, VOLOPT_FORCEGID, val);
556
557 #endif /* FORCE_UIDGID */
558     } else if (optionok(tmp, "root_preexec:", val)) {
559         setoption(options, save, VOLOPT_ROOTPREEXEC, val);
560
561     } else if (optionok(tmp, "preexec:", val)) {
562         setoption(options, save, VOLOPT_PREEXEC, val);
563
564     } else if (optionok(tmp, "root_postexec:", val)) {
565         setoption(options, save, VOLOPT_ROOTPOSTEXEC, val);
566
567     } else if (optionok(tmp, "postexec:", val)) {
568         setoption(options, save, VOLOPT_POSTEXEC, val);
569
570     } else if (optionok(tmp, "allowed_hosts:", val)) {
571         setoption(options, save, VOLOPT_ALLOWED_HOSTS, val);
572
573     } else if (optionok(tmp, "denied_hosts:", val)) {
574         setoption(options, save, VOLOPT_DENIED_HOSTS, val);
575
576     } else if (optionok(tmp, "ea:", val)) {
577         if (strcasecmp(val + 1, "ad") == 0)
578             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AD;
579         else if (strcasecmp(val + 1, "sys") == 0)
580             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_SYS;
581         else if (strcasecmp(val + 1, "none") == 0)
582             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_NONE;
583
584     } else if (optionok(tmp, "volsizelimit:", val)) {
585         options[VOLOPT_LIMITSIZE].i_value = (uint32_t)strtoul(val + 1, NULL, 10);
586
587     } else {
588         /* ignore unknown options */
589         LOG(log_debug, logtype_afpd, "ignoring unknown volume option: %s", tmp);
590
591     }
592 }
593
594 /* ----------------- */
595 static void showvol(const ucs2_t *name)
596 {
597     struct vol  *volume;
598     for ( volume = Volumes; volume; volume = volume->v_next ) {
599         if (volume->v_hide && !strcasecmp_w( volume->v_name, name ) ) {
600             volume->v_hide = 0;
601             return;
602         }
603     }
604 }
605
606 /* ------------------------------- */
607 static int creatvol(AFPObj *obj, struct passwd *pwd,
608                     char *path, char *name,
609                     struct vol_option *options,
610                     const int user /* user defined volume */
611     )
612 {
613     struct vol  *volume;
614     int         suffixlen, vlen, tmpvlen, u8mvlen, macvlen;
615     int         hide = 0;
616     char        tmpname[AFPVOL_U8MNAMELEN+1];
617     ucs2_t      u8mtmpname[(AFPVOL_U8MNAMELEN+1)*2], mactmpname[(AFPVOL_MACNAMELEN+1)*2];
618     char        suffix[6]; /* max is #FFFF */
619     u_int16_t   flags;
620
621     LOG(log_debug, logtype_afpd, "createvol: Volume '%s'", name);
622
623     if ( name == NULL || *name == '\0' ) {
624         if ((name = strrchr( path, '/' )) == NULL) {
625             return -1;  /* Obviously not a fully qualified path */
626         }
627
628         /* if you wish to share /, you need to specify a name. */
629         if (*++name == '\0')
630             return -1;
631     }
632
633     /* suffix for mangling use (lastvid + 1)   */
634     /* because v_vid has not been decided yet. */
635     suffixlen = sprintf(suffix, "%c%X", MANGLE_CHAR, lastvid + 1 );
636
637     vlen = strlen( name );
638
639     /* Unicode Volume Name */
640     /* Firstly convert name from unixcharset to UTF8-MAC */
641     flags = CONV_IGNORE;
642     tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
643     if (tmpvlen <= 0) {
644         strcpy(tmpname, "???");
645         tmpvlen = 3;
646     }
647
648     /* Do we have to mangle ? */
649     if ( (flags & CONV_REQMANGLE) || (tmpvlen > obj->options.volnamelen)) {
650         if (tmpvlen + suffixlen > obj->options.volnamelen) {
651             flags = CONV_FORCE;
652             tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, obj->options.volnamelen - suffixlen, &flags);
653             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
654         }
655         strcat(tmpname, suffix);
656         tmpvlen = strlen(tmpname);
657     }
658
659     /* Secondly convert name from UTF8-MAC to UCS2 */
660     if ( 0 >= ( u8mvlen = convert_string(CH_UTF8_MAC, CH_UCS2, tmpname, tmpvlen, u8mtmpname, AFPVOL_U8MNAMELEN*2)) )
661         return -1;
662
663     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' -> UTF8-MAC Name: '%s'", name, tmpname);
664
665     /* Maccharset Volume Name */
666     /* Firsty convert name from unixcharset to maccharset */
667     flags = CONV_IGNORE;
668     tmpvlen = convert_charset(obj->options.unixcharset, obj->options.maccharset, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
669     if (tmpvlen <= 0) {
670         strcpy(tmpname, "???");
671         tmpvlen = 3;
672     }
673
674     /* Do we have to mangle ? */
675     if ( (flags & CONV_REQMANGLE) || (tmpvlen > AFPVOL_MACNAMELEN)) {
676         if (tmpvlen + suffixlen > AFPVOL_MACNAMELEN) {
677             flags = CONV_FORCE;
678             tmpvlen = convert_charset(obj->options.unixcharset,
679                                       obj->options.maccharset,
680                                       0,
681                                       name,
682                                       vlen,
683                                       tmpname,
684                                       AFPVOL_MACNAMELEN - suffixlen,
685                                       &flags);
686             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
687         }
688         strcat(tmpname, suffix);
689         tmpvlen = strlen(tmpname);
690     }
691
692     /* Secondly convert name from maccharset to UCS2 */
693     if ( 0 >= ( macvlen = convert_string(obj->options.maccharset,
694                                          CH_UCS2,
695                                          tmpname,
696                                          tmpvlen,
697                                          mactmpname,
698                                          AFPVOL_U8MNAMELEN*2)) )
699         return -1;
700
701     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' ->  Longname: '%s'", name, tmpname);
702
703     /* check duplicate */
704     for ( volume = Volumes; volume; volume = volume->v_next ) {
705         if ((utf8_encoding() && (strcasecmp_w(volume->v_u8mname, u8mtmpname) == 0))
706              ||
707             (!utf8_encoding() && (strcasecmp_w(volume->v_macname, mactmpname) == 0))) {
708             LOG (log_error, logtype_afpd,
709                  "Duplicate volume name, check AppleVolumes files: previous: \"%s\", new: \"%s\"",
710                  volume->v_localname, name);
711             if (volume->v_deleted) {
712                 volume->v_new = hide = 1;
713             }
714             else {
715                 return -1;  /* Won't be able to access it, anyway... */
716             }
717         }
718     }
719
720     if (!( volume = (struct vol *)calloc(1, sizeof( struct vol ))) ) {
721         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
722         return -1;
723     }
724     if ( NULL == ( volume->v_localname = strdup(name))) {
725         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
726         free(volume);
727         return -1;
728     }
729
730     if ( NULL == ( volume->v_u8mname = strdup_w(u8mtmpname))) {
731         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
732         volume_free(volume);
733         free(volume);
734         return -1;
735     }
736     if ( NULL == ( volume->v_macname = strdup_w(mactmpname))) {
737         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
738         volume_free(volume);
739         free(volume);
740         return -1;
741     }
742     if (!( volume->v_path = (char *)malloc( strlen( path ) + 1 )) ) {
743         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
744         volume_free(volume);
745         free(volume);
746         return -1;
747     }
748
749     volume->v_name = utf8_encoding()?volume->v_u8mname:volume->v_macname;
750     volume->v_hide = hide;
751     strcpy( volume->v_path, path );
752
753 #ifdef __svr4__
754     volume->v_qfd = -1;
755 #endif /* __svr4__ */
756     /* os X start at 1 and use network order ie. 1 2 3 */
757     volume->v_vid = ++lastvid;
758     volume->v_vid = htons(volume->v_vid);
759 #ifdef HAVE_ACLS
760     if (check_vol_acl_support(volume))
761         volume->v_flags |= AFPVOL_ACLS
762 ;
763 #endif
764
765     /* handle options */
766     if (options) {
767         volume->v_casefold = options[VOLOPT_CASEFOLD].i_value;
768         volume->v_flags |= options[VOLOPT_FLAGS].i_value;
769
770         if (options[VOLOPT_EA_VFS].i_value)
771             volume->v_vfs_ea = options[VOLOPT_EA_VFS].i_value;
772
773         volume->v_ad_options = 0;
774         if ((volume->v_flags & AFPVOL_NODEV))
775             volume->v_ad_options |= ADVOL_NODEV;
776         if ((volume->v_flags & AFPVOL_CACHE))
777             volume->v_ad_options |= ADVOL_CACHE;
778         if ((volume->v_flags & AFPVOL_UNIX_PRIV))
779             volume->v_ad_options |= ADVOL_UNIXPRIV;
780         if ((volume->v_flags & AFPVOL_INV_DOTS))
781             volume->v_ad_options |= ADVOL_INVDOTS;
782         if ((volume->v_flags & AFPVOL_NOADOUBLE))
783             volume->v_ad_options |= ADVOL_NOADOUBLE;
784
785         if (options[VOLOPT_PASSWORD].c_value)
786             volume->v_password = strdup(options[VOLOPT_PASSWORD].c_value);
787
788         if (options[VOLOPT_VETO].c_value)
789             volume->v_veto = strdup(options[VOLOPT_VETO].c_value);
790
791         if (options[VOLOPT_ENCODING].c_value)
792             volume->v_volcodepage = strdup(options[VOLOPT_ENCODING].c_value);
793
794         if (options[VOLOPT_MACCHARSET].c_value)
795             volume->v_maccodepage = strdup(options[VOLOPT_MACCHARSET].c_value);
796
797         if (options[VOLOPT_DBPATH].c_value)
798             volume->v_dbpath = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_DBPATH].c_value, pwd, path, name);
799
800         if (options[VOLOPT_CNIDSCHEME].c_value)
801             volume->v_cnidscheme = strdup(options[VOLOPT_CNIDSCHEME].c_value);
802
803         if (options[VOLOPT_CNIDSERVER].c_value)
804             volume->v_cnidserver = strdup(options[VOLOPT_CNIDSERVER].c_value);
805
806         if (options[VOLOPT_CNIDPORT].c_value)
807             volume->v_cnidport = strdup(options[VOLOPT_CNIDPORT].c_value);
808
809         if (options[VOLOPT_UMASK].i_value)
810             volume->v_umask = (mode_t)options[VOLOPT_UMASK].i_value;
811
812         if (options[VOLOPT_DPERM].i_value)
813             volume->v_dperm = (mode_t)options[VOLOPT_DPERM].i_value;
814
815         if (options[VOLOPT_FPERM].i_value)
816             volume->v_fperm = (mode_t)options[VOLOPT_FPERM].i_value;
817
818         if (options[VOLOPT_DFLTPERM].i_value)
819             volume->v_perm = (mode_t)options[VOLOPT_DFLTPERM].i_value;
820
821         if (options[VOLOPT_ADOUBLE].i_value)
822             volume->v_adouble = options[VOLOPT_ADOUBLE].i_value;
823         else
824             volume->v_adouble = AD_VERSION;
825
826         if (options[VOLOPT_LIMITSIZE].i_value)
827             volume->v_limitsize = options[VOLOPT_LIMITSIZE].i_value;
828
829         /* Mac to Unix conversion flags*/
830         volume->v_mtou_flags = 0;
831         if (!(volume->v_flags & AFPVOL_NOHEX))
832             volume->v_mtou_flags |= CONV_ESCAPEHEX;
833         if (!(volume->v_flags & AFPVOL_USEDOTS))
834             volume->v_mtou_flags |= CONV_ESCAPEDOTS;
835         if ((volume->v_flags & AFPVOL_EILSEQ))
836             volume->v_mtou_flags |= CONV__EILSEQ;
837
838         if ((volume->v_casefold & AFPVOL_MTOUUPPER))
839             volume->v_mtou_flags |= CONV_TOUPPER;
840         else if ((volume->v_casefold & AFPVOL_MTOULOWER))
841             volume->v_mtou_flags |= CONV_TOLOWER;
842
843         /* Unix to Mac conversion flags*/
844         volume->v_utom_flags = CONV_IGNORE | CONV_UNESCAPEHEX;
845         if ((volume->v_casefold & AFPVOL_UTOMUPPER))
846             volume->v_utom_flags |= CONV_TOUPPER;
847         else if ((volume->v_casefold & AFPVOL_UTOMLOWER))
848             volume->v_utom_flags |= CONV_TOLOWER;
849
850         if ((volume->v_flags & AFPVOL_EILSEQ))
851             volume->v_utom_flags |= CONV__EILSEQ;
852
853 #ifdef FORCE_UIDGID
854         if (options[VOLOPT_FORCEUID].c_value) {
855             volume->v_forceuid = strdup(options[VOLOPT_FORCEUID].c_value);
856         } else {
857             volume->v_forceuid = NULL; /* set as null so as to return 0 later on */
858         }
859
860         if (options[VOLOPT_FORCEGID].c_value) {
861             volume->v_forcegid = strdup(options[VOLOPT_FORCEGID].c_value);
862         } else {
863             volume->v_forcegid = NULL; /* set as null so as to return 0 later on */
864         }
865 #endif
866         if (!user) {
867             if (options[VOLOPT_PREEXEC].c_value)
868                 volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_PREEXEC].c_value, pwd, path, name);
869             volume->v_preexec_close = options[VOLOPT_PREEXEC].i_value;
870
871             if (options[VOLOPT_POSTEXEC].c_value)
872                 volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_POSTEXEC].c_value, pwd, path, name);
873
874             if (options[VOLOPT_ROOTPREEXEC].c_value)
875                 volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPREEXEC].c_value, pwd, path,  name);
876             volume->v_root_preexec_close = options[VOLOPT_ROOTPREEXEC].i_value;
877
878             if (options[VOLOPT_ROOTPOSTEXEC].c_value)
879                 volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPOSTEXEC].c_value, pwd, path,  name);
880         }
881     }
882     volume->v_dperm |= volume->v_perm;
883     volume->v_fperm |= volume->v_perm;
884
885     /* Check EA support on volume */
886     if (volume->v_vfs_ea == AFPVOL_EA_AUTO)
887         check_ea_sys_support(volume);
888     initvol_vfs(volume);
889
890     /* get/store uuid from file in afpd master*/
891     if ((parent_or_child == 0) && (volume->v_flags & AFPVOL_TM)) {
892         char *uuid = get_vol_uuid(obj, volume->v_localname);
893         if (!uuid) {
894             LOG(log_error, logtype_afpd, "Volume '%s': couldn't get UUID",
895                 volume->v_localname);
896         } else {
897             volume->v_uuid = uuid;
898             LOG(log_debug, logtype_afpd, "Volume '%s': UUID '%s'",
899                 volume->v_localname, volume->v_uuid);
900         }
901     }
902
903     volume->v_next = Volumes;
904     Volumes = volume;
905     return 0;
906 }
907
908 /* ---------------- */
909 static char *myfgets( char *buf, int size, FILE *fp)
910 {
911     char    *p;
912     int     c;
913
914     p = buf;
915     while ((EOF != ( c = getc( fp )) ) && ( size > 1 )) {
916         if ( c == '\n' || c == '\r' ) {
917             if (p != buf && *(p -1) == '\\') {
918                 p--;
919                 size++;
920                 continue;
921             }
922             *p++ = '\n';
923             break;
924         } else {
925             *p++ = c;
926         }
927         size--;
928     }
929
930     if ( p == buf ) {
931         return( NULL );
932     } else {
933         *p = '\0';
934         return( buf );
935     }
936 }
937
938
939 /* check access list. this function wants something of the following
940  * form:
941  *        @group,name,name2,@group2,name3
942  *
943  * a NULL argument allows everybody to have access.
944  * we return three things:
945  *     -1: no list
946  *      0: list exists, but name isn't in it
947  *      1: in list
948  */
949
950 #ifndef NO_REAL_USER_NAME
951 /* authentication is case insensitive
952  * FIXME should we do the same with group name?
953  */
954 #define access_strcmp strcasecmp
955
956 #else
957 #define access_strcmp strcmp
958
959 #endif
960
961 static int accessvol(const char *args, const char *name)
962 {
963     char buf[MAXPATHLEN + 1], *p;
964     struct group *gr;
965
966     if (!args)
967         return -1;
968
969     strlcpy(buf, args, sizeof(buf));
970     if ((p = strtok(buf, ",")) == NULL) /* nothing, return okay */
971         return -1;
972
973     while (p) {
974         if (*p == '@') { /* it's a group */
975             if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid))
976                 return 1;
977         } else if (access_strcmp(p, name) == 0) /* it's a user name */
978             return 1;
979         p = strtok(NULL, ",");
980     }
981
982     return 0;
983 }
984
985 static int hostaccessvol(int type, const char *volname, const char *args, const AFPObj *obj)
986 {
987     int mask_int;
988     char buf[MAXPATHLEN + 1], *p, *b;
989     DSI *dsi = obj->handle;
990     struct sockaddr_storage client;
991
992     if (!args)
993         return -1;
994
995     strlcpy(buf, args, sizeof(buf));
996     if ((p = strtok_r(buf, ",", &b)) == NULL) /* nothing, return okay */
997         return -1;
998
999     if (obj->proto != AFPPROTO_DSI)
1000         return -1;
1001
1002     while (p) {
1003         int ret;
1004         char *ipaddr, *mask_char;
1005         struct addrinfo hints, *ai;
1006
1007         ipaddr = strtok(p, "/");
1008         mask_char = strtok(NULL,"/");
1009
1010         /* Get address from string with getaddrinfo */
1011         memset(&hints, 0, sizeof hints);
1012         hints.ai_family = AF_UNSPEC;
1013         hints.ai_socktype = SOCK_STREAM;
1014         if ((ret = getaddrinfo(ipaddr, NULL, &hints, &ai)) != 0) {
1015             LOG(log_error, logtype_afpd, "hostaccessvol: getaddrinfo: %s\n", gai_strerror(ret));
1016             continue;
1017         }
1018
1019         /* netmask */
1020         if (mask_char != NULL)
1021             mask_int = atoi(mask_char); /* apply_ip_mask does range checking on it */
1022         else {
1023             if (ai->ai_family == AF_INET) /* IPv4 */
1024                 mask_int = 32;
1025             else                          /* IPv6 */
1026                 mask_int = 128;
1027         }
1028
1029         /* Apply mask to addresses */
1030         client = dsi->client;
1031         apply_ip_mask((struct sockaddr *)&client, mask_int);
1032         apply_ip_mask(ai->ai_addr, mask_int);
1033
1034         if (compare_ip((struct sockaddr *)&client, ai->ai_addr) == 0) {
1035             if (type == VOLOPT_DENIED_HOSTS)
1036                 LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s' by denied list",
1037                     getip_string((struct sockaddr *)&client), volname);
1038             freeaddrinfo(ai);
1039             return 1;
1040         }
1041
1042         /* next address */
1043         freeaddrinfo(ai);
1044         p = strtok_r(NULL, ",", &b);
1045     }
1046
1047     if (type == VOLOPT_ALLOWED_HOSTS)
1048         LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s', not in allowed list",
1049             getip_string((struct sockaddr *)&dsi->client), volname);
1050     return 0;
1051 }
1052
1053 static void setextmap(char *ext, char *type, char *creator, int user)
1054 {
1055     struct extmap   *em;
1056     int                 cnt;
1057
1058     if (Extmap == NULL) {
1059         if (( Extmap = calloc(1, sizeof( struct extmap ))) == NULL ) {
1060             LOG(log_error, logtype_afpd, "setextmap: calloc: %s", strerror(errno) );
1061             return;
1062         }
1063     }
1064     ext++;
1065     for ( em = Extmap, cnt = 0; em->em_ext; em++, cnt++) {
1066         if ( (strdiacasecmp( em->em_ext, ext )) == 0 ) {
1067             break;
1068         }
1069     }
1070
1071     if ( em->em_ext == NULL ) {
1072         if (!(Extmap  = realloc( Extmap, sizeof( struct extmap ) * (cnt +2))) ) {
1073             LOG(log_error, logtype_afpd, "setextmap: realloc: %s", strerror(errno) );
1074             return;
1075         }
1076         (Extmap +cnt +1)->em_ext = NULL;
1077         em = Extmap +cnt;
1078     } else if ( !user ) {
1079         return;
1080     }
1081     if (em->em_ext)
1082         free(em->em_ext);
1083
1084     if (!(em->em_ext = strdup(  ext))) {
1085         LOG(log_error, logtype_afpd, "setextmap: strdup: %s", strerror(errno) );
1086         return;
1087     }
1088
1089     if ( *type == '\0' ) {
1090         memcpy(em->em_type, "\0\0\0\0", sizeof( em->em_type ));
1091     } else {
1092         memcpy(em->em_type, type, sizeof( em->em_type ));
1093     }
1094     if ( *creator == '\0' ) {
1095         memcpy(em->em_creator, "\0\0\0\0", sizeof( em->em_creator ));
1096     } else {
1097         memcpy(em->em_creator, creator, sizeof( em->em_creator ));
1098     }
1099 }
1100
1101 /* -------------------------- */
1102 static int extmap_cmp(const void *map1, const void *map2)
1103 {
1104     const struct extmap *em1 = map1;
1105     const struct extmap *em2 = map2;
1106     return strdiacasecmp(em1->em_ext, em2->em_ext);
1107 }
1108
1109 static void sortextmap( void)
1110 {
1111     struct extmap   *em;
1112
1113     Extmap_cnt = 0;
1114     if ((em = Extmap) == NULL) {
1115         return;
1116     }
1117     while (em->em_ext) {
1118         em++;
1119         Extmap_cnt++;
1120     }
1121     if (Extmap_cnt) {
1122         qsort(Extmap, Extmap_cnt, sizeof(struct extmap), extmap_cmp);
1123         if (*Extmap->em_ext == 0) {
1124             /* the first line is really "." the default entry,
1125              * we remove the leading '.' in setextmap
1126              */
1127             Defextmap = Extmap;
1128         }
1129     }
1130 }
1131
1132 /* ----------------------
1133  */
1134 static void free_extmap( void)
1135 {
1136     struct extmap   *em;
1137
1138     if (Extmap) {
1139         for ( em = Extmap; em->em_ext; em++) {
1140             free (em->em_ext);
1141         }
1142         free(Extmap);
1143         Extmap = NULL;
1144         Defextmap = Extmap;
1145         Extmap_cnt = 0;
1146     }
1147 }
1148
1149 /* ----------------------
1150  */
1151 static int volfile_changed(struct afp_volume_name *p)
1152 {
1153     struct stat      st;
1154     char *name;
1155
1156     if (p->full_name)
1157         name = p->full_name;
1158     else
1159         name = p->name;
1160
1161     if (!stat( name, &st) && st.st_mtime > p->mtime) {
1162         p->mtime = st.st_mtime;
1163         return 1;
1164     }
1165     return 0;
1166 }
1167
1168 /* ----------------------
1169  * Read a volume configuration file and add the volumes contained within to
1170  * the global volume list. This gets called from the forked afpd childs.
1171  * The master now reads this too for Zeroconf announcements.
1172  *
1173  * If p2 is non-NULL, the file that is opened is
1174  * p1/p2
1175  *
1176  * Lines that begin with # and blank lines are ignored.
1177  * Volume lines are of the form:
1178  *      <unix path> [<volume name>] [allow:<user>,<@group>,...] \
1179  *                           [codepage:<file>] [casefold:<num>]
1180  *      <extension> TYPE [CREATOR]
1181  *
1182  */
1183 static int readvolfile(AFPObj *obj, struct afp_volume_name *p1, char *p2, int user, struct passwd *pwent)
1184 {
1185     FILE        *fp;
1186     char        path[MAXPATHLEN + 1];
1187     char        tmp[MAXPATHLEN + 1];
1188     char        volname[AFPVOL_U8MNAMELEN + 1];
1189     char        buf[BUFSIZ];
1190     char        type[5], creator[5];
1191     char        *u, *p;
1192     int         fd;
1193     int         i;
1194     struct passwd   *pw;
1195     struct vol_option   save_options[VOLOPT_NUM];
1196     struct vol_option   options[VOLOPT_NUM];
1197     struct stat         st;
1198
1199     if (!p1->name)
1200         return -1;
1201     p1->mtime = 0;
1202     strcpy( path, p1->name );
1203     if ( p2 != NULL ) {
1204         strcat( path, "/" );
1205         strcat( path, p2 );
1206         if (p1->full_name) {
1207             free(p1->full_name);
1208         }
1209         p1->full_name = strdup(path);
1210     }
1211
1212     if (NULL == ( fp = fopen( path, "r" )) ) {
1213         return( -1 );
1214     }
1215     fd = fileno(fp);
1216     if (fd != -1 && !fstat( fd, &st) ) {
1217         p1->mtime = st.st_mtime;
1218     }
1219
1220     if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
1221         LOG(log_error, logtype_afpd, "readvolfile: can't lock volume file \"%s\"", path);
1222         if ( fclose( fp ) != 0 ) {
1223             LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1224         }
1225         return -1;
1226     }
1227
1228     memset(save_options, 0, sizeof(save_options));
1229
1230     /* Enable some default options for all volumes */
1231     save_options[VOLOPT_FLAGS].i_value |= AFPVOL_CACHE;
1232     save_options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AUTO;
1233     LOG(log_maxdebug, logtype_afpd, "readvolfile: seeding default umask: %04o",
1234         obj->options.umask);
1235     save_options[VOLOPT_UMASK].i_value = obj->options.umask;
1236
1237     LOG(log_debug, logtype_afpd, "readvolfile: \"%s\"", path);
1238
1239     while ( myfgets( buf, sizeof( buf ), fp ) != NULL ) {
1240         initline( strlen( buf ), buf );
1241         parseline( sizeof( path ) - 1, path );
1242         switch ( *path ) {
1243         case '\0' :
1244         case '#' :
1245             continue;
1246
1247         case ':':
1248             /* change the default options for this file */
1249             if (strncmp(path, VOLOPT_DEFAULT, VOLOPT_DEFAULT_LEN) == 0) {
1250                 *tmp = '\0';
1251                 for (i = 0; i < VOLOPT_NUM; i++) {
1252                     if (parseline( sizeof( path ) - VOLOPT_DEFAULT_LEN - 1,
1253                                    path + VOLOPT_DEFAULT_LEN) < 0)
1254                         break;
1255                     volset(save_options, NULL, tmp, sizeof(tmp) - 1,
1256                            path + VOLOPT_DEFAULT_LEN);
1257                 }
1258             }
1259             break;
1260
1261         case '~' :
1262             if (( p = strchr( path, '/' )) != NULL ) {
1263                 *p++ = '\0';
1264             }
1265             u = path;
1266             u++;
1267             if ( *u == '\0' ) {
1268                 u = obj->username;
1269             }
1270             if ( u == NULL || *u == '\0' || ( pw = getpwnam( u )) == NULL ) {
1271                 continue;
1272             }
1273             strcpy( tmp, pw->pw_dir );
1274             if ( p != NULL && *p != '\0' ) {
1275                 strcat( tmp, "/" );
1276                 strcat( tmp, p );
1277             }
1278             /* fall through */
1279
1280         case '/' :
1281             /* send path through variable substitution */
1282             if (*path != '~') /* need to copy path to tmp */
1283                 strcpy(tmp, path);
1284             if (!pwent && obj->username)
1285                 pwent = getpwnam(obj->username);
1286
1287             if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
1288                 continue;
1289
1290             /* this is sort of braindead. basically, i want to be
1291              * able to specify things in any order, but i don't want to
1292              * re-write everything. */
1293
1294             memcpy(options, save_options, sizeof(options));
1295             *volname = '\0';
1296
1297             /* read in up to VOLOP_NUM possible options */
1298             for (i = 0; i < VOLOPT_NUM; i++) {
1299                 if (parseline( sizeof( tmp ) - 1, tmp ) < 0)
1300                     break;
1301
1302                 volset(options, save_options, volname, sizeof(volname) - 1, tmp);
1303             }
1304
1305             /* check allow/deny lists (if not afpd master loading volumes for Zeroconf reg.):
1306                allow -> either no list (-1), or in list (1)
1307                deny -> either no list (-1), or not in list (0) */
1308             if (parent_or_child == 0
1309                 ||
1310                 (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
1311                  (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1) &&
1312                  hostaccessvol(VOLOPT_ALLOWED_HOSTS, volname, options[VOLOPT_ALLOWED_HOSTS].c_value, obj) &&
1313                  (hostaccessvol(VOLOPT_DENIED_HOSTS, volname, options[VOLOPT_DENIED_HOSTS].c_value, obj) < 1))) {
1314
1315                 /* handle read-only behaviour. semantics:
1316                  * 1) neither the rolist nor the rwlist exist -> rw
1317                  * 2) rolist exists -> ro if user is in it.
1318                  * 3) rwlist exists -> ro unless user is in it. */
1319                 if (parent_or_child == 1
1320                     &&
1321                     ((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0)
1322                     &&
1323                     ((accessvol(options[VOLOPT_ROLIST].c_value, obj->username) == 1) ||
1324                      !accessvol(options[VOLOPT_RWLIST].c_value, obj->username)))
1325                     options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
1326
1327                 /* do variable substitution for volname */
1328                 if (volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL) == NULL)
1329                     continue;
1330
1331                 creatvol(obj, pwent, path, tmp, options, p2 != NULL);
1332             }
1333             volfree(options, save_options);
1334             break;
1335
1336         case '.' :
1337             parseline( sizeof( type ) - 1, type );
1338             parseline( sizeof( creator ) - 1, creator );
1339             setextmap( path, type, creator, user);
1340             break;
1341
1342         default :
1343             break;
1344         }
1345     }
1346     volfree(save_options, NULL);
1347     sortextmap();
1348     if ( fclose( fp ) != 0 ) {
1349         LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1350     }
1351     p1->loaded = 1;
1352     return( 0 );
1353 }
1354
1355 /* ------------------------------- */
1356 static void volume_free(struct vol *vol)
1357 {
1358     free(vol->v_localname);
1359     vol->v_localname = NULL;
1360     free(vol->v_u8mname);
1361     vol->v_u8mname = NULL;
1362     free(vol->v_macname);
1363     vol->v_macname = NULL;
1364     free(vol->v_path);
1365     free(vol->v_password);
1366     free(vol->v_veto);
1367     free(vol->v_volcodepage);
1368     free(vol->v_maccodepage);
1369     free(vol->v_cnidscheme);
1370     free(vol->v_dbpath);
1371     free(vol->v_gvs);
1372 #ifdef FORCE_UIDGID
1373     free(vol->v_forceuid);
1374     free(vol->v_forcegid);
1375 #endif /* FORCE_UIDGID */
1376     if (vol->v_uuid)
1377         free(vol->v_uuid);
1378 }
1379
1380 /* ------------------------------- */
1381 static void free_volumes(void )
1382 {
1383     struct vol  *vol;
1384     struct vol  *nvol, *ovol;
1385
1386     for ( vol = Volumes; vol; vol = vol->v_next ) {
1387         if (( vol->v_flags & AFPVOL_OPEN ) ) {
1388             vol->v_deleted = 1;
1389             continue;
1390         }
1391         volume_free(vol);
1392     }
1393
1394     for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
1395         nvol = vol->v_next;
1396
1397         if (vol->v_localname == NULL) {
1398             if (Volumes == vol) {
1399                 Volumes = nvol;
1400                 ovol = Volumes;
1401             }
1402             else {
1403                 ovol->v_next = nvol;
1404             }
1405             free(vol);
1406         }
1407         else {
1408             ovol = vol;
1409         }
1410     }
1411 }
1412
1413 /* ------------------------------- */
1414 static void volume_unlink(struct vol *volume)
1415 {
1416     struct vol *vol, *ovol, *nvol;
1417
1418     if (volume == Volumes) {
1419         Volumes = Volumes->v_next;
1420         return;
1421     }
1422     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1423         nvol = vol->v_next;
1424
1425         if (vol == volume) {
1426             ovol->v_next = nvol;
1427             break;
1428         }
1429         else {
1430             ovol = vol;
1431         }
1432     }
1433 }
1434
1435 static off_t getused_size; /* result of getused() */
1436
1437 /*!
1438   nftw callback for getused()
1439  */
1440 static int getused_stat(const char *path,
1441                         const struct stat *statp,
1442                         int tflag,
1443                         struct FTW *ftw)
1444 {
1445     off_t low, high;
1446
1447     if (tflag == FTW_F || tflag == FTW_D) {
1448         getused_size += statp->st_blocks * 512;
1449     }
1450
1451     return 0;
1452 }
1453
1454 /*!
1455  * Calculate used size of a volume with nftw
1456  *
1457  * The result is cached, we're try to avoid frequently calling nftw()
1458  *
1459  * 1) Call nftw an refresh if:
1460  * 1a) - we're called the first time 
1461  * 1b) - volume modification date is not yet set and the last time we've been called is
1462  *       longer then 30 sec ago
1463  * 1c) - the last volume modification is less then 30 sec old
1464  *
1465  * @param vol     (r) volume to calculate
1466  */
1467 static int getused(const struct vol *vol)
1468 {
1469     static time_t vol_mtime = 0;
1470     int ret = 0;
1471     time_t now = time(NULL);
1472
1473     if (!vol_mtime
1474         || (!vol->v_mtime && ((vol_mtime + 30) < now))
1475         || (vol->v_mtime && ((vol_mtime + 30) < vol->v_mtime))
1476         ) {
1477         vol_mtime = now;
1478         getused_size = 0;
1479         ret = nftw(vol->v_path, getused_stat, NULL, 20, FTW_PHYS); /* 2 */
1480     } else {
1481         LOG(log_debug, logtype_afpd, "volparams: cached used: %" PRIu64 " bytes",
1482             getused_size);
1483     }
1484
1485     return ret;
1486 }
1487
1488 static int getvolspace(struct vol *vol,
1489                        u_int32_t *bfree, u_int32_t *btotal,
1490                        VolSpace *xbfree, VolSpace *xbtotal, u_int32_t *bsize)
1491 {
1492     int         spaceflag, rc;
1493     u_int32_t   maxsize;
1494     VolSpace    used;
1495 #ifndef NO_QUOTA_SUPPORT
1496     VolSpace    qfree, qtotal;
1497 #endif
1498
1499     spaceflag = AFPVOL_GVSMASK & vol->v_flags;
1500     /* report up to 2GB if afp version is < 2.2 (4GB if not) */
1501     maxsize = (vol->v_flags & AFPVOL_A2VOL) ? 0x01fffe00 :
1502         (((afp_version < 22) || (vol->v_flags & AFPVOL_LIMITSIZE))
1503          ? 0x7fffffffL : 0xffffffffL);
1504
1505 #ifdef AFS
1506     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_AFSGVS ) {
1507         if ( afs_getvolspace( vol, xbfree, xbtotal, bsize ) == AFP_OK ) {
1508             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_AFSGVS;
1509             goto getvolspace_done;
1510         }
1511     }
1512 #endif
1513
1514     if (( rc = ustatfs_getvolspace( vol, xbfree, xbtotal, bsize)) != AFP_OK ) {
1515         return( rc );
1516     }
1517
1518 #define min(a,b)    ((a)<(b)?(a):(b))
1519 #ifndef NO_QUOTA_SUPPORT
1520     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_UQUOTA ) {
1521         if ( uquota_getvolspace( vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
1522             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_UQUOTA;
1523             *xbfree = min(*xbfree, qfree);
1524             *xbtotal = min( *xbtotal, qtotal);
1525             goto getvolspace_done;
1526         }
1527     }
1528 #endif
1529     vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_USTATFS;
1530
1531 getvolspace_done:
1532     if (vol->v_limitsize) {
1533         if (getused(vol) != 0)
1534             return AFPERR_MISC;
1535         LOG(log_debug, logtype_afpd, "volparams: used on volume: %" PRIu64 " bytes",
1536             getused_size);
1537
1538         *xbtotal = min(*xbtotal, (vol->v_limitsize * 1024 * 1024));
1539         *xbfree = min(*xbfree, *xbtotal < getused_size ? 0 : *xbtotal - getused_size);
1540     }
1541
1542     *bfree = min( *xbfree, maxsize);
1543     *btotal = min( *xbtotal, maxsize);
1544     return( AFP_OK );
1545 }
1546
1547 /* -----------------------
1548  * set volume creation date
1549  * avoid duplicate, well at least it tries
1550  */
1551 static void vol_setdate(u_int16_t id, struct adouble *adp, time_t date)
1552 {
1553     struct vol  *volume;
1554     struct vol  *vol = Volumes;
1555
1556     for ( volume = Volumes; volume; volume = volume->v_next ) {
1557         if (volume->v_vid == id) {
1558             vol = volume;
1559         }
1560         else if ((time_t)(AD_DATE_FROM_UNIX(date)) == volume->v_ctime) {
1561             date = date+1;
1562             volume = Volumes; /* restart */
1563         }
1564     }
1565     vol->v_ctime = AD_DATE_FROM_UNIX(date);
1566     ad_setdate(adp, AD_DATE_CREATE | AD_DATE_UNIX, date);
1567 }
1568
1569 /* ----------------------- */
1570 static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, char *buf, size_t *buflen)
1571 {
1572     struct adouble  ad;
1573     int         bit = 0, isad = 1;
1574     u_int32_t       aint;
1575     u_short     ashort;
1576     u_int32_t       bfree, btotal, bsize;
1577     VolSpace            xbfree, xbtotal; /* extended bytes */
1578     char        *data, *nameoff = NULL;
1579     char                *slash;
1580
1581     LOG(log_debug, logtype_afpd, "getvolparams: Volume '%s'", vol->v_localname);
1582
1583     /* courtesy of jallison@whistle.com:
1584      * For MacOS8.x support we need to create the
1585      * .Parent file here if it doesn't exist. */
1586
1587     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1588     if ( ad_open_metadata( vol->v_path, ADFLAGS_DIR, O_CREAT, &ad) < 0 ) {
1589         isad = 0;
1590         vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1591
1592     } else if (ad_get_MD_flags( &ad ) & O_CREAT) {
1593         slash = strrchr( vol->v_path, '/' );
1594         if(slash)
1595             slash++;
1596         else
1597             slash = vol->v_path;
1598         if (ad_getentryoff(&ad, ADEID_NAME)) {
1599             ad_setentrylen( &ad, ADEID_NAME, strlen( slash ));
1600             memcpy(ad_entry( &ad, ADEID_NAME ), slash,
1601                    ad_getentrylen( &ad, ADEID_NAME ));
1602         }
1603         vol_setdate(vol->v_vid, &ad, st->st_mtime);
1604         ad_flush(&ad);
1605     }
1606     else {
1607         if (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0)
1608             vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1609         else
1610             vol->v_ctime = aint;
1611     }
1612
1613     if (( bitmap & ( (1<<VOLPBIT_BFREE)|(1<<VOLPBIT_BTOTAL) |
1614                      (1<<VOLPBIT_XBFREE)|(1<<VOLPBIT_XBTOTAL) |
1615                      (1<<VOLPBIT_BSIZE)) ) != 0 ) {
1616         if ( getvolspace( vol, &bfree, &btotal, &xbfree, &xbtotal,
1617                           &bsize) != AFP_OK ) {
1618             if ( isad ) {
1619                 ad_close( &ad, ADFLAGS_HF );
1620             }
1621             return( AFPERR_PARAM );
1622         }
1623     }
1624
1625     data = buf;
1626     while ( bitmap != 0 ) {
1627         while (( bitmap & 1 ) == 0 ) {
1628             bitmap = bitmap>>1;
1629             bit++;
1630         }
1631
1632         switch ( bit ) {
1633         case VOLPBIT_ATTR :
1634             ashort = 0;
1635             /* check for read-only.
1636              * NOTE: we don't actually set the read-only flag unless
1637              *       it's passed in that way as it's possible to mount
1638              *       a read-write filesystem under a read-only one. */
1639             if ((vol->v_flags & AFPVOL_RO) ||
1640                 ((utime(vol->v_path, NULL) < 0) && (errno == EROFS))) {
1641                 ashort |= VOLPBIT_ATTR_RO;
1642             }
1643             /* prior 2.1 only VOLPBIT_ATTR_RO is defined */
1644             if (afp_version > 20) {
1645                 if (0 == (vol->v_flags & AFPVOL_NOFILEID) && vol->v_cdb != NULL &&
1646                     (vol->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1647                     ashort |= VOLPBIT_ATTR_FILEID;
1648                 }
1649                 ashort |= VOLPBIT_ATTR_CATSEARCH;
1650
1651                 if (afp_version >= 30) {
1652                     ashort |= VOLPBIT_ATTR_UTF8;
1653                     if (vol->v_flags & AFPVOL_UNIX_PRIV)
1654                         ashort |= VOLPBIT_ATTR_UNIXPRIV;
1655                     if (vol->v_flags & AFPVOL_TM)
1656                         ashort |= VOLPBIT_ATTR_TM;
1657
1658                     if (afp_version >= 32) {
1659                         if (vol->v_vfs_ea)
1660                             ashort |= VOLPBIT_ATTR_EXT_ATTRS;
1661                         if (vol->v_flags & AFPVOL_ACLS)
1662                             ashort |= VOLPBIT_ATTR_ACLS;
1663                     }
1664                 }
1665             }
1666             ashort = htons(ashort);
1667             memcpy(data, &ashort, sizeof( ashort ));
1668             data += sizeof( ashort );
1669             break;
1670
1671         case VOLPBIT_SIG :
1672             ashort = htons( AFPVOLSIG_DEFAULT );
1673             memcpy(data, &ashort, sizeof( ashort ));
1674             data += sizeof( ashort );
1675             break;
1676
1677         case VOLPBIT_CDATE :
1678             aint = vol->v_ctime;
1679             memcpy(data, &aint, sizeof( aint ));
1680             data += sizeof( aint );
1681             break;
1682
1683         case VOLPBIT_MDATE :
1684             if ( st->st_mtime > vol->v_mtime ) {
1685                 vol->v_mtime = st->st_mtime;
1686             }
1687             aint = AD_DATE_FROM_UNIX(vol->v_mtime);
1688             memcpy(data, &aint, sizeof( aint ));
1689             data += sizeof( aint );
1690             break;
1691
1692         case VOLPBIT_BDATE :
1693             if (!isad ||  (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1694                 aint = AD_DATE_START;
1695             memcpy(data, &aint, sizeof( aint ));
1696             data += sizeof( aint );
1697             break;
1698
1699         case VOLPBIT_VID :
1700             memcpy(data, &vol->v_vid, sizeof( vol->v_vid ));
1701             data += sizeof( vol->v_vid );
1702             break;
1703
1704         case VOLPBIT_BFREE :
1705             bfree = htonl( bfree );
1706             memcpy(data, &bfree, sizeof( bfree ));
1707             data += sizeof( bfree );
1708             break;
1709
1710         case VOLPBIT_BTOTAL :
1711             btotal = htonl( btotal );
1712             memcpy(data, &btotal, sizeof( btotal ));
1713             data += sizeof( btotal );
1714             break;
1715
1716 #ifndef NO_LARGE_VOL_SUPPORT
1717         case VOLPBIT_XBFREE :
1718             xbfree = hton64( xbfree );
1719 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1720             bcopy(&xbfree, data, sizeof(xbfree));
1721 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1722             memcpy(data, &xbfree, sizeof( xbfree ));
1723 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1724             data += sizeof( xbfree );
1725             break;
1726
1727         case VOLPBIT_XBTOTAL :
1728             xbtotal = hton64( xbtotal );
1729 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1730             bcopy(&xbtotal, data, sizeof(xbtotal));
1731 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1732             memcpy(data, &xbtotal, sizeof( xbtotal ));
1733 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1734             data += sizeof( xbfree );
1735             break;
1736 #endif /* ! NO_LARGE_VOL_SUPPORT */
1737
1738         case VOLPBIT_NAME :
1739             nameoff = data;
1740             data += sizeof( u_int16_t );
1741             break;
1742
1743         case VOLPBIT_BSIZE:  /* block size */
1744             bsize = htonl(bsize);
1745             memcpy(data, &bsize, sizeof(bsize));
1746             data += sizeof(bsize);
1747             break;
1748
1749         default :
1750             if ( isad ) {
1751                 ad_close( &ad, ADFLAGS_HF );
1752             }
1753             return( AFPERR_BITMAP );
1754         }
1755         bitmap = bitmap>>1;
1756         bit++;
1757     }
1758     if ( nameoff ) {
1759         ashort = htons( data - buf );
1760         memcpy(nameoff, &ashort, sizeof( ashort ));
1761         /* name is always in mac charset */
1762         aint = ucs2_to_charset( vol->v_maccharset, vol->v_macname, data+1, AFPVOL_MACNAMELEN + 1);
1763         if ( aint <= 0 ) {
1764             *buflen = 0;
1765             return AFPERR_MISC;
1766         }
1767
1768         *data++ = aint;
1769         data += aint;
1770     }
1771     if ( isad ) {
1772         ad_close_metadata( &ad);
1773     }
1774     *buflen = data - buf;
1775     return( AFP_OK );
1776 }
1777
1778 /* ------------------------- */
1779 static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, size_t *rbuflen)
1780 {
1781     struct stat st;
1782     int     ret;
1783     size_t  buflen;
1784
1785     if ( stat( vol->v_path, &st ) < 0 ) {
1786         *rbuflen = 0;
1787         return( AFPERR_PARAM );
1788     }
1789     /* save the volume device number */
1790     vol->v_dev = st.st_dev;
1791
1792     buflen = *rbuflen - sizeof( bitmap );
1793     if (( ret = getvolparams( bitmap, vol, &st,
1794                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
1795         *rbuflen = 0;
1796         return( ret );
1797     }
1798     *rbuflen = buflen + sizeof( bitmap );
1799     bitmap = htons( bitmap );
1800     memcpy(rbuf, &bitmap, sizeof( bitmap ));
1801     return( AFP_OK );
1802
1803 }
1804
1805 /* ------------------------------- */
1806 void load_volumes(AFPObj *obj)
1807 {
1808     struct passwd   *pwent;
1809
1810     if (Volumes) {
1811         int changed = 0;
1812
1813         /* check files date */
1814         if (obj->options.defaultvol.loaded) {
1815             changed = volfile_changed(&obj->options.defaultvol);
1816         }
1817         if (obj->options.systemvol.loaded) {
1818             changed |= volfile_changed(&obj->options.systemvol);
1819         }
1820         if (obj->options.uservol.loaded) {
1821             changed |= volfile_changed(&obj->options.uservol);
1822         }
1823         if (!changed)
1824             return;
1825
1826         free_extmap();
1827         free_volumes();
1828     }
1829
1830     if (parent_or_child == 0) {
1831         LOG(log_debug, logtype_afpd, "load_volumes: AFP MASTER");
1832     } else {
1833         LOG(log_debug, logtype_afpd, "load_volumes: user: %s", obj->username);
1834     }
1835
1836     pwent = getpwnam(obj->username);
1837     if ( (obj->options.flags & OPTION_USERVOLFIRST) == 0 ) {
1838         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent);
1839     }
1840
1841     if ((*obj->username == '\0') || (obj->options.flags & OPTION_NOUSERVOL)) {
1842         readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent);
1843     } else if (pwent) {
1844         /*
1845          * Read user's AppleVolumes or .AppleVolumes file
1846          * If neither are readable, read the default volumes file. if
1847          * that doesn't work, create a user share.
1848          */
1849         if (obj->options.uservol.name) {
1850             free(obj->options.uservol.name);
1851         }
1852         obj->options.uservol.name = strdup(pwent->pw_dir);
1853         if ( readvolfile(obj, &obj->options.uservol,    "AppleVolumes", 1, pwent) < 0 &&
1854              readvolfile(obj, &obj->options.uservol, ".AppleVolumes", 1, pwent) < 0 &&
1855              readvolfile(obj, &obj->options.uservol, "applevolumes", 1, pwent) < 0 &&
1856              readvolfile(obj, &obj->options.uservol, ".applevolumes", 1, pwent) < 0 &&
1857              obj->options.defaultvol.name != NULL ) {
1858             if (readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent) < 0)
1859                 creatvol(obj, pwent, pwent->pw_dir, NULL, NULL, 1);
1860         }
1861     }
1862     if ( obj->options.flags & OPTION_USERVOLFIRST ) {
1863         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent );
1864     }
1865
1866     if ( obj->options.closevol ) {
1867         struct vol *vol;
1868
1869         for ( vol = Volumes; vol; vol = vol->v_next ) {
1870             if (vol->v_deleted && !vol->v_new ) {
1871                 of_closevol(vol);
1872                 deletevol(vol);
1873                 vol = Volumes;
1874             }
1875         }
1876     }
1877 }
1878
1879 /* ------------------------------- */
1880 int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
1881 {
1882     struct timeval  tv;
1883     struct stat     st;
1884     struct vol      *volume;
1885     char    *data;
1886     char        *namebuf;
1887     int         vcnt;
1888     size_t      len;
1889
1890     load_volumes(obj);
1891
1892     data = rbuf + 5;
1893     for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
1894         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
1895             struct maccess ma;
1896
1897             if ( stat( volume->v_path, &st ) < 0 ) {
1898                 LOG(log_info, logtype_afpd, "afp_getsrvrparms(%s): stat: %s",
1899                     volume->v_path, strerror(errno) );
1900                 continue;       /* can't access directory */
1901             }
1902             if (!S_ISDIR(st.st_mode)) {
1903                 continue;       /* not a dir */
1904             }
1905             accessmode(volume->v_path, &ma, NULL, &st);
1906             if ((ma.ma_user & (AR_UREAD | AR_USEARCH)) != (AR_UREAD | AR_USEARCH)) {
1907                 continue;   /* no r-x access */
1908             }
1909         }
1910         if (volume->v_hide) {
1911             continue;       /* config file changed but the volume was mounted */
1912         }
1913
1914         if (utf8_encoding()) {
1915             len = ucs2_to_charset_allocate(CH_UTF8_MAC, &namebuf, volume->v_u8mname);
1916         } else {
1917             len = ucs2_to_charset_allocate(obj->options.maccharset, &namebuf, volume->v_macname);
1918         }
1919
1920         if (len == (size_t)-1)
1921             continue;
1922
1923         /* set password bit if there's a volume password */
1924         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
1925
1926         /* Apple 2 clients running ProDOS-8 expect one volume to have
1927            bit 0 of this byte set.  They will not recognize anything
1928            on the server unless this is the case.  I have not
1929            completely worked this out, but it's related to booting
1930            from the server.  Support for that function is a ways
1931            off.. <shirsch@ibm.net> */
1932         *data |= (volume->v_flags & AFPVOL_A2VOL) ? AFPSRVR_CONFIGINFO : 0;
1933         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
1934         *data++ = len;
1935         memcpy(data, namebuf, len );
1936         data += len;
1937         free(namebuf);
1938         vcnt++;
1939     }
1940
1941     *rbuflen = data - rbuf;
1942     data = rbuf;
1943     if ( gettimeofday( &tv, NULL ) < 0 ) {
1944         LOG(log_error, logtype_afpd, "afp_getsrvrparms(%s): gettimeofday: %s", volume->v_path, strerror(errno) );
1945         *rbuflen = 0;
1946         return AFPERR_PARAM;
1947     }
1948     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
1949     memcpy(data, &tv.tv_sec, sizeof( u_int32_t));
1950     data += sizeof( u_int32_t);
1951     *data = vcnt;
1952     return( AFP_OK );
1953 }
1954
1955 /* ------------------------- */
1956 static int volume_codepage(AFPObj *obj, struct vol *volume)
1957 {
1958     struct charset_functions *charset;
1959     /* Codepages */
1960
1961     if (!volume->v_volcodepage)
1962         volume->v_volcodepage = strdup("UTF8");
1963
1964     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1965         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1966         return -1;
1967     }
1968
1969     if ( NULL == (charset = find_charset_functions(volume->v_volcodepage)) || charset->flags & CHARSET_ICONV ) {
1970         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
1971     }
1972
1973     if (!volume->v_maccodepage)
1974         volume->v_maccodepage = strdup(obj->options.maccodepage);
1975
1976     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
1977         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
1978         return -1;
1979     }
1980
1981     if ( NULL == ( charset = find_charset_functions(volume->v_maccodepage)) || ! (charset->flags & CHARSET_CLIENT) ) {
1982         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
1983         return -1;
1984     }
1985     volume->v_kTextEncoding = htonl(charset->kTextEncoding);
1986     return 0;
1987 }
1988
1989 /* ------------------------- */
1990 static int volume_openDB(struct vol *volume)
1991 {
1992     int flags = 0;
1993
1994     if ((volume->v_flags & AFPVOL_NODEV)) {
1995         flags |= CNID_FLAG_NODEV;
1996     }
1997
1998     if (volume->v_cnidscheme == NULL) {
1999         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
2000         LOG(log_info, logtype_afpd, "Volume %s use CNID scheme %s.",
2001             volume->v_path, volume->v_cnidscheme);
2002     }
2003
2004     LOG(log_info, logtype_afpd, "CNID server: %s:%s",
2005         volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2006         volume->v_cnidport ? volume->v_cnidport : Cnid_port);
2007
2008 #if 0
2009 /* Found this in branch dir-rewrite, maybe we want to use it sometimes */
2010
2011     /* Legacy pre 2.1 way of sharing eg CD-ROM */
2012     if (strcmp(volume->v_cnidscheme, "last") == 0) {
2013         /* "last" is gone. We support it by switching to in-memory "tdb" */
2014         volume->v_cnidscheme = strdup("tdb");
2015         flags |= CNID_FLAG_MEMORY;
2016     }
2017
2018     /* New way of sharing CD-ROM */
2019     if (volume->v_flags & AFPVOL_CDROM) {
2020         flags |= CNID_FLAG_MEMORY;
2021         if (strcmp(volume->v_cnidscheme, "tdb") != 0) {
2022             free(volume->v_cnidscheme);
2023             volume->v_cnidscheme = strdup("tdb");
2024             LOG(log_info, logtype_afpd, "Volume %s is ejectable, switching to scheme %s.",
2025                 volume->v_path, volume->v_cnidscheme);
2026         }
2027     }
2028 #endif
2029
2030     volume->v_cdb = cnid_open(volume->v_path,
2031                               volume->v_umask,
2032                               volume->v_cnidscheme,
2033                               flags,
2034                               volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2035                               volume->v_cnidport ? volume->v_cnidport : Cnid_port);
2036
2037     if ( ! volume->v_cdb && ! (flags & CNID_FLAG_MEMORY)) {
2038         /* The first attempt failed and it wasn't yet an attempt to open in-memory */
2039         LOG(log_error, logtype_afpd, "Can't open volume \"%s\" CNID backend \"%s\" ",
2040             volume->v_path, volume->v_cnidscheme);
2041         LOG(log_error, logtype_afpd, "Reopen volume %s using in memory temporary CNID DB.",
2042             volume->v_path);
2043         flags |= CNID_FLAG_MEMORY;
2044         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, "tdb", flags, NULL, NULL);
2045 #ifdef SERVERTEXT
2046         /* kill ourself with SIGUSR2 aka msg pending */
2047         if (volume->v_cdb) {
2048             setmessage("Something wrong with the volume's CNID DB, using temporary CNID DB instead."
2049                        "Check server messages for details!");
2050             kill(getpid(), SIGUSR2);
2051             /* deactivate cnid caching/storing in AppleDouble files */
2052             volume->v_flags &= ~AFPVOL_CACHE;
2053         }
2054 #endif
2055     }
2056
2057     return (!volume->v_cdb)?-1:0;
2058 }
2059
2060 /*
2061   Check if the underlying filesystem supports EAs for ea:sys volumes.
2062   If not, switch to ea:ad.
2063   As we can't check (requires write access) on ro-volumes, we switch ea:auto
2064   volumes that are options:ro to ea:none.
2065 */
2066 static void check_ea_sys_support(struct vol *vol)
2067 {
2068     uid_t process_uid = 0;
2069     char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
2070     const char *eacontent = "yes";
2071
2072     if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
2073
2074         if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
2075             LOG(log_info, logtype_afpd, "read-only volume '%s', can't test for EA support, disabling EAs", vol->v_localname);
2076             vol->v_vfs_ea = AFPVOL_EA_NONE;
2077             return;
2078         }
2079
2080         mktemp(eaname);
2081
2082         process_uid = geteuid();
2083         if (process_uid)
2084             if (seteuid(0) == -1) {
2085                 LOG(log_error, logtype_afpd, "check_ea_sys_support: can't seteuid(0): %s", strerror(errno));
2086                 exit(EXITERR_SYS);
2087             }
2088
2089         if ((sys_setxattr(vol->v_path, eaname, eacontent, 4, 0)) == 0) {
2090             sys_removexattr(vol->v_path, eaname);
2091             vol->v_vfs_ea = AFPVOL_EA_SYS;
2092         } else {
2093             LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes, using ea:ad instead",
2094                 vol->v_localname);
2095             vol->v_vfs_ea = AFPVOL_EA_AD;
2096         }
2097
2098         if (process_uid) {
2099             if (seteuid(process_uid) == -1) {
2100                 LOG(log_error, logtype_afpd, "can't seteuid back %s", strerror(errno));
2101                 exit(EXITERR_SYS);
2102             }
2103         }
2104     }
2105 }
2106
2107 /* -------------------------
2108  * we are the user here
2109  */
2110 int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2111 {
2112     struct stat st;
2113     char    *volname;
2114     char        *p;
2115
2116     struct vol  *volume;
2117     struct dir  *dir;
2118     int     len, ret;
2119     size_t  namelen;
2120     u_int16_t   bitmap;
2121     char        path[ MAXPATHLEN + 1];
2122     char        *vol_uname;
2123     char        *vol_mname;
2124     char        *volname_tmp;
2125
2126     ibuf += 2;
2127     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2128     bitmap = ntohs( bitmap );
2129     ibuf += sizeof( bitmap );
2130
2131     *rbuflen = 0;
2132     if (( bitmap & (1<<VOLPBIT_VID)) == 0 ) {
2133         return AFPERR_BITMAP;
2134     }
2135
2136     len = (unsigned char)*ibuf++;
2137     volname = obj->oldtmp;
2138
2139     if ((volname_tmp = strchr(volname,'+')) != NULL)
2140         volname = volname_tmp+1;
2141
2142     if (utf8_encoding()) {
2143         namelen = convert_string(CH_UTF8_MAC, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
2144     } else {
2145         namelen = convert_string(obj->options.maccharset, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
2146     }
2147
2148     if ( namelen <= 0) {
2149         return AFPERR_PARAM;
2150     }
2151
2152     ibuf += len;
2153     if ((len + 1) & 1) /* pad to an even boundary */
2154         ibuf++;
2155
2156     load_volumes(obj);
2157
2158     for ( volume = Volumes; volume; volume = volume->v_next ) {
2159         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
2160             break;
2161         }
2162     }
2163
2164     if ( volume == NULL ) {
2165         return AFPERR_PARAM;
2166     }
2167
2168     /* check for a volume password */
2169     if (volume->v_password && strncmp(ibuf, volume->v_password, VOLPASSLEN)) {
2170         return AFPERR_ACCESS;
2171     }
2172
2173     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
2174         /* the volume is already open */
2175 #ifdef FORCE_UIDGID
2176         set_uidgid ( volume );
2177 #endif
2178         return stat_vol(bitmap, volume, rbuf, rbuflen);
2179     }
2180
2181     if (volume->v_root_preexec) {
2182         if ((ret = afprun(1, volume->v_root_preexec, NULL)) && volume->v_root_preexec_close) {
2183             LOG(log_error, logtype_afpd, "afp_openvol(%s): root preexec : %d", volume->v_path, ret );
2184             return AFPERR_MISC;
2185         }
2186     }
2187
2188 #ifdef FORCE_UIDGID
2189     set_uidgid ( volume );
2190 #endif
2191
2192     if (volume->v_preexec) {
2193         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
2194             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
2195             return AFPERR_MISC;
2196         }
2197     }
2198
2199     if ( stat( volume->v_path, &st ) < 0 ) {
2200         return AFPERR_PARAM;
2201     }
2202
2203     if ( chdir( volume->v_path ) < 0 ) {
2204         return AFPERR_PARAM;
2205     }
2206
2207     if ( NULL == getcwd(path, MAXPATHLEN)) {
2208         /* shouldn't be fatal but it will fail later */
2209         LOG(log_error, logtype_afpd, "afp_openvol(%s): volume pathlen too long", volume->v_path);
2210         return AFPERR_MISC;
2211     }
2212
2213     /* Normalize volume path */
2214 #ifdef REALPATH_TAKES_NULL
2215     if ((volume->v_path = realpath(path, NULL)) == NULL)
2216         return AFPERR_MISC;
2217 #else
2218     if ((volume->v_path = malloc(MAXPATHLEN+1)) == NULL)
2219         return AFPERR_MISC;
2220     if (realpath(path, volume->v_path) == NULL) {
2221         free(volume->v_path);
2222         return AFPERR_MISC;
2223     }
2224     /* Safe some memory */
2225     char *tmp;
2226     if ((tmp = strdup(volume->v_path)) == NULL) {
2227         free(volume->v_path);
2228         return AFPERR_MISC;
2229     }
2230     free(volume->v_path);
2231     volume->v_path = tmp;
2232 #endif
2233
2234     if (volume_codepage(obj, volume) < 0) {
2235         ret = AFPERR_MISC;
2236         goto openvol_err;
2237     }
2238
2239     /* initialize volume variables
2240      * FIXME file size
2241      */
2242     if (utf8_encoding()) {
2243         volume->max_filename = UTF8FILELEN_EARLY;
2244     }
2245     else {
2246         volume->max_filename = MACFILELEN;
2247     }
2248
2249     volume->v_flags |= AFPVOL_OPEN;
2250     volume->v_cdb = NULL;
2251
2252     if (utf8_encoding()) {
2253         len = convert_string_allocate(CH_UCS2, CH_UTF8_MAC, volume->v_u8mname, namelen, &vol_mname);
2254     } else {
2255         len = convert_string_allocate(CH_UCS2, obj->options.maccharset, volume->v_macname, namelen, &vol_mname);
2256     }
2257     if ( !vol_mname || len <= 0) {
2258         ret = AFPERR_MISC;
2259         goto openvol_err;
2260     }
2261
2262     if ((vol_uname = strrchr(path, '/')) == NULL)
2263         vol_uname = path;
2264     else if (*(vol_uname + 1) != '\0')
2265         vol_uname++;
2266
2267     if ((dir = dir_new(vol_mname,
2268                        vol_uname,
2269                        volume,
2270                        DIRDID_ROOT_PARENT,
2271                        DIRDID_ROOT,
2272                        bfromcstr(volume->v_path),
2273                        &st)
2274             ) == NULL) {
2275         free(vol_mname);
2276         LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
2277         ret = AFPERR_MISC;
2278         goto openvol_err;
2279     }
2280     free(vol_mname);
2281     volume->v_root = dir;
2282     curdir = dir;
2283
2284     if (volume_openDB(volume) < 0) {
2285         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s",
2286             volume->v_path, volume->v_cnidscheme);
2287         ret = AFPERR_MISC;
2288         goto openvol_err;
2289     }
2290
2291     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
2292     if (ret == AFP_OK) {
2293
2294         if (!(volume->v_flags & AFPVOL_RO)) {
2295             handle_special_folders( volume );
2296             savevolinfo(volume,
2297                         volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2298                         volume->v_cnidport   ? volume->v_cnidport   : Cnid_port);
2299         }
2300
2301         /*
2302          * If you mount a volume twice, the second time the trash appears on
2303          * the desk-top.  That's because the Mac remembers the DID for the
2304          * trash (even for volumes in different zones, on different servers).
2305          * Just so this works better, we prime the DID cache with the trash,
2306          * fixing the trash at DID 17.
2307          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
2308          */
2309         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
2310
2311             /* FIXME find db time stamp */
2312             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
2313                 LOG (log_error, logtype_afpd,
2314                      "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
2315                      volume->v_path);
2316                 ret = AFPERR_MISC;
2317                 goto openvol_err;
2318             }
2319         }
2320         else {
2321             p = Trash;
2322             cname( volume, volume->v_root, &p );
2323         }
2324         return( AFP_OK );
2325     }
2326
2327 openvol_err:
2328     if (volume->v_root) {
2329         dir_free( volume->v_root );
2330         volume->v_root = NULL;
2331     }
2332
2333     volume->v_flags &= ~AFPVOL_OPEN;
2334     if (volume->v_cdb != NULL) {
2335         cnid_close(volume->v_cdb);
2336         volume->v_cdb = NULL;
2337     }
2338     *rbuflen = 0;
2339     return ret;
2340 }
2341
2342 /* ------------------------- */
2343 static void closevol(struct vol *vol)
2344 {
2345     if (!vol)
2346         return;
2347
2348     dir_free( vol->v_root );
2349     vol->v_root = NULL;
2350     if (vol->v_cdb != NULL) {
2351         cnid_close(vol->v_cdb);
2352         vol->v_cdb = NULL;
2353     }
2354
2355     if (vol->v_postexec) {
2356         afprun(0, vol->v_postexec, NULL);
2357     }
2358     if (vol->v_root_postexec) {
2359         afprun(1, vol->v_root_postexec, NULL);
2360     }
2361 }
2362
2363 /* ------------------------- */
2364 void close_all_vol(void)
2365 {
2366     struct vol  *ovol;
2367     curdir = NULL;
2368     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2369         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2370             ovol->v_flags &= ~AFPVOL_OPEN;
2371             closevol(ovol);
2372         }
2373     }
2374 }
2375
2376 /* ------------------------- */
2377 static void deletevol(struct vol *vol)
2378 {
2379     struct vol  *ovol;
2380
2381     vol->v_flags &= ~AFPVOL_OPEN;
2382     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2383         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2384             break;
2385         }
2386     }
2387     if ( ovol != NULL ) {
2388         /* Even if chdir fails, we can't say afp_closevol fails. */
2389         if ( chdir( ovol->v_path ) == 0 ) {
2390             curdir = ovol->v_root;
2391         }
2392     }
2393
2394     closevol(vol);
2395     if (vol->v_deleted) {
2396         showvol(vol->v_name);
2397         volume_free(vol);
2398         volume_unlink(vol);
2399         free(vol);
2400     }
2401 }
2402
2403 /* ------------------------- */
2404 int afp_closevol(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2405 {
2406     struct vol  *vol;
2407     u_int16_t   vid;
2408
2409     *rbuflen = 0;
2410     ibuf += 2;
2411     memcpy(&vid, ibuf, sizeof( vid ));
2412     if (NULL == ( vol = getvolbyvid( vid )) ) {
2413         return( AFPERR_PARAM );
2414     }
2415
2416     deletevol(vol);
2417     current_vol = NULL;
2418
2419     return( AFP_OK );
2420 }
2421
2422 /* ------------------------- */
2423 struct vol *getvolbyvid(const u_int16_t vid )
2424 {
2425     struct vol  *vol;
2426
2427     for ( vol = Volumes; vol; vol = vol->v_next ) {
2428         if ( vid == vol->v_vid ) {
2429             break;
2430         }
2431     }
2432     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
2433         return( NULL );
2434     }
2435
2436 #ifdef FORCE_UIDGID
2437     set_uidgid ( vol );
2438 #endif /* FORCE_UIDGID */
2439
2440     current_vol = vol;
2441
2442     return( vol );
2443 }
2444
2445 /* ------------------------ */
2446 static int ext_cmp_key(const void *key, const void *obj)
2447 {
2448     const char          *p = key;
2449     const struct extmap *em = obj;
2450     return strdiacasecmp(p, em->em_ext);
2451 }
2452 struct extmap *getextmap(const char *path)
2453 {
2454     char      *p;
2455     struct extmap *em;
2456
2457     if (!Extmap_cnt || NULL == ( p = strrchr( path, '.' )) ) {
2458         return( Defextmap );
2459     }
2460     p++;
2461     if (!*p) {
2462         return( Defextmap );
2463     }
2464     em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
2465     if (em) {
2466         return( em );
2467     } else {
2468         return( Defextmap );
2469     }
2470 }
2471
2472 /* ------------------------- */
2473 struct extmap *getdefextmap(void)
2474 {
2475     return( Defextmap );
2476 }
2477
2478 /* --------------------------
2479    poll if a volume is changed by other processes.
2480    return
2481    0 no attention msg sent
2482    1 attention msg sent
2483    -1 error (socket closed)
2484
2485    Note: if attention return -1 no packet has been
2486    sent because the buffer is full, we don't care
2487    either there's no reader or there's a lot of
2488    traffic and another pollvoltime will follow
2489 */
2490 int  pollvoltime(AFPObj *obj)
2491
2492 {
2493     struct vol       *vol;
2494     struct timeval   tv;
2495     struct stat      st;
2496
2497     if (!(afp_version > 21 && obj->options.server_notif))
2498         return 0;
2499
2500     if ( gettimeofday( &tv, NULL ) < 0 )
2501         return 0;
2502
2503     for ( vol = Volumes; vol; vol = vol->v_next ) {
2504         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
2505             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
2506                 vol->v_mtime = st.st_mtime;
2507                 if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
2508                     return -1;
2509                 return 1;
2510             }
2511         }
2512     }
2513     return 0;
2514 }
2515
2516 /* ------------------------- */
2517 void setvoltime(AFPObj *obj, struct vol *vol)
2518 {
2519     struct timeval  tv;
2520
2521     if ( gettimeofday( &tv, NULL ) < 0 ) {
2522         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
2523         return;
2524     }
2525     if( utime( vol->v_path, NULL ) < 0 ) {
2526         /* write of time failed ... probably a read only filesys,
2527          * where no other users can interfere, so there's no issue here
2528          */
2529     }
2530
2531     /* a little granularity */
2532     if (vol->v_mtime < tv.tv_sec) {
2533         vol->v_mtime = tv.tv_sec;
2534         /* or finder doesn't update free space
2535          * AFP 3.2 and above clients seem to be ok without so many notification
2536          */
2537         if (afp_version < 32 && obj->options.server_notif) {
2538             obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
2539         }
2540     }
2541 }
2542
2543 /* ------------------------- */
2544 int afp_getvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,char *rbuf, size_t *rbuflen)
2545 {
2546     struct vol  *vol;
2547     u_int16_t   vid, bitmap;
2548
2549     ibuf += 2;
2550     memcpy(&vid, ibuf, sizeof( vid ));
2551     ibuf += sizeof( vid );
2552     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2553     bitmap = ntohs( bitmap );
2554
2555     if (NULL == ( vol = getvolbyvid( vid )) ) {
2556         *rbuflen = 0;
2557         return( AFPERR_PARAM );
2558     }
2559
2560     return stat_vol(bitmap, vol, rbuf, rbuflen);
2561 }
2562
2563 /* ------------------------- */
2564 int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,  size_t *rbuflen)
2565 {
2566     struct adouble ad;
2567     struct vol  *vol;
2568     u_int16_t   vid, bitmap;
2569     u_int32_t   aint;
2570
2571     ibuf += 2;
2572     *rbuflen = 0;
2573
2574     memcpy(&vid, ibuf, sizeof( vid ));
2575     ibuf += sizeof( vid );
2576     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2577     bitmap = ntohs( bitmap );
2578     ibuf += sizeof(bitmap);
2579
2580     if (( vol = getvolbyvid( vid )) == NULL ) {
2581         return( AFPERR_PARAM );
2582     }
2583
2584     if ((vol->v_flags & AFPVOL_RO))
2585         return AFPERR_VLOCK;
2586
2587     /* we can only set the backup date. */
2588     if (bitmap != (1 << VOLPBIT_BDATE))
2589         return AFPERR_BITMAP;
2590
2591     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2592     if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
2593                   0666, &ad) < 0 ) {
2594         if (errno == EROFS)
2595             return AFPERR_VLOCK;
2596
2597         return AFPERR_ACCESS;
2598     }
2599
2600     memcpy(&aint, ibuf, sizeof(aint));
2601     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2602     ad_flush(&ad);
2603     ad_close(&ad, ADFLAGS_HF);
2604     return( AFP_OK );
2605 }
2606
2607 /* ------------------------- */
2608 int wincheck(const struct vol *vol, const char *path)
2609 {
2610     int len;
2611
2612     if (!(vol->v_flags & AFPVOL_MSWINDOWS))
2613         return 1;
2614
2615     /* empty paths are not allowed */
2616     if ((len = strlen(path)) == 0)
2617         return 0;
2618
2619     /* leading or trailing whitespaces are not allowed, carriage returns
2620      * and probably other whitespace is okay, tabs are not allowed
2621      */
2622     if ((path[0] == ' ') || (path[len-1] == ' '))
2623         return 0;
2624
2625     /* certain characters are not allowed */
2626     if (strpbrk(path, MSWINDOWS_BADCHARS))
2627         return 0;
2628
2629     /* everything else is okay */
2630     return 1;
2631 }
2632
2633
2634 /*
2635  * precreate a folder
2636  * this is only intended for folders in the volume root
2637  * It will *not* work if the folder name contains extended characters
2638  */
2639 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2640 {
2641     char        *p,*q,*r;
2642     struct adouble  ad;
2643     u_int16_t   attr;
2644     struct stat st;
2645     int     ret;
2646
2647
2648     p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2649     if ( p == NULL) {
2650         LOG(log_error, logtype_afpd,"malloc failed");
2651         exit (EXITERR_SYS);
2652     }
2653
2654     q=strdup(folder->name);
2655     if ( q == NULL) {
2656         LOG(log_error, logtype_afpd,"malloc failed");
2657         exit (EXITERR_SYS);
2658     }
2659
2660     strcpy(p, vol->v_path);
2661     strcat(p, "/");
2662
2663     r=q;
2664     while (*r) {
2665         if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2666             *r=toupper(*r);
2667         else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2668             *r=tolower(*r);
2669         r++;
2670     }
2671     strcat(p, q);
2672
2673     if ( (ret = stat( p, &st )) < 0 ) {
2674         if (folder->precreate) {
2675             if (ad_mkdir(p, folder->mode)) {
2676                 LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2677                 free(p);
2678                 free(q);
2679                 return -1;
2680             }
2681             ret = 0;
2682         }
2683     }
2684
2685     if ( !ret && folder->hide) {
2686         /* Hide it */
2687         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2688         if (ad_open_metadata( p, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
2689             free (p);
2690             free(q);
2691             return (-1);
2692         }
2693
2694         ad_setname(&ad, folder->name);
2695
2696         ad_getattr(&ad, &attr);
2697         attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2698         ad_setattr(&ad, attr);
2699
2700         /* do the same with the finder info */
2701         if (ad_entry(&ad, ADEID_FINDERI)) {
2702             memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2703             attr   |= htons(FINDERINFO_INVISIBLE);
2704             memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2705         }
2706
2707         ad_flush( &ad );
2708         ad_close_metadata( &ad);
2709     }
2710     free(p);
2711     free(q);
2712     return 0;
2713 }
2714
2715 static void handle_special_folders (const struct vol * vol)
2716 {
2717     const _special_folder *p = &special_folders[0];
2718
2719     if ((vol->v_flags & AFPVOL_RO))
2720         return;
2721
2722     for (; p->name != NULL; p++) {
2723         create_special_folder (vol, p);
2724     }
2725 }
2726
2727 const struct vol *getvolumes(void)
2728 {
2729     return Volumes;
2730 }
2731
2732 void unload_volumes_and_extmap(void)
2733 {
2734     LOG(log_debug, logtype_afpd, "unload_volumes_and_extmap");
2735     free_extmap();
2736     free_volumes();
2737 }
2738
2739 /* 
2740  * Get a volumes UUID from the config file.
2741  * If there is none, it is generated and stored there.
2742  *
2743  * Returns pointer to allocated storage on success, NULL on error.
2744  */
2745 static char *get_vol_uuid(const AFPObj *obj, const char *volname)
2746 {
2747     char *volname_conf;
2748     char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
2749     FILE *fp;
2750     struct stat tmpstat;
2751     int fd;
2752     
2753     if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
2754         /* scan in the conf file */
2755         while (fgets(buf, sizeof(buf), fp) != NULL) { 
2756             p = buf;
2757             while (p && isblank(*p))
2758                 p++;
2759             if (!p || (*p == '#') || (*p == '\n'))
2760                 continue;                             /* invalid line */
2761             if (*p == '"') {
2762                 p++;
2763                 if ((volname_conf = strtok( p, "\"" )) == NULL)
2764                     continue;                         /* syntax error */
2765             } else {
2766                 if ((volname_conf = strtok( p, " \t" )) == NULL)
2767                     continue;                         /* syntax error: invalid name */
2768             }
2769             p = strchr(p, '\0');
2770             p++;
2771             if (*p == '\0')
2772                 continue;                             /* syntax error */
2773             
2774             if (strcmp(volname, volname_conf) != 0)
2775                 continue;                             /* another volume name */
2776                 
2777             while (p && isblank(*p))
2778                 p++;
2779
2780             if (sscanf(p, "%36s", uuid) == 1 ) {
2781                 for (int i=0; uuid[i]; i++)
2782                     uuid[i] = toupper(uuid[i]);
2783                 LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
2784                 fclose(fp);
2785                 return strdup(uuid);
2786             }
2787         }
2788     }
2789
2790     if (fp)
2791         fclose(fp);
2792
2793     /*  not found or no file, reopen in append mode */
2794
2795     if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
2796         if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
2797             LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
2798                 obj->options.uuidconf, strerror(errno));
2799             return NULL;
2800         }
2801         if (( fp = fdopen( fd, "w" )) == NULL ) {
2802             LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
2803                 obj->options.uuidconf, strerror(errno));
2804             close(fd);
2805             return NULL;
2806         }
2807     } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
2808         LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
2809             obj->options.uuidconf, strerror(errno));
2810         return NULL;
2811     }
2812     fseek(fp, 0L, SEEK_END);
2813     if(ftell(fp) == 0) {                     /* size = 0 */
2814         fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
2815         fprintf(fp, "# This file is auto-generated by afpd\n");
2816         fprintf(fp, "# and stores UUIDs for TM volumes.\n\n");
2817     } else {
2818         fseek(fp, -1L, SEEK_END);
2819         if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
2820     }                    
2821     
2822     /* generate uuid and write to file */
2823     atalk_uuid_t id;
2824     const char *cp;
2825     randombytes((void *)id, 16);
2826     cp = uuid_bin2string(id);
2827
2828     LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
2829
2830     fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
2831     fclose(fp);
2832     
2833     return strdup(cp);
2834 }