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