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