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