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