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