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