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