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