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