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