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