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