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