]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
Completely disable all AppleTalk stuff if not enabled
[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   options[VOLOPT_NUM];
1193     struct stat         st;
1194
1195     if (!p1->name)
1196         return -1;
1197     p1->mtime = 0;
1198     strcpy( path, p1->name );
1199     if ( p2 != NULL ) {
1200         strcat( path, "/" );
1201         strcat( path, p2 );
1202         if (p1->full_name) {
1203             free(p1->full_name);
1204         }
1205         p1->full_name = strdup(path);
1206     }
1207
1208     if (NULL == ( fp = fopen( path, "r" )) ) {
1209         return( -1 );
1210     }
1211     fd = fileno(fp);
1212     if (fd != -1 && !fstat( fd, &st) ) {
1213         p1->mtime = st.st_mtime;
1214     }
1215
1216     /* try putting a read lock on the volume file twice, sleep 1 second if first attempt fails */
1217     int retries = 2;
1218     while (1) {
1219         if ((read_lock(fd, 0, SEEK_SET, 0)) != 0) {
1220             retries--;
1221             if (!retries) {
1222                 LOG(log_error, logtype_afpd, "readvolfile: can't lock volume file \"%s\"", path);
1223                 if ( fclose( fp ) != 0 ) {
1224                     LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1225                 }
1226                 return -1;
1227             }
1228             sleep(1);
1229             continue;
1230         }
1231         break;
1232     }
1233
1234     memset(save_options, 0, sizeof(save_options));
1235
1236     /* Enable some default options for all volumes */
1237     save_options[VOLOPT_FLAGS].i_value |= AFPVOL_CACHE;
1238 #ifdef HAVE_ACLS
1239     save_options[VOLOPT_FLAGS].i_value |= AFPVOL_ACLS;
1240 #endif
1241     save_options[VOLOPT_EA_VFS].i_value = AFPVOL_EA_AUTO;
1242     LOG(log_maxdebug, logtype_afpd, "readvolfile: seeding default umask: %04o",
1243         obj->options.umask);
1244     save_options[VOLOPT_UMASK].i_value = obj->options.umask;
1245
1246     LOG(log_debug, logtype_afpd, "readvolfile: \"%s\"", path);
1247
1248     while ( myfgets( buf, sizeof( buf ), fp ) != NULL ) {
1249         initline( strlen( buf ), buf );
1250         parseline( sizeof( path ) - 1, path );
1251         switch ( *path ) {
1252         case '\0' :
1253         case '#' :
1254             continue;
1255
1256         case ':':
1257             /* change the default options for this file */
1258             if (strncmp(path, VOLOPT_DEFAULT, VOLOPT_DEFAULT_LEN) == 0) {
1259                 *tmp = '\0';
1260                 for (i = 0; i < VOLOPT_NUM; i++) {
1261                     if (parseline( sizeof( path ) - VOLOPT_DEFAULT_LEN - 1,
1262                                    path + VOLOPT_DEFAULT_LEN) < 0)
1263                         break;
1264                     volset(save_options, NULL, tmp, sizeof(tmp) - 1,
1265                            path + VOLOPT_DEFAULT_LEN);
1266                 }
1267             }
1268             break;
1269
1270         case '~' :
1271             if (( p = strchr( path, '/' )) != NULL ) {
1272                 *p++ = '\0';
1273             }
1274             u = path;
1275             u++;
1276             if ( *u == '\0' ) {
1277                 u = obj->username;
1278             }
1279             if ( u == NULL || *u == '\0' || ( pw = getpwnam( u )) == NULL ) {
1280                 continue;
1281             }
1282             strcpy( tmp, pw->pw_dir );
1283             if ( p != NULL && *p != '\0' ) {
1284                 strcat( tmp, "/" );
1285                 strcat( tmp, p );
1286             }
1287             /* fall through */
1288
1289         case '/' :
1290             /* send path through variable substitution */
1291             if (*path != '~') /* need to copy path to tmp */
1292                 strcpy(tmp, path);
1293             if (!pwent && obj->username)
1294                 pwent = getpwnam(obj->username);
1295
1296             if (volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL) == NULL)
1297                 continue;
1298
1299             /* this is sort of braindead. basically, i want to be
1300              * able to specify things in any order, but i don't want to
1301              * re-write everything. */
1302
1303             memcpy(options, save_options, sizeof(options));
1304             *volname = '\0';
1305
1306             /* read in up to VOLOP_NUM possible options */
1307             for (i = 0; i < VOLOPT_NUM; i++) {
1308                 if (parseline( sizeof( tmp ) - 1, tmp ) < 0)
1309                     break;
1310
1311                 volset(options, save_options, volname, sizeof(volname) - 1, tmp);
1312             }
1313
1314             /* check allow/deny lists (if not afpd master loading volumes for Zeroconf reg.):
1315                allow -> either no list (-1), or in list (1)
1316                deny -> either no list (-1), or not in list (0) */
1317             if (parent_or_child == 0
1318                 ||
1319                 (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
1320                  (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1) &&
1321                  hostaccessvol(VOLOPT_ALLOWED_HOSTS, volname, options[VOLOPT_ALLOWED_HOSTS].c_value, obj) &&
1322                  (hostaccessvol(VOLOPT_DENIED_HOSTS, volname, options[VOLOPT_DENIED_HOSTS].c_value, obj) < 1))) {
1323
1324                 /* handle read-only behaviour. semantics:
1325                  * 1) neither the rolist nor the rwlist exist -> rw
1326                  * 2) rolist exists -> ro if user is in it.
1327                  * 3) rwlist exists -> ro unless user is in it. */
1328                 if (parent_or_child == 1
1329                     &&
1330                     ((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0)
1331                     &&
1332                     ((accessvol(options[VOLOPT_ROLIST].c_value, obj->username) == 1) ||
1333                      !accessvol(options[VOLOPT_RWLIST].c_value, obj->username)))
1334                     options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
1335
1336                 /* do variable substitution for volname */
1337                 if (volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL) == NULL)
1338                     continue;
1339
1340                 creatvol(obj, pwent, path, tmp, options, p2 != NULL);
1341             }
1342             volfree(options, save_options);
1343             break;
1344
1345         case '.' :
1346             parseline( sizeof( type ) - 1, type );
1347             parseline( sizeof( creator ) - 1, creator );
1348             setextmap( path, type, creator, user);
1349             break;
1350
1351         default :
1352             break;
1353         }
1354     }
1355     volfree(save_options, NULL);
1356     sortextmap();
1357     if ( fclose( fp ) != 0 ) {
1358         LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1359     }
1360     p1->loaded = 1;
1361     return( 0 );
1362 }
1363
1364 /* ------------------------------- */
1365 static void volume_free(struct vol *vol)
1366 {
1367     free(vol->v_localname);
1368     vol->v_localname = NULL;
1369     free(vol->v_u8mname);
1370     vol->v_u8mname = NULL;
1371     free(vol->v_macname);
1372     vol->v_macname = NULL;
1373     free(vol->v_path);
1374     free(vol->v_password);
1375     free(vol->v_veto);
1376     free(vol->v_volcodepage);
1377     free(vol->v_maccodepage);
1378     free(vol->v_cnidscheme);
1379     free(vol->v_dbpath);
1380     free(vol->v_gvs);
1381 #ifdef FORCE_UIDGID
1382     free(vol->v_forceuid);
1383     free(vol->v_forcegid);
1384 #endif /* FORCE_UIDGID */
1385     if (vol->v_uuid)
1386         free(vol->v_uuid);
1387 }
1388
1389 /* ------------------------------- */
1390 static void free_volumes(void )
1391 {
1392     struct vol  *vol;
1393     struct vol  *nvol, *ovol;
1394
1395     for ( vol = Volumes; vol; vol = vol->v_next ) {
1396         if (( vol->v_flags & AFPVOL_OPEN ) ) {
1397             vol->v_deleted = 1;
1398             continue;
1399         }
1400         volume_free(vol);
1401     }
1402
1403     for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
1404         nvol = vol->v_next;
1405
1406         if (vol->v_localname == NULL) {
1407             if (Volumes == vol) {
1408                 Volumes = nvol;
1409                 ovol = Volumes;
1410             }
1411             else {
1412                 ovol->v_next = nvol;
1413             }
1414             free(vol);
1415         }
1416         else {
1417             ovol = vol;
1418         }
1419     }
1420 }
1421
1422 /* ------------------------------- */
1423 static void volume_unlink(struct vol *volume)
1424 {
1425     struct vol *vol, *ovol, *nvol;
1426
1427     if (volume == Volumes) {
1428         Volumes = Volumes->v_next;
1429         return;
1430     }
1431     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1432         nvol = vol->v_next;
1433
1434         if (vol == volume) {
1435             ovol->v_next = nvol;
1436             break;
1437         }
1438         else {
1439             ovol = vol;
1440         }
1441     }
1442 }
1443
1444 static off_t getused_size; /* result of getused() */
1445
1446 /*!
1447   nftw callback for getused()
1448  */
1449 static int getused_stat(const char *path,
1450                         const struct stat *statp,
1451                         int tflag,
1452                         struct FTW *ftw)
1453 {
1454     off_t low, high;
1455
1456     if (tflag == FTW_F || tflag == FTW_D) {
1457         getused_size += statp->st_blocks * 512;
1458     }
1459
1460     return 0;
1461 }
1462
1463 #define GETUSED_CACHETIME 5
1464 /*!
1465  * Calculate used size of a volume with nftw
1466  *
1467  * The result is cached, we're try to avoid frequently calling nftw()
1468  *
1469  * 1) Call nftw an refresh if:
1470  * 1a) - we're called the first time 
1471  * 1b) - volume modification date is not yet set and the last time we've been called is
1472  *       longer then 30 sec ago
1473  * 1c) - the last volume modification is less then 30 sec old
1474  *
1475  * @param vol     (rw) volume to calculate
1476  */
1477 static int getused(struct vol *vol)
1478 {
1479     static time_t vol_mtime = 0;
1480     int ret = 0;
1481     time_t now = time(NULL);
1482
1483     if (!vol_mtime
1484         || (!vol->v_mtime && ((vol_mtime + GETUSED_CACHETIME) < now))
1485         || (vol->v_mtime && ((vol_mtime + GETUSED_CACHETIME) < vol->v_mtime))
1486         ) {
1487         vol_mtime = now;
1488         getused_size = 0;
1489         vol->v_written = 0;
1490         ret = nftw(vol->v_path, getused_stat, NULL, 20, FTW_PHYS); /* 2 */
1491         LOG(log_debug, logtype_afpd, "volparams: from nftw: %" PRIu64 " bytes",
1492             getused_size);
1493     } else {
1494         getused_size += vol->v_written;
1495         vol->v_written = 0;
1496         LOG(log_debug, logtype_afpd, "volparams: cached used: %" PRIu64 " bytes",
1497             getused_size);
1498     }
1499
1500     return ret;
1501 }
1502
1503 static int getvolspace(struct vol *vol,
1504                        u_int32_t *bfree, u_int32_t *btotal,
1505                        VolSpace *xbfree, VolSpace *xbtotal, u_int32_t *bsize)
1506 {
1507     int         spaceflag, rc;
1508     u_int32_t   maxsize;
1509     VolSpace    used;
1510 #ifndef NO_QUOTA_SUPPORT
1511     VolSpace    qfree, qtotal;
1512 #endif
1513
1514     spaceflag = AFPVOL_GVSMASK & vol->v_flags;
1515     /* report up to 2GB if afp version is < 2.2 (4GB if not) */
1516     maxsize = (vol->v_flags & AFPVOL_A2VOL) ? 0x01fffe00 :
1517         (((afp_version < 22) || (vol->v_flags & AFPVOL_LIMITSIZE))
1518          ? 0x7fffffffL : 0xffffffffL);
1519
1520 #ifdef AFS
1521     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_AFSGVS ) {
1522         if ( afs_getvolspace( vol, xbfree, xbtotal, bsize ) == AFP_OK ) {
1523             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_AFSGVS;
1524             goto getvolspace_done;
1525         }
1526     }
1527 #endif
1528
1529     if (( rc = ustatfs_getvolspace( vol, xbfree, xbtotal, bsize)) != AFP_OK ) {
1530         return( rc );
1531     }
1532
1533 #define min(a,b)    ((a)<(b)?(a):(b))
1534 #ifndef NO_QUOTA_SUPPORT
1535     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_UQUOTA ) {
1536         if ( uquota_getvolspace( vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
1537             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_UQUOTA;
1538             *xbfree = min(*xbfree, qfree);
1539             *xbtotal = min( *xbtotal, qtotal);
1540             goto getvolspace_done;
1541         }
1542     }
1543 #endif
1544     vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_USTATFS;
1545
1546 getvolspace_done:
1547     if (vol->v_limitsize) {
1548         if (getused(vol) != 0)
1549             return AFPERR_MISC;
1550         LOG(log_debug, logtype_afpd, "volparams: used on volume: %" PRIu64 " bytes",
1551             getused_size);
1552         vol->v_tm_used = getused_size;
1553
1554         *xbtotal = min(*xbtotal, (vol->v_limitsize * 1024 * 1024));
1555         *xbfree = min(*xbfree, *xbtotal < getused_size ? 0 : *xbtotal - getused_size);
1556     }
1557
1558     *bfree = min( *xbfree, maxsize);
1559     *btotal = min( *xbtotal, maxsize);
1560     return( AFP_OK );
1561 }
1562
1563 #define FCE_TM_DELTA 10  /* send notification every 10 seconds */
1564 void vol_fce_tm_event(void)
1565 {
1566     static time_t last;
1567     time_t now = time(NULL);
1568     struct vol  *vol = Volumes;
1569
1570     if ((last + FCE_TM_DELTA) < now) {
1571         last = now;
1572         for ( ; vol; vol = vol->v_next ) {
1573             if (vol->v_flags & AFPVOL_TM)
1574                 (void)fce_register_tm_size(vol->v_path, vol->v_tm_used + vol->v_written);
1575         }
1576     }
1577 }
1578
1579 /* -----------------------
1580  * set volume creation date
1581  * avoid duplicate, well at least it tries
1582  */
1583 static void vol_setdate(u_int16_t id, struct adouble *adp, time_t date)
1584 {
1585     struct vol  *volume;
1586     struct vol  *vol = Volumes;
1587
1588     for ( volume = Volumes; volume; volume = volume->v_next ) {
1589         if (volume->v_vid == id) {
1590             vol = volume;
1591         }
1592         else if ((time_t)(AD_DATE_FROM_UNIX(date)) == volume->v_ctime) {
1593             date = date+1;
1594             volume = Volumes; /* restart */
1595         }
1596     }
1597     vol->v_ctime = AD_DATE_FROM_UNIX(date);
1598     ad_setdate(adp, AD_DATE_CREATE | AD_DATE_UNIX, date);
1599 }
1600
1601 /* ----------------------- */
1602 static int getvolparams( u_int16_t bitmap, struct vol *vol, struct stat *st, char *buf, size_t *buflen)
1603 {
1604     struct adouble  ad;
1605     int         bit = 0, isad = 1;
1606     u_int32_t       aint;
1607     u_short     ashort;
1608     u_int32_t       bfree, btotal, bsize;
1609     VolSpace            xbfree, xbtotal; /* extended bytes */
1610     char        *data, *nameoff = NULL;
1611     char                *slash;
1612
1613     LOG(log_debug, logtype_afpd, "getvolparams: Volume '%s'", vol->v_localname);
1614
1615     /* courtesy of jallison@whistle.com:
1616      * For MacOS8.x support we need to create the
1617      * .Parent file here if it doesn't exist. */
1618
1619     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1620     if ( ad_open_metadata( vol->v_path, ADFLAGS_DIR, O_CREAT, &ad) < 0 ) {
1621         isad = 0;
1622         vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1623
1624     } else if (ad_get_MD_flags( &ad ) & O_CREAT) {
1625         slash = strrchr( vol->v_path, '/' );
1626         if(slash)
1627             slash++;
1628         else
1629             slash = vol->v_path;
1630         if (ad_getentryoff(&ad, ADEID_NAME)) {
1631             ad_setentrylen( &ad, ADEID_NAME, strlen( slash ));
1632             memcpy(ad_entry( &ad, ADEID_NAME ), slash,
1633                    ad_getentrylen( &ad, ADEID_NAME ));
1634         }
1635         vol_setdate(vol->v_vid, &ad, st->st_mtime);
1636         ad_flush(&ad);
1637     }
1638     else {
1639         if (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0)
1640             vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1641         else
1642             vol->v_ctime = aint;
1643     }
1644
1645     if (( bitmap & ( (1<<VOLPBIT_BFREE)|(1<<VOLPBIT_BTOTAL) |
1646                      (1<<VOLPBIT_XBFREE)|(1<<VOLPBIT_XBTOTAL) |
1647                      (1<<VOLPBIT_BSIZE)) ) != 0 ) {
1648         if ( getvolspace( vol, &bfree, &btotal, &xbfree, &xbtotal,
1649                           &bsize) != AFP_OK ) {
1650             if ( isad ) {
1651                 ad_close( &ad, ADFLAGS_HF );
1652             }
1653             return( AFPERR_PARAM );
1654         }
1655     }
1656
1657     data = buf;
1658     while ( bitmap != 0 ) {
1659         while (( bitmap & 1 ) == 0 ) {
1660             bitmap = bitmap>>1;
1661             bit++;
1662         }
1663
1664         switch ( bit ) {
1665         case VOLPBIT_ATTR :
1666             ashort = 0;
1667             /* check for read-only.
1668              * NOTE: we don't actually set the read-only flag unless
1669              *       it's passed in that way as it's possible to mount
1670              *       a read-write filesystem under a read-only one. */
1671             if ((vol->v_flags & AFPVOL_RO) ||
1672                 ((utime(vol->v_path, NULL) < 0) && (errno == EROFS))) {
1673                 ashort |= VOLPBIT_ATTR_RO;
1674             }
1675             /* prior 2.1 only VOLPBIT_ATTR_RO is defined */
1676             if (afp_version > 20) {
1677                 if (0 == (vol->v_flags & AFPVOL_NOFILEID) && vol->v_cdb != NULL &&
1678                     (vol->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1679                     ashort |= VOLPBIT_ATTR_FILEID;
1680                 }
1681                 ashort |= VOLPBIT_ATTR_CATSEARCH;
1682
1683                 if (afp_version >= 30) {
1684                     ashort |= VOLPBIT_ATTR_UTF8;
1685                     if (vol->v_flags & AFPVOL_UNIX_PRIV)
1686                         ashort |= VOLPBIT_ATTR_UNIXPRIV;
1687                     if (vol->v_flags & AFPVOL_TM)
1688                         ashort |= VOLPBIT_ATTR_TM;
1689                     if (vol->v_flags & AFPVOL_NONETIDS)
1690                         ashort |= VOLPBIT_ATTR_NONETIDS;
1691                     if (afp_version >= 32) {
1692                         if (vol->v_vfs_ea)
1693                             ashort |= VOLPBIT_ATTR_EXT_ATTRS;
1694                         if (vol->v_flags & AFPVOL_ACLS)
1695                             ashort |= VOLPBIT_ATTR_ACLS;
1696                     }
1697                 }
1698             }
1699             ashort = htons(ashort);
1700             memcpy(data, &ashort, sizeof( ashort ));
1701             data += sizeof( ashort );
1702             break;
1703
1704         case VOLPBIT_SIG :
1705             ashort = htons( AFPVOLSIG_DEFAULT );
1706             memcpy(data, &ashort, sizeof( ashort ));
1707             data += sizeof( ashort );
1708             break;
1709
1710         case VOLPBIT_CDATE :
1711             aint = vol->v_ctime;
1712             memcpy(data, &aint, sizeof( aint ));
1713             data += sizeof( aint );
1714             break;
1715
1716         case VOLPBIT_MDATE :
1717             if ( st->st_mtime > vol->v_mtime ) {
1718                 vol->v_mtime = st->st_mtime;
1719             }
1720             aint = AD_DATE_FROM_UNIX(vol->v_mtime);
1721             memcpy(data, &aint, sizeof( aint ));
1722             data += sizeof( aint );
1723             break;
1724
1725         case VOLPBIT_BDATE :
1726             if (!isad ||  (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1727                 aint = AD_DATE_START;
1728             memcpy(data, &aint, sizeof( aint ));
1729             data += sizeof( aint );
1730             break;
1731
1732         case VOLPBIT_VID :
1733             memcpy(data, &vol->v_vid, sizeof( vol->v_vid ));
1734             data += sizeof( vol->v_vid );
1735             break;
1736
1737         case VOLPBIT_BFREE :
1738             bfree = htonl( bfree );
1739             memcpy(data, &bfree, sizeof( bfree ));
1740             data += sizeof( bfree );
1741             break;
1742
1743         case VOLPBIT_BTOTAL :
1744             btotal = htonl( btotal );
1745             memcpy(data, &btotal, sizeof( btotal ));
1746             data += sizeof( btotal );
1747             break;
1748
1749 #ifndef NO_LARGE_VOL_SUPPORT
1750         case VOLPBIT_XBFREE :
1751             xbfree = hton64( xbfree );
1752 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1753             bcopy(&xbfree, data, sizeof(xbfree));
1754 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1755             memcpy(data, &xbfree, sizeof( xbfree ));
1756 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1757             data += sizeof( xbfree );
1758             break;
1759
1760         case VOLPBIT_XBTOTAL :
1761             xbtotal = hton64( xbtotal );
1762 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1763             bcopy(&xbtotal, data, sizeof(xbtotal));
1764 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1765             memcpy(data, &xbtotal, sizeof( xbtotal ));
1766 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1767             data += sizeof( xbfree );
1768             break;
1769 #endif /* ! NO_LARGE_VOL_SUPPORT */
1770
1771         case VOLPBIT_NAME :
1772             nameoff = data;
1773             data += sizeof( u_int16_t );
1774             break;
1775
1776         case VOLPBIT_BSIZE:  /* block size */
1777             bsize = htonl(bsize);
1778             memcpy(data, &bsize, sizeof(bsize));
1779             data += sizeof(bsize);
1780             break;
1781
1782         default :
1783             if ( isad ) {
1784                 ad_close( &ad, ADFLAGS_HF );
1785             }
1786             return( AFPERR_BITMAP );
1787         }
1788         bitmap = bitmap>>1;
1789         bit++;
1790     }
1791     if ( nameoff ) {
1792         ashort = htons( data - buf );
1793         memcpy(nameoff, &ashort, sizeof( ashort ));
1794         /* name is always in mac charset */
1795         aint = ucs2_to_charset( vol->v_maccharset, vol->v_macname, data+1, AFPVOL_MACNAMELEN + 1);
1796         if ( aint <= 0 ) {
1797             *buflen = 0;
1798             return AFPERR_MISC;
1799         }
1800
1801         *data++ = aint;
1802         data += aint;
1803     }
1804     if ( isad ) {
1805         ad_close_metadata( &ad);
1806     }
1807     *buflen = data - buf;
1808     return( AFP_OK );
1809 }
1810
1811 /* ------------------------- */
1812 static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, size_t *rbuflen)
1813 {
1814     struct stat st;
1815     int     ret;
1816     size_t  buflen;
1817
1818     if ( stat( vol->v_path, &st ) < 0 ) {
1819         *rbuflen = 0;
1820         return( AFPERR_PARAM );
1821     }
1822     /* save the volume device number */
1823     vol->v_dev = st.st_dev;
1824
1825     buflen = *rbuflen - sizeof( bitmap );
1826     if (( ret = getvolparams( bitmap, vol, &st,
1827                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
1828         *rbuflen = 0;
1829         return( ret );
1830     }
1831     *rbuflen = buflen + sizeof( bitmap );
1832     bitmap = htons( bitmap );
1833     memcpy(rbuf, &bitmap, sizeof( bitmap ));
1834     return( AFP_OK );
1835
1836 }
1837
1838 /* ------------------------------- */
1839 void load_volumes(AFPObj *obj)
1840 {
1841     struct passwd   *pwent;
1842
1843     if (Volumes) {
1844         int changed = 0;
1845
1846         /* check files date */
1847         if (obj->options.defaultvol.loaded) {
1848             changed = volfile_changed(&obj->options.defaultvol);
1849         }
1850         if (obj->options.systemvol.loaded) {
1851             changed |= volfile_changed(&obj->options.systemvol);
1852         }
1853         if (obj->options.uservol.loaded) {
1854             changed |= volfile_changed(&obj->options.uservol);
1855         }
1856         if (!changed)
1857             return;
1858
1859         free_extmap();
1860         free_volumes();
1861     }
1862
1863     if (parent_or_child == 0) {
1864         LOG(log_debug, logtype_afpd, "load_volumes: AFP MASTER");
1865     } else {
1866         LOG(log_debug, logtype_afpd, "load_volumes: user: %s", obj->username);
1867     }
1868
1869     pwent = getpwnam(obj->username);
1870     if ( (obj->options.flags & OPTION_USERVOLFIRST) == 0 ) {
1871         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent);
1872     }
1873
1874     if ((*obj->username == '\0') || (obj->options.flags & OPTION_NOUSERVOL)) {
1875         readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent);
1876     } else if (pwent) {
1877         /*
1878          * Read user's AppleVolumes or .AppleVolumes file
1879          * If neither are readable, read the default volumes file. if
1880          * that doesn't work, create a user share.
1881          */
1882         if (obj->options.uservol.name) {
1883             free(obj->options.uservol.name);
1884         }
1885         obj->options.uservol.name = strdup(pwent->pw_dir);
1886         if ( readvolfile(obj, &obj->options.uservol,    "AppleVolumes", 1, pwent) < 0 &&
1887              readvolfile(obj, &obj->options.uservol, ".AppleVolumes", 1, pwent) < 0 &&
1888              readvolfile(obj, &obj->options.uservol, "applevolumes", 1, pwent) < 0 &&
1889              readvolfile(obj, &obj->options.uservol, ".applevolumes", 1, pwent) < 0 &&
1890              obj->options.defaultvol.name != NULL ) {
1891             if (readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent) < 0)
1892                 creatvol(obj, pwent, pwent->pw_dir, NULL, NULL, 1);
1893         }
1894     }
1895     if ( obj->options.flags & OPTION_USERVOLFIRST ) {
1896         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent );
1897     }
1898
1899     if ( obj->options.closevol ) {
1900         struct vol *vol;
1901
1902         for ( vol = Volumes; vol; vol = vol->v_next ) {
1903             if (vol->v_deleted && !vol->v_new ) {
1904                 of_closevol(vol);
1905                 deletevol(vol);
1906                 vol = Volumes;
1907             }
1908         }
1909     }
1910 }
1911
1912 /* ------------------------------- */
1913 int afp_getsrvrparms(AFPObj *obj, char *ibuf _U_, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
1914 {
1915     struct timeval  tv;
1916     struct stat     st;
1917     struct vol      *volume;
1918     char    *data;
1919     char        *namebuf;
1920     int         vcnt;
1921     size_t      len;
1922
1923     load_volumes(obj);
1924
1925     data = rbuf + 5;
1926     for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
1927         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
1928             struct maccess ma;
1929
1930             if ( stat( volume->v_path, &st ) < 0 ) {
1931                 LOG(log_info, logtype_afpd, "afp_getsrvrparms(%s): stat: %s",
1932                     volume->v_path, strerror(errno) );
1933                 continue;       /* can't access directory */
1934             }
1935             if (!S_ISDIR(st.st_mode)) {
1936                 continue;       /* not a dir */
1937             }
1938             accessmode(volume->v_path, &ma, NULL, &st);
1939             if ((ma.ma_user & (AR_UREAD | AR_USEARCH)) != (AR_UREAD | AR_USEARCH)) {
1940                 continue;   /* no r-x access */
1941             }
1942         }
1943         if (volume->v_hide) {
1944             continue;       /* config file changed but the volume was mounted */
1945         }
1946
1947         if (utf8_encoding()) {
1948             len = ucs2_to_charset_allocate(CH_UTF8_MAC, &namebuf, volume->v_u8mname);
1949         } else {
1950             len = ucs2_to_charset_allocate(obj->options.maccharset, &namebuf, volume->v_macname);
1951         }
1952
1953         if (len == (size_t)-1)
1954             continue;
1955
1956         /* set password bit if there's a volume password */
1957         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
1958
1959         /* Apple 2 clients running ProDOS-8 expect one volume to have
1960            bit 0 of this byte set.  They will not recognize anything
1961            on the server unless this is the case.  I have not
1962            completely worked this out, but it's related to booting
1963            from the server.  Support for that function is a ways
1964            off.. <shirsch@ibm.net> */
1965         *data |= (volume->v_flags & AFPVOL_A2VOL) ? AFPSRVR_CONFIGINFO : 0;
1966         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
1967         *data++ = len;
1968         memcpy(data, namebuf, len );
1969         data += len;
1970         free(namebuf);
1971         vcnt++;
1972     }
1973
1974     *rbuflen = data - rbuf;
1975     data = rbuf;
1976     if ( gettimeofday( &tv, NULL ) < 0 ) {
1977         LOG(log_error, logtype_afpd, "afp_getsrvrparms(%s): gettimeofday: %s", volume->v_path, strerror(errno) );
1978         *rbuflen = 0;
1979         return AFPERR_PARAM;
1980     }
1981     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
1982     memcpy(data, &tv.tv_sec, sizeof( u_int32_t));
1983     data += sizeof( u_int32_t);
1984     *data = vcnt;
1985     return( AFP_OK );
1986 }
1987
1988 /* ------------------------- */
1989 static int volume_codepage(AFPObj *obj, struct vol *volume)
1990 {
1991     struct charset_functions *charset;
1992     /* Codepages */
1993
1994     if (!volume->v_volcodepage)
1995         volume->v_volcodepage = strdup("UTF8");
1996
1997     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1998         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1999         return -1;
2000     }
2001
2002     if ( NULL == (charset = find_charset_functions(volume->v_volcodepage)) || charset->flags & CHARSET_ICONV ) {
2003         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
2004     }
2005
2006     if (!volume->v_maccodepage)
2007         volume->v_maccodepage = strdup(obj->options.maccodepage);
2008
2009     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
2010         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
2011         return -1;
2012     }
2013
2014     if ( NULL == ( charset = find_charset_functions(volume->v_maccodepage)) || ! (charset->flags & CHARSET_CLIENT) ) {
2015         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
2016         return -1;
2017     }
2018     volume->v_kTextEncoding = htonl(charset->kTextEncoding);
2019     return 0;
2020 }
2021
2022 /* ------------------------- */
2023 static int volume_openDB(struct vol *volume)
2024 {
2025     int flags = 0;
2026
2027     if ((volume->v_flags & AFPVOL_NODEV)) {
2028         flags |= CNID_FLAG_NODEV;
2029     }
2030
2031     if (volume->v_cnidscheme == NULL) {
2032         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
2033         LOG(log_info, logtype_afpd, "Volume %s use CNID scheme %s.",
2034             volume->v_path, volume->v_cnidscheme);
2035     }
2036
2037     LOG(log_info, logtype_afpd, "CNID server: %s:%s",
2038         volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2039         volume->v_cnidport ? volume->v_cnidport : Cnid_port);
2040
2041 #if 0
2042 /* Found this in branch dir-rewrite, maybe we want to use it sometimes */
2043
2044     /* Legacy pre 2.1 way of sharing eg CD-ROM */
2045     if (strcmp(volume->v_cnidscheme, "last") == 0) {
2046         /* "last" is gone. We support it by switching to in-memory "tdb" */
2047         volume->v_cnidscheme = strdup("tdb");
2048         flags |= CNID_FLAG_MEMORY;
2049     }
2050
2051     /* New way of sharing CD-ROM */
2052     if (volume->v_flags & AFPVOL_CDROM) {
2053         flags |= CNID_FLAG_MEMORY;
2054         if (strcmp(volume->v_cnidscheme, "tdb") != 0) {
2055             free(volume->v_cnidscheme);
2056             volume->v_cnidscheme = strdup("tdb");
2057             LOG(log_info, logtype_afpd, "Volume %s is ejectable, switching to scheme %s.",
2058                 volume->v_path, volume->v_cnidscheme);
2059         }
2060     }
2061 #endif
2062
2063     volume->v_cdb = cnid_open(volume->v_path,
2064                               volume->v_umask,
2065                               volume->v_cnidscheme,
2066                               flags,
2067                               volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2068                               volume->v_cnidport ? volume->v_cnidport : Cnid_port);
2069
2070     if ( ! volume->v_cdb && ! (flags & CNID_FLAG_MEMORY)) {
2071         /* The first attempt failed and it wasn't yet an attempt to open in-memory */
2072         LOG(log_error, logtype_afpd, "Can't open volume \"%s\" CNID backend \"%s\" ",
2073             volume->v_path, volume->v_cnidscheme);
2074         LOG(log_error, logtype_afpd, "Reopen volume %s using in memory temporary CNID DB.",
2075             volume->v_path);
2076         flags |= CNID_FLAG_MEMORY;
2077         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, "tdb", flags, NULL, NULL);
2078 #ifdef SERVERTEXT
2079         /* kill ourself with SIGUSR2 aka msg pending */
2080         if (volume->v_cdb) {
2081             setmessage("Something wrong with the volume's CNID DB, using temporary CNID DB instead."
2082                        "Check server messages for details!");
2083             kill(getpid(), SIGUSR2);
2084             /* deactivate cnid caching/storing in AppleDouble files */
2085             volume->v_flags &= ~AFPVOL_CACHE;
2086         }
2087 #endif
2088     }
2089
2090     return (!volume->v_cdb)?-1:0;
2091 }
2092
2093 /*
2094   Check if the underlying filesystem supports EAs for ea:sys volumes.
2095   If not, switch to ea:ad.
2096   As we can't check (requires write access) on ro-volumes, we switch ea:auto
2097   volumes that are options:ro to ea:none.
2098 */
2099 static void check_ea_sys_support(struct vol *vol)
2100 {
2101     uid_t process_uid = 0;
2102     char eaname[] = {"org.netatalk.supports-eas.XXXXXX"};
2103     const char *eacontent = "yes";
2104
2105     if (vol->v_vfs_ea == AFPVOL_EA_AUTO) {
2106
2107         if ((vol->v_flags & AFPVOL_RO) == AFPVOL_RO) {
2108             LOG(log_info, logtype_afpd, "read-only volume '%s', can't test for EA support, disabling EAs", vol->v_localname);
2109             vol->v_vfs_ea = AFPVOL_EA_NONE;
2110             return;
2111         }
2112
2113         mktemp(eaname);
2114
2115         process_uid = geteuid();
2116         if (process_uid)
2117             if (seteuid(0) == -1) {
2118                 LOG(log_error, logtype_afpd, "check_ea_sys_support: can't seteuid(0): %s", strerror(errno));
2119                 exit(EXITERR_SYS);
2120             }
2121
2122         if ((sys_setxattr(vol->v_path, eaname, eacontent, 4, 0)) == 0) {
2123             sys_removexattr(vol->v_path, eaname);
2124             vol->v_vfs_ea = AFPVOL_EA_SYS;
2125         } else {
2126             LOG(log_warning, logtype_afpd, "volume \"%s\" does not support Extended Attributes, using ea:ad instead",
2127                 vol->v_localname);
2128             vol->v_vfs_ea = AFPVOL_EA_AD;
2129         }
2130
2131         if (process_uid) {
2132             if (seteuid(process_uid) == -1) {
2133                 LOG(log_error, logtype_afpd, "can't seteuid back %s", strerror(errno));
2134                 exit(EXITERR_SYS);
2135             }
2136         }
2137     }
2138 }
2139
2140 /* -------------------------
2141  * we are the user here
2142  */
2143 int afp_openvol(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2144 {
2145     struct stat st;
2146     char    *volname;
2147     char        *p;
2148
2149     struct vol  *volume;
2150     struct dir  *dir;
2151     int     len, ret;
2152     size_t  namelen;
2153     u_int16_t   bitmap;
2154     char        path[ MAXPATHLEN + 1];
2155     char        *vol_uname;
2156     char        *vol_mname;
2157     char        *volname_tmp;
2158
2159     ibuf += 2;
2160     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2161     bitmap = ntohs( bitmap );
2162     ibuf += sizeof( bitmap );
2163
2164     *rbuflen = 0;
2165     if (( bitmap & (1<<VOLPBIT_VID)) == 0 ) {
2166         return AFPERR_BITMAP;
2167     }
2168
2169     len = (unsigned char)*ibuf++;
2170     volname = obj->oldtmp;
2171
2172     if ((volname_tmp = strchr(volname,'+')) != NULL)
2173         volname = volname_tmp+1;
2174
2175     if (utf8_encoding()) {
2176         namelen = convert_string(CH_UTF8_MAC, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
2177     } else {
2178         namelen = convert_string(obj->options.maccharset, CH_UCS2, ibuf, len, volname, sizeof(obj->oldtmp));
2179     }
2180
2181     if ( namelen <= 0) {
2182         return AFPERR_PARAM;
2183     }
2184
2185     ibuf += len;
2186     if ((len + 1) & 1) /* pad to an even boundary */
2187         ibuf++;
2188
2189     load_volumes(obj);
2190
2191     for ( volume = Volumes; volume; volume = volume->v_next ) {
2192         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
2193             break;
2194         }
2195     }
2196
2197     if ( volume == NULL ) {
2198         return AFPERR_PARAM;
2199     }
2200
2201     /* check for a volume password */
2202     if (volume->v_password && strncmp(ibuf, volume->v_password, VOLPASSLEN)) {
2203         return AFPERR_ACCESS;
2204     }
2205
2206     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
2207         /* the volume is already open */
2208 #ifdef FORCE_UIDGID
2209         set_uidgid ( volume );
2210 #endif
2211         return stat_vol(bitmap, volume, rbuf, rbuflen);
2212     }
2213
2214     if (volume->v_root_preexec) {
2215         if ((ret = afprun(1, volume->v_root_preexec, NULL)) && volume->v_root_preexec_close) {
2216             LOG(log_error, logtype_afpd, "afp_openvol(%s): root preexec : %d", volume->v_path, ret );
2217             return AFPERR_MISC;
2218         }
2219     }
2220
2221 #ifdef FORCE_UIDGID
2222     set_uidgid ( volume );
2223 #endif
2224
2225     if (volume->v_preexec) {
2226         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
2227             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
2228             return AFPERR_MISC;
2229         }
2230     }
2231
2232     if ( stat( volume->v_path, &st ) < 0 ) {
2233         return AFPERR_PARAM;
2234     }
2235
2236     if ( chdir( volume->v_path ) < 0 ) {
2237         return AFPERR_PARAM;
2238     }
2239
2240     if ( NULL == getcwd(path, MAXPATHLEN)) {
2241         /* shouldn't be fatal but it will fail later */
2242         LOG(log_error, logtype_afpd, "afp_openvol(%s): volume pathlen too long", volume->v_path);
2243         return AFPERR_MISC;
2244     }
2245
2246     /* Normalize volume path */
2247 #ifdef REALPATH_TAKES_NULL
2248     if ((volume->v_path = realpath(path, NULL)) == NULL)
2249         return AFPERR_MISC;
2250 #else
2251     if ((volume->v_path = malloc(MAXPATHLEN+1)) == NULL)
2252         return AFPERR_MISC;
2253     if (realpath(path, volume->v_path) == NULL) {
2254         free(volume->v_path);
2255         return AFPERR_MISC;
2256     }
2257     /* Safe some memory */
2258     char *tmp;
2259     if ((tmp = strdup(volume->v_path)) == NULL) {
2260         free(volume->v_path);
2261         return AFPERR_MISC;
2262     }
2263     free(volume->v_path);
2264     volume->v_path = tmp;
2265 #endif
2266
2267     if (volume_codepage(obj, volume) < 0) {
2268         ret = AFPERR_MISC;
2269         goto openvol_err;
2270     }
2271
2272     /* initialize volume variables
2273      * FIXME file size
2274      */
2275     if (utf8_encoding()) {
2276         volume->max_filename = UTF8FILELEN_EARLY;
2277     }
2278     else {
2279         volume->max_filename = MACFILELEN;
2280     }
2281
2282     volume->v_flags |= AFPVOL_OPEN;
2283     volume->v_cdb = NULL;
2284
2285     if (utf8_encoding()) {
2286         len = convert_string_allocate(CH_UCS2, CH_UTF8_MAC, volume->v_u8mname, namelen, &vol_mname);
2287     } else {
2288         len = convert_string_allocate(CH_UCS2, obj->options.maccharset, volume->v_macname, namelen, &vol_mname);
2289     }
2290     if ( !vol_mname || len <= 0) {
2291         ret = AFPERR_MISC;
2292         goto openvol_err;
2293     }
2294
2295     if ((vol_uname = strrchr(path, '/')) == NULL)
2296         vol_uname = path;
2297     else if (*(vol_uname + 1) != '\0')
2298         vol_uname++;
2299
2300     if ((dir = dir_new(vol_mname,
2301                        vol_uname,
2302                        volume,
2303                        DIRDID_ROOT_PARENT,
2304                        DIRDID_ROOT,
2305                        bfromcstr(volume->v_path),
2306                        &st)
2307             ) == NULL) {
2308         free(vol_mname);
2309         LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
2310         ret = AFPERR_MISC;
2311         goto openvol_err;
2312     }
2313     free(vol_mname);
2314     volume->v_root = dir;
2315     curdir = dir;
2316
2317     if (volume_openDB(volume) < 0) {
2318         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s",
2319             volume->v_path, volume->v_cnidscheme);
2320         ret = AFPERR_MISC;
2321         goto openvol_err;
2322     }
2323
2324     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
2325
2326     if (ret == AFP_OK) {
2327         handle_special_folders(volume);
2328         savevolinfo(volume,
2329                     volume->v_cnidserver ? volume->v_cnidserver : Cnid_srv,
2330                     volume->v_cnidport   ? volume->v_cnidport   : Cnid_port);
2331
2332
2333         /*
2334          * If you mount a volume twice, the second time the trash appears on
2335          * the desk-top.  That's because the Mac remembers the DID for the
2336          * trash (even for volumes in different zones, on different servers).
2337          * Just so this works better, we prime the DID cache with the trash,
2338          * fixing the trash at DID 17.
2339          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
2340          */
2341         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
2342
2343             /* FIXME find db time stamp */
2344             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
2345                 LOG (log_error, logtype_afpd,
2346                      "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
2347                      volume->v_path);
2348                 ret = AFPERR_MISC;
2349                 goto openvol_err;
2350             }
2351         }
2352         else {
2353             p = Trash;
2354             cname( volume, volume->v_root, &p );
2355         }
2356         return( AFP_OK );
2357     }
2358
2359 openvol_err:
2360     if (volume->v_root) {
2361         dir_free( volume->v_root );
2362         volume->v_root = NULL;
2363     }
2364
2365     volume->v_flags &= ~AFPVOL_OPEN;
2366     if (volume->v_cdb != NULL) {
2367         cnid_close(volume->v_cdb);
2368         volume->v_cdb = NULL;
2369     }
2370     *rbuflen = 0;
2371     return ret;
2372 }
2373
2374 /* ------------------------- */
2375 static void closevol(struct vol *vol)
2376 {
2377     if (!vol)
2378         return;
2379
2380     dir_free( vol->v_root );
2381     vol->v_root = NULL;
2382     if (vol->v_cdb != NULL) {
2383         cnid_close(vol->v_cdb);
2384         vol->v_cdb = NULL;
2385     }
2386
2387     if (vol->v_postexec) {
2388         afprun(0, vol->v_postexec, NULL);
2389     }
2390     if (vol->v_root_postexec) {
2391         afprun(1, vol->v_root_postexec, NULL);
2392     }
2393 }
2394
2395 /* ------------------------- */
2396 void close_all_vol(void)
2397 {
2398     struct vol  *ovol;
2399     curdir = NULL;
2400     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2401         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2402             ovol->v_flags &= ~AFPVOL_OPEN;
2403             closevol(ovol);
2404         }
2405     }
2406 }
2407
2408 /* ------------------------- */
2409 static void deletevol(struct vol *vol)
2410 {
2411     struct vol  *ovol;
2412
2413     vol->v_flags &= ~AFPVOL_OPEN;
2414     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
2415         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
2416             break;
2417         }
2418     }
2419     if ( ovol != NULL ) {
2420         /* Even if chdir fails, we can't say afp_closevol fails. */
2421         if ( chdir( ovol->v_path ) == 0 ) {
2422             curdir = ovol->v_root;
2423         }
2424     }
2425
2426     closevol(vol);
2427     if (vol->v_deleted) {
2428         showvol(vol->v_name);
2429         volume_free(vol);
2430         volume_unlink(vol);
2431         free(vol);
2432     }
2433 }
2434
2435 /* ------------------------- */
2436 int afp_closevol(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2437 {
2438     struct vol  *vol;
2439     u_int16_t   vid;
2440
2441     *rbuflen = 0;
2442     ibuf += 2;
2443     memcpy(&vid, ibuf, sizeof( vid ));
2444     if (NULL == ( vol = getvolbyvid( vid )) ) {
2445         return( AFPERR_PARAM );
2446     }
2447
2448     deletevol(vol);
2449     current_vol = NULL;
2450
2451     return( AFP_OK );
2452 }
2453
2454 /* ------------------------- */
2455 struct vol *getvolbyvid(const u_int16_t vid )
2456 {
2457     struct vol  *vol;
2458
2459     for ( vol = Volumes; vol; vol = vol->v_next ) {
2460         if ( vid == vol->v_vid ) {
2461             break;
2462         }
2463     }
2464     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
2465         return( NULL );
2466     }
2467
2468 #ifdef FORCE_UIDGID
2469     set_uidgid ( vol );
2470 #endif /* FORCE_UIDGID */
2471
2472     current_vol = vol;
2473
2474     return( vol );
2475 }
2476
2477 /* ------------------------ */
2478 static int ext_cmp_key(const void *key, const void *obj)
2479 {
2480     const char          *p = key;
2481     const struct extmap *em = obj;
2482     return strdiacasecmp(p, em->em_ext);
2483 }
2484 struct extmap *getextmap(const char *path)
2485 {
2486     char      *p;
2487     struct extmap *em;
2488
2489     if (!Extmap_cnt || NULL == ( p = strrchr( path, '.' )) ) {
2490         return( Defextmap );
2491     }
2492     p++;
2493     if (!*p) {
2494         return( Defextmap );
2495     }
2496     em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
2497     if (em) {
2498         return( em );
2499     } else {
2500         return( Defextmap );
2501     }
2502 }
2503
2504 /* ------------------------- */
2505 struct extmap *getdefextmap(void)
2506 {
2507     return( Defextmap );
2508 }
2509
2510 /* --------------------------
2511    poll if a volume is changed by other processes.
2512    return
2513    0 no attention msg sent
2514    1 attention msg sent
2515    -1 error (socket closed)
2516
2517    Note: if attention return -1 no packet has been
2518    sent because the buffer is full, we don't care
2519    either there's no reader or there's a lot of
2520    traffic and another pollvoltime will follow
2521 */
2522 int  pollvoltime(AFPObj *obj)
2523
2524 {
2525     struct vol       *vol;
2526     struct timeval   tv;
2527     struct stat      st;
2528
2529     if (!(afp_version > 21 && obj->options.server_notif))
2530         return 0;
2531
2532     if ( gettimeofday( &tv, NULL ) < 0 )
2533         return 0;
2534
2535     for ( vol = Volumes; vol; vol = vol->v_next ) {
2536         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
2537             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
2538                 vol->v_mtime = st.st_mtime;
2539                 if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
2540                     return -1;
2541                 return 1;
2542             }
2543         }
2544     }
2545     return 0;
2546 }
2547
2548 /* ------------------------- */
2549 void setvoltime(AFPObj *obj, struct vol *vol)
2550 {
2551     struct timeval  tv;
2552
2553     if ( gettimeofday( &tv, NULL ) < 0 ) {
2554         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
2555         return;
2556     }
2557     if( utime( vol->v_path, NULL ) < 0 ) {
2558         /* write of time failed ... probably a read only filesys,
2559          * where no other users can interfere, so there's no issue here
2560          */
2561     }
2562
2563     /* a little granularity */
2564     if (vol->v_mtime < tv.tv_sec) {
2565         vol->v_mtime = tv.tv_sec;
2566         /* or finder doesn't update free space
2567          * AFP 3.2 and above clients seem to be ok without so many notification
2568          */
2569         if (afp_version < 32 && obj->options.server_notif) {
2570             obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
2571         }
2572     }
2573 }
2574
2575 /* ------------------------- */
2576 int afp_getvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_,char *rbuf, size_t *rbuflen)
2577 {
2578     struct vol  *vol;
2579     u_int16_t   vid, bitmap;
2580
2581     ibuf += 2;
2582     memcpy(&vid, ibuf, sizeof( vid ));
2583     ibuf += sizeof( vid );
2584     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2585     bitmap = ntohs( bitmap );
2586
2587     if (NULL == ( vol = getvolbyvid( vid )) ) {
2588         *rbuflen = 0;
2589         return( AFPERR_PARAM );
2590     }
2591
2592     return stat_vol(bitmap, vol, rbuf, rbuflen);
2593 }
2594
2595 /* ------------------------- */
2596 int afp_setvolparams(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_,  size_t *rbuflen)
2597 {
2598     struct adouble ad;
2599     struct vol  *vol;
2600     u_int16_t   vid, bitmap;
2601     u_int32_t   aint;
2602
2603     ibuf += 2;
2604     *rbuflen = 0;
2605
2606     memcpy(&vid, ibuf, sizeof( vid ));
2607     ibuf += sizeof( vid );
2608     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2609     bitmap = ntohs( bitmap );
2610     ibuf += sizeof(bitmap);
2611
2612     if (( vol = getvolbyvid( vid )) == NULL ) {
2613         return( AFPERR_PARAM );
2614     }
2615
2616     if ((vol->v_flags & AFPVOL_RO))
2617         return AFPERR_VLOCK;
2618
2619     /* we can only set the backup date. */
2620     if (bitmap != (1 << VOLPBIT_BDATE))
2621         return AFPERR_BITMAP;
2622
2623     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2624     if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
2625                   0666, &ad) < 0 ) {
2626         if (errno == EROFS)
2627             return AFPERR_VLOCK;
2628
2629         return AFPERR_ACCESS;
2630     }
2631
2632     memcpy(&aint, ibuf, sizeof(aint));
2633     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2634     ad_flush(&ad);
2635     ad_close(&ad, ADFLAGS_HF);
2636     return( AFP_OK );
2637 }
2638
2639 /* ------------------------- */
2640 int wincheck(const struct vol *vol, const char *path)
2641 {
2642     int len;
2643
2644     if (!(vol->v_flags & AFPVOL_MSWINDOWS))
2645         return 1;
2646
2647     /* empty paths are not allowed */
2648     if ((len = strlen(path)) == 0)
2649         return 0;
2650
2651     /* leading or trailing whitespaces are not allowed, carriage returns
2652      * and probably other whitespace is okay, tabs are not allowed
2653      */
2654     if ((path[0] == ' ') || (path[len-1] == ' '))
2655         return 0;
2656
2657     /* certain characters are not allowed */
2658     if (strpbrk(path, MSWINDOWS_BADCHARS))
2659         return 0;
2660
2661     /* everything else is okay */
2662     return 1;
2663 }
2664
2665
2666 /*
2667  * precreate a folder
2668  * this is only intended for folders in the volume root
2669  * It will *not* work if the folder name contains extended characters
2670  */
2671 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2672 {
2673     char        *p,*q,*r;
2674     struct adouble  ad;
2675     u_int16_t   attr;
2676     struct stat st;
2677     int     ret;
2678
2679
2680     p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2681     if ( p == NULL) {
2682         LOG(log_error, logtype_afpd,"malloc failed");
2683         exit (EXITERR_SYS);
2684     }
2685
2686     q=strdup(folder->name);
2687     if ( q == NULL) {
2688         LOG(log_error, logtype_afpd,"malloc failed");
2689         exit (EXITERR_SYS);
2690     }
2691
2692     strcpy(p, vol->v_path);
2693     strcat(p, "/");
2694
2695     r=q;
2696     while (*r) {
2697         if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2698             *r=toupper(*r);
2699         else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2700             *r=tolower(*r);
2701         r++;
2702     }
2703     strcat(p, q);
2704
2705     if ( (ret = stat( p, &st )) < 0 ) {
2706         if (folder->precreate) {
2707             if (ad_mkdir(p, folder->mode)) {
2708                 LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2709                 free(p);
2710                 free(q);
2711                 return -1;
2712             }
2713             ret = 0;
2714         }
2715     }
2716
2717     if ( !ret && folder->hide) {
2718         /* Hide it */
2719         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2720         if (ad_open_metadata( p, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
2721             free (p);
2722             free(q);
2723             return (-1);
2724         }
2725
2726         ad_setname(&ad, folder->name);
2727
2728         ad_getattr(&ad, &attr);
2729         attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2730         ad_setattr(&ad, attr);
2731
2732         /* do the same with the finder info */
2733         if (ad_entry(&ad, ADEID_FINDERI)) {
2734             memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2735             attr   |= htons(FINDERINFO_INVISIBLE);
2736             memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2737         }
2738
2739         ad_flush( &ad );
2740         ad_close_metadata( &ad);
2741     }
2742     free(p);
2743     free(q);
2744     return 0;
2745 }
2746
2747 static void handle_special_folders (const struct vol * vol)
2748 {
2749     const _special_folder *p = &special_folders[0];
2750     uid_t process_uid;
2751
2752     process_uid = geteuid();
2753     if (process_uid) {
2754         if (seteuid(0) == -1) {
2755             process_uid = 0;
2756         }
2757     }
2758
2759     for (; p->name != NULL; p++) {
2760         create_special_folder (vol, p);
2761     }
2762
2763     if (process_uid) {
2764         if (seteuid(process_uid) == -1) {
2765             LOG(log_error, logtype_logger, "can't seteuid back %s", strerror(errno));
2766             exit(EXITERR_SYS);
2767         }
2768     }
2769 }
2770
2771 const struct vol *getvolumes(void)
2772 {
2773     return Volumes;
2774 }
2775
2776 void unload_volumes_and_extmap(void)
2777 {
2778     LOG(log_debug, logtype_afpd, "unload_volumes_and_extmap");
2779     free_extmap();
2780     free_volumes();
2781 }
2782
2783 /* 
2784  * Get a volumes UUID from the config file.
2785  * If there is none, it is generated and stored there.
2786  *
2787  * Returns pointer to allocated storage on success, NULL on error.
2788  */
2789 static char *get_vol_uuid(const AFPObj *obj, const char *volname)
2790 {
2791     char *volname_conf;
2792     char buf[1024], uuid[UUID_PRINTABLE_STRING_LENGTH], *p;
2793     FILE *fp;
2794     struct stat tmpstat;
2795     int fd;
2796     
2797     if ((fp = fopen(obj->options.uuidconf, "r")) != NULL) {  /* read open? */
2798         /* scan in the conf file */
2799         while (fgets(buf, sizeof(buf), fp) != NULL) { 
2800             p = buf;
2801             while (p && isblank(*p))
2802                 p++;
2803             if (!p || (*p == '#') || (*p == '\n'))
2804                 continue;                             /* invalid line */
2805             if (*p == '"') {
2806                 p++;
2807                 if ((volname_conf = strtok( p, "\"" )) == NULL)
2808                     continue;                         /* syntax error */
2809             } else {
2810                 if ((volname_conf = strtok( p, " \t" )) == NULL)
2811                     continue;                         /* syntax error: invalid name */
2812             }
2813             p = strchr(p, '\0');
2814             p++;
2815             if (*p == '\0')
2816                 continue;                             /* syntax error */
2817             
2818             if (strcmp(volname, volname_conf) != 0)
2819                 continue;                             /* another volume name */
2820                 
2821             while (p && isblank(*p))
2822                 p++;
2823
2824             if (sscanf(p, "%36s", uuid) == 1 ) {
2825                 for (int i=0; uuid[i]; i++)
2826                     uuid[i] = toupper(uuid[i]);
2827                 LOG(log_debug, logtype_afpd, "get_uuid('%s'): UUID: '%s'", volname, uuid);
2828                 fclose(fp);
2829                 return strdup(uuid);
2830             }
2831         }
2832     }
2833
2834     if (fp)
2835         fclose(fp);
2836
2837     /*  not found or no file, reopen in append mode */
2838
2839     if (stat(obj->options.uuidconf, &tmpstat)) {                /* no file */
2840         if (( fd = creat(obj->options.uuidconf, 0644 )) < 0 ) {
2841             LOG(log_error, logtype_afpd, "ERROR: Cannot create %s (%s).",
2842                 obj->options.uuidconf, strerror(errno));
2843             return NULL;
2844         }
2845         if (( fp = fdopen( fd, "w" )) == NULL ) {
2846             LOG(log_error, logtype_afpd, "ERROR: Cannot fdopen %s (%s).",
2847                 obj->options.uuidconf, strerror(errno));
2848             close(fd);
2849             return NULL;
2850         }
2851     } else if ((fp = fopen(obj->options.uuidconf, "a+")) == NULL) { /* not found */
2852         LOG(log_error, logtype_afpd, "Cannot create or append to %s (%s).",
2853             obj->options.uuidconf, strerror(errno));
2854         return NULL;
2855     }
2856     fseek(fp, 0L, SEEK_END);
2857     if(ftell(fp) == 0) {                     /* size = 0 */
2858         fprintf(fp, "# DON'T TOUCH NOR COPY THOUGHTLESSLY!\n");
2859         fprintf(fp, "# This file is auto-generated by afpd\n");
2860         fprintf(fp, "# and stores UUIDs for TM volumes.\n\n");
2861     } else {
2862         fseek(fp, -1L, SEEK_END);
2863         if(fgetc(fp) != '\n') fputc('\n', fp); /* last char is \n? */
2864     }                    
2865     
2866     /* generate uuid and write to file */
2867     atalk_uuid_t id;
2868     const char *cp;
2869     randombytes((void *)id, 16);
2870     cp = uuid_bin2string(id);
2871
2872     LOG(log_debug, logtype_afpd, "get_uuid('%s'): generated UUID '%s'", volname, cp);
2873
2874     fprintf(fp, "\"%s\"\t%36s\n", volname, cp);
2875     fclose(fp);
2876     
2877     return strdup(cp);
2878 }