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