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