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