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