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