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