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