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