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