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