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