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