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