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