]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
sigquit
[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             else if (strcasecmp(p, "nonetids") == 0)
516                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NONETIDS;
517             p = strtok(NULL, ",");
518         }
519
520     } else if (optionok(tmp, "cnidserver:", val)) {
521         setoption(options, save, VOLOPT_CNIDSERVER, val);
522
523         char *p = strrchr(val + 1, ':');
524         if (p) {
525             *p = 0;
526             setoption(options, save, VOLOPT_CNIDPORT, p);
527         }
528
529         LOG(log_debug, logtype_afpd, "CNID Server for volume '%s': %s:%s",
530             volname, val + 1, p ? p + 1 : Cnid_port);
531
532     } else if (optionok(tmp, "dbpath:", val)) {
533         setoption(options, save, VOLOPT_DBPATH, val);
534
535     } else if (optionok(tmp, "umask:", val)) {
536         options[VOLOPT_UMASK].i_value = (int)strtol(val +1, NULL, 8);
537     } else if (optionok(tmp, "dperm:", val)) {
538         options[VOLOPT_DPERM].i_value = (int)strtol(val+1, NULL, 8);
539     } else if (optionok(tmp, "fperm:", val)) {
540         options[VOLOPT_FPERM].i_value = (int)strtol(val+1, NULL, 8);
541     } else if (optionok(tmp, "perm:", val)) {
542         options[VOLOPT_DFLTPERM].i_value = (int)strtol(val+1, NULL, 8);
543     } else if (optionok(tmp, "password:", val)) {
544         setoption(options, save, VOLOPT_PASSWORD, val);
545
546 #ifdef FORCE_UIDGID
547
548         /* this code allows forced uid/gid per volume settings */
549     } else if (optionok(tmp, "forceuid:", val)) {
550         setoption(options, save, VOLOPT_FORCEUID, val);
551     } else if (optionok(tmp, "forcegid:", val)) {
552         setoption(options, save, VOLOPT_FORCEGID, val);
553
554 #endif /* FORCE_UIDGID */
555     } else if (optionok(tmp, "root_preexec:", val)) {
556         setoption(options, save, VOLOPT_ROOTPREEXEC, val);
557
558     } else if (optionok(tmp, "preexec:", val)) {
559         setoption(options, save, VOLOPT_PREEXEC, val);
560
561     } else if (optionok(tmp, "root_postexec:", val)) {
562         setoption(options, save, VOLOPT_ROOTPOSTEXEC, val);
563
564     } else if (optionok(tmp, "postexec:", val)) {
565         setoption(options, save, VOLOPT_POSTEXEC, val);
566
567     } else if (optionok(tmp, "allowed_hosts:", val)) {
568         setoption(options, save, VOLOPT_ALLOWED_HOSTS, val);
569
570     } else if (optionok(tmp, "denied_hosts:", val)) {
571         setoption(options, save, VOLOPT_DENIED_HOSTS, val);
572
573     } else if (optionok(tmp, "ea:", val)) {
574         if (strcasecmp(val + 1, "ad") == 0)
575             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AD;
576         else if (strcasecmp(val + 1, "sys") == 0)
577             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_SYS;
578         else if (strcasecmp(val + 1, "none") == 0)
579             options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_NONE;
580
581     } else if (optionok(tmp, "volsizelimit:", val)) {
582         options[VOLOPT_LIMITSIZE].i_value = (uint32_t)strtoul(val + 1, NULL, 10);
583
584     } else {
585         /* ignore unknown options */
586         LOG(log_debug, logtype_afpd, "ignoring unknown volume option: %s", tmp);
587
588     }
589 }
590
591 /* ----------------- */
592 static void showvol(const ucs2_t *name)
593 {
594     struct vol  *volume;
595     for ( volume = Volumes; volume; volume = volume->v_next ) {
596         if (volume->v_hide && !strcasecmp_w( volume->v_name, name ) ) {
597             volume->v_hide = 0;
598             return;
599         }
600     }
601 }
602
603 /* ------------------------------- */
604 static int creatvol(AFPObj *obj, struct passwd *pwd,
605                     char *path, char *name,
606                     struct vol_option *options,
607                     const int user /* user defined volume */
608     )
609 {
610     struct vol  *volume;
611     int         suffixlen, vlen, tmpvlen, u8mvlen, macvlen;
612     int         hide = 0;
613     char        tmpname[AFPVOL_U8MNAMELEN+1];
614     ucs2_t      u8mtmpname[(AFPVOL_U8MNAMELEN+1)*2], mactmpname[(AFPVOL_MACNAMELEN+1)*2];
615     char        suffix[6]; /* max is #FFFF */
616     u_int16_t   flags;
617
618     LOG(log_debug, logtype_afpd, "createvol: Volume '%s'", name);
619
620     if ( name == NULL || *name == '\0' ) {
621         if ((name = strrchr( path, '/' )) == NULL) {
622             return -1;  /* Obviously not a fully qualified path */
623         }
624
625         /* if you wish to share /, you need to specify a name. */
626         if (*++name == '\0')
627             return -1;
628     }
629
630     /* suffix for mangling use (lastvid + 1)   */
631     /* because v_vid has not been decided yet. */
632     suffixlen = sprintf(suffix, "%c%X", MANGLE_CHAR, lastvid + 1 );
633
634     vlen = strlen( name );
635
636     /* Unicode Volume Name */
637     /* Firstly convert name from unixcharset to UTF8-MAC */
638     flags = CONV_IGNORE;
639     tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
640     if (tmpvlen <= 0) {
641         strcpy(tmpname, "???");
642         tmpvlen = 3;
643     }
644
645     /* Do we have to mangle ? */
646     if ( (flags & CONV_REQMANGLE) || (tmpvlen > obj->options.volnamelen)) {
647         if (tmpvlen + suffixlen > obj->options.volnamelen) {
648             flags = CONV_FORCE;
649             tmpvlen = convert_charset(obj->options.unixcharset, CH_UTF8_MAC, 0, name, vlen, tmpname, obj->options.volnamelen - suffixlen, &flags);
650             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
651         }
652         strcat(tmpname, suffix);
653         tmpvlen = strlen(tmpname);
654     }
655
656     /* Secondly convert name from UTF8-MAC to UCS2 */
657     if ( 0 >= ( u8mvlen = convert_string(CH_UTF8_MAC, CH_UCS2, tmpname, tmpvlen, u8mtmpname, AFPVOL_U8MNAMELEN*2)) )
658         return -1;
659
660     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' -> UTF8-MAC Name: '%s'", name, tmpname);
661
662     /* Maccharset Volume Name */
663     /* Firsty convert name from unixcharset to maccharset */
664     flags = CONV_IGNORE;
665     tmpvlen = convert_charset(obj->options.unixcharset, obj->options.maccharset, 0, name, vlen, tmpname, AFPVOL_U8MNAMELEN, &flags);
666     if (tmpvlen <= 0) {
667         strcpy(tmpname, "???");
668         tmpvlen = 3;
669     }
670
671     /* Do we have to mangle ? */
672     if ( (flags & CONV_REQMANGLE) || (tmpvlen > AFPVOL_MACNAMELEN)) {
673         if (tmpvlen + suffixlen > AFPVOL_MACNAMELEN) {
674             flags = CONV_FORCE;
675             tmpvlen = convert_charset(obj->options.unixcharset,
676                                       obj->options.maccharset,
677                                       0,
678                                       name,
679                                       vlen,
680                                       tmpname,
681                                       AFPVOL_MACNAMELEN - suffixlen,
682                                       &flags);
683             tmpname[tmpvlen >= 0 ? tmpvlen : 0] = 0;
684         }
685         strcat(tmpname, suffix);
686         tmpvlen = strlen(tmpname);
687     }
688
689     /* Secondly convert name from maccharset to UCS2 */
690     if ( 0 >= ( macvlen = convert_string(obj->options.maccharset,
691                                          CH_UCS2,
692                                          tmpname,
693                                          tmpvlen,
694                                          mactmpname,
695                                          AFPVOL_U8MNAMELEN*2)) )
696         return -1;
697
698     LOG(log_maxdebug, logtype_afpd, "createvol: Volume '%s' ->  Longname: '%s'", name, tmpname);
699
700     /* check duplicate */
701     for ( volume = Volumes; volume; volume = volume->v_next ) {
702         if ((utf8_encoding() && (strcasecmp_w(volume->v_u8mname, u8mtmpname) == 0))
703              ||
704             (!utf8_encoding() && (strcasecmp_w(volume->v_macname, mactmpname) == 0))) {
705             LOG (log_error, logtype_afpd,
706                  "Duplicate volume name, check AppleVolumes files: previous: \"%s\", new: \"%s\"",
707                  volume->v_localname, name);
708             if (volume->v_deleted) {
709                 volume->v_new = hide = 1;
710             }
711             else {
712                 return -1;  /* Won't be able to access it, anyway... */
713             }
714         }
715     }
716
717     if (!( volume = (struct vol *)calloc(1, sizeof( struct vol ))) ) {
718         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
719         return -1;
720     }
721     if ( NULL == ( volume->v_localname = strdup(name))) {
722         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
723         free(volume);
724         return -1;
725     }
726
727     if ( NULL == ( volume->v_u8mname = strdup_w(u8mtmpname))) {
728         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
729         volume_free(volume);
730         free(volume);
731         return -1;
732     }
733     if ( NULL == ( volume->v_macname = strdup_w(mactmpname))) {
734         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
735         volume_free(volume);
736         free(volume);
737         return -1;
738     }
739     if (!( volume->v_path = (char *)malloc( strlen( path ) + 1 )) ) {
740         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
741         volume_free(volume);
742         free(volume);
743         return -1;
744     }
745
746     volume->v_name = utf8_encoding()?volume->v_u8mname:volume->v_macname;
747     volume->v_hide = hide;
748     strcpy( volume->v_path, path );
749
750 #ifdef __svr4__
751     volume->v_qfd = -1;
752 #endif /* __svr4__ */
753     /* os X start at 1 and use network order ie. 1 2 3 */
754     volume->v_vid = ++lastvid;
755     volume->v_vid = htons(volume->v_vid);
756 #ifdef HAVE_ACLS
757     if (check_vol_acl_support(volume))
758         volume->v_flags |= AFPVOL_ACLS
759 ;
760 #endif
761
762     /* handle options */
763     if (options) {
764         volume->v_casefold = options[VOLOPT_CASEFOLD].i_value;
765         volume->v_flags |= options[VOLOPT_FLAGS].i_value;
766
767         if (options[VOLOPT_EA_VFS].i_value)
768             volume->v_vfs_ea = options[VOLOPT_EA_VFS].i_value;
769
770         volume->v_ad_options = 0;
771         if ((volume->v_flags & AFPVOL_NODEV))
772             volume->v_ad_options |= ADVOL_NODEV;
773         if ((volume->v_flags & AFPVOL_CACHE))
774             volume->v_ad_options |= ADVOL_CACHE;
775         if ((volume->v_flags & AFPVOL_UNIX_PRIV))
776             volume->v_ad_options |= ADVOL_UNIXPRIV;
777         if ((volume->v_flags & AFPVOL_INV_DOTS))
778             volume->v_ad_options |= ADVOL_INVDOTS;
779         if ((volume->v_flags & AFPVOL_NOADOUBLE))
780             volume->v_ad_options |= ADVOL_NOADOUBLE;
781
782         if (options[VOLOPT_PASSWORD].c_value)
783             volume->v_password = strdup(options[VOLOPT_PASSWORD].c_value);
784
785         if (options[VOLOPT_VETO].c_value)
786             volume->v_veto = strdup(options[VOLOPT_VETO].c_value);
787
788         if (options[VOLOPT_ENCODING].c_value)
789             volume->v_volcodepage = strdup(options[VOLOPT_ENCODING].c_value);
790
791         if (options[VOLOPT_MACCHARSET].c_value)
792             volume->v_maccodepage = strdup(options[VOLOPT_MACCHARSET].c_value);
793
794         if (options[VOLOPT_DBPATH].c_value)
795             volume->v_dbpath = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_DBPATH].c_value, pwd, path, name);
796
797         if (options[VOLOPT_CNIDSCHEME].c_value)
798             volume->v_cnidscheme = strdup(options[VOLOPT_CNIDSCHEME].c_value);
799
800         if (options[VOLOPT_CNIDSERVER].c_value)
801             volume->v_cnidserver = strdup(options[VOLOPT_CNIDSERVER].c_value);
802
803         if (options[VOLOPT_CNIDPORT].c_value)
804             volume->v_cnidport = strdup(options[VOLOPT_CNIDPORT].c_value);
805
806         if (options[VOLOPT_UMASK].i_value)
807             volume->v_umask = (mode_t)options[VOLOPT_UMASK].i_value;
808
809         if (options[VOLOPT_DPERM].i_value)
810             volume->v_dperm = (mode_t)options[VOLOPT_DPERM].i_value;
811
812         if (options[VOLOPT_FPERM].i_value)
813             volume->v_fperm = (mode_t)options[VOLOPT_FPERM].i_value;
814
815         if (options[VOLOPT_DFLTPERM].i_value)
816             volume->v_perm = (mode_t)options[VOLOPT_DFLTPERM].i_value;
817
818         if (options[VOLOPT_ADOUBLE].i_value)
819             volume->v_adouble = options[VOLOPT_ADOUBLE].i_value;
820         else
821             volume->v_adouble = AD_VERSION;
822
823         if (options[VOLOPT_LIMITSIZE].i_value)
824             volume->v_limitsize = options[VOLOPT_LIMITSIZE].i_value;
825
826         /* Mac to Unix conversion flags*/
827         volume->v_mtou_flags = 0;
828         if (!(volume->v_flags & AFPVOL_NOHEX))
829             volume->v_mtou_flags |= CONV_ESCAPEHEX;
830         if (!(volume->v_flags & AFPVOL_USEDOTS))
831             volume->v_mtou_flags |= CONV_ESCAPEDOTS;
832         if ((volume->v_flags & AFPVOL_EILSEQ))
833             volume->v_mtou_flags |= CONV__EILSEQ;
834
835         if ((volume->v_casefold & AFPVOL_MTOUUPPER))
836             volume->v_mtou_flags |= CONV_TOUPPER;
837         else if ((volume->v_casefold & AFPVOL_MTOULOWER))
838             volume->v_mtou_flags |= CONV_TOLOWER;
839
840         /* Unix to Mac conversion flags*/
841         volume->v_utom_flags = CONV_IGNORE | CONV_UNESCAPEHEX;
842         if ((volume->v_casefold & AFPVOL_UTOMUPPER))
843             volume->v_utom_flags |= CONV_TOUPPER;
844         else if ((volume->v_casefold & AFPVOL_UTOMLOWER))
845             volume->v_utom_flags |= CONV_TOLOWER;
846
847         if ((volume->v_flags & AFPVOL_EILSEQ))
848             volume->v_utom_flags |= CONV__EILSEQ;
849
850 #ifdef FORCE_UIDGID
851         if (options[VOLOPT_FORCEUID].c_value) {
852             volume->v_forceuid = strdup(options[VOLOPT_FORCEUID].c_value);
853         } else {
854             volume->v_forceuid = NULL; /* set as null so as to return 0 later on */
855         }
856
857         if (options[VOLOPT_FORCEGID].c_value) {
858             volume->v_forcegid = strdup(options[VOLOPT_FORCEGID].c_value);
859         } else {
860             volume->v_forcegid = NULL; /* set as null so as to return 0 later on */
861         }
862 #endif
863         if (!user) {
864             if (options[VOLOPT_PREEXEC].c_value)
865                 volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_PREEXEC].c_value, pwd, path, name);
866             volume->v_preexec_close = options[VOLOPT_PREEXEC].i_value;
867
868             if (options[VOLOPT_POSTEXEC].c_value)
869                 volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_POSTEXEC].c_value, pwd, path, name);
870
871             if (options[VOLOPT_ROOTPREEXEC].c_value)
872                 volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPREEXEC].c_value, pwd, path,  name);
873             volume->v_root_preexec_close = options[VOLOPT_ROOTPREEXEC].i_value;
874
875             if (options[VOLOPT_ROOTPOSTEXEC].c_value)
876                 volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPOSTEXEC].c_value, pwd, path,  name);
877         }
878     }
879     volume->v_dperm |= volume->v_perm;
880     volume->v_fperm |= volume->v_perm;
881
882     /* Check EA support on volume */
883     if (volume->v_vfs_ea == AFPVOL_EA_AUTO)
884         check_ea_sys_support(volume);
885     initvol_vfs(volume);
886
887     /* get/store uuid from file in afpd master*/
888     if ((parent_or_child == 0) && (volume->v_flags & AFPVOL_TM)) {
889         char *uuid = get_vol_uuid(obj, volume->v_localname);
890         if (!uuid) {
891             LOG(log_error, logtype_afpd, "Volume '%s': couldn't get UUID",
892                 volume->v_localname);
893         } else {
894             volume->v_uuid = uuid;
895             LOG(log_debug, logtype_afpd, "Volume '%s': UUID '%s'",
896                 volume->v_localname, volume->v_uuid);
897         }
898     }
899
900     volume->v_next = Volumes;
901     Volumes = volume;
902     return 0;
903 }
904
905 /* ---------------- */
906 static char *myfgets( char *buf, int size, FILE *fp)
907 {
908     char    *p;
909     int     c;
910
911     p = buf;
912     while ((EOF != ( c = getc( fp )) ) && ( size > 1 )) {
913         if ( c == '\n' || c == '\r' ) {
914             if (p != buf && *(p -1) == '\\') {
915                 p--;
916                 size++;
917                 continue;
918             }
919             *p++ = '\n';
920             break;
921         } else {
922             *p++ = c;
923         }
924         size--;
925     }
926
927     if ( p == buf ) {
928         return( NULL );
929     } else {
930         *p = '\0';
931         return( buf );
932     }
933 }
934
935
936 /* check access list. this function wants something of the following
937  * form:
938  *        @group,name,name2,@group2,name3
939  *
940  * a NULL argument allows everybody to have access.
941  * we return three things:
942  *     -1: no list
943  *      0: list exists, but name isn't in it
944  *      1: in list
945  */
946
947 #ifndef NO_REAL_USER_NAME
948 /* authentication is case insensitive
949  * FIXME should we do the same with group name?
950  */
951 #define access_strcmp strcasecmp
952
953 #else
954 #define access_strcmp strcmp
955
956 #endif
957
958 static int accessvol(const char *args, const char *name)
959 {
960     char buf[MAXPATHLEN + 1], *p;
961     struct group *gr;
962
963     if (!args)
964         return -1;
965
966     strlcpy(buf, args, sizeof(buf));
967     if ((p = strtok(buf, ",")) == NULL) /* nothing, return okay */
968         return -1;
969
970     while (p) {
971         if (*p == '@') { /* it's a group */
972             if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid))
973                 return 1;
974         } else if (access_strcmp(p, name) == 0) /* it's a user name */
975             return 1;
976         p = strtok(NULL, ",");
977     }
978
979     return 0;
980 }
981
982 static int hostaccessvol(int type, const char *volname, const char *args, const AFPObj *obj)
983 {
984     int mask_int;
985     char buf[MAXPATHLEN + 1], *p, *b;
986     DSI *dsi = obj->handle;
987     struct sockaddr_storage client;
988
989     if (!args)
990         return -1;
991
992     strlcpy(buf, args, sizeof(buf));
993     if ((p = strtok_r(buf, ",", &b)) == NULL) /* nothing, return okay */
994         return -1;
995
996     if (obj->proto != AFPPROTO_DSI)
997         return -1;
998
999     while (p) {
1000         int ret;
1001         char *ipaddr, *mask_char;
1002         struct addrinfo hints, *ai;
1003
1004         ipaddr = strtok(p, "/");
1005         mask_char = strtok(NULL,"/");
1006
1007         /* Get address from string with getaddrinfo */
1008         memset(&hints, 0, sizeof hints);
1009         hints.ai_family = AF_UNSPEC;
1010         hints.ai_socktype = SOCK_STREAM;
1011         if ((ret = getaddrinfo(ipaddr, NULL, &hints, &ai)) != 0) {
1012             LOG(log_error, logtype_afpd, "hostaccessvol: getaddrinfo: %s\n", gai_strerror(ret));
1013             continue;
1014         }
1015
1016         /* netmask */
1017         if (mask_char != NULL)
1018             mask_int = atoi(mask_char); /* apply_ip_mask does range checking on it */
1019         else {
1020             if (ai->ai_family == AF_INET) /* IPv4 */
1021                 mask_int = 32;
1022             else                          /* IPv6 */
1023                 mask_int = 128;
1024         }
1025
1026         /* Apply mask to addresses */
1027         client = dsi->client;
1028         apply_ip_mask((struct sockaddr *)&client, mask_int);
1029         apply_ip_mask(ai->ai_addr, mask_int);
1030
1031         if (compare_ip((struct sockaddr *)&client, ai->ai_addr) == 0) {
1032             if (type == VOLOPT_DENIED_HOSTS)
1033                 LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s' by denied list",
1034                     getip_string((struct sockaddr *)&client), volname);
1035             freeaddrinfo(ai);
1036             return 1;
1037         }
1038
1039         /* next address */
1040         freeaddrinfo(ai);
1041         p = strtok_r(NULL, ",", &b);
1042     }
1043
1044     if (type == VOLOPT_ALLOWED_HOSTS)
1045         LOG(log_info, logtype_afpd, "AFP access denied for client IP '%s' to volume '%s', not in allowed list",
1046             getip_string((struct sockaddr *)&dsi->client), volname);
1047     return 0;
1048 }
1049
1050 static void setextmap(char *ext, char *type, char *creator, int user)
1051 {
1052     struct extmap   *em;
1053     int                 cnt;
1054
1055     if (Extmap == NULL) {
1056         if (( Extmap = calloc(1, sizeof( struct extmap ))) == NULL ) {
1057             LOG(log_error, logtype_afpd, "setextmap: calloc: %s", strerror(errno) );
1058             return;
1059         }
1060     }
1061     ext++;
1062     for ( em = Extmap, cnt = 0; em->em_ext; em++, cnt++) {
1063         if ( (strdiacasecmp( em->em_ext, ext )) == 0 ) {
1064             break;
1065         }
1066     }
1067
1068     if ( em->em_ext == NULL ) {
1069         if (!(Extmap  = realloc( Extmap, sizeof( struct extmap ) * (cnt +2))) ) {
1070             LOG(log_error, logtype_afpd, "setextmap: realloc: %s", strerror(errno) );
1071             return;
1072         }
1073         (Extmap +cnt +1)->em_ext = NULL;
1074         em = Extmap +cnt;
1075     } else if ( !user ) {
1076         return;
1077     }
1078     if (em->em_ext)
1079         free(em->em_ext);
1080
1081     if (!(em->em_ext = strdup(  ext))) {
1082         LOG(log_error, logtype_afpd, "setextmap: strdup: %s", strerror(errno) );
1083         return;
1084     }
1085
1086     if ( *type == '\0' ) {
1087         memcpy(em->em_type, "\0\0\0\0", sizeof( em->em_type ));
1088     } else {
1089         memcpy(em->em_type, type, sizeof( em->em_type ));
1090     }
1091     if ( *creator == '\0' ) {
1092         memcpy(em->em_creator, "\0\0\0\0", sizeof( em->em_creator ));
1093     } else {
1094         memcpy(em->em_creator, creator, sizeof( em->em_creator ));
1095     }
1096 }
1097
1098 /* -------------------------- */
1099 static int extmap_cmp(const void *map1, const void *map2)
1100 {
1101     const struct extmap *em1 = map1;
1102     const struct extmap *em2 = map2;
1103     return strdiacasecmp(em1->em_ext, em2->em_ext);
1104 }
1105
1106 static void sortextmap( void)
1107 {
1108     struct extmap   *em;
1109
1110     Extmap_cnt = 0;
1111     if ((em = Extmap) == NULL) {
1112         return;
1113     }
1114     while (em->em_ext) {
1115         em++;
1116         Extmap_cnt++;
1117     }
1118     if (Extmap_cnt) {
1119         qsort(Extmap, Extmap_cnt, sizeof(struct extmap), extmap_cmp);
1120         if (*Extmap->em_ext == 0) {
1121             /* the first line is really "." the default entry,
1122              * we remove the leading '.' in setextmap
1123              */
1124             Defextmap = Extmap;
1125         }
1126     }
1127 }
1128
1129 /* ----------------------
1130  */
1131 static void free_extmap( void)
1132 {
1133     struct extmap   *em;
1134
1135     if (Extmap) {
1136         for ( em = Extmap; em->em_ext; em++) {
1137             free (em->em_ext);
1138         }
1139         free(Extmap);
1140         Extmap = NULL;
1141         Defextmap = Extmap;
1142         Extmap_cnt = 0;
1143     }
1144 }
1145
1146 /* ----------------------
1147  */
1148 static int volfile_changed(struct afp_volume_name *p)
1149 {
1150     struct stat      st;
1151     char *name;
1152
1153     if (p->full_name)
1154         name = p->full_name;
1155     else
1156         name = p->name;
1157
1158     if (!stat( name, &st) && st.st_mtime > p->mtime) {
1159         p->mtime = st.st_mtime;
1160         return 1;
1161     }
1162     return 0;
1163 }
1164
1165 /* ----------------------
1166  * Read a volume configuration file and add the volumes contained within to
1167  * the global volume list. This gets called from the forked afpd childs.
1168  * The master now reads this too for Zeroconf announcements.
1169  *
1170  * If p2 is non-NULL, the file that is opened is
1171  * p1/p2
1172  *
1173  * Lines that begin with # and blank lines are ignored.
1174  * Volume lines are of the form:
1175  *      <unix path> [<volume name>] [allow:<user>,<@group>,...] \
1176  *                           [codepage:<file>] [casefold:<num>]
1177  *      <extension> TYPE [CREATOR]
1178  *
1179  */
1180 static int readvolfile(AFPObj *obj, struct afp_volume_name *p1, char *p2, int user, struct passwd *pwent)
1181 {
1182     FILE        *fp;
1183     char        path[MAXPATHLEN + 1];
1184     char        tmp[MAXPATHLEN + 1];
1185     char        volname[AFPVOL_U8MNAMELEN + 1];
1186     char        buf[BUFSIZ];
1187     char        type[5], creator[5];
1188     char        *u, *p;
1189     int         fd;
1190     int         i;
1191     struct passwd   *pw;
1192     struct vol_option   save_options[VOLOPT_NUM];
1193     struct vol_option   options[VOLOPT_NUM];
1194     struct stat         st;
1195
1196     if (!p1->name)
1197         return -1;
1198     p1->mtime = 0;
1199     strcpy( path, p1->name );
1200     if ( p2 != NULL ) {
1201         strcat( path, "/" );
1202         strcat( path, p2 );
1203         if (p1->full_name) {
1204             free(p1->full_name);
1205         }
1206         p1->full_name = strdup(path);
1207     }
1208
1209     if (NULL == ( fp = fopen( path, "r" )) ) {
1210         return( -1 );
1211     }
1212     fd = fileno(fp);
1213     if (fd != -1 && !fstat( fd, &st) ) {
1214         p1->mtime = st.st_mtime;
1215     }
1216
1217     if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
1218         LOG(log_error, logtype_afpd, "readvolfile: can't lock volume file \"%s\"", path);
1219         if ( fclose( fp ) != 0 ) {
1220             LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1221         }
1222         return -1;
1223     }
1224
1225     memset(save_options, 0, sizeof(save_options));
1226
1227     /* Enable some default options for all volumes */
1228     save_options[VOLOPT_FLAGS].i_value |= AFPVOL_CACHE;
1229     save_options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AUTO;
1230     LOG(log_maxdebug, logtype_afpd, "readvolfile: seeding default umask: %04o",
1231         obj->options.umask);
1232     save_options[VOLOPT_UMASK].i_value = obj->options.umask;
1233
1234     LOG(log_debug, logtype_afpd, "readvolfile: \"%s\"", path);
1235
1236     while ( myfgets( buf, sizeof( buf ), fp ) != NULL ) {
1237         initline( strlen( buf ), buf );
1238         parseline( sizeof( path ) - 1, path );
1239         switch ( *path ) {
1240         case '\0' :
1241         case '#' :
1242             continue;
1243
1244         case ':':
1245             /* change the default options for this file */
1246             if (strncmp(path, VOLOPT_DEFAULT, VOLOPT_DEFAULT_LEN) == 0) {
1247                 *tmp = '\0';
1248                 for (i = 0; i < VOLOPT_NUM; i++) {
1249                     if (parseline( sizeof( path ) - VOLOPT_DEFAULT_LEN - 1,
1250                                    path + VOLOPT_DEFAULT_LEN) < 0)
1251                         break;
1252                     volset(save_options, NULL, tmp, sizeof(tmp) - 1,
1253                            path + VOLOPT_DEFAULT_LEN);
1254                 }
1255             }
1256             break;
1257
1258         case '~' :
1259             if (( p = strchr( path, '/' )) != NULL ) {
1260                 *p++ = '\0';
1261             }
1262             u = path;
1263             u++;
1264             if ( *u == '\0' ) {
1265                 u = obj->username;
1266             }
1267             if ( u == NULL || *u == '\0' || ( pw = getpwnam( u )) == NULL ) {
1268                 continue;
1269             }
1270             strcpy( tmp, pw->pw_dir );
1271             if ( p != NULL && *p != '\0' ) {
1272                 strcat( tmp, "/" );
1273                 strcat( tmp, p );
1274             }
1275             /* fall through */
1276
1277         case '/' :
1278             /* send path through variable substitution */
1279             if (*path != '~') /* need to copy path to tmp */
1280                 strcpy(tmp, path);
1281             if (!pwent && obj->username)
1282                 pwent = getpwnam(obj->username);
1283
1284             if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
1285                 continue;
1286
1287             /* this is sort of braindead. basically, i want to be
1288              * able to specify things in any order, but i don't want to
1289              * re-write everything. */
1290
1291             memcpy(options, save_options, sizeof(options));
1292             *volname = '\0';
1293
1294             /* read in up to VOLOP_NUM possible options */
1295             for (i = 0; i < VOLOPT_NUM; i++) {
1296                 if (parseline( sizeof( tmp ) - 1, tmp ) < 0)
1297                     break;
1298
1299                 volset(options, save_options, volname, sizeof(volname) - 1, tmp);
1300             }
1301
1302             /* check allow/deny lists (if not afpd master loading volumes for Zeroconf reg.):
1303                allow -> either no list (-1), or in list (1)
1304                deny -> either no list (-1), or not in list (0) */
1305             if (parent_or_child == 0
1306                 ||
1307                 (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
1308                  (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1) &&
1309                  hostaccessvol(VOLOPT_ALLOWED_HOSTS, volname, options[VOLOPT_ALLOWED_HOSTS].c_value, obj) &&
1310                  (hostaccessvol(VOLOPT_DENIED_HOSTS, volname, options[VOLOPT_DENIED_HOSTS].c_value, obj) < 1))) {
1311
1312                 /* handle read-only behaviour. semantics:
1313                  * 1) neither the rolist nor the rwlist exist -> rw
1314                  * 2) rolist exists -> ro if user is in it.
1315                  * 3) rwlist exists -> ro unless user is in it. */
1316                 if (parent_or_child == 1
1317                     &&
1318                     ((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0)
1319                     &&
1320                     ((accessvol(options[VOLOPT_ROLIST].c_value, obj->username) == 1) ||
1321                      !accessvol(options[VOLOPT_RWLIST].c_value, obj->username)))
1322                     options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
1323
1324                 /* do variable substitution for volname */
1325                 if (volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL) == NULL)
1326                     continue;
1327
1328                 creatvol(obj, pwent, path, tmp, options, p2 != NULL);
1329             }
1330             volfree(options, save_options);
1331             break;
1332
1333         case '.' :
1334             parseline( sizeof( type ) - 1, type );
1335             parseline( sizeof( creator ) - 1, creator );
1336             setextmap( path, type, creator, user);
1337             break;
1338
1339         default :
1340             break;
1341         }
1342     }
1343     volfree(save_options, NULL);
1344     sortextmap();
1345     if ( fclose( fp ) != 0 ) {
1346         LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1347     }
1348     p1->loaded = 1;
1349     return( 0 );
1350 }
1351
1352 /* ------------------------------- */
1353 static void volume_free(struct vol *vol)
1354 {
1355     free(vol->v_localname);
1356     vol->v_localname = NULL;
1357     free(vol->v_u8mname);
1358     vol->v_u8mname = NULL;
1359     free(vol->v_macname);
1360     vol->v_macname = NULL;
1361     free(vol->v_path);
1362     free(vol->v_password);
1363     free(vol->v_veto);
1364     free(vol->v_volcodepage);
1365     free(vol->v_maccodepage);
1366     free(vol->v_cnidscheme);
1367     free(vol->v_dbpath);
1368     free(vol->v_gvs);
1369 #ifdef FORCE_UIDGID
1370     free(vol->v_forceuid);
1371     free(vol->v_forcegid);
1372 #endif /* FORCE_UIDGID */
1373     if (vol->v_uuid)
1374         free(vol->v_uuid);
1375 }
1376
1377 /* ------------------------------- */
1378 static void free_volumes(void )
1379 {
1380     struct vol  *vol;
1381     struct vol  *nvol, *ovol;
1382
1383     for ( vol = Volumes; vol; vol = vol->v_next ) {
1384         if (( vol->v_flags & AFPVOL_OPEN ) ) {
1385             vol->v_deleted = 1;
1386             continue;
1387         }
1388         volume_free(vol);
1389     }
1390
1391     for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
1392         nvol = vol->v_next;
1393
1394         if (vol->v_localname == NULL) {
1395             if (Volumes == vol) {
1396                 Volumes = nvol;
1397                 ovol = Volumes;
1398             }
1399             else {
1400                 ovol->v_next = nvol;
1401             }
1402             free(vol);
1403         }
1404         else {
1405             ovol = vol;
1406         }
1407     }
1408 }
1409
1410 /* ------------------------------- */
1411 static void volume_unlink(struct vol *volume)
1412 {
1413     struct vol *vol, *ovol, *nvol;
1414
1415     if (volume == Volumes) {
1416         Volumes = Volumes->v_next;
1417         return;
1418     }
1419     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1420         nvol = vol->v_next;
1421
1422         if (vol == volume) {
1423             ovol->v_next = nvol;
1424             break;
1425         }
1426         else {
1427             ovol = vol;
1428         }
1429     }
1430 }
1431
1432 static off_t getused_size; /* result of getused() */
1433
1434 /*!
1435   nftw callback for getused()
1436  */
1437 static int getused_stat(const char *path,
1438                         const struct stat *statp,
1439                         int tflag,
1440                         struct FTW *ftw)
1441 {
1442     off_t low, high;
1443
1444     if (tflag == FTW_F || tflag == FTW_D) {
1445         getused_size += statp->st_blocks * 512;
1446     }
1447
1448     return 0;
1449 }
1450
1451 #define GETUSED_CACHETIME 5
1452 /*!
1453  * Calculate used size of a volume with nftw
1454  *
1455  * The result is cached, we're try to avoid frequently calling nftw()
1456  *
1457  * 1) Call nftw an refresh if:
1458  * 1a) - we're called the first time 
1459  * 1b) - volume modification date is not yet set and the last time we've been called is
1460  *       longer then 30 sec ago
1461  * 1c) - the last volume modification is less then 30 sec old
1462  *
1463  * @param vol     (r) volume to calculate
1464  */
1465 static int getused(const struct vol *vol)
1466 {
1467     static time_t vol_mtime = 0;
1468     int ret = 0;
1469     time_t now = time(NULL);
1470
1471     if (!vol_mtime
1472         || (!vol->v_mtime && ((vol_mtime + GETUSED_CACHETIME) < now))
1473         || (vol->v_mtime && ((vol_mtime + GETUSED_CACHETIME) < vol->v_mtime))
1474         ) {
1475         vol_mtime = now;
1476         getused_size = 0;
1477         ret = nftw(vol->v_path, getused_stat, NULL, 20, FTW_PHYS); /* 2 */
1478         LOG(log_debug, logtype_afpd, "volparams: from nftw: %" PRIu64 " bytes",
1479             getused_size);
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                     if (vol->v_flags & AFPVOL_NONETIDS)
1658                         ashort |= VOLPBIT_ATTR_NONETIDS;
1659                     if (afp_version >= 32) {
1660                         if (vol->v_vfs_ea)
1661                             ashort |= VOLPBIT_ATTR_EXT_ATTRS;
1662                         if (vol->v_flags & AFPVOL_ACLS)
1663                             ashort |= VOLPBIT_ATTR_ACLS;
1664                     }
1665                 }
1666             }
1667             ashort = htons(ashort);
1668             memcpy(data, &ashort, sizeof( ashort ));
1669             data += sizeof( ashort );
1670             break;
1671
1672         case VOLPBIT_SIG :
1673             ashort = htons( AFPVOLSIG_DEFAULT );
1674             memcpy(data, &ashort, sizeof( ashort ));
1675             data += sizeof( ashort );
1676             break;
1677
1678         case VOLPBIT_CDATE :
1679             aint = vol->v_ctime;
1680             memcpy(data, &aint, sizeof( aint ));
1681             data += sizeof( aint );
1682             break;
1683
1684         case VOLPBIT_MDATE :
1685             if ( st->st_mtime > vol->v_mtime ) {
1686                 vol->v_mtime = st->st_mtime;
1687             }
1688             aint = AD_DATE_FROM_UNIX(vol->v_mtime);
1689             memcpy(data, &aint, sizeof( aint ));
1690             data += sizeof( aint );
1691             break;
1692
1693         case VOLPBIT_BDATE :
1694             if (!isad ||  (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1695                 aint = AD_DATE_START;
1696             memcpy(data, &aint, sizeof( aint ));
1697             data += sizeof( aint );
1698             break;
1699
1700         case VOLPBIT_VID :
1701             memcpy(data, &vol->v_vid, sizeof( vol->v_vid ));
1702             data += sizeof( vol->v_vid );
1703             break;
1704
1705         case VOLPBIT_BFREE :
1706             bfree = htonl( bfree );
1707             memcpy(data, &bfree, sizeof( bfree ));
1708             data += sizeof( bfree );
1709             break;
1710
1711         case VOLPBIT_BTOTAL :
1712             btotal = htonl( btotal );
1713             memcpy(data, &btotal, sizeof( btotal ));
1714             data += sizeof( btotal );
1715             break;
1716
1717 #ifndef NO_LARGE_VOL_SUPPORT
1718         case VOLPBIT_XBFREE :
1719             xbfree = hton64( xbfree );
1720 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1721             bcopy(&xbfree, data, sizeof(xbfree));
1722 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1723             memcpy(data, &xbfree, sizeof( xbfree ));
1724 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1725             data += sizeof( xbfree );
1726             break;
1727
1728         case VOLPBIT_XBTOTAL :
1729             xbtotal = hton64( xbtotal );
1730 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1731             bcopy(&xbtotal, data, sizeof(xbtotal));
1732 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1733             memcpy(data, &xbtotal, sizeof( xbtotal ));
1734 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1735             data += sizeof( xbfree );
1736             break;
1737 #endif /* ! NO_LARGE_VOL_SUPPORT */
1738
1739         case VOLPBIT_NAME :
1740             nameoff = data;
1741             data += sizeof( u_int16_t );
1742             break;
1743
1744         case VOLPBIT_BSIZE:  /* block size */
1745             bsize = htonl(bsize);
1746             memcpy(data, &bsize, sizeof(bsize));
1747             data += sizeof(bsize);
1748             break;
1749
1750         default :
1751             if ( isad ) {
1752                 ad_close( &ad, ADFLAGS_HF );
1753             }
1754             return( AFPERR_BITMAP );
1755         }
1756         bitmap = bitmap>>1;
1757         bit++;
1758     }
1759     if ( nameoff ) {
1760         ashort = htons( data - buf );
1761         memcpy(nameoff, &ashort, sizeof( ashort ));
1762         /* name is always in mac charset */
1763         aint = ucs2_to_charset( vol->v_maccharset, vol->v_macname, data+1, AFPVOL_MACNAMELEN + 1);
1764         if ( aint <= 0 ) {
1765             *buflen = 0;
1766             return AFPERR_MISC;
1767         }
1768
1769         *data++ = aint;
1770         data += aint;
1771     }
1772     if ( isad ) {
1773         ad_close_metadata( &ad);
1774     }
1775     *buflen = data - buf;
1776     return( AFP_OK );
1777 }
1778
1779 /* ------------------------- */
1780 static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, size_t *rbuflen)
1781 {
1782     struct stat st;
1783     int     ret;
1784     size_t  buflen;
1785
1786     if ( stat( vol->v_path, &st ) < 0 ) {
1787         *rbuflen = 0;
1788         return( AFPERR_PARAM );
1789     }
1790     /* save the volume device number */
1791     vol->v_dev = st.st_dev;
1792
1793     buflen = *rbuflen - sizeof( bitmap );
1794     if (( ret = getvolparams( bitmap, vol, &st,
1795                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
1796         *rbuflen = 0;
1797         return( ret );
1798     }
1799     *rbuflen = buflen + sizeof( bitmap );
1800     bitmap = htons( bitmap );
1801     memcpy(rbuf, &bitmap, sizeof( bitmap ));
1802     return( AFP_OK );
1803
1804 }
1805
1806 /* ------------------------------- */
1807 void load_volumes(AFPObj *obj)
1808 {
1809     struct passwd   *pwent;
1810
1811     if (Volumes) {
1812         int changed = 0;
1813
1814         /* check files date */
1815         if (obj->options.defaultvol.loaded) {
1816             changed = volfile_changed(&obj->options.defaultvol);
1817         }
1818         if (obj->options.systemvol.loaded) {
1819             changed |= volfile_changed(&obj->options.systemvol);
1820         }
1821         if (obj->options.uservol.loaded) {
1822             changed |= volfile_changed(&obj->options.uservol);
1823         }
1824         if (!changed)
1825             return;
1826
1827         free_extmap();
1828         free_volumes();
1829     }
1830
1831     if (parent_or_child == 0) {
1832         LOG(log_debug, logtype_afpd, "load_volumes: AFP MASTER");
1833     } else {
1834         LOG(log_debug, logtype_afpd, "load_volumes: user: %s", obj->username);
1835     }
1836
1837     pwent = getpwnam(obj->username);
1838     if ( (obj->options.flags & OPTION_USERVOLFIRST) == 0 ) {
1839         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent);
1840     }
1841
1842     if ((*obj->username == '\0') || (obj->options.flags & OPTION_NOUSERVOL)) {
1843         readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent);
1844     } else if (pwent) {
1845         /*
1846          * Read user's AppleVolumes or .AppleVolumes file
1847          * If neither are readable, read the default volumes file. if
1848          * that doesn't work, create a user share.
1849          */
1850         if (obj->options.uservol.name) {
1851             free(obj->options.uservol.name);
1852         }
1853         obj->options.uservol.name = strdup(pwent->pw_dir);
1854         if ( 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              readvolfile(obj, &obj->options.uservol, ".applevolumes", 1, pwent) < 0 &&
1858              obj->options.defaultvol.name != NULL ) {
1859             if (readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent) < 0)
1860                 creatvol(obj, pwent, pwent->pw_dir, NULL, NULL, 1);
1861         }
1862     }
1863     if ( obj->options.flags & OPTION_USERVOLFIRST ) {
1864         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent );
1865     }
1866
1867     if ( obj->options.closevol ) {
1868         struct vol *vol;
1869
1870         for ( vol = Volumes; vol; vol = vol->v_next ) {
1871             if (vol->v_deleted && !vol->v_new ) {
1872                 of_closevol(vol);
1873                 deletevol(vol);
1874                 vol = Volumes;
1875             }
1876         }
1877     }
1878 }
1879
1880 /* ------------------------------- */
1881 int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
1882 {
1883     struct timeval  tv;
1884     struct stat     st;
1885     struct vol      *volume;
1886     char    *data;
1887     char        *namebuf;
1888     int         vcnt;
1889     size_t      len;
1890
1891     load_volumes(obj);
1892
1893     data = rbuf + 5;
1894     for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
1895         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
1896             struct maccess ma;
1897
1898             if ( stat( volume->v_path, &st ) < 0 ) {
1899                 LOG(log_info, logtype_afpd, "afp_getsrvrparms(%s): stat: %s",
1900                     volume->v_path, strerror(errno) );
1901                 continue;       /* can't access directory */
1902             }
1903             if (!S_ISDIR(st.st_mode)) {
1904                 continue;       /* not a dir */
1905             }
1906             accessmode(volume->v_path, &ma, NULL, &st);
1907             if ((ma.ma_user & (AR_UREAD | AR_USEARCH)) != (AR_UREAD | AR_USEARCH)) {
1908                 continue;   /* no r-x access */
1909             }
1910         }
1911         if (volume->v_hide) {
1912             continue;       /* config file changed but the volume was mounted */
1913         }
1914
1915         if (utf8_encoding()) {
1916             len = ucs2_to_charset_allocate(CH_UTF8_MAC, &namebuf, volume->v_u8mname);
1917         } else {
1918             len = ucs2_to_charset_allocate(obj->options.maccharset, &namebuf, volume->v_macname);
1919         }
1920
1921         if (len == (size_t)-1)
1922             continue;
1923
1924         /* set password bit if there's a volume password */
1925         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
1926
1927         /* Apple 2 clients running ProDOS-8 expect one volume to have
1928            bit 0 of this byte set.  They will not recognize anything
1929            on the server unless this is the case.  I have not
1930            completely worked this out, but it's related to booting
1931            from the server.  Support for that function is a ways
1932            off.. <shirsch@ibm.net> */
1933         *data |= (volume->v_flags & AFPVOL_A2VOL) ? AFPSRVR_CONFIGINFO : 0;
1934         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
1935         *data++ = len;
1936         memcpy(data, namebuf, len );
1937         data += len;
1938         free(namebuf);
1939         vcnt++;
1940     }
1941
1942     *rbuflen = data - rbuf;
1943     data = rbuf;
1944     if ( gettimeofday( &tv, NULL ) < 0 ) {
1945         LOG(log_error, logtype_afpd, "afp_getsrvrparms(%s): gettimeofday: %s", volume->v_path, strerror(errno) );
1946         *rbuflen = 0;
1947         return AFPERR_PARAM;
1948     }
1949     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
1950     memcpy(data, &tv.tv_sec, sizeof( u_int32_t));
1951     data += sizeof( u_int32_t);
1952     *data = vcnt;
1953     return( AFP_OK );
1954 }
1955
1956 /* ------------------------- */
1957 static int volume_codepage(AFPObj *obj, struct vol *volume)
1958 {
1959     struct charset_functions *charset;
1960     /* Codepages */
1961
1962     if (!volume->v_volcodepage)
1963         volume->v_volcodepage = strdup("UTF8");
1964
1965     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1966         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1967         return -1;
1968     }
1969
1970     if ( NULL == (charset = find_charset_functions(volume->v_volcodepage)) || charset->flags & CHARSET_ICONV ) {
1971         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
1972     }
1973
1974     if (!volume->v_maccodepage)
1975         volume->v_maccodepage = strdup(obj->options.maccodepage);
1976
1977     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
1978         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
1979         return -1;
1980     }
1981
1982     if ( NULL == ( charset = find_charset_functions(volume->v_maccodepage)) || ! (charset->flags & CHARSET_CLIENT) ) {
1983         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
1984         return -1;
1985     }
1986     volume->v_kTextEncoding = htonl(charset->kTextEncoding);
1987     return 0;
1988 }
1989
1990 /* ------------------------- */
1991 static int volume_openDB(struct vol *volume)
1992 {
1993     int flags = 0;
1994
1995     if ((volume->v_flags & AFPVOL_NODEV)) {
1996         flags |= CNID_FLAG_NODEV;
1997     }
1998
1999     if (volume->v_cnidscheme == NULL) {
2000         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
2001         LOG(log_info, logtype_afpd, "Volume %s use CNID scheme %s.",
2002             volume->v_path, volume->v_cnidscheme);
2003     }
2004
2005     LOG(log_info, logtype_afpd, "CNID server: %s:%s",
2006         volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2007         volume->v_cnidport ? volume->v_cnidport : Cnid_port);
2008
2009 #if 0
2010 /* Found this in branch dir-rewrite, maybe we want to use it sometimes */
2011
2012     /* Legacy pre 2.1 way of sharing eg CD-ROM */
2013     if (strcmp(volume->v_cnidscheme, "last") == 0) {
2014         /* "last" is gone. We support it by switching to in-memory "tdb" */
2015         volume->v_cnidscheme = strdup("tdb");
2016         flags |= CNID_FLAG_MEMORY;
2017     }
2018
2019     /* New way of sharing CD-ROM */
2020     if (volume->v_flags & AFPVOL_CDROM) {
2021         flags |= CNID_FLAG_MEMORY;
2022         if (strcmp(volume->v_cnidscheme, "tdb") != 0) {
2023             free(volume->v_cnidscheme);
2024             volume->v_cnidscheme = strdup("tdb");
2025             LOG(log_info, logtype_afpd, "Volume %s is ejectable, switching to scheme %s.",
2026                 volume->v_path, volume->v_cnidscheme);
2027         }
2028     }
2029 #endif
2030
2031     volume->v_cdb = cnid_open(volume->v_path,
2032                               volume->v_umask,
2033                               volume->v_cnidscheme,
2034                               flags,
2035                               volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2036                               volume->v_cnidport ? volume->v_cnidport : Cnid_port);
2037
2038     if ( ! volume->v_cdb && ! (flags & CNID_FLAG_MEMORY)) {
2039         /* The first attempt failed and it wasn't yet an attempt to open in-memory */
2040         LOG(log_error, logtype_afpd, "Can't open volume \"%s\" CNID backend \"%s\" ",
2041             volume->v_path, volume->v_cnidscheme);
2042         LOG(log_error, logtype_afpd, "Reopen volume %s using in memory temporary CNID DB.",
2043             volume->v_path);
2044         flags |= CNID_FLAG_MEMORY;
2045         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, "tdb", flags, NULL, NULL);
2046 #ifdef SERVERTEXT
2047         /* kill ourself with SIGUSR2 aka msg pending */
2048         if (volume->v_cdb) {
2049             setmessage("Something wrong with the volume's CNID DB, using temporary CNID DB instead."
2050                        "Check server messages for details!");
2051             kill(getpid(), SIGUSR2);
2052             /* deactivate cnid caching/storing in AppleDouble files */
2053             volume->v_flags &= ~AFPVOL_CACHE;
2054         }
2055 #endif
2056     }
2057
2058     return (!volume->v_cdb)?-1:0;
2059 }
2060
2061 /*
2062   Check if the underlying filesystem supports EAs for ea:sys volumes.
2063   If not, switch to ea:ad.
2064   As we can't check (requires write access) on ro-volumes, we switch ea:auto
2065   volumes that are options:ro to ea:none.
2066 */
2067 static void check_ea_sys_support(struct vol *vol)
2068 {
2069     uid_t process_uid = 0;
2070     char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
2071     const char *eacontent = "yes";
2072
2073     if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
2074
2075         if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
2076             LOG(log_info, logtype_afpd, "read-only volume '%s', can't test for EA support, disabling EAs", vol->v_localname);
2077             vol->v_vfs_ea = AFPVOL_EA_NONE;
2078             return;
2079         }
2080
2081         mktemp(eaname);
2082
2083         process_uid = geteuid();
2084         if (process_uid)
2085             if (seteuid(0) == -1) {
2086                 LOG(log_error, logtype_afpd, "check_ea_sys_support: can't seteuid(0): %s", strerror(errno));
2087                 exit(EXITERR_SYS);
2088             }
2089
2090         if ((sys_setxattr(vol->v_path, eaname, eacontent, 4, 0)) == 0) {
2091             sys_removexattr(vol->v_path, eaname);
2092             vol->v_vfs_ea = AFPVOL_EA_SYS;
2093         } else {
2094             LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes, using ea:ad instead",
2095                 vol->v_localname);
2096             vol->v_vfs_ea = AFPVOL_EA_AD;
2097         }
2098
2099         if (process_uid) {
2100             if (seteuid(process_uid) == -1) {
2101                 LOG(log_error, logtype_afpd, "can't seteuid back %s", strerror(errno));
2102                 exit(EXITERR_SYS);
2103             }
2104         }
2105     }
2106 }
2107
2108 /* -------------------------
2109  * we are the user here
2110  */
2111 int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2112 {
2113     struct stat st;
2114     char    *volname;
2115     char        *p;
2116
2117     struct vol  *volume;
2118     struct dir  *dir;
2119     int     len, ret;
2120     size_t  namelen;
2121     u_int16_t   bitmap;
2122     char        path[ MAXPATHLEN + 1];
2123     char        *vol_uname;
2124     char        *vol_mname;
2125     char        *volname_tmp;
2126
2127     ibuf += 2;
2128     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2129     bitmap = ntohs( bitmap );
2130     ibuf += sizeof( bitmap );
2131
2132     *rbuflen = 0;
2133     if (( bitmap & (1<<VOLPBIT_VID)) == 0 ) {
2134         return AFPERR_BITMAP;
2135     }
2136
2137     len = (unsigned char)*ibuf++;
2138     volname = obj->oldtmp;
2139
2140     if ((volname_tmp = strchr(volname,'+')) != NULL)
2141         volname = volname_tmp+1;
2142
2143     if (utf8_encoding()) {
2144         namelen = convert_string(CH_UTF8_MAC, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
2145     } else {
2146         namelen = convert_string(obj->options.maccharset, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
2147     }
2148
2149     if ( namelen <= 0) {
2150         return AFPERR_PARAM;
2151     }
2152
2153     ibuf += len;
2154     if ((len + 1) & 1) /* pad to an even boundary */
2155         ibuf++;
2156
2157     load_volumes(obj);
2158
2159     for ( volume = Volumes; volume; volume = volume->v_next ) {
2160         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
2161             break;
2162         }
2163     }
2164
2165     if ( volume == NULL ) {
2166         return AFPERR_PARAM;
2167     }
2168
2169     /* check for a volume password */
2170     if (volume->v_password && strncmp(ibuf, volume->v_password, VOLPASSLEN)) {
2171         return AFPERR_ACCESS;
2172     }
2173
2174     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
2175         /* the volume is already open */
2176 #ifdef FORCE_UIDGID
2177         set_uidgid ( volume );
2178 #endif
2179         return stat_vol(bitmap, volume, rbuf, rbuflen);
2180     }
2181
2182     if (volume->v_root_preexec) {
2183         if ((ret = afprun(1, volume->v_root_preexec, NULL)) && volume->v_root_preexec_close) {
2184             LOG(log_error, logtype_afpd, "afp_openvol(%s): root preexec : %d", volume->v_path, ret );
2185             return AFPERR_MISC;
2186         }
2187     }
2188
2189 #ifdef FORCE_UIDGID
2190     set_uidgid ( volume );
2191 #endif
2192
2193     if (volume->v_preexec) {
2194         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
2195             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
2196             return AFPERR_MISC;
2197         }
2198     }
2199
2200     if ( stat( volume->v_path, &st ) < 0 ) {
2201         return AFPERR_PARAM;
2202     }
2203
2204     if ( chdir( volume->v_path ) < 0 ) {
2205         return AFPERR_PARAM;
2206     }
2207
2208     if ( NULL == getcwd(path, MAXPATHLEN)) {
2209         /* shouldn't be fatal but it will fail later */
2210         LOG(log_error, logtype_afpd, "afp_openvol(%s): volume pathlen too long", volume->v_path);
2211         return AFPERR_MISC;
2212     }
2213
2214     /* Normalize volume path */
2215 #ifdef REALPATH_TAKES_NULL
2216     if ((volume->v_path = realpath(path, NULL)) == NULL)
2217         return AFPERR_MISC;
2218 #else
2219     if ((volume->v_path = malloc(MAXPATHLEN+1)) == NULL)
2220         return AFPERR_MISC;
2221     if (realpath(path, volume->v_path) == NULL) {
2222         free(volume->v_path);
2223         return AFPERR_MISC;
2224     }
2225     /* Safe some memory */
2226     char *tmp;
2227     if ((tmp = strdup(volume->v_path)) == NULL) {
2228         free(volume->v_path);
2229         return AFPERR_MISC;
2230     }
2231     free(volume->v_path);
2232     volume->v_path = tmp;
2233 #endif
2234
2235     if (volume_codepage(obj, volume) < 0) {
2236         ret = AFPERR_MISC;
2237         goto openvol_err;
2238     }
2239
2240     /* initialize volume variables
2241      * FIXME file size
2242      */
2243     if (utf8_encoding()) {
2244         volume->max_filename = UTF8FILELEN_EARLY;
2245     }
2246     else {
2247         volume->max_filename = MACFILELEN;
2248     }
2249
2250     volume->v_flags |= AFPVOL_OPEN;
2251     volume->v_cdb = NULL;
2252
2253     if (utf8_encoding()) {
2254         len = convert_string_allocate(CH_UCS2, CH_UTF8_MAC, volume->v_u8mname, namelen, &vol_mname);
2255     } else {
2256         len = convert_string_allocate(CH_UCS2, obj->options.maccharset, volume->v_macname, namelen, &vol_mname);
2257     }
2258     if ( !vol_mname || len <= 0) {
2259         ret = AFPERR_MISC;
2260         goto openvol_err;
2261     }
2262
2263     if ((vol_uname = strrchr(path, '/')) == NULL)
2264         vol_uname = path;
2265     else if (*(vol_uname + 1) != '\0')
2266         vol_uname++;
2267
2268     if ((dir = dir_new(vol_mname,
2269                        vol_uname,
2270                        volume,
2271                        DIRDID_ROOT_PARENT,
2272                        DIRDID_ROOT,
2273                        bfromcstr(volume->v_path),
2274                        &st)
2275             ) == NULL) {
2276         free(vol_mname);
2277         LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
2278         ret = AFPERR_MISC;
2279         goto openvol_err;
2280     }
2281     free(vol_mname);
2282     volume->v_root = dir;
2283     curdir = dir;
2284
2285     if (volume_openDB(volume) < 0) {
2286         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s",
2287             volume->v_path, volume->v_cnidscheme);
2288         ret = AFPERR_MISC;
2289         goto openvol_err;
2290     }
2291
2292     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
2293     if (ret == AFP_OK) {
2294
2295         if (!(volume->v_flags & AFPVOL_RO)) {
2296             handle_special_folders( volume );
2297             savevolinfo(volume,
2298                         volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2299                         volume->v_cnidport   ? volume->v_cnidport   : Cnid_port);
2300         }
2301
2302         /*
2303          * If you mount a volume twice, the second time the trash appears on
2304          * the desk-top.  That's because the Mac remembers the DID for the
2305          * trash (even for volumes in different zones, on different servers).
2306          * Just so this works better, we prime the DID cache with the trash,
2307          * fixing the trash at DID 17.
2308          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
2309          */
2310         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
2311
2312             /* FIXME find db time stamp */
2313             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
2314                 LOG (log_error, logtype_afpd,
2315                      "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
2316                      volume->v_path);
2317                 ret = AFPERR_MISC;
2318                 goto openvol_err;
2319             }
2320         }
2321         else {
2322             p = Trash;
2323             cname( volume, volume->v_root, &p );
2324         }
2325         return( AFP_OK );
2326     }
2327
2328 openvol_err:
2329     if (volume->v_root) {
2330         dir_free( volume->v_root );
2331         volume->v_root = NULL;
2332     }
2333
2334     volume->v_flags &= ~AFPVOL_OPEN;
2335     if (volume->v_cdb != NULL) {
2336         cnid_close(volume->v_cdb);
2337         volume->v_cdb = NULL;
2338     }
2339     *rbuflen = 0;
2340     return ret;
2341 }
2342
2343 /* ------------------------- */
2344 static void closevol(struct vol *vol)
2345 {
2346     if (!vol)
2347         return;
2348
2349     dir_free( vol->v_root );
2350     vol->v_root = NULL;
2351     if (vol->v_cdb != NULL) {
2352         cnid_close(vol->v_cdb);
2353         vol->v_cdb = NULL;
2354     }
2355
2356     if (vol->v_postexec) {
2357         afprun(0, vol->v_postexec, NULL);
2358     }
2359     if (vol->v_root_postexec) {
2360         afprun(1, vol->v_root_postexec, NULL);
2361     }
2362 }
2363
2364 /* ------------------------- */
2365 void close_all_vol(void)
2366 {
2367     struct vol  *ovol;
2368     curdir = NULL;
2369     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2370         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2371             ovol->v_flags &= ~AFPVOL_OPEN;
2372             closevol(ovol);
2373         }
2374     }
2375 }
2376
2377 /* ------------------------- */
2378 static void deletevol(struct vol *vol)
2379 {
2380     struct vol  *ovol;
2381
2382     vol->v_flags &= ~AFPVOL_OPEN;
2383     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2384         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2385             break;
2386         }
2387     }
2388     if ( ovol != NULL ) {
2389         /* Even if chdir fails, we can't say afp_closevol fails. */
2390         if ( chdir( ovol->v_path ) == 0 ) {
2391             curdir = ovol->v_root;
2392         }
2393     }
2394
2395     closevol(vol);
2396     if (vol->v_deleted) {
2397         showvol(vol->v_name);
2398         volume_free(vol);
2399         volume_unlink(vol);
2400         free(vol);
2401     }
2402 }
2403
2404 /* ------------------------- */
2405 int afp_closevol(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2406 {
2407     struct vol  *vol;
2408     u_int16_t   vid;
2409
2410     *rbuflen = 0;
2411     ibuf += 2;
2412     memcpy(&vid, ibuf, sizeof( vid ));
2413     if (NULL == ( vol = getvolbyvid( vid )) ) {
2414         return( AFPERR_PARAM );
2415     }
2416
2417     deletevol(vol);
2418     current_vol = NULL;
2419
2420     return( AFP_OK );
2421 }
2422
2423 /* ------------------------- */
2424 struct vol *getvolbyvid(const u_int16_t vid )
2425 {
2426     struct vol  *vol;
2427
2428     for ( vol = Volumes; vol; vol = vol->v_next ) {
2429         if ( vid == vol->v_vid ) {
2430             break;
2431         }
2432     }
2433     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
2434         return( NULL );
2435     }
2436
2437 #ifdef FORCE_UIDGID
2438     set_uidgid ( vol );
2439 #endif /* FORCE_UIDGID */
2440
2441     current_vol = vol;
2442
2443     return( vol );
2444 }
2445
2446 /* ------------------------ */
2447 static int ext_cmp_key(const void *key, const void *obj)
2448 {
2449     const char          *p = key;
2450     const struct extmap *em = obj;
2451     return strdiacasecmp(p, em->em_ext);
2452 }
2453 struct extmap *getextmap(const char *path)
2454 {
2455     char      *p;
2456     struct extmap *em;
2457
2458     if (!Extmap_cnt || NULL == ( p = strrchr( path, '.' )) ) {
2459         return( Defextmap );
2460     }
2461     p++;
2462     if (!*p) {
2463         return( Defextmap );
2464     }
2465     em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
2466     if (em) {
2467         return( em );
2468     } else {
2469         return( Defextmap );
2470     }
2471 }
2472
2473 /* ------------------------- */
2474 struct extmap *getdefextmap(void)
2475 {
2476     return( Defextmap );
2477 }
2478
2479 /* --------------------------
2480    poll if a volume is changed by other processes.
2481    return
2482    0 no attention msg sent
2483    1 attention msg sent
2484    -1 error (socket closed)
2485
2486    Note: if attention return -1 no packet has been
2487    sent because the buffer is full, we don't care
2488    either there's no reader or there's a lot of
2489    traffic and another pollvoltime will follow
2490 */
2491 int  pollvoltime(AFPObj *obj)
2492
2493 {
2494     struct vol       *vol;
2495     struct timeval   tv;
2496     struct stat      st;
2497
2498     if (!(afp_version > 21 && obj->options.server_notif))
2499         return 0;
2500
2501     if ( gettimeofday( &tv, NULL ) < 0 )
2502         return 0;
2503
2504     for ( vol = Volumes; vol; vol = vol->v_next ) {
2505         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
2506             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
2507                 vol->v_mtime = st.st_mtime;
2508                 if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
2509                     return -1;
2510                 return 1;
2511             }
2512         }
2513     }
2514     return 0;
2515 }
2516
2517 /* ------------------------- */
2518 void setvoltime(AFPObj *obj, struct vol *vol)
2519 {
2520     struct timeval  tv;
2521
2522     if ( gettimeofday( &tv, NULL ) < 0 ) {
2523         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
2524         return;
2525     }
2526     if( utime( vol->v_path, NULL ) < 0 ) {
2527         /* write of time failed ... probably a read only filesys,
2528          * where no other users can interfere, so there's no issue here
2529          */
2530     }
2531
2532     /* a little granularity */
2533     if (vol->v_mtime < tv.tv_sec) {
2534         vol->v_mtime = tv.tv_sec;
2535         /* or finder doesn't update free space
2536          * AFP 3.2 and above clients seem to be ok without so many notification
2537          */
2538         if (afp_version < 32 && obj->options.server_notif) {
2539             obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
2540         }
2541     }
2542 }
2543
2544 /* ------------------------- */
2545 int afp_getvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,char *rbuf, size_t *rbuflen)
2546 {
2547     struct vol  *vol;
2548     u_int16_t   vid, bitmap;
2549
2550     ibuf += 2;
2551     memcpy(&vid, ibuf, sizeof( vid ));
2552     ibuf += sizeof( vid );
2553     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2554     bitmap = ntohs( bitmap );
2555
2556     if (NULL == ( vol = getvolbyvid( vid )) ) {
2557         *rbuflen = 0;
2558         return( AFPERR_PARAM );
2559     }
2560
2561     return stat_vol(bitmap, vol, rbuf, rbuflen);
2562 }
2563
2564 /* ------------------------- */
2565 int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,  size_t *rbuflen)
2566 {
2567     struct adouble ad;
2568     struct vol  *vol;
2569     u_int16_t   vid, bitmap;
2570     u_int32_t   aint;
2571
2572     ibuf += 2;
2573     *rbuflen = 0;
2574
2575     memcpy(&vid, ibuf, sizeof( vid ));
2576     ibuf += sizeof( vid );
2577     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2578     bitmap = ntohs( bitmap );
2579     ibuf += sizeof(bitmap);
2580
2581     if (( vol = getvolbyvid( vid )) == NULL ) {
2582         return( AFPERR_PARAM );
2583     }
2584
2585     if ((vol->v_flags & AFPVOL_RO))
2586         return AFPERR_VLOCK;
2587
2588     /* we can only set the backup date. */
2589     if (bitmap != (1 << VOLPBIT_BDATE))
2590         return AFPERR_BITMAP;
2591
2592     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2593     if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
2594                   0666, &ad) < 0 ) {
2595         if (errno == EROFS)
2596             return AFPERR_VLOCK;
2597
2598         return AFPERR_ACCESS;
2599     }
2600
2601     memcpy(&aint, ibuf, sizeof(aint));
2602     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2603     ad_flush(&ad);
2604     ad_close(&ad, ADFLAGS_HF);
2605     return( AFP_OK );
2606 }
2607
2608 /* ------------------------- */
2609 int wincheck(const struct vol *vol, const char *path)
2610 {
2611     int len;
2612
2613     if (!(vol->v_flags & AFPVOL_MSWINDOWS))
2614         return 1;
2615
2616     /* empty paths are not allowed */
2617     if ((len = strlen(path)) == 0)
2618         return 0;
2619
2620     /* leading or trailing whitespaces are not allowed, carriage returns
2621      * and probably other whitespace is okay, tabs are not allowed
2622      */
2623     if ((path[0] == ' ') || (path[len-1] == ' '))
2624         return 0;
2625
2626     /* certain characters are not allowed */
2627     if (strpbrk(path, MSWINDOWS_BADCHARS))
2628         return 0;
2629
2630     /* everything else is okay */
2631     return 1;
2632 }
2633
2634
2635 /*
2636  * precreate a folder
2637  * this is only intended for folders in the volume root
2638  * It will *not* work if the folder name contains extended characters
2639  */
2640 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2641 {
2642     char        *p,*q,*r;
2643     struct adouble  ad;
2644     u_int16_t   attr;
2645     struct stat st;
2646     int     ret;
2647
2648
2649     p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2650     if ( p == NULL) {
2651         LOG(log_error, logtype_afpd,"malloc failed");
2652         exit (EXITERR_SYS);
2653     }
2654
2655     q=strdup(folder->name);
2656     if ( q == NULL) {
2657         LOG(log_error, logtype_afpd,"malloc failed");
2658         exit (EXITERR_SYS);
2659     }
2660
2661     strcpy(p, vol->v_path);
2662     strcat(p, "/");
2663
2664     r=q;
2665     while (*r) {
2666         if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2667             *r=toupper(*r);
2668         else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2669             *r=tolower(*r);
2670         r++;
2671     }
2672     strcat(p, q);
2673
2674     if ( (ret = stat( p, &st )) < 0 ) {
2675         if (folder->precreate) {
2676             if (ad_mkdir(p, folder->mode)) {
2677                 LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2678                 free(p);
2679                 free(q);
2680                 return -1;
2681             }
2682             ret = 0;
2683         }
2684     }
2685
2686     if ( !ret && folder->hide) {
2687         /* Hide it */
2688         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2689         if (ad_open_metadata( p, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
2690             free (p);
2691             free(q);
2692             return (-1);
2693         }
2694
2695         ad_setname(&ad, folder->name);
2696
2697         ad_getattr(&ad, &attr);
2698         attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2699         ad_setattr(&ad, attr);
2700
2701         /* do the same with the finder info */
2702         if (ad_entry(&ad, ADEID_FINDERI)) {
2703             memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2704             attr   |= htons(FINDERINFO_INVISIBLE);
2705             memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2706         }
2707
2708         ad_flush( &ad );
2709         ad_close_metadata( &ad);
2710     }
2711     free(p);
2712     free(q);
2713     return 0;
2714 }
2715
2716 static void handle_special_folders (const struct vol * vol)
2717 {
2718     const _special_folder *p = &special_folders[0];
2719
2720     if ((vol->v_flags & AFPVOL_RO))
2721         return;
2722
2723     for (; p->name != NULL; p++) {
2724         create_special_folder (vol, p);
2725     }
2726 }
2727
2728 const struct vol *getvolumes(void)
2729 {
2730     return Volumes;
2731 }
2732
2733 void unload_volumes_and_extmap(void)
2734 {
2735     LOG(log_debug, logtype_afpd, "unload_volumes_and_extmap");
2736     free_extmap();
2737     free_volumes();
2738 }
2739
2740 /* 
2741  * Get a volumes UUID from the config file.
2742  * If there is none, it is generated and stored there.
2743  *
2744  * Returns pointer to allocated storage on success, NULL on error.
2745  */
2746 static char *get_vol_uuid(const AFPObj *obj, const char *volname)
2747 {
2748     char *volname_conf;
2749     char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
2750     FILE *fp;
2751     struct stat tmpstat;
2752     int fd;
2753     
2754     if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
2755         /* scan in the conf file */
2756         while (fgets(buf, sizeof(buf), fp) != NULL) { 
2757             p = buf;
2758             while (p && isblank(*p))
2759                 p++;
2760             if (!p || (*p == '#') || (*p == '\n'))
2761                 continue;                             /* invalid line */
2762             if (*p == '"') {
2763                 p++;
2764                 if ((volname_conf = strtok( p, "\"" )) == NULL)
2765                     continue;                         /* syntax error */
2766             } else {
2767                 if ((volname_conf = strtok( p, " \t" )) == NULL)
2768                     continue;                         /* syntax error: invalid name */
2769             }
2770             p = strchr(p, '\0');
2771             p++;
2772             if (*p == '\0')
2773                 continue;                             /* syntax error */
2774             
2775             if (strcmp(volname, volname_conf) != 0)
2776                 continue;                             /* another volume name */
2777                 
2778             while (p && isblank(*p))
2779                 p++;
2780
2781             if (sscanf(p, "%36s", uuid) == 1 ) {
2782                 for (int i=0; uuid[i]; i++)
2783                     uuid[i] = toupper(uuid[i]);
2784                 LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
2785                 fclose(fp);
2786                 return strdup(uuid);
2787             }
2788         }
2789     }
2790
2791     if (fp)
2792         fclose(fp);
2793
2794     /*  not found or no file, reopen in append mode */
2795
2796     if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
2797         if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
2798             LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
2799                 obj->options.uuidconf, strerror(errno));
2800             return NULL;
2801         }
2802         if (( fp = fdopen( fd, "w" )) == NULL ) {
2803             LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
2804                 obj->options.uuidconf, strerror(errno));
2805             close(fd);
2806             return NULL;
2807         }
2808     } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
2809         LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
2810             obj->options.uuidconf, strerror(errno));
2811         return NULL;
2812     }
2813     fseek(fp, 0L, SEEK_END);
2814     if(ftell(fp) == 0) {                     /* size = 0 */
2815         fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
2816         fprintf(fp, "# This file is auto-generated by afpd\n");
2817         fprintf(fp, "# and stores UUIDs for TM volumes.\n\n");
2818     } else {
2819         fseek(fp, -1L, SEEK_END);
2820         if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
2821     }                    
2822     
2823     /* generate uuid and write to file */
2824     atalk_uuid_t id;
2825     const char *cp;
2826     randombytes((void *)id, 16);
2827     cp = uuid_bin2string(id);
2828
2829     LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
2830
2831     fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
2832     fclose(fp);
2833     
2834     return strdup(cp);
2835 }