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