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