]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
remove compiler warnings
[netatalk.git] / etc / afpd / volume.c
1 /*
2  * $Id: volume.c,v 1.73 2008-12-03 18:35:44 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 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     volume->v_dir = volume->v_root = dir;
1734     volume->v_hash = dirhash();
1735
1736     curdir = volume->v_dir;
1737     if (volume->v_cnidscheme == NULL) {
1738         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
1739         LOG(log_warning, logtype_afpd, "Warning: No CNID scheme for volume %s. Using default.",
1740                volume->v_path);
1741     }
1742     if (volume->v_dbpath)
1743         volume->v_cdb = cnid_open (volume->v_dbpath, volume->v_umask, volume->v_cnidscheme, (volume->v_flags & AFPVOL_NODEV));
1744     else
1745         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, volume->v_cnidscheme, (volume->v_flags & AFPVOL_NODEV));
1746     if (volume->v_cdb == NULL) {
1747         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s", 
1748             volume->v_path, volume->v_cnidscheme);
1749         ret = AFPERR_MISC;
1750         goto openvol_err;
1751     }
1752
1753     /* Codepages */
1754
1755     if (!volume->v_volcodepage)
1756         volume->v_volcodepage = strdup("UTF8");
1757
1758     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1759         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1760         ret = AFPERR_MISC;
1761         goto openvol_err;
1762     }
1763
1764     if ( NULL == ( volume->v_vol = find_charset_functions(volume->v_volcodepage)) || volume->v_vol->flags & CHARSET_ICONV ) {
1765         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
1766     }   
1767
1768     if (!volume->v_maccodepage)
1769         volume->v_maccodepage = strdup(obj->options.maccodepage);
1770
1771     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
1772         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
1773         ret = AFPERR_MISC;
1774         goto openvol_err;
1775     }
1776
1777     if ( NULL == ( volume->v_mac = find_charset_functions(volume->v_maccodepage)) || ! (volume->v_mac->flags & CHARSET_CLIENT) ) {
1778         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
1779         ret = AFPERR_MISC;
1780         goto openvol_err;
1781     }   
1782
1783     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
1784     if (ret == AFP_OK) {
1785
1786         if (!(volume->v_flags & AFPVOL_RO)) {
1787             handle_special_folders( volume );
1788             savevoloptions( volume);
1789         }
1790
1791         /*
1792          * If you mount a volume twice, the second time the trash appears on
1793          * the desk-top.  That's because the Mac remembers the DID for the
1794          * trash (even for volumes in different zones, on different servers).
1795          * Just so this works better, we prime the DID cache with the trash,
1796          * fixing the trash at DID 17.
1797          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
1798          */
1799         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1800
1801             /* FIXME find db time stamp */
1802             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
1803                 LOG (log_error, logtype_afpd, 
1804                       "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
1805                       volume->v_path);
1806                 ret = AFPERR_MISC;
1807                 goto openvol_err;
1808             }
1809         }
1810         else {
1811             p = Trash;
1812             cname( volume, volume->v_dir, &p );
1813         }
1814         return( AFP_OK );
1815     }
1816
1817 openvol_err:
1818     if (volume->v_dir) {
1819         hash_free( volume->v_hash);
1820         dirfree( volume->v_dir );
1821         volume->v_dir = volume->v_root = NULL;
1822     }
1823
1824     volume->v_flags &= ~AFPVOL_OPEN;
1825     if (volume->v_cdb != NULL) {
1826         cnid_close(volume->v_cdb);
1827         volume->v_cdb = NULL;
1828     }
1829     *rbuflen = 0;
1830     return ret;
1831 }
1832
1833 /* ------------------------- */
1834 static void closevol(struct vol *vol)
1835 {
1836     if (!vol)
1837         return;
1838
1839     hash_free( vol->v_hash);
1840     dirfree( vol->v_root );
1841     vol->v_dir = NULL;
1842     if (vol->v_cdb != NULL) {
1843         cnid_close(vol->v_cdb);
1844         vol->v_cdb = NULL;
1845     }
1846
1847     if (vol->v_postexec) {
1848         afprun(0, vol->v_postexec, NULL);
1849     }
1850     if (vol->v_root_postexec) {
1851         afprun(1, vol->v_root_postexec, NULL);
1852     }
1853 }
1854
1855 /* ------------------------- */
1856 void close_all_vol(void)
1857 {
1858     struct vol  *ovol;
1859     curdir = NULL;
1860     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
1861         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
1862             ovol->v_flags &= ~AFPVOL_OPEN;
1863             closevol(ovol);
1864         }
1865     }
1866 }
1867
1868 /* ------------------------- */
1869 static void deletevol(struct vol *vol)
1870 {
1871     struct vol  *ovol;
1872
1873     vol->v_flags &= ~AFPVOL_OPEN;
1874     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
1875         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
1876             break;
1877         }
1878     }
1879     if ( ovol != NULL ) {
1880         /* Even if chdir fails, we can't say afp_closevol fails. */
1881         if ( chdir( ovol->v_path ) == 0 ) {
1882             curdir = ovol->v_dir;
1883         }
1884     }
1885
1886     closevol(vol);
1887     if (vol->v_deleted) {
1888         showvol(vol->v_name);
1889         volume_free(vol);
1890         volume_unlink(vol);
1891         free(vol);
1892     }
1893 }
1894
1895 /* ------------------------- */
1896 int afp_closevol(obj, ibuf, ibuflen, rbuf, rbuflen )
1897 AFPObj  *obj _U_;
1898 char    *ibuf, *rbuf _U_;
1899 int     ibuflen _U_, *rbuflen;
1900 {
1901     struct vol  *vol;
1902     u_int16_t   vid;
1903
1904     *rbuflen = 0;
1905     ibuf += 2;
1906     memcpy(&vid, ibuf, sizeof( vid ));
1907     if (NULL == ( vol = getvolbyvid( vid )) ) {
1908         return( AFPERR_PARAM );
1909     }
1910
1911     deletevol(vol);
1912
1913     return( AFP_OK );
1914 }
1915
1916 /* ------------------------- */
1917 struct vol *getvolbyvid(const u_int16_t vid )
1918 {
1919     struct vol  *vol;
1920
1921     for ( vol = Volumes; vol; vol = vol->v_next ) {
1922         if ( vid == vol->v_vid ) {
1923             break;
1924         }
1925     }
1926     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
1927         return( NULL );
1928     }
1929
1930 #ifdef FORCE_UIDGID
1931     set_uidgid ( vol );
1932 #endif /* FORCE_UIDGID */
1933
1934     return( vol );
1935 }
1936
1937 /* ------------------------ */
1938 static int ext_cmp_key(const void *key, const void *obj)
1939 {
1940     const char          *p = key;
1941     const struct extmap *em = obj;
1942     return strdiacasecmp(p, em->em_ext);
1943 }
1944 struct extmap *getextmap(const char *path)
1945 {
1946     char          *p;
1947     struct extmap *em;
1948
1949     if (NULL == ( p = strrchr( path, '.' )) ) {
1950         return( Defextmap );
1951     }
1952     p++;
1953     if (!*p || !Extmap_cnt) {
1954         return( Defextmap );
1955     }
1956     em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
1957     if (em) {
1958         return( em );
1959     } else {
1960         return( Defextmap );
1961     }
1962 }
1963
1964 /* ------------------------- */
1965 struct extmap *getdefextmap(void)
1966 {
1967     return( Defextmap );
1968 }
1969
1970 /* --------------------------
1971    poll if a volume is changed by other processes.
1972 */
1973 int  pollvoltime(obj)
1974 AFPObj *obj;
1975 {
1976     struct vol       *vol;
1977     struct timeval   tv;
1978     struct stat      st;
1979     
1980     if (!(afp_version > 21 && obj->options.server_notif)) 
1981          return 0;
1982
1983     if ( gettimeofday( &tv, 0 ) < 0 ) 
1984          return 0;
1985
1986     for ( vol = Volumes; vol; vol = vol->v_next ) {
1987         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
1988             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
1989                 vol->v_mtime = st.st_mtime;
1990                 if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
1991                     return -1;
1992                 return 1;
1993             }
1994         }
1995     }
1996     return 0;
1997 }
1998
1999 /* ------------------------- */
2000 void setvoltime(obj, vol )
2001 AFPObj *obj;
2002 struct vol      *vol;
2003 {
2004     struct timeval      tv;
2005
2006     /* just looking at vol->v_mtime is broken seriously since updates
2007      * from other users afpd processes never are seen.
2008      * This is not the most elegant solution (a shared memory between
2009      * the afpd processes would come closer)
2010      * [RS] */
2011
2012     if ( gettimeofday( &tv, 0 ) < 0 ) {
2013         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
2014         return;
2015     }
2016     if( utime( vol->v_path, NULL ) < 0 ) {
2017         /* write of time failed ... probably a read only filesys,
2018          * where no other users can interfere, so there's no issue here
2019          */
2020     }
2021
2022     /* a little granularity */
2023     if (vol->v_mtime < tv.tv_sec) {
2024         vol->v_mtime = tv.tv_sec;
2025         /* or finder doesn't update free space */
2026         if (afp_version > 21 && obj->options.server_notif) {
2027             obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
2028         }
2029     }
2030 }
2031
2032 /* ------------------------- */
2033 int afp_getvolparams(obj, ibuf, ibuflen, rbuf, rbuflen )
2034 AFPObj  *obj _U_;
2035 char    *ibuf, *rbuf;
2036 int     ibuflen _U_, *rbuflen;
2037 {
2038     struct vol  *vol;
2039     u_int16_t   vid, bitmap;
2040
2041     ibuf += 2;
2042     memcpy(&vid, ibuf, sizeof( vid ));
2043     ibuf += sizeof( vid );
2044     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2045     bitmap = ntohs( bitmap );
2046
2047     if (NULL == ( vol = getvolbyvid( vid )) ) {
2048         *rbuflen = 0;
2049         return( AFPERR_PARAM );
2050     }
2051
2052     return stat_vol(bitmap, vol, rbuf, rbuflen);
2053 }
2054
2055 /* ------------------------- */
2056 int afp_setvolparams(obj, ibuf, ibuflen, rbuf, rbuflen )
2057 AFPObj  *obj _U_;
2058 char    *ibuf, *rbuf _U_;
2059 int     ibuflen _U_, *rbuflen;
2060 {
2061     struct adouble ad;
2062     struct vol  *vol;
2063     u_int16_t   vid, bitmap;
2064     u_int32_t   aint;
2065
2066     ibuf += 2;
2067     *rbuflen = 0;
2068
2069     memcpy(&vid, ibuf, sizeof( vid ));
2070     ibuf += sizeof( vid );
2071     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2072     bitmap = ntohs( bitmap );
2073     ibuf += sizeof(bitmap);
2074
2075     if (( vol = getvolbyvid( vid )) == NULL ) {
2076         return( AFPERR_PARAM );
2077     }
2078
2079     if ((vol->v_flags & AFPVOL_RO))
2080         return AFPERR_VLOCK;
2081
2082     /* we can only set the backup date. */
2083     if (bitmap != (1 << VOLPBIT_BDATE))
2084         return AFPERR_BITMAP;
2085
2086     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2087     if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
2088                   0666, &ad) < 0 ) {
2089         if (errno == EROFS)
2090             return AFPERR_VLOCK;
2091
2092         return AFPERR_ACCESS;
2093     }
2094
2095     memcpy(&aint, ibuf, sizeof(aint));
2096     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2097     ad_flush(&ad);
2098     ad_close(&ad, ADFLAGS_HF);
2099     return( AFP_OK );
2100 }
2101
2102 /* ------------------------- */
2103 int wincheck(const struct vol *vol, const char *path)
2104 {
2105     int len;
2106
2107     if (!(vol->v_flags & AFPVOL_MSWINDOWS))
2108         return 1;
2109
2110     /* empty paths are not allowed */
2111     if ((len = strlen(path)) == 0)
2112         return 0;
2113
2114     /* leading or trailing whitespaces are not allowed, carriage returns
2115      * and probably other whitespace is okay, tabs are not allowed
2116      */
2117     if ((path[0] == ' ') || (path[len-1] == ' '))
2118         return 0;
2119
2120     /* certain characters are not allowed */
2121     if (strpbrk(path, MSWINDOWS_BADCHARS))
2122         return 0;
2123
2124     /* everything else is okay */
2125     return 1;
2126 }
2127
2128
2129 /*
2130  * precreate a folder 
2131  * this is only intended for folders in the volume root 
2132  * It will *not* work if the folder name contains extended characters 
2133  */
2134 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2135 {
2136         char            *p,*q,*r;
2137         struct adouble  ad;
2138         u_int16_t       attr;
2139         struct stat     st;
2140         int             ret;
2141
2142
2143         p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2144         if ( p == NULL) {
2145                 LOG(log_error, logtype_afpd,"malloc failed");
2146                 exit (EXITERR_SYS);
2147         }
2148
2149         q=strdup(folder->name);
2150         if ( q == NULL) {
2151                 LOG(log_error, logtype_afpd,"malloc failed");
2152                 exit (EXITERR_SYS);
2153         }
2154
2155         strcpy(p, vol->v_path);
2156         strcat(p, "/");
2157
2158         r=q;
2159         while (*r) {
2160                 if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2161                         *r=toupper(*r);
2162                 else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2163                         *r=tolower(*r);
2164                 r++;
2165         }
2166         strcat(p, q);
2167
2168         if ( (ret = stat( p, &st )) < 0 ) {
2169                 if (folder->precreate) {
2170                     if (ad_mkdir(p, folder->mode)) {
2171                         LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2172                         free(p);
2173                         free(q);
2174                         return -1;
2175                     }
2176                     ret = 0;
2177                 }
2178         }
2179
2180         if ( !ret && folder->hide) {
2181                 /* Hide it */
2182                 ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2183                 if (ad_open( p, vol_noadouble(vol) | ADFLAGS_HF|ADFLAGS_DIR,
2184                         O_RDWR|O_CREAT, 0666, &ad) < 0) {
2185                         free (p);
2186                         free(q);
2187                         return (-1);
2188                 }
2189                 if ((ad_get_HF_flags( &ad ) & O_CREAT) ) {
2190                     if (ad_getentryoff(&ad, ADEID_NAME)) {
2191                         ad_setentrylen( &ad, ADEID_NAME, strlen(folder->name));
2192                         memcpy(ad_entry( &ad, ADEID_NAME ), folder->name,
2193                                ad_getentrylen( &ad, ADEID_NAME ));
2194                     }
2195                 }
2196  
2197                 ad_getattr(&ad, &attr);
2198                 attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2199                 ad_setattr(&ad, attr);
2200
2201                 /* do the same with the finder info */
2202                 if (ad_entry(&ad, ADEID_FINDERI)) {
2203                         memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2204                         attr   |= htons(FINDERINFO_INVISIBLE);
2205                         memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2206                 }
2207
2208                 ad_flush( &ad );
2209                 ad_close( &ad, ADFLAGS_HF );
2210         }
2211         free(p);
2212         free(q);
2213         return 0;
2214 }
2215
2216 static void handle_special_folders (const struct vol * vol)
2217 {
2218         const _special_folder *p = &special_folders[0];
2219
2220         if ((vol->v_flags & AFPVOL_RO))
2221                 return;
2222
2223         for (; p->name != NULL; p++) {
2224                 create_special_folder (vol, p);
2225         }
2226 }
2227
2228 /*
2229  * Save the volume options to a file, used by
2230  * shell utilities.
2231  * Writing the file everytime a volume is opened is
2232  * unnecessary, but it shouldn't hurt much.
2233  */
2234 static int savevoloptions (const struct vol *vol)
2235 {
2236     char buf[16348];
2237     char item[MAXPATHLEN];
2238     int fd;
2239     int ret = 0;
2240     struct flock lock;
2241     const _vol_opt_name *op = &vol_opt_names[0];
2242     const _vol_opt_name *cf = &vol_opt_casefold[0];
2243
2244     strlcpy (item, vol->v_path, sizeof(item));
2245     strlcat (item, "/.AppleDesktop/", sizeof(item));
2246     strlcat (item, VOLINFOFILE, sizeof(item));
2247
2248     if ((fd = open( item, O_RDWR | O_CREAT , 0666)) <0 ) {
2249         LOG(log_debug, logtype_afpd,"Error opening %s: %s", item, strerror(errno));
2250         return (-1);
2251     }
2252
2253     /* try to get a lock */
2254     lock.l_start  = 0;
2255     lock.l_whence = SEEK_SET;
2256     lock.l_len    = 0;
2257     lock.l_type   = F_WRLCK;
2258
2259     if (fcntl(fd, F_SETLK, &lock) < 0) {
2260         if (errno == EACCES || errno == EAGAIN) {
2261             /* ignore, other process already writing the file */
2262             return 0;
2263         } else {
2264             LOG(log_error, logtype_cnid, "savevoloptions: cannot get lock: %s", strerror(errno));
2265             return (-1);
2266         }
2267     }
2268
2269     /* write volume options */
2270     snprintf(buf, sizeof(buf), "MAC_CHARSET:%s\n", vol->v_maccodepage);
2271     snprintf(item, sizeof(item), "VOL_CHARSET:%s\n", vol->v_volcodepage);
2272     strlcat(buf, item, sizeof(buf));
2273
2274     switch (vol->v_adouble) {
2275         case AD_VERSION1:
2276             strlcat(buf, "ADOUBLE_VER:v1\n", sizeof(buf));
2277             break;
2278         case AD_VERSION2:
2279             strlcat(buf, "ADOUBLE_VER:v2\n", sizeof(buf));
2280             break;
2281         case AD_VERSION2_OSX:
2282             strlcat(buf, "ADOUBLE_VER:osx\n", sizeof(buf));
2283             break;
2284         case AD_VERSION1_ADS:
2285             strlcat(buf, "ADOUBLE_VER:ads\n", sizeof(buf));
2286             break;
2287         case AD_VERSION1_SFM:
2288             strlcat(buf, "ADOUBLE_VER:sfm\n", sizeof(buf));
2289             break;
2290     }
2291
2292     strlcat(buf, "CNIDBACKEND:", sizeof(buf));
2293     strlcat(buf, vol->v_cnidscheme, sizeof(buf));
2294     strlcat(buf, "\n", sizeof(buf));
2295
2296     strlcat(buf, "CNIDDBDHOST:", sizeof(buf));
2297     strlcat(buf, Cnid_srv, sizeof(buf));
2298     strlcat(buf, "\n", sizeof(buf));
2299
2300     snprintf(item, sizeof(item), "CNIDDBDPORT:%u\n", Cnid_port);
2301     strlcat(buf, item, sizeof(buf));
2302
2303     strcpy(item, "CNID_DBPATH:");
2304     if (vol->v_dbpath)
2305         strlcat(item, vol->v_dbpath, sizeof(item));
2306     else
2307         strlcat(item, vol->v_path, sizeof(item));
2308     strlcat(item, "\n", sizeof(item));
2309     strlcat(buf, item, sizeof(buf));
2310
2311     /* volume flags */
2312     strcpy(item, "VOLUME_OPTS:");
2313     for (;op->name; op++) {
2314         if ( (vol->v_flags & op->option) ) {
2315             strlcat(item, op->name, sizeof(item));
2316             strlcat(item, " ", sizeof(item));
2317         }
2318     }
2319     strlcat(item, "\n", sizeof(item));
2320     strlcat(buf, item, sizeof(buf));
2321
2322     /* casefold flags */
2323     strcpy(item, "VOLCASEFOLD:");
2324     for (;cf->name; cf++) {
2325         if ( (vol->v_casefold & cf->option) ) {
2326             strlcat(item, cf->name, sizeof(item));
2327             strlcat(item, " ", sizeof(item));
2328         }
2329     }
2330     strlcat(item, "\n", sizeof(item));
2331     strlcat(buf, item, sizeof(buf));
2332
2333     if (strlen(buf) >= sizeof(buf)-1)
2334         LOG(log_debug, logtype_afpd,"Error writing .volinfo file: buffer too small, %s", buf);
2335
2336
2337    if (write( fd, buf, strlen(buf)) < 0) {
2338        LOG(log_debug, logtype_afpd,"Error writing .volinfo file: %s", strerror(errno));
2339        goto done;
2340    }
2341    ftruncate(fd, strlen(buf));
2342
2343 done:
2344    lock.l_type = F_UNLCK;
2345    fcntl(fd, F_SETLK, &lock);
2346    close (fd);
2347    return ret;
2348 }