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