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