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