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