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