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