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