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