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