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