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