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