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