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