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