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