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