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