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