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