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