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