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