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