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