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