]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/volume.c
a6d3cdb9e3ed2898c29e7db549c4981b7ef23f8d
[netatalk.git] / etc / afpd / volume.c
1 /*
2  * $Id: volume.c,v 1.51.2.7.2.33.2.7 2005-06-02 12:49:41 didg Exp $
3  *
4  * Copyright (c) 1990,1993 Regents of The University of Michigan.
5  * All Rights Reserved.  See COPYRIGHT.
6  */
7
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #endif /* HAVE_CONFIG_H */
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <dirent.h>
16 #include <pwd.h>
17 #include <grp.h>
18 #include <utime.h>
19 #include <errno.h>
20 #ifdef HAVE_STRINGS_H
21 #include <strings.h>
22 #endif
23 /* STDC check */
24 #if STDC_HEADERS
25 #include <string.h>
26 #else /* STDC_HEADERS */
27 #ifndef HAVE_STRCHR
28 #define strchr index
29 #define strrchr index
30 #endif /* HAVE_STRCHR */
31 char *strchr (), *strrchr ();
32 #ifndef HAVE_MEMCPY
33 #define memcpy(d,s,n) bcopy ((s), (d), (n))
34 #define memmove(d,s,n) bcopy ((s), (d), (n))
35 #endif /* ! HAVE_MEMCPY */
36 #endif /* STDC_HEADERS */
37 #include <sys/param.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <atalk/asp.h>
42 #include <atalk/dsi.h>
43 #include <atalk/adouble.h>
44 #include <atalk/afp.h>
45 #include <atalk/util.h>
46 #include <atalk/logger.h>
47 #ifdef CNID_DB
48 #include <atalk/cnid.h>
49 #endif /* CNID_DB*/
50
51 #include "globals.h"
52 #include "directory.h"
53 #include "file.h"
54 #include "volume.h"
55 #include "unix.h"
56
57 extern int afprun(int root, char *cmd, int *outfd);
58
59 #ifndef MIN
60 #define MIN(a, b) ((a) < (b) ? (a) : (b))
61 #endif /* ! MIN */
62
63 #ifndef NO_LARGE_VOL_SUPPORT
64 #if BYTE_ORDER == BIG_ENDIAN
65 #define hton64(x)       (x)
66 #define ntoh64(x)       (x)
67 #else /* BYTE_ORDER == BIG_ENDIAN */
68 #define hton64(x)       ((u_int64_t) (htonl(((x) >> 32) & 0xffffffffLL)) | \
69                          (u_int64_t) ((htonl(x) & 0xffffffffLL) << 32))
70 #define ntoh64(x)       (hton64(x))
71 #endif /* BYTE_ORDER == BIG_ENDIAN */
72 #endif /* ! NO_LARGE_VOL_SUPPORT */
73
74 static struct vol *Volumes = NULL;
75 static u_int16_t        lastvid = 0;
76 static char             *Trash = "\02\024Network Trash Folder";
77
78 static struct extmap    *Extmap = NULL, *Defextmap = NULL;
79 static int              Extmap_cnt;
80 static void             free_extmap(void);
81
82 #define VOLOPT_ALLOW      0  /* user allow list */
83 #define VOLOPT_DENY       1  /* user deny list */
84 #define VOLOPT_RWLIST     2  /* user rw list */
85 #define VOLOPT_ROLIST     3  /* user ro list */
86 #define VOLOPT_PASSWORD   4  /* volume password */
87 #define VOLOPT_CASEFOLD   5  /* character case mangling */
88 #define VOLOPT_FLAGS      6  /* various flags */
89 #define VOLOPT_DBPATH     7  /* path to database */
90 #define VOLOPT_MAPCHARS   8  /* does mtou and utom mappings. syntax:
91 m and u can be double-byte hex
92 strings if necessary.
93 m=u -> map both ways
94   m>u -> map m to u
95   m<u -> map u to m
96   !u  -> make u illegal always
97   ~u  -> make u illegal only as the first
98   part of a double-byte character.
99   */
100 #define VOLOPT_VETO          10  /* list of veto filespec */
101 #define VOLOPT_PREEXEC       11  /* preexec command */
102 #define VOLOPT_ROOTPREEXEC   12  /* root preexec command */
103
104 #define VOLOPT_POSTEXEC      13  /* postexec command */
105 #define VOLOPT_ROOTPOSTEXEC  14  /* root postexec command */
106
107 #define VOLOPT_ENCODING      15  /* mac encoding (pre OSX)*/
108 #define VOLOPT_MACCHARSET    16
109 #define VOLOPT_CNIDSCHEME    17
110 #define VOLOPT_ADOUBLE       18  /* adouble version */
111 #ifdef FORCE_UIDGID
112 #warning UIDGID
113 #include "uid.h"
114
115 #define VOLOPT_FORCEUID  19  /* force uid for username x */
116 #define VOLOPT_FORCEGID  20  /* force gid for group x */
117 #define VOLOPT_UMASK     21
118 #define VOLOPT_DFLTPERM  22
119 #else 
120 #define VOLOPT_UMASK     19
121 #define VOLOPT_DFLTPERM  20
122 #endif /* FORCE_UIDGID */
123
124 #define VOLOPT_MAX       (VOLOPT_DFLTPERM +1)
125
126 #define VOLOPT_NUM        (VOLOPT_MAX + 1)
127
128 #define VOLPASSLEN  8
129 #define VOLOPT_DEFAULT     ":DEFAULT:"
130 #define VOLOPT_DEFAULT_LEN 9
131   struct vol_option {
132       char *c_value;
133       int i_value;
134   };
135
136 typedef struct _special_folder {
137         const char *name;
138         int precreate;
139         mode_t mode;
140         int hide;
141 } _special_folder;
142
143 static const _special_folder special_folders[] = {
144   {"Network Trash Folder",     1,  0777,  1},
145   {"Temporary Items",          1,  0777,  1},
146   {".AppleDesktop",            1,  0777,  0},
147 #if 0
148   {"TheFindByContentFolder",   0,     0,  1},
149   {"TheVolumeSettingsFolder",  0,     0,  1},
150 #endif
151   {NULL, 0, 0, 0}};
152
153 typedef struct _volopt_name {
154         const u_int32_t option;
155         const char      *name;
156 } _vol_opt_name;
157
158 static const _vol_opt_name vol_opt_names[] = {
159     {AFPVOL_A2VOL,      "PRODOS"},      /* prodos volume */
160     {AFPVOL_CRLF,       "CRLF"},        /* cr/lf translation */
161     {AFPVOL_NOADOUBLE,  "NOADOUBLE"},   /* don't create .AppleDouble by default */
162     {AFPVOL_RO,         "READONLY"},    /* read-only volume */
163     {AFPVOL_MSWINDOWS,  "MSWINDOWS"},   /* deal with ms-windows yuckiness. this is going away. */
164     {AFPVOL_NOHEX,      "NOHEX"},       /* don't do :hex translation */
165     {AFPVOL_USEDOTS,    "USEDOTS"},     /* use real dots */
166     {AFPVOL_LIMITSIZE,  "LIMITSIZE"},   /* limit size for older macs */
167     {AFPVOL_MAPASCII,   "MAPASCII"},    /* map the ascii range as well */
168     {AFPVOL_DROPBOX,    "DROPBOX"},     /* dropkludge dropbox support */
169     {AFPVOL_NOFILEID,   "NOFILEID"},    /* don't advertise createid resolveid and deleteid calls */
170     {AFPVOL_NOSTAT,     "NOSTAT"},      /* advertise the volume even if we can't stat() it
171                                          * maybe because it will be mounted later in preexec */
172     {AFPVOL_UNIX_PRIV,  "UNIXPRIV"},    /* support unix privileges */
173     {AFPVOL_NODEV,      "NODEV"},       /* always use 0 for device number in cnid calls */
174     {0, NULL}
175 };
176
177 static const _vol_opt_name vol_opt_casefold[] = {
178     {AFPVOL_MTOUUPPER,  "MTOULOWER"},
179     {AFPVOL_MTOULOWER,  "MTOULOWER"},
180     {AFPVOL_UTOMUPPER,  "UTOMUPPER"},
181     {AFPVOL_UTOMLOWER,  "UTOMLOWER"},
182     {0, NULL}
183 };
184
185 static void handle_special_folders (const struct vol *);
186 static int savevoloptions (const struct vol *);
187
188 static __inline__ void volfree(struct vol_option *options,
189                                const struct vol_option *save)
190 {
191     int i;
192
193     if (save) {
194         for (i = 0; i < VOLOPT_MAX; i++) {
195             if (options[i].c_value && (options[i].c_value != save[i].c_value))
196                 free(options[i].c_value);
197         }
198     } else {
199         for (i = 0; i < VOLOPT_MAX; i++) {
200             if (options[i].c_value)
201                 free(options[i].c_value);
202         }
203     }
204 }
205
206
207 /* handle variable substitutions. here's what we understand:
208  * $b   -> basename of path
209  * $c   -> client ip/appletalk address
210  * $d   -> volume pathname on server
211  * $f   -> full name (whatever's in the gecos field)
212  * $g   -> group
213  * $h   -> hostname 
214  * $i   -> client ip/appletalk address without port
215  * $s   -> server name (hostname if it doesn't exist)
216  * $u   -> username (guest is usually nobody)
217  * $v   -> volume name or basename if null
218  * $z   -> zone (may not exist)
219  * $$   -> $
220  *
221  *
222  */
223 #define is_var(a, b) (strncmp((a), (b), 2) == 0)
224
225 static char *volxlate(AFPObj *obj, char *dest, size_t destlen,
226                      char *src, struct passwd *pwd, char *path, char *volname)
227 {
228     char *p, *q;
229     int len;
230     char *ret;
231     
232     if (!src) {
233         return NULL;
234     }
235     if (!dest) {
236         dest = calloc(destlen +1, 1);
237     }
238     ret = dest;
239     if (!ret) {
240         return NULL;
241     }
242     strlcpy(dest, src, destlen +1);
243     if ((p = strchr(src, '$')) == NULL) /* nothing to do */
244         return ret;
245
246     /* first part of the path. just forward to the next variable. */
247     len = MIN(p - src, destlen);
248     if (len > 0) {
249         destlen -= len;
250         dest += len;
251     }
252
253     while (p && destlen > 0) {
254         /* now figure out what the variable is */
255         q = NULL;
256         if (is_var(p, "$b")) {
257             if (path) {
258                 if ((q = strrchr(path, '/')) == NULL)
259                     q = path;
260                 else if (*(q + 1) != '\0')
261                     q++;
262             }
263         } else if (is_var(p, "$c")) {
264             if (obj->proto == AFPPROTO_ASP) {
265                 ASP asp = obj->handle;
266
267                 len = sprintf(dest, "%u.%u", ntohs(asp->asp_sat.sat_addr.s_net),
268                               asp->asp_sat.sat_addr.s_node);
269                 dest += len;
270                 destlen -= len;
271
272             } else if (obj->proto == AFPPROTO_DSI) {
273                 DSI *dsi = obj->handle;
274
275                 len = sprintf(dest, "%s:%u", inet_ntoa(dsi->client.sin_addr),
276                               ntohs(dsi->client.sin_port));
277                 dest += len;
278                 destlen -= len;
279             }
280         } else if (is_var(p, "$d")) {
281              q = path;
282         } else if (is_var(p, "$f")) {
283             if ((q = strchr(pwd->pw_gecos, ',')))
284                 *q = '\0';
285             q = pwd->pw_gecos;
286         } else if (is_var(p, "$g")) {
287             struct group *grp = getgrgid(pwd->pw_gid);
288             if (grp)
289                 q = grp->gr_name;
290         } else if (is_var(p, "$h")) {
291             q = obj->options.hostname;
292         } else if (is_var(p, "$i")) {
293             if (obj->proto == AFPPROTO_ASP) {
294                 ASP asp = obj->handle;
295  
296                 len = sprintf(dest, "%u", ntohs(asp->asp_sat.sat_addr.s_net));
297                 dest += len;
298                 destlen -= len;
299  
300             } else if (obj->proto == AFPPROTO_DSI) {
301                 DSI *dsi = obj->handle;
302  
303                 q = inet_ntoa(dsi->client.sin_addr);
304             }
305         } else if (is_var(p, "$s")) {
306             if (obj->Obj)
307                 q = obj->Obj;
308             else if (obj->options.server) {
309                 q = obj->options.server;
310             } else
311                 q = obj->options.hostname;
312         } else if (is_var(p, "$u")) {
313             q = obj->username;
314         } else if (is_var(p, "$v")) {
315             if (volname) {
316                 q = volname;
317             }
318             else if (path) {
319                 if ((q = strrchr(path, '/')) == NULL)
320                     q = path;
321                 else if (*(q + 1) != '\0')
322                     q++;
323             }
324         } else if (is_var(p, "$z")) {
325             q = obj->Zone;
326         } else if (is_var(p, "$$")) {
327             q = "$";
328         } else
329             q = p;
330
331         /* copy the stuff over. if we don't understand something that we
332          * should, just skip it over. */
333         if (q) {
334             len = MIN(p == q ? 2 : strlen(q), destlen);
335             strncpy(dest, q, len);
336             dest += len;
337             destlen -= len;
338         }
339
340         /* stuff up to next $ */
341         src = p + 2;
342         p = strchr(src, '$');
343         len = p ? MIN(p - src, destlen) : destlen;
344         if (len > 0) {
345             strncpy(dest, src, len);
346             dest += len;
347             destlen -= len;
348         }
349     }
350     return ret;
351 }
352
353 /* to make sure that val is valid, make sure to select an opt that
354    includes val */
355 static int optionok(const char *buf, const char *opt, const char *val) 
356 {
357     if (!strstr(buf,opt))
358         return 0;
359     if (!val[1])
360         return 0;
361     return 1;    
362 }
363
364
365 /* -------------------- */
366 static void setoption(struct vol_option *options, struct vol_option *save, int opt, const char *val)
367 {
368     if (options[opt].c_value && (!save || options[opt].c_value != save[opt].c_value))
369         free(options[opt].c_value);
370     options[opt].c_value = strdup(val + 1);
371 }
372
373 /* ------------------------------------------
374    handle all the options. tmp can't be NULL. */
375 static void volset(struct vol_option *options, struct vol_option *save, 
376                    char *volname, int vlen,
377                    const char *tmp)
378 {
379     char *val;
380
381     val = strchr(tmp, ':');
382     if (!val) {
383         /* we'll assume it's a volume name. */
384         strncpy(volname, tmp, vlen);
385         volname[vlen] = 0;
386         return;
387     }
388 #if 0
389     LOG(log_debug, logtype_afpd, "Parsing volset %s", val);
390 #endif
391     if (optionok(tmp, "allow:", val)) {
392         setoption(options, save, VOLOPT_ALLOW, val);
393
394     } else if (optionok(tmp, "deny:", val)) {
395         setoption(options, save, VOLOPT_DENY, val);
396
397     } else if (optionok(tmp, "rwlist:", val)) {
398         setoption(options, save, VOLOPT_RWLIST, val);
399
400     } else if (optionok(tmp, "rolist:", val)) {
401         setoption(options, save, VOLOPT_ROLIST, val);
402
403     } else if (optionok(tmp, "codepage:", val)) {
404         LOG (log_error, logtype_afpd, "The old codepage system has been removed. Please make sure to read the documentation !!!!");
405         /* Make sure we don't screw anything */
406         exit (EXITERR_CONF);
407     } else if (optionok(tmp, "volcharset:", val)) {
408         setoption(options, save, VOLOPT_ENCODING, val);
409     } else if (optionok(tmp, "maccharset:", val)) {
410         setoption(options, save, VOLOPT_MACCHARSET, val);
411     } else if (optionok(tmp, "veto:", val)) {
412         setoption(options, save, VOLOPT_VETO, val);
413     } else if (optionok(tmp, "cnidscheme:", val)) {
414         setoption(options, save, VOLOPT_CNIDSCHEME, val);
415     } else if (optionok(tmp, "casefold:", val)) {
416         if (strcasecmp(val + 1, "tolower") == 0)
417             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMLOWER;
418         else if (strcasecmp(val + 1, "toupper") == 0)
419             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UMUPPER;
420         else if (strcasecmp(val + 1, "xlatelower") == 0)
421             options[VOLOPT_CASEFOLD].i_value = AFPVOL_UUPPERMLOWER;
422         else if (strcasecmp(val + 1, "xlateupper") == 0)
423             options[VOLOPT_CASEFOLD].i_value = AFPVOL_ULOWERMUPPER;
424     } else if (optionok(tmp, "adouble:", val)) {
425         if (strcasecmp(val + 1, "v1") == 0)
426             options[VOLOPT_ADOUBLE].i_value = AD_VERSION1;
427 #if AD_VERSION == AD_VERSION2            
428         else if (strcasecmp(val + 1, "v2") == 0)
429             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2;
430         else if (strcasecmp(val + 1, "osx") == 0)
431             options[VOLOPT_ADOUBLE].i_value = AD_VERSION2_OSX;
432 #endif
433     } else if (optionok(tmp, "options:", val)) {
434         char *p;
435
436         if ((p = strtok(val + 1, ",")) == NULL) /* nothing */
437             return;
438
439         while (p) {
440             if (strcasecmp(p, "prodos") == 0)
441                 options[VOLOPT_FLAGS].i_value |= AFPVOL_A2VOL;
442             else if (strcasecmp(p, "mswindows") == 0) {
443                 options[VOLOPT_FLAGS].i_value |= AFPVOL_MSWINDOWS | AFPVOL_USEDOTS;
444             } else if (strcasecmp(p, "crlf") == 0)
445                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CRLF;
446             else if (strcasecmp(p, "noadouble") == 0)
447                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOADOUBLE;
448             else if (strcasecmp(p, "ro") == 0)
449                 options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
450             else if (strcasecmp(p, "nohex") == 0)
451                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOHEX;
452             else if (strcasecmp(p, "usedots") == 0)
453                 options[VOLOPT_FLAGS].i_value |= AFPVOL_USEDOTS;
454             else if (strcasecmp(p, "limitsize") == 0)
455                 options[VOLOPT_FLAGS].i_value |= AFPVOL_LIMITSIZE;
456             /* support for either "dropbox" or "dropkludge" */
457             else if (strcasecmp(p, "dropbox") == 0)
458                 options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
459             else if (strcasecmp(p, "dropkludge") == 0)
460                 options[VOLOPT_FLAGS].i_value |= AFPVOL_DROPBOX;
461             else if (strcasecmp(p, "nofileid") == 0)
462                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOFILEID;
463             else if (strcasecmp(p, "nostat") == 0)
464                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NOSTAT;
465             else if (strcasecmp(p, "preexec_close") == 0)
466                 options[VOLOPT_PREEXEC].i_value = 1;
467             else if (strcasecmp(p, "root_preexec_close") == 0)
468                 options[VOLOPT_ROOTPREEXEC].i_value = 1;
469             else if (strcasecmp(p, "upriv") == 0)
470                 options[VOLOPT_FLAGS].i_value |= AFPVOL_UNIX_PRIV;
471             else if (strcasecmp(p, "nodev") == 0)
472                 options[VOLOPT_FLAGS].i_value |= AFPVOL_NODEV;
473             else if (strcasecmp(p, "cachecnid") == 0)
474                 options[VOLOPT_FLAGS].i_value |= AFPVOL_CACHE;
475
476             p = strtok(NULL, ",");
477         }
478
479     } else if (optionok(tmp, "dbpath:", val)) {
480         setoption(options, save, VOLOPT_DBPATH, val);
481
482     } else if (optionok(tmp, "umask:", val)) {
483         options[VOLOPT_UMASK].i_value = (int)strtol(val +1, NULL, 8);
484     } else if (optionok(tmp, "perm:", val)) {
485         options[VOLOPT_DFLTPERM].i_value = (int)strtol(val+1, NULL, 8);
486     } else if (optionok(tmp, "mapchars:",val)) {
487         setoption(options, save, VOLOPT_MAPCHARS, val);
488
489     } else if (optionok(tmp, "password:", val)) {
490         setoption(options, save, VOLOPT_PASSWORD, val);
491
492 #ifdef FORCE_UIDGID
493
494         /* this code allows forced uid/gid per volume settings */
495     } else if (optionok(tmp, "forceuid:", val)) {
496         setoption(options, save, VOLOPT_FORCEUID, val);
497     } else if (optionok(tmp, "forcegid:", val)) {
498         setoption(options, save, VOLOPT_FORCEGID, val);
499
500 #endif /* FORCE_UIDGID */
501     } else if (optionok(tmp, "root_preexec:", val)) {
502         setoption(options, save, VOLOPT_ROOTPREEXEC, val);
503
504     } else if (optionok(tmp, "preexec:", val)) {
505         setoption(options, save, VOLOPT_PREEXEC, val);
506
507     } else if (optionok(tmp, "root_postexec:", val)) {
508         setoption(options, save, VOLOPT_ROOTPOSTEXEC, val);
509
510     } else if (optionok(tmp, "postexec:", val)) {
511         setoption(options, save, VOLOPT_POSTEXEC, val);
512
513     } else {
514         /* ignore unknown options */
515         LOG(log_debug, logtype_afpd, "ignoring unknown volume option: %s", tmp);
516
517     } 
518 }
519
520 /* ----------------- */
521 static void showvol(const ucs2_t *name)
522 {
523     struct vol  *volume;
524     for ( volume = Volumes; volume; volume = volume->v_next ) {
525         if (volume->v_hide && !strcasecmp_w( volume->v_name, name ) ) {
526             volume->v_hide = 0;
527             return;
528         }
529     }
530 }
531
532 /* ----------------- 
533  * FIXME should be define elsewhere
534 */
535 static int validupath_adouble(const struct vol *vol, const char *name) 
536 {
537     return (vol->v_flags & AFPVOL_USEDOTS) ? strncasecmp(name,".Apple", 6) && strcasecmp(name, ".Parent")
538                                            : name[0] != '.';
539 }                                           
540
541 /* ----------------- */
542 static int validupath_osx(const struct vol *vol, const char *name) 
543 {
544     return strncasecmp(name,".Apple", 6) && strncasecmp(name,"._", 2);
545 }             
546
547 /* ---------------- */
548 static void initvoladouble(struct vol *vol)
549 {
550     if (vol->v_adouble == AD_VERSION2_OSX) {
551         vol->validupath  = validupath_osx;
552         vol->ad_path     = ad_path_osx;
553     }
554     else {
555         vol->validupath  = validupath_adouble;
556         vol->ad_path     = ad_path;
557     }
558 }
559
560 /* ------------------------------- */
561 static int creatvol(AFPObj *obj, struct passwd *pwd, 
562                     char *path, char *name, 
563                     struct vol_option *options, 
564                     const int user /* user defined volume */
565                     )
566 {
567     struct vol  *volume;
568     int         vlen;
569     int         hide = 0;
570     ucs2_t      tmpname[512];
571
572     if ( name == NULL || *name == '\0' ) {
573         if ((name = strrchr( path, '/' )) == NULL) {
574             return -1;  /* Obviously not a fully qualified path */
575         }
576
577         /* if you wish to share /, you need to specify a name. */
578         if (*++name == '\0')
579             return -1;
580     }
581
582     vlen = strlen( name );
583     if ( vlen > AFPVOL_NAMELEN ) {
584         vlen = AFPVOL_NAMELEN;
585         name[AFPVOL_NAMELEN] = '\0';
586     }
587
588     /* convert name to UCS2 first */
589     if ( 0 >= ( vlen = convert_string(obj->options.unixcharset, CH_UCS2, name, vlen, tmpname, 512)) )
590         return -1;
591
592     for ( volume = Volumes; volume; volume = volume->v_next ) {
593         if ( strcasecmp_w( volume->v_name, tmpname ) == 0 ) {
594            if (volume->v_deleted) {
595                hide = 1;
596            }
597            else {
598                return -1;       /* Won't be able to access it, anyway... */
599            }
600         }
601     }
602
603
604     if (!( volume = (struct vol *)calloc(1, sizeof( struct vol ))) ) {
605         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
606         return -1;
607     }
608     if ( NULL == ( volume->v_name = strdup_w(tmpname))) {
609         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
610         free(volume);
611         return -1;
612     }
613     if (!( volume->v_path = (char *)malloc( strlen( path ) + 1 )) ) {
614         LOG(log_error, logtype_afpd, "creatvol: malloc: %s", strerror(errno) );
615         free(volume->v_name);
616         free(volume);
617         return -1;
618     }
619     volume->v_hide = hide;
620     strcpy( volume->v_path, path );
621
622 #ifdef __svr4__
623     volume->v_qfd = -1;
624 #endif /* __svr4__ */
625     /* os X start at 1 and use network order ie. 1 2 3 */
626     volume->v_vid = ++lastvid;
627     volume->v_vid = htons(volume->v_vid);
628
629     /* handle options */
630     if (options) {
631         /* should we casefold? */
632         volume->v_casefold = options[VOLOPT_CASEFOLD].i_value;
633
634         /* shift in some flags */
635         volume->v_flags = options[VOLOPT_FLAGS].i_value;
636
637         volume->v_ad_options = 0;
638         if ((volume->v_flags & AFPVOL_NODEV))
639             volume->v_ad_options |= ADVOL_NODEV;
640         if ((volume->v_flags & AFPVOL_CACHE))
641             volume->v_ad_options |= ADVOL_CACHE;
642         if ((volume->v_flags & AFPVOL_UNIX_PRIV))
643             volume->v_ad_options |= ADVOL_UNIXPRIV;
644
645         if (options[VOLOPT_PASSWORD].c_value)
646             volume->v_password = strdup(options[VOLOPT_PASSWORD].c_value);
647
648         if (options[VOLOPT_VETO].c_value)
649             volume->v_veto = strdup(options[VOLOPT_VETO].c_value);
650
651         if (options[VOLOPT_ENCODING].c_value)
652             volume->v_volcodepage = strdup(options[VOLOPT_ENCODING].c_value);
653
654         if (options[VOLOPT_MACCHARSET].c_value)
655             volume->v_maccodepage = strdup(options[VOLOPT_MACCHARSET].c_value);
656
657         if (options[VOLOPT_DBPATH].c_value)
658             volume->v_dbpath = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_DBPATH].c_value, pwd, path, name);
659
660        if (options[VOLOPT_CNIDSCHEME].c_value)
661            volume->v_cnidscheme = strdup(options[VOLOPT_CNIDSCHEME].c_value);
662
663         if (options[VOLOPT_UMASK].i_value)
664             volume->v_umask = (mode_t)options[VOLOPT_UMASK].i_value;
665
666         if (options[VOLOPT_DFLTPERM].i_value)
667             volume->v_perm = (mode_t)options[VOLOPT_DFLTPERM].i_value;
668
669         if (options[VOLOPT_ADOUBLE].i_value)
670             volume->v_adouble = options[VOLOPT_ADOUBLE].i_value;
671         else 
672             volume->v_adouble = AD_VERSION;
673 #ifdef FORCE_UIDGID
674         if (options[VOLOPT_FORCEUID].c_value) {
675             volume->v_forceuid = strdup(options[VOLOPT_FORCEUID].c_value);
676         } else {
677             volume->v_forceuid = NULL; /* set as null so as to return 0 later on */
678         }
679
680         if (options[VOLOPT_FORCEGID].c_value) {
681             volume->v_forcegid = strdup(options[VOLOPT_FORCEGID].c_value);
682         } else {
683             volume->v_forcegid = NULL; /* set as null so as to return 0 later on */
684         }
685 #endif
686         if (!user) {
687             if (options[VOLOPT_PREEXEC].c_value)
688                 volume->v_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_PREEXEC].c_value, pwd, path, name);
689             volume->v_preexec_close = options[VOLOPT_PREEXEC].i_value;
690
691             if (options[VOLOPT_POSTEXEC].c_value)
692                 volume->v_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_POSTEXEC].c_value, pwd, path, name);
693
694             if (options[VOLOPT_ROOTPREEXEC].c_value)
695                 volume->v_root_preexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPREEXEC].c_value, pwd, path,  name);
696             volume->v_root_preexec_close = options[VOLOPT_ROOTPREEXEC].i_value;
697
698             if (options[VOLOPT_ROOTPOSTEXEC].c_value)
699                 volume->v_root_postexec = volxlate(obj, NULL, MAXPATHLEN, options[VOLOPT_ROOTPOSTEXEC].c_value, pwd, path,  name);
700         }
701     }
702
703     initvoladouble(volume);
704     volume->v_next = Volumes;
705     Volumes = volume;
706     return 0;
707 }
708
709 /* ---------------- */
710 static char *myfgets( buf, size, fp )
711 char    *buf;
712 int             size;
713 FILE    *fp;
714 {
715     char        *p;
716     int         c;
717
718     p = buf;
719     while ((EOF != ( c = getc( fp )) ) && ( size > 0 )) {
720         if ( c == '\n' || c == '\r' ) {
721             *p++ = '\n';
722             break;
723         } else {
724             *p++ = c;
725         }
726         size--;
727     }
728
729     if ( p == buf ) {
730         return( NULL );
731     } else {
732         *p = '\0';
733         return( buf );
734     }
735 }
736
737
738 /* check access list. this function wants something of the following
739  * form:
740  *        @group,name,name2,@group2,name3
741  *
742  * a NULL argument allows everybody to have access.
743  * we return three things:
744  *     -1: no list
745  *      0: list exists, but name isn't in it
746  *      1: in list
747  */
748
749 #ifndef NO_REAL_USER_NAME
750 /* authentication is case insensitive 
751  * FIXME should we do the same with group name?
752 */
753 #define access_strcmp strcasecmp
754
755 #else
756 #define access_strcmp strcmp
757
758 #endif
759
760 static int accessvol(args, name)
761 const char *args;
762 const char *name;
763 {
764     char buf[MAXPATHLEN + 1], *p;
765     struct group *gr;
766
767     if (!args)
768         return -1;
769
770     strlcpy(buf, args, sizeof(buf));
771     if ((p = strtok(buf, ",")) == NULL) /* nothing, return okay */
772         return -1;
773
774     while (p) {
775         if (*p == '@') { /* it's a group */
776             if ((gr = getgrnam(p + 1)) && gmem(gr->gr_gid))
777                 return 1;
778         } else if (access_strcmp(p, name) == 0) /* it's a user name */
779             return 1;
780         p = strtok(NULL, ",");
781     }
782
783     return 0;
784 }
785
786 static void setextmap( ext, type, creator, user)
787 char            *ext, *type, *creator;
788 int                     user;
789 {
790     struct extmap       *em;
791     int                 cnt;
792
793     if (Extmap == NULL) {
794         if (( Extmap = calloc(1, sizeof( struct extmap ))) == NULL ) {
795             LOG(log_error, logtype_afpd, "setextmap: calloc: %s", strerror(errno) );
796             return;
797         }
798     }
799     ext++;
800     for ( em = Extmap, cnt = 0; em->em_ext; em++, cnt++) {
801         if ( (strdiacasecmp( em->em_ext, ext )) == 0 ) {
802             break;
803         }
804     }
805
806     if ( em->em_ext == NULL ) {
807         if (!(Extmap  = realloc( Extmap, sizeof( struct extmap ) * (cnt +2))) ) {
808             LOG(log_error, logtype_afpd, "setextmap: realloc: %s", strerror(errno) );
809             return;
810         }
811         (Extmap +cnt +1)->em_ext = NULL;
812         em = Extmap +cnt;
813     } else if ( !user ) {
814         return;
815     }
816     if (em->em_ext)
817         free(em->em_ext);
818
819     if (!(em->em_ext = strdup(  ext))) {
820         LOG(log_error, logtype_afpd, "setextmap: strdup: %s", strerror(errno) );
821         return;
822     }
823
824     if ( *type == '\0' ) {
825         memcpy(em->em_type, "????", sizeof( em->em_type ));
826     } else {
827         memcpy(em->em_type, type, sizeof( em->em_type ));
828     }
829     if ( *creator == '\0' ) {
830         memcpy(em->em_creator, "UNIX", sizeof( em->em_creator ));
831     } else {
832         memcpy(em->em_creator, creator, sizeof( em->em_creator ));
833     }
834 }
835
836 /* -------------------------- */
837 static int extmap_cmp(const void *map1, const void *map2)
838 {
839     const struct extmap *em1 = map1;
840     const struct extmap *em2 = map2;
841     return strdiacasecmp(em1->em_ext, em2->em_ext);
842 }
843
844 static void sortextmap( void)
845 {
846     struct extmap       *em;
847
848     Extmap_cnt = 0;
849     if ((em = Extmap) == NULL) {
850         return;
851     }
852     while (em->em_ext) {
853         em++;
854         Extmap_cnt++;
855     }
856     if (Extmap_cnt) {
857         qsort(Extmap, Extmap_cnt, sizeof(struct extmap), extmap_cmp);
858         if (*Extmap->em_ext == 0) {
859             /* the first line is really "." the default entry, 
860              * we remove the leading '.' in setextmap
861             */
862             Defextmap = Extmap;
863         }
864     }
865 }
866
867 /* ----------------------
868 */
869 static void free_extmap( void)
870 {
871     struct extmap       *em;
872
873     if (Extmap) {
874         for ( em = Extmap; em->em_ext; em++) {
875              free (em->em_ext);
876         }
877         free(Extmap);
878         Extmap = NULL;
879         Defextmap = Extmap;
880         Extmap_cnt = 0;
881     }
882 }
883
884 /* ----------------------
885 */
886 static int volfile_changed(struct afp_volume_name *p) 
887 {
888     struct stat      st;
889     char *name;
890     
891     if (p->full_name) 
892         name = p->full_name;
893     else
894         name = p->name;
895         
896     if (!stat( name, &st) && st.st_mtime > p->mtime) {
897         p->mtime = st.st_mtime;
898         return 1;
899     }
900     return 0;
901 }
902
903 /* ----------------------
904  * Read a volume configuration file and add the volumes contained within to
905  * the global volume list.  If p2 is non-NULL, the file that is opened is
906  * p1/p2
907  * 
908  * Lines that begin with # and blank lines are ignored.
909  * Volume lines are of the form:
910  *              <unix path> [<volume name>] [allow:<user>,<@group>,...] \
911  *                           [codepage:<file>] [casefold:<num>]
912  *              <extension> TYPE [CREATOR]
913  */
914 static int readvolfile(obj, p1, p2, user, pwent)
915 AFPObj      *obj;
916 struct afp_volume_name  *p1;
917 char        *p2;
918 int             user;
919 struct passwd *pwent;
920 {
921     FILE                *fp;
922     char                path[ MAXPATHLEN + 1], tmp[ MAXPATHLEN + 1],
923     volname[ AFPVOL_NAMELEN + 1 ], buf[ BUFSIZ ],
924     type[ 5 ], creator[ 5 ];
925     char                *u, *p;
926     struct passwd       *pw;
927     struct vol_option   options[VOLOPT_NUM], save_options[VOLOPT_NUM];
928     int                 i;
929     struct stat         st;
930     int                 fd;
931
932     if (!p1->name)
933         return -1;
934     p1->mtime = 0;
935     strcpy( path, p1->name );
936     if ( p2 != NULL ) {
937         strcat( path, "/" );
938         strcat( path, p2 );
939         if (p1->full_name) {
940             free(p1->full_name);
941         }
942         p1->full_name = strdup(path);
943     }
944
945     if (NULL == ( fp = fopen( path, "r" )) ) {
946         return( -1 );
947     }
948     fd = fileno(fp);
949     if (fd != -1 && !fstat( fd, &st) ) {
950         p1->mtime = st.st_mtime;
951     }
952
953     memset(save_options, 0, sizeof(save_options));
954     while ( myfgets( buf, sizeof( buf ), fp ) != NULL ) {
955         initline( strlen( buf ), buf );
956         parseline( sizeof( path ) - 1, path );
957         switch ( *path ) {
958         case '\0' :
959         case '#' :
960             continue;
961
962         case ':':
963             /* change the default options for this file */
964             if (strncmp(path, VOLOPT_DEFAULT, VOLOPT_DEFAULT_LEN) == 0) {
965                 *tmp = '\0';
966                 for (i = 0; i < VOLOPT_NUM; i++) {
967                     if (parseline( sizeof( path ) - VOLOPT_DEFAULT_LEN - 1,
968                                    path + VOLOPT_DEFAULT_LEN) < 0)
969                         break;
970                     volset(save_options, NULL, tmp, sizeof(tmp) - 1,
971                            path + VOLOPT_DEFAULT_LEN);
972                 }
973             }
974             break;
975
976         case '~' :
977             if (( p = strchr( path, '/' )) != NULL ) {
978                 *p++ = '\0';
979             }
980             u = path;
981             u++;
982             if ( *u == '\0' ) {
983                 u = obj->username;
984             }
985             if ( u == NULL || *u == '\0' || ( pw = getpwnam( u )) == NULL ) {
986                 continue;
987             }
988             strcpy( tmp, pw->pw_dir );
989             if ( p != NULL && *p != '\0' ) {
990                 strcat( tmp, "/" );
991                 strcat( tmp, p );
992             }
993             /* Tag a user's home directory with their umask.  Note, this will
994              * be overwritten if the user actually specifies a umask: option
995              * for a '~' volume. */
996             save_options[VOLOPT_UMASK].i_value = obj->options.save_mask;
997             /* fall through */
998
999         case '/' :
1000             /* send path through variable substitution */
1001             if (*path != '~') /* need to copy path to tmp */
1002                 strcpy(tmp, path);
1003             if (!pwent)
1004                 pwent = getpwnam(obj->username);
1005             volxlate(obj, path, sizeof(path) - 1, tmp, pwent, NULL, NULL);
1006
1007             /* this is sort of braindead. basically, i want to be
1008              * able to specify things in any order, but i don't want to 
1009              * re-write everything. 
1010              *
1011              * currently we have options: 
1012              *   volname
1013              *   codepage:x
1014              *   casefold:x
1015              *   allow:x,y,@z
1016              *   deny:x,y,@z
1017              *   rwlist:x,y,@z
1018              *   rolist:x,y,@z
1019              *   options:prodos,crlf,noadouble,ro...
1020              *   dbpath:x
1021              *   password:x
1022              *   preexec:x
1023              *
1024              *   namemask:x,y,!z  (not implemented yet)
1025              */
1026             memcpy(options, save_options, sizeof(options));
1027             *volname = '\0';
1028
1029             /* read in up to VOLOP_NUM possible options */
1030             for (i = 0; i < VOLOPT_NUM; i++) {
1031                 if (parseline( sizeof( tmp ) - 1, tmp ) < 0)
1032                     break;
1033
1034                 volset(options, save_options, volname, sizeof(volname) - 1, tmp);
1035             }
1036
1037             /* check allow/deny lists:
1038                allow -> either no list (-1), or in list (1)
1039                deny -> either no list (-1), or not in list (0) */
1040             if (accessvol(options[VOLOPT_ALLOW].c_value, obj->username) &&
1041                     (accessvol(options[VOLOPT_DENY].c_value, obj->username) < 1)) {
1042
1043                 /* handle read-only behaviour. semantics:
1044                  * 1) neither the rolist nor the rwlist exist -> rw
1045                  * 2) rolist exists -> ro if user is in it.
1046                  * 3) rwlist exists -> ro unless user is in it. */
1047                 if (((options[VOLOPT_FLAGS].i_value & AFPVOL_RO) == 0) &&
1048                         ((accessvol(options[VOLOPT_ROLIST].c_value,
1049                                     obj->username) == 1) ||
1050                          !accessvol(options[VOLOPT_RWLIST].c_value,
1051                                     obj->username)))
1052                     options[VOLOPT_FLAGS].i_value |= AFPVOL_RO;
1053
1054                 /* do variable substitution for volname */
1055                 volxlate(obj, tmp, sizeof(tmp) - 1, volname, pwent, path, NULL);
1056                 creatvol(obj, pwent, path, tmp, options, p2 != NULL);
1057             }
1058             volfree(options, save_options);
1059             break;
1060
1061         case '.' :
1062             parseline( sizeof( type ) - 1, type );
1063             parseline( sizeof( creator ) - 1, creator );
1064             setextmap( path, type, creator, user);
1065             break;
1066
1067         default :
1068             break;
1069         }
1070     }
1071     volfree(save_options, NULL);
1072     sortextmap();
1073     if ( fclose( fp ) != 0 ) {
1074         LOG(log_error, logtype_afpd, "readvolfile: fclose: %s", strerror(errno) );
1075     }
1076     p1->loaded = 1;
1077     return( 0 );
1078 }
1079
1080 /* ------------------------------- */
1081 static void volume_free(struct vol *vol)
1082 {
1083     free(vol->v_name);
1084     vol->v_name = NULL;
1085     free(vol->v_path);
1086     free(vol->v_password);
1087     free(vol->v_veto);
1088     free(vol->v_volcodepage);
1089     free(vol->v_maccodepage);
1090     free(vol->v_cnidscheme);
1091     free(vol->v_dbpath);
1092     free(vol->v_gvs);
1093 #ifdef FORCE_UIDGID
1094     free(vol->v_forceuid);
1095     free(vol->v_forcegid);
1096 #endif /* FORCE_UIDGID */
1097 }
1098
1099 /* ------------------------------- */
1100 static void free_volumes(void )
1101 {
1102     struct vol  *vol;
1103     struct vol  *nvol, *ovol;
1104
1105     for ( vol = Volumes; vol; vol = vol->v_next ) {
1106         if (( vol->v_flags & AFPVOL_OPEN ) ) {
1107             vol->v_deleted = 1;
1108             continue;
1109         }
1110         volume_free(vol);
1111     }
1112
1113     for ( vol = Volumes, ovol = NULL; vol; vol = nvol) {
1114         nvol = vol->v_next;
1115
1116         if (vol->v_name == NULL) {
1117            if (Volumes == vol) {
1118                Volumes = nvol;
1119                ovol = Volumes;
1120            }
1121            else {
1122               ovol->v_next = nvol;
1123            }
1124            free(vol);
1125         }
1126         else {
1127            ovol = vol;
1128         }
1129     }
1130 }
1131
1132 /* ------------------------------- */
1133 static void volume_unlink(struct vol *volume)
1134 {
1135 struct vol *vol, *ovol, *nvol;
1136
1137     if (volume == Volumes) {
1138         Volumes = Volumes->v_next;
1139         return;
1140     }
1141     for ( vol = Volumes->v_next, ovol = Volumes; vol; vol = nvol) {
1142         nvol = vol->v_next;
1143
1144         if (vol == volume) {
1145             ovol->v_next = nvol;
1146             break;
1147         }
1148         else {
1149            ovol = vol;
1150         }
1151     }
1152 }
1153
1154 static int getvolspace( vol, bfree, btotal, xbfree, xbtotal, bsize )
1155 struct vol      *vol;
1156 u_int32_t       *bfree, *btotal, *bsize;
1157 VolSpace    *xbfree, *xbtotal;
1158 {
1159     int         spaceflag, rc;
1160     u_int32_t   maxsize;
1161 #ifndef NO_QUOTA_SUPPORT
1162     VolSpace    qfree, qtotal;
1163 #endif
1164
1165     spaceflag = AFPVOL_GVSMASK & vol->v_flags;
1166     /* report up to 2GB if afp version is < 2.2 (4GB if not) */
1167     maxsize = (vol->v_flags & AFPVOL_A2VOL) ? 0x01fffe00 :
1168               (((afp_version < 22) || (vol->v_flags & AFPVOL_LIMITSIZE))
1169                ? 0x7fffffffL : 0xffffffffL);
1170
1171 #ifdef AFS
1172     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_AFSGVS ) {
1173         if ( afs_getvolspace( vol, xbfree, xbtotal, bsize ) == AFP_OK ) {
1174             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_AFSGVS;
1175             goto getvolspace_done;
1176         }
1177     }
1178 #endif
1179
1180     if (( rc = ustatfs_getvolspace( vol, xbfree, xbtotal,
1181                                     bsize)) != AFP_OK ) {
1182         return( rc );
1183     }
1184
1185 #define min(a,b)        ((a)<(b)?(a):(b))
1186 #ifndef NO_QUOTA_SUPPORT
1187     if ( spaceflag == AFPVOL_NONE || spaceflag == AFPVOL_UQUOTA ) {
1188         if ( uquota_getvolspace( vol, &qfree, &qtotal, *bsize ) == AFP_OK ) {
1189             vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_UQUOTA;
1190             *xbfree = min(*xbfree, qfree);
1191             *xbtotal = min( *xbtotal, qtotal);
1192             goto getvolspace_done;
1193         }
1194     }
1195 #endif
1196     vol->v_flags = ( ~AFPVOL_GVSMASK & vol->v_flags ) | AFPVOL_USTATFS;
1197
1198 getvolspace_done:
1199     *bfree = min( *xbfree, maxsize);
1200     *btotal = min( *xbtotal, maxsize);
1201     return( AFP_OK );
1202 }
1203
1204 /* ----------------------- 
1205  * set volume creation date
1206  * avoid duplicate, well at least it tries
1207 */
1208 static void vol_setdate(u_int16_t id, struct adouble *adp, time_t date)
1209 {
1210     struct vol  *volume;
1211     struct vol  *vol = Volumes;
1212
1213     for ( volume = Volumes; volume; volume = volume->v_next ) {
1214         if (volume->v_vid == id) {
1215             vol = volume;
1216         }
1217         else if (AD_DATE_FROM_UNIX(date) == volume->v_ctime) {
1218             date = date+1;
1219             volume = Volumes; /* restart */
1220         }
1221     }
1222     vol->v_ctime = AD_DATE_FROM_UNIX(date);
1223     ad_setdate(adp, AD_DATE_CREATE | AD_DATE_UNIX, date);
1224 }
1225
1226 /* ----------------------- */
1227 static int getvolparams( bitmap, vol, st, buf, buflen )
1228 u_int16_t       bitmap;
1229 struct vol      *vol;
1230 struct stat     *st;
1231 char    *buf;
1232 int             *buflen;
1233 {
1234     struct adouble      ad;
1235     int                 bit = 0, isad = 1;
1236     u_int32_t           aint;
1237     u_short             ashort;
1238     u_int32_t           bfree, btotal, bsize;
1239     VolSpace            xbfree, xbtotal; /* extended bytes */
1240     char                *data, *nameoff = NULL;
1241     char                *slash;
1242
1243     /* courtesy of jallison@whistle.com:
1244      * For MacOS8.x support we need to create the
1245      * .Parent file here if it doesn't exist. */
1246
1247     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1248     if ( ad_open( vol->v_path, vol_noadouble(vol) |
1249                   ADFLAGS_HF|ADFLAGS_DIR, O_RDWR | O_CREAT,
1250                   0666, &ad) < 0 ) {
1251         isad = 0;
1252         vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1253
1254     } else if (ad_get_HF_flags( &ad ) & O_CREAT) {
1255         slash = strrchr( vol->v_path, '/' );
1256         if(slash)
1257             slash++;
1258         else
1259             slash = vol->v_path;
1260         if (ad_getentryoff(&ad, ADEID_NAME)) {
1261             ad_setentrylen( &ad, ADEID_NAME, strlen( slash ));
1262             memcpy(ad_entry( &ad, ADEID_NAME ), slash,
1263                ad_getentrylen( &ad, ADEID_NAME ));
1264         }
1265         vol_setdate(vol->v_vid, &ad, st->st_mtime);
1266         ad_flush(&ad, ADFLAGS_HF);
1267     }
1268     else {
1269         if (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0)
1270             vol->v_ctime = AD_DATE_FROM_UNIX(st->st_mtime);
1271         else 
1272             vol->v_ctime = aint;
1273     }
1274
1275     if (( bitmap & ( (1<<VOLPBIT_BFREE)|(1<<VOLPBIT_BTOTAL) |
1276                      (1<<VOLPBIT_XBFREE)|(1<<VOLPBIT_XBTOTAL) |
1277                      (1<<VOLPBIT_BSIZE)) ) != 0 ) {
1278         if ( getvolspace( vol, &bfree, &btotal, &xbfree, &xbtotal,
1279                           &bsize) < 0 ) {
1280             if ( isad ) {
1281                 ad_close( &ad, ADFLAGS_HF );
1282             }
1283             return( AFPERR_PARAM );
1284         }
1285     }
1286
1287     data = buf;
1288     while ( bitmap != 0 ) {
1289         while (( bitmap & 1 ) == 0 ) {
1290             bitmap = bitmap>>1;
1291             bit++;
1292         }
1293
1294         switch ( bit ) {
1295         case VOLPBIT_ATTR :
1296             ashort = 0;
1297             if (0 == (vol->v_flags & AFPVOL_NOFILEID) && vol->v_cdb != NULL &&
1298                            (vol->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1299                 ashort = VOLPBIT_ATTR_FILEID;
1300             }
1301             /* check for read-only.
1302              * NOTE: we don't actually set the read-only flag unless
1303              *       it's passed in that way as it's possible to mount
1304              *       a read-write filesystem under a read-only one. */
1305             if ((vol->v_flags & AFPVOL_RO) ||
1306                     ((utime(vol->v_path, NULL) < 0) && (errno == EROFS))) {
1307                 ashort |= VOLPBIT_ATTR_RO;
1308             }
1309             ashort |= VOLPBIT_ATTR_CATSEARCH;
1310             if (afp_version >= 30) {
1311                 ashort |= VOLPBIT_ATTR_UTF8;
1312                 if (vol->v_flags & AFPVOL_UNIX_PRIV)
1313                     ashort |= VOLPBIT_ATTR_UNIXPRIV;
1314             }
1315             ashort = htons(ashort);
1316             memcpy(data, &ashort, sizeof( ashort ));
1317             data += sizeof( ashort );
1318             break;
1319
1320         case VOLPBIT_SIG :
1321             ashort = htons( AFPVOLSIG_DEFAULT );
1322             memcpy(data, &ashort, sizeof( ashort ));
1323             data += sizeof( ashort );
1324             break;
1325
1326         case VOLPBIT_CDATE :
1327             aint = vol->v_ctime;
1328             memcpy(data, &aint, sizeof( aint ));
1329             data += sizeof( aint );
1330             break;
1331
1332         case VOLPBIT_MDATE :
1333             if ( st->st_mtime > vol->v_mtime ) {
1334                 vol->v_mtime = st->st_mtime;
1335             }
1336             aint = AD_DATE_FROM_UNIX(vol->v_mtime);
1337             memcpy(data, &aint, sizeof( aint ));
1338             data += sizeof( aint );
1339             break;
1340
1341         case VOLPBIT_BDATE :
1342             if (!isad ||  (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1343                 aint = AD_DATE_START;
1344             memcpy(data, &aint, sizeof( aint ));
1345             data += sizeof( aint );
1346             break;
1347
1348         case VOLPBIT_VID :
1349             memcpy(data, &vol->v_vid, sizeof( vol->v_vid ));
1350             data += sizeof( vol->v_vid );
1351             break;
1352
1353         case VOLPBIT_BFREE :
1354             bfree = htonl( bfree );
1355             memcpy(data, &bfree, sizeof( bfree ));
1356             data += sizeof( bfree );
1357             break;
1358
1359         case VOLPBIT_BTOTAL :
1360             btotal = htonl( btotal );
1361             memcpy(data, &btotal, sizeof( btotal ));
1362             data += sizeof( btotal );
1363             break;
1364
1365 #ifndef NO_LARGE_VOL_SUPPORT
1366         case VOLPBIT_XBFREE :
1367             xbfree = hton64( xbfree );
1368 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1369             bcopy(&xbfree, data, sizeof(xbfree));
1370 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1371             memcpy(data, &xbfree, sizeof( xbfree ));
1372 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1373             data += sizeof( xbfree );
1374             break;
1375
1376         case VOLPBIT_XBTOTAL :
1377             xbtotal = hton64( xbtotal );
1378 #if defined(__GNUC__) && defined(HAVE_GCC_MEMCPY_BUG)
1379             bcopy(&xbtotal, data, sizeof(xbtotal));
1380 #else /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1381             memcpy(data, &xbtotal, sizeof( xbtotal ));
1382 #endif /* __GNUC__ && HAVE_GCC_MEMCPY_BUG */
1383             data += sizeof( xbfree );
1384             break;
1385 #endif /* ! NO_LARGE_VOL_SUPPORT */
1386
1387         case VOLPBIT_NAME :
1388             nameoff = data;
1389             data += sizeof( u_int16_t );
1390             break;
1391
1392         case VOLPBIT_BSIZE:  /* block size */
1393             bsize = htonl(bsize);
1394             memcpy(data, &bsize, sizeof(bsize));
1395             data += sizeof(bsize);
1396             break;
1397
1398         default :
1399             if ( isad ) {
1400                 ad_close( &ad, ADFLAGS_HF );
1401             }
1402             return( AFPERR_BITMAP );
1403         }
1404         bitmap = bitmap>>1;
1405         bit++;
1406     }
1407     if ( nameoff ) {
1408         ashort = htons( data - buf );
1409         memcpy(nameoff, &ashort, sizeof( ashort ));
1410         aint = ucs2_to_charset( (utf8_encoding()?CH_UTF8_MAC:vol->v_maccharset), vol->v_name, data+1, 255);
1411         if ( aint <= 0 ) {
1412             *buflen = 0;
1413             return AFPERR_MISC;
1414         }
1415                 
1416         *data++ = aint;
1417         data += aint;
1418     }
1419     if ( isad ) {
1420         ad_close( &ad, ADFLAGS_HF );
1421     }
1422     *buflen = data - buf;
1423     return( AFP_OK );
1424 }
1425
1426 /* ------------------------- */
1427 static int stat_vol(u_int16_t bitmap, struct vol *vol, char *rbuf, int *rbuflen)
1428 {
1429     struct stat st;
1430     int         buflen, ret;
1431
1432     if ( stat( vol->v_path, &st ) < 0 ) {
1433         *rbuflen = 0;
1434         return( AFPERR_PARAM );
1435     }
1436     /* save the volume device number */
1437     vol->v_dev = st.st_dev;
1438
1439     buflen = *rbuflen - sizeof( bitmap );
1440     if (( ret = getvolparams( bitmap, vol, &st,
1441                               rbuf + sizeof( bitmap ), &buflen )) != AFP_OK ) {
1442         *rbuflen = 0;
1443         return( ret );
1444     }
1445     *rbuflen = buflen + sizeof( bitmap );
1446     bitmap = htons( bitmap );
1447     memcpy(rbuf, &bitmap, sizeof( bitmap ));
1448     return( AFP_OK );
1449
1450 }
1451
1452 /* ------------------------------- */
1453 void load_volumes(AFPObj *obj)
1454 {
1455     struct passwd       *pwent;
1456
1457     if (Volumes) {
1458         int changed = 0;
1459         
1460         /* check files date */
1461         if (obj->options.defaultvol.loaded) {
1462             changed = volfile_changed(&obj->options.defaultvol);
1463         }
1464         if (obj->options.systemvol.loaded) {
1465             changed |= volfile_changed(&obj->options.systemvol);
1466         }
1467         if (obj->options.uservol.loaded) {
1468             changed |= volfile_changed(&obj->options.uservol);
1469         }
1470         if (!changed)
1471             return;
1472         
1473         free_extmap();
1474         free_volumes();
1475     }
1476     
1477     pwent = getpwnam(obj->username);
1478     if ( (obj->options.flags & OPTION_USERVOLFIRST) == 0 ) {
1479         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent);
1480     }
1481
1482     if ((*obj->username == '\0') || (obj->options.flags & OPTION_NOUSERVOL)) {
1483         readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent);
1484     } else if (pwent) {
1485         /*
1486         * Read user's AppleVolumes or .AppleVolumes file
1487         * If neither are readable, read the default volumes file. if
1488         * that doesn't work, create a user share.
1489         */
1490         if (obj->options.uservol.name) {
1491             free(obj->options.uservol.name);
1492         }
1493         obj->options.uservol.name = strdup(pwent->pw_dir);
1494         if ( readvolfile(obj, &obj->options.uservol,    "AppleVolumes", 1, pwent) < 0 &&
1495                 readvolfile(obj, &obj->options.uservol, ".AppleVolumes", 1, pwent) < 0 &&
1496                 readvolfile(obj, &obj->options.uservol, "applevolumes", 1, pwent) < 0 &&
1497                 readvolfile(obj, &obj->options.uservol, ".applevolumes", 1, pwent) < 0 &&
1498                 obj->options.defaultvol.name != NULL ) {
1499             if (readvolfile(obj, &obj->options.defaultvol, NULL, 1, pwent) < 0)
1500                 creatvol(obj, pwent, pwent->pw_dir, NULL, NULL, 1);
1501         }
1502     }
1503     if ( obj->options.flags & OPTION_USERVOLFIRST ) {
1504         readvolfile(obj, &obj->options.systemvol, NULL, 0, pwent );
1505     }
1506 }
1507
1508 /* ------------------------------- */
1509 int afp_getsrvrparms(obj, ibuf, ibuflen, rbuf, rbuflen )
1510 AFPObj      *obj;
1511 char    *ibuf, *rbuf;
1512 int     ibuflen, *rbuflen;
1513 {
1514     struct timeval      tv;
1515     struct stat         st;
1516     struct vol          *volume;
1517     char        *data;
1518     char                *namebuf;
1519     int                 vcnt;
1520     size_t              len;
1521
1522     load_volumes(obj);
1523
1524     data = rbuf + 5;
1525     for ( vcnt = 0, volume = Volumes; volume; volume = volume->v_next ) {
1526         if (!(volume->v_flags & AFPVOL_NOSTAT)) {
1527             if ( stat( volume->v_path, &st ) < 0 ) {
1528                 LOG(log_info, logtype_afpd, "afp_getsrvrparms(%s): stat: %s",
1529                         volume->v_path, strerror(errno) );
1530                 continue;               /* can't access directory */
1531             }
1532             if (!S_ISDIR(st.st_mode)) {
1533                 continue;               /* not a dir */
1534             }
1535         }
1536         if (volume->v_hide) {
1537             continue;           /* config file changed but the volume was mounted */
1538         }
1539         len = ucs2_to_charset_allocate((utf8_encoding()?CH_UTF8_MAC:obj->options.maccharset),
1540                                         &namebuf, volume->v_name);
1541         if (len == (size_t)-1)
1542                 continue;
1543
1544         /* set password bit if there's a volume password */
1545         *data = (volume->v_password) ? AFPSRVR_PASSWD : 0;
1546
1547         /* Apple 2 clients running ProDOS-8 expect one volume to have
1548            bit 0 of this byte set.  They will not recognize anything
1549            on the server unless this is the case.  I have not
1550            completely worked this out, but it's related to booting
1551            from the server.  Support for that function is a ways
1552            off.. <shirsch@ibm.net> */
1553         *data |= (volume->v_flags & AFPVOL_A2VOL) ? AFPSRVR_CONFIGINFO : 0;
1554         *data++ |= 0; /* UNIX PRIVS BIT ..., OSX doesn't seem to use it, so we don't either */
1555         *data++ = len;
1556         memcpy(data, namebuf, len );
1557         data += len;
1558         free(namebuf);
1559         vcnt++;
1560     }
1561
1562     *rbuflen = data - rbuf;
1563     data = rbuf;
1564     if ( gettimeofday( &tv, 0 ) < 0 ) {
1565         LOG(log_error, logtype_afpd, "afp_getsrvrparms(%s): gettimeofday: %s", volume->v_path, strerror(errno) );
1566         *rbuflen = 0;
1567         return AFPERR_PARAM;
1568     }
1569     tv.tv_sec = AD_DATE_FROM_UNIX(tv.tv_sec);
1570     memcpy(data, &tv.tv_sec, sizeof( u_int32_t));
1571     data += sizeof( u_int32_t);
1572     *data = vcnt;
1573     return( AFP_OK );
1574 }
1575
1576 /* ------------------------- 
1577  * we are the user here
1578 */
1579 int afp_openvol(obj, ibuf, ibuflen, rbuf, rbuflen )
1580 AFPObj      *obj;
1581 char    *ibuf, *rbuf;
1582 int             ibuflen, *rbuflen;
1583 {
1584     struct stat st;
1585     char        *volname;
1586     char        *p;
1587     struct vol  *volume;
1588     struct dir  *dir;
1589     int         len, ret;
1590     size_t      namelen;
1591     u_int16_t   bitmap;
1592     char        path[ MAXPATHLEN + 1];
1593     char        *vol_uname;
1594     char        *vol_mname;
1595
1596     ibuf += 2;
1597     memcpy(&bitmap, ibuf, sizeof( bitmap ));
1598     bitmap = ntohs( bitmap );
1599     ibuf += sizeof( bitmap );
1600     if (( bitmap & (1<<VOLPBIT_VID)) == 0 ) {
1601         *rbuflen = 0;
1602         return AFPERR_BITMAP;
1603     }
1604
1605     len = (unsigned char)*ibuf++;
1606     volname = obj->oldtmp;
1607     namelen = convert_string( (utf8_encoding()?CH_UTF8_MAC:obj->options.maccharset), CH_UCS2,
1608                               ibuf, len, volname, sizeof(obj->oldtmp));
1609     if ( namelen <= 0){
1610         *rbuflen = 0;
1611         return AFPERR_PARAM;
1612     }
1613
1614     ibuf += len;
1615     if ((len + 1) & 1) /* pad to an even boundary */
1616         ibuf++;
1617
1618     load_volumes(obj);
1619
1620     for ( volume = Volumes; volume; volume = volume->v_next ) {
1621         if ( strcasecmp_w( (ucs2_t*) volname, volume->v_name ) == 0 ) {
1622             break;
1623         }
1624     }
1625
1626     if ( volume == NULL ) {
1627         *rbuflen = 0;
1628         return AFPERR_PARAM;
1629     }
1630
1631     /* check for a volume password */
1632     if (volume->v_password && strncmp(ibuf, volume->v_password, VOLPASSLEN)) {
1633         *rbuflen = 0;
1634         return AFPERR_ACCESS;
1635     }
1636
1637     if (( volume->v_flags & AFPVOL_OPEN  ) ) {
1638         /* the volume is already open */
1639 #ifdef FORCE_UIDGID
1640         set_uidgid ( volume );
1641 #endif
1642         return stat_vol(bitmap, volume, rbuf, rbuflen);
1643     }
1644
1645     /* initialize volume variables
1646      * FIXME file size
1647     */
1648     if (afp_version >= 30) {
1649         volume->max_filename = 255;
1650     }
1651     else {
1652         volume->max_filename = MACFILELEN;
1653     }
1654
1655     volume->v_dir = volume->v_root = NULL;
1656
1657     volume->v_flags |= AFPVOL_OPEN;
1658     volume->v_cdb = NULL;  
1659
1660     if (volume->v_root_preexec) {
1661         if ((ret = afprun(1, volume->v_root_preexec, NULL)) && volume->v_root_preexec_close) {
1662             LOG(log_error, logtype_afpd, "afp_openvol(%s): root preexec : %d", volume->v_path, ret );
1663             ret = AFPERR_MISC;
1664             goto openvol_err;
1665         }
1666     }
1667
1668 #ifdef FORCE_UIDGID
1669     set_uidgid ( volume );
1670 #endif
1671
1672     if (volume->v_preexec) {
1673         if ((ret = afprun(0, volume->v_preexec, NULL)) && volume->v_preexec_close) {
1674             LOG(log_error, logtype_afpd, "afp_openvol(%s): preexec : %d", volume->v_path, ret );
1675             ret = AFPERR_MISC;
1676             goto openvol_err;
1677         }
1678     }
1679
1680     if ( stat( volume->v_path, &st ) < 0 ) {
1681         ret = AFPERR_PARAM;
1682         goto openvol_err;
1683     }
1684
1685     if ( chdir( volume->v_path ) < 0 ) {
1686         ret = AFPERR_PARAM;
1687         goto openvol_err;
1688     }
1689
1690     len = convert_string_allocate( CH_UCS2, (utf8_encoding()?CH_UTF8_MAC:obj->options.maccharset),
1691                                        volume->v_name, namelen, &vol_mname);
1692     if ( !vol_mname || len <= 0) {
1693         ret = AFPERR_MISC;
1694         goto openvol_err;
1695     }
1696     
1697     if ( NULL == getcwd(path, MAXPATHLEN)) {
1698         /* shouldn't be fatal but it will fail later */
1699         LOG(log_error, logtype_afpd, "afp_openvol(%s): volume pathlen too long", volume->v_path);
1700         ret = AFPERR_MISC;
1701         goto openvol_err;
1702     }        
1703     
1704     if ((vol_uname = strrchr(path, '/')) == NULL)
1705          vol_uname = path;
1706     else if (*(vol_uname + 1) != '\0')
1707          vol_uname++;
1708         
1709     if ((dir = dirnew(vol_mname, vol_uname) ) == NULL) {
1710         free(vol_mname);
1711         LOG(log_error, logtype_afpd, "afp_openvol(%s): malloc: %s", volume->v_path, strerror(errno) );
1712         ret = AFPERR_MISC;
1713         goto openvol_err;
1714     }
1715     free(vol_mname);
1716
1717     dir->d_did = DIRDID_ROOT;
1718     dir->d_color = DIRTREE_COLOR_BLACK; /* root node is black */
1719     volume->v_dir = volume->v_root = dir;
1720
1721     curdir = volume->v_dir;
1722     if (volume->v_cnidscheme == NULL) {
1723         volume->v_cnidscheme = strdup(DEFAULT_CNID_SCHEME);
1724         LOG(log_warning, logtype_afpd, "Warning: No CNID scheme for volume %s. Using default.",
1725                volume->v_path);
1726     }
1727     if (volume->v_dbpath)
1728         volume->v_cdb = cnid_open (volume->v_dbpath, volume->v_umask, volume->v_cnidscheme, (volume->v_flags & AFPVOL_NODEV));
1729     else
1730         volume->v_cdb = cnid_open (volume->v_path, volume->v_umask, volume->v_cnidscheme, (volume->v_flags & AFPVOL_NODEV));
1731     if (volume->v_cdb == NULL) {
1732         LOG(log_error, logtype_afpd, "Fatal error: cannot open CNID or invalid CNID backend for %s: %s", 
1733             volume->v_path, volume->v_cnidscheme);
1734         ret = AFPERR_MISC;
1735         goto openvol_err;
1736     }
1737
1738     /* Codepages */
1739
1740     if (!volume->v_volcodepage)
1741         volume->v_volcodepage = strdup("UTF8");
1742
1743     if ( (charset_t) -1 == ( volume->v_volcharset = add_charset(volume->v_volcodepage)) ) {
1744         LOG (log_error, logtype_afpd, "Setting codepage %s as volume codepage failed", volume->v_volcodepage);
1745         ret = AFPERR_MISC;
1746         goto openvol_err;
1747     }
1748
1749     if ( NULL == ( volume->v_vol = find_charset_functions(volume->v_volcodepage)) || volume->v_vol->flags & CHARSET_ICONV ) {
1750         LOG (log_warning, logtype_afpd, "WARNING: volume encoding %s is *not* supported by netatalk, expect problems !!!!", volume->v_volcodepage);
1751     }   
1752
1753     if (!volume->v_maccodepage)
1754         volume->v_maccodepage = strdup(obj->options.maccodepage);
1755
1756     if ( (charset_t) -1 == ( volume->v_maccharset = add_charset(volume->v_maccodepage)) ) {
1757         LOG (log_error, logtype_afpd, "Setting codepage %s as mac codepage failed", volume->v_maccodepage);
1758         ret = AFPERR_MISC;
1759         goto openvol_err;
1760     }
1761
1762     if ( NULL == ( volume->v_mac = find_charset_functions(volume->v_maccodepage)) || ! (volume->v_mac->flags & CHARSET_CLIENT) ) {
1763         LOG (log_error, logtype_afpd, "Fatal error: mac charset %s not supported", volume->v_maccodepage);
1764         ret = AFPERR_MISC;
1765         goto openvol_err;
1766     }   
1767
1768     ret  = stat_vol(bitmap, volume, rbuf, rbuflen);
1769     if (ret == AFP_OK) {
1770
1771         if (!(volume->v_flags & AFPVOL_RO)) {
1772             handle_special_folders( volume );
1773             savevoloptions( volume);
1774         }
1775
1776         /*
1777          * If you mount a volume twice, the second time the trash appears on
1778          * the desk-top.  That's because the Mac remembers the DID for the
1779          * trash (even for volumes in different zones, on different servers).
1780          * Just so this works better, we prime the DID cache with the trash,
1781          * fixing the trash at DID 17.
1782          * FIXME (RL): should it be done inside a CNID backend ? (always returning Trash DID when asked) ?
1783          */
1784         if ((volume->v_cdb->flags & CNID_FLAG_PERSISTENT)) {
1785
1786             /* FIXME find db time stamp */
1787             if (cnid_getstamp(volume->v_cdb, volume->v_stamp, sizeof(volume->v_stamp)) < 0) {
1788                 LOG (log_error, logtype_afpd, 
1789                       "afp_openvol(%s): Fatal error: Unable to get stamp value from CNID backend",
1790                       volume->v_path);
1791                 ret = AFPERR_MISC;
1792                 goto openvol_err;
1793             }
1794         }
1795         else {
1796             p = Trash;
1797             cname( volume, volume->v_dir, &p );
1798         }
1799         return( AFP_OK );
1800     }
1801
1802 openvol_err:
1803     if (volume->v_dir) {
1804         dirfree( volume->v_dir );
1805         volume->v_dir = volume->v_root = NULL;
1806     }
1807
1808     volume->v_flags &= ~AFPVOL_OPEN;
1809     if (volume->v_cdb != NULL) {
1810         cnid_close(volume->v_cdb);
1811         volume->v_cdb = NULL;
1812     }
1813     *rbuflen = 0;
1814     return ret;
1815 }
1816
1817 /* ------------------------- */
1818 static void closevol(struct vol *vol)
1819 {
1820     if (!vol)
1821         return;
1822
1823     dirfree( vol->v_root );
1824     vol->v_dir = NULL;
1825     if (vol->v_cdb != NULL) {
1826         cnid_close(vol->v_cdb);
1827         vol->v_cdb = NULL;
1828     }
1829
1830     if (vol->v_postexec) {
1831         afprun(0, vol->v_postexec, NULL);
1832     }
1833     if (vol->v_root_postexec) {
1834         afprun(1, vol->v_root_postexec, NULL);
1835     }
1836 }
1837
1838 /* ------------------------- */
1839 void close_all_vol(void)
1840 {
1841     struct vol  *ovol;
1842     curdir = NULL;
1843     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
1844         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
1845             ovol->v_flags &= ~AFPVOL_OPEN;
1846             closevol(ovol);
1847         }
1848     }
1849 }
1850
1851 /* ------------------------- */
1852 int afp_closevol(obj, ibuf, ibuflen, rbuf, rbuflen )
1853 AFPObj      *obj;
1854 char    *ibuf, *rbuf;
1855 int             ibuflen, *rbuflen;
1856 {
1857     struct vol  *vol, *ovol;
1858     u_int16_t   vid;
1859
1860     *rbuflen = 0;
1861     ibuf += 2;
1862     memcpy(&vid, ibuf, sizeof( vid ));
1863     if (NULL == ( vol = getvolbyvid( vid )) ) {
1864         return( AFPERR_PARAM );
1865     }
1866
1867     vol->v_flags &= ~AFPVOL_OPEN;
1868     for ( ovol = Volumes; ovol; ovol = ovol->v_next ) {
1869         if ( (ovol->v_flags & AFPVOL_OPEN) ) {
1870             break;
1871         }
1872     }
1873     if ( ovol != NULL ) {
1874         /* Even if chdir fails, we can't say afp_closevol fails. */
1875         if ( chdir( ovol->v_path ) == 0 ) {
1876             curdir = ovol->v_dir;
1877         }
1878     }
1879
1880     closevol(vol);
1881     if (vol->v_deleted) {
1882         showvol(vol->v_name);
1883         volume_free(vol);
1884         volume_unlink(vol);
1885         free(vol);
1886     }
1887     return( AFP_OK );
1888 }
1889
1890 /* ------------------------- */
1891 struct vol *getvolbyvid(const u_int16_t vid )
1892 {
1893     struct vol  *vol;
1894
1895     for ( vol = Volumes; vol; vol = vol->v_next ) {
1896         if ( vid == vol->v_vid ) {
1897             break;
1898         }
1899     }
1900     if ( vol == NULL || ( vol->v_flags & AFPVOL_OPEN ) == 0 ) {
1901         return( NULL );
1902     }
1903
1904 #ifdef FORCE_UIDGID
1905     set_uidgid ( vol );
1906 #endif /* FORCE_UIDGID */
1907
1908     return( vol );
1909 }
1910
1911 /* ------------------------ */
1912 static int ext_cmp_key(const void *key, const void *obj)
1913 {
1914     const char          *p = key;
1915     const struct extmap *em = obj;
1916     return strdiacasecmp(p, em->em_ext);
1917 }
1918 struct extmap *getextmap(const char *path)
1919 {
1920     char          *p;
1921     struct extmap *em;
1922
1923     if (NULL == ( p = strrchr( path, '.' )) ) {
1924         return( Defextmap );
1925     }
1926     p++;
1927     if (!*p || !Extmap_cnt) {
1928         return( Defextmap );
1929     }
1930     em = bsearch(p, Extmap, Extmap_cnt, sizeof(struct extmap), ext_cmp_key);
1931     if (em) {
1932         return( em );
1933     } else {
1934         return( Defextmap );
1935     }
1936 }
1937
1938 /* ------------------------- */
1939 struct extmap *getdefextmap(void)
1940 {
1941     return( Defextmap );
1942 }
1943
1944 /* --------------------------
1945    poll if a volume is changed by other processes.
1946 */
1947 int  pollvoltime(obj)
1948 AFPObj *obj;
1949 {
1950     struct vol       *vol;
1951     struct timeval   tv;
1952     struct stat      st;
1953     
1954     if (!(afp_version > 21 && obj->options.server_notif)) 
1955          return 0;
1956
1957     if ( gettimeofday( &tv, 0 ) < 0 ) 
1958          return 0;
1959
1960     for ( vol = Volumes; vol; vol = vol->v_next ) {
1961         if ( (vol->v_flags & AFPVOL_OPEN)  && vol->v_mtime + 30 < tv.tv_sec) {
1962             if ( !stat( vol->v_path, &st ) && vol->v_mtime != st.st_mtime ) {
1963                 vol->v_mtime = st.st_mtime;
1964                 if (!obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED))
1965                     return -1;
1966                 return 1;
1967             }
1968         }
1969     }
1970     return 0;
1971 }
1972
1973 /* ------------------------- */
1974 void setvoltime(obj, vol )
1975 AFPObj *obj;
1976 struct vol      *vol;
1977 {
1978     struct timeval      tv;
1979
1980     /* just looking at vol->v_mtime is broken seriously since updates
1981      * from other users afpd processes never are seen.
1982      * This is not the most elegant solution (a shared memory between
1983      * the afpd processes would come closer)
1984      * [RS] */
1985
1986     if ( gettimeofday( &tv, 0 ) < 0 ) {
1987         LOG(log_error, logtype_afpd, "setvoltime(%s): gettimeofday: %s", vol->v_path, strerror(errno) );
1988         return;
1989     }
1990     if( utime( vol->v_path, NULL ) < 0 ) {
1991         /* write of time failed ... probably a read only filesys,
1992          * where no other users can interfere, so there's no issue here
1993          */
1994     }
1995
1996     /* a little granularity */
1997     if (vol->v_mtime < tv.tv_sec) {
1998         vol->v_mtime = tv.tv_sec;
1999         /* or finder doesn't update free space */
2000         if (afp_version > 21 && obj->options.server_notif) {
2001             obj->attention(obj->handle, AFPATTN_NOTIFY | AFPATTN_VOLCHANGED);
2002         }
2003     }
2004 }
2005
2006 /* ------------------------- */
2007 int afp_getvolparams(obj, ibuf, ibuflen, rbuf, rbuflen )
2008 AFPObj      *obj;
2009 char    *ibuf, *rbuf;
2010 int             ibuflen, *rbuflen;
2011 {
2012     struct vol  *vol;
2013     u_int16_t   vid, bitmap;
2014
2015     ibuf += 2;
2016     memcpy(&vid, ibuf, sizeof( vid ));
2017     ibuf += sizeof( vid );
2018     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2019     bitmap = ntohs( bitmap );
2020
2021     if (NULL == ( vol = getvolbyvid( vid )) ) {
2022         *rbuflen = 0;
2023         return( AFPERR_PARAM );
2024     }
2025
2026     return stat_vol(bitmap, vol, rbuf, rbuflen);
2027 }
2028
2029 /* ------------------------- */
2030 int afp_setvolparams(obj, ibuf, ibuflen, rbuf, rbuflen )
2031 AFPObj      *obj;
2032 char    *ibuf, *rbuf;
2033 int             ibuflen, *rbuflen;
2034 {
2035     struct adouble ad;
2036     struct vol  *vol;
2037     u_int16_t   vid, bitmap;
2038     u_int32_t   aint;
2039
2040     ibuf += 2;
2041     *rbuflen = 0;
2042
2043     memcpy(&vid, ibuf, sizeof( vid ));
2044     ibuf += sizeof( vid );
2045     memcpy(&bitmap, ibuf, sizeof( bitmap ));
2046     bitmap = ntohs( bitmap );
2047     ibuf += sizeof(bitmap);
2048
2049     if (( vol = getvolbyvid( vid )) == NULL ) {
2050         return( AFPERR_PARAM );
2051     }
2052
2053     if ((vol->v_flags & AFPVOL_RO))
2054         return AFPERR_VLOCK;
2055
2056     /* we can only set the backup date. */
2057     if (bitmap != (1 << VOLPBIT_BDATE))
2058         return AFPERR_BITMAP;
2059
2060     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2061     if ( ad_open( vol->v_path, ADFLAGS_HF|ADFLAGS_DIR, O_RDWR,
2062                   0666, &ad) < 0 ) {
2063         if (errno == EROFS)
2064             return AFPERR_VLOCK;
2065
2066         return AFPERR_ACCESS;
2067     }
2068
2069     memcpy(&aint, ibuf, sizeof(aint));
2070     ad_setdate(&ad, AD_DATE_BACKUP, aint);
2071     ad_flush(&ad, ADFLAGS_HF);
2072     ad_close(&ad, ADFLAGS_HF);
2073     return( AFP_OK );
2074 }
2075
2076 /* ------------------------- */
2077 int wincheck(const struct vol *vol, const char *path)
2078 {
2079     int len;
2080
2081     if (!(vol->v_flags & AFPVOL_MSWINDOWS))
2082         return 1;
2083
2084     /* empty paths are not allowed */
2085     if ((len = strlen(path)) == 0)
2086         return 0;
2087
2088     /* leading or trailing whitespaces are not allowed, carriage returns
2089      * and probably other whitespace is okay, tabs are not allowed
2090      */
2091     if ((path[0] == ' ') || (path[len-1] == ' '))
2092         return 0;
2093
2094     /* certain characters are not allowed */
2095     if (strpbrk(path, MSWINDOWS_BADCHARS))
2096         return 0;
2097
2098     /* everything else is okay */
2099     return 1;
2100 }
2101
2102
2103 /*
2104  * precreate a folder 
2105  * this is only intended for folders in the volume root 
2106  * It will *not* work if the folder name contains extended characters 
2107  */
2108 static int create_special_folder (const struct vol *vol, const struct _special_folder *folder)
2109 {
2110         char            *p,*q,*r;
2111         struct adouble  ad;
2112         u_int16_t       attr;
2113         struct stat     st;
2114         int             ret;
2115
2116
2117         p = (char *) malloc ( strlen(vol->v_path)+strlen(folder->name)+2);
2118         if ( p == NULL) {
2119                 LOG(log_error, logtype_afpd,"malloc failed");
2120                 exit (EXITERR_SYS);
2121         }
2122
2123         q=strdup(folder->name);
2124         if ( q == NULL) {
2125                 LOG(log_error, logtype_afpd,"malloc failed");
2126                 exit (EXITERR_SYS);
2127         }
2128
2129         strcpy(p, vol->v_path);
2130         strcat(p, "/");
2131
2132         r=q;
2133         while (*r) {
2134                 if ((vol->v_casefold & AFPVOL_MTOUUPPER))
2135                         *r=toupper(*r);
2136                 else if ((vol->v_casefold & AFPVOL_MTOULOWER))
2137                         *r=tolower(*r);
2138                 r++;
2139         }
2140         strcat(p, q);
2141
2142         if ( (ret = stat( p, &st )) < 0 ) {
2143                 if (folder->precreate) {
2144                     if (ad_mkdir(p, folder->mode)) {
2145                         LOG(log_debug, logtype_afpd,"Creating '%s' failed in %s: %s", p, vol->v_path, strerror(errno));
2146                         free(p);
2147                         free(q);
2148                         return -1;
2149                     }
2150                     ret = 0;
2151                 }
2152         }
2153
2154         if ( !ret && folder->hide) {
2155                 /* Hide it */
2156                 ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2157                 if (ad_open( p, vol_noadouble(vol) | ADFLAGS_HF|ADFLAGS_DIR,
2158                         O_RDWR|O_CREAT, 0666, &ad) < 0) {
2159                         free (p);
2160                         free(q);
2161                         return (-1);
2162                 }
2163                 if ((ad_get_HF_flags( &ad ) & O_CREAT) ) {
2164                     if (ad_getentryoff(&ad, ADEID_NAME)) {
2165                         ad_setentrylen( &ad, ADEID_NAME, strlen(folder->name));
2166                         memcpy(ad_entry( &ad, ADEID_NAME ), folder->name,
2167                                ad_getentrylen( &ad, ADEID_NAME ));
2168                     }
2169                 }
2170  
2171                 ad_getattr(&ad, &attr);
2172                 attr |= htons( ntohs( attr ) | ATTRBIT_INVISIBLE );
2173                 ad_setattr(&ad, attr);
2174 #if 0           
2175                 /* do the same with the finder info */
2176                 if (ad_entry(&ad, ADEID_FINDERI)) {
2177                         memcpy(&attr, ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, sizeof(attr));
2178                         attr   |= htons(FINDERINFO_INVISIBLE);
2179                         memcpy(ad_entry(&ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,&attr, sizeof(attr));
2180                 }
2181 #endif    
2182                 ad_flush( &ad, ADFLAGS_HF );
2183                 ad_close( &ad, ADFLAGS_HF );
2184         }
2185         free(p);
2186         free(q);
2187         return 0;
2188 }
2189
2190 static void handle_special_folders (const struct vol * vol)
2191 {
2192         const _special_folder *p = &special_folders[0];
2193
2194         if ((vol->v_flags & AFPVOL_RO))
2195                 return;
2196
2197         for (; p->name != NULL; p++) {
2198                 create_special_folder (vol, p);
2199         }
2200 }
2201
2202 /*
2203  * Save the volume options to a file, used by
2204  * shell utilities.
2205  * Writing the file everytime a volume is opened is
2206  * unnecessary, but it shouldn't hurt much.
2207  */
2208 static int savevoloptions (const struct vol *vol)
2209 {
2210     char buf[16348];
2211     char item[MAXPATHLEN];
2212     int fd;
2213     int ret = 0;
2214     struct flock lock;
2215     const _vol_opt_name *op = &vol_opt_names[0];
2216     const _vol_opt_name *cf = &vol_opt_casefold[0];
2217
2218     strlcpy (item, vol->v_path, sizeof(item));
2219     strlcat (item, "/.AppleDesktop/", sizeof(item));
2220     strlcat (item, VOLINFOFILE, sizeof(item));
2221
2222     if ((fd = open( item, O_RDWR | O_CREAT , 0666)) <0 ) {
2223         LOG(log_debug, logtype_afpd,"Error opening %s: %s", item, strerror(errno));
2224         return (-1);
2225     }
2226
2227     /* try to get a lock */
2228     lock.l_start  = 0;
2229     lock.l_whence = SEEK_SET;
2230     lock.l_len    = 0;
2231     lock.l_type   = F_WRLCK;
2232
2233     if (fcntl(fd, F_SETLK, &lock) < 0) {
2234         if (errno == EACCES || errno == EAGAIN) {
2235             /* ignore, other process already writing the file */
2236             return 0;
2237         } else {
2238             LOG(log_error, logtype_cnid, "savevoloptions: cannot get lock: %s", strerror(errno));
2239             return (-1);
2240         }
2241     }
2242
2243     /* write volume options */
2244     snprintf(buf, sizeof(buf), "MAC_CHARSET:%s\n", vol->v_maccodepage);
2245     snprintf(item, sizeof(item), "VOL_CHARSET:%s\n", vol->v_volcodepage);
2246     strlcat(buf, item, sizeof(buf));
2247
2248     switch (vol->v_adouble) {
2249         case AD_VERSION1:
2250             strlcat(buf, "ADOUBLE_VER:v1\n", sizeof(buf));
2251             break;
2252         case AD_VERSION2:
2253             strlcat(buf, "ADOUBLE_VER:v2\n", sizeof(buf));
2254             break;
2255         case AD_VERSION2_OSX:
2256             strlcat(buf, "ADOUBLE_VER:osx\n", sizeof(buf));
2257             break;
2258     }
2259
2260     strlcat(buf, "CNIDBACKEND:", sizeof(buf));
2261     strlcat(buf, vol->v_cnidscheme, sizeof(buf));
2262     strlcat(buf, "\n", sizeof(buf));
2263
2264     strlcat(buf, "CNIDDBDHOST:", sizeof(buf));
2265     strlcat(buf, Cnid_srv, sizeof(buf));
2266     strlcat(buf, "\n", sizeof(buf));
2267
2268     snprintf(item, sizeof(item), "CNIDDBDPORT:%u\n", Cnid_port);
2269     strlcat(buf, item, sizeof(buf));
2270
2271     strcpy(item, "CNID_DBPATH:");
2272     if (vol->v_dbpath)
2273         strlcat(item, vol->v_dbpath, sizeof(item));
2274     else
2275         strlcat(item, vol->v_path, sizeof(item));
2276     strlcat(item, "\n", sizeof(item));
2277     strlcat(buf, item, sizeof(buf));
2278
2279     /* volume flags */
2280     strcpy(item, "VOLUME_OPTS:");
2281     for (;op->name; op++) {
2282         if ( (vol->v_flags & op->option) ) {
2283             strlcat(item, op->name, sizeof(item));
2284             strlcat(item, " ", sizeof(item));
2285         }
2286     }
2287     strlcat(item, "\n", sizeof(item));
2288     strlcat(buf, item, sizeof(buf));
2289
2290     /* casefold flags */
2291     strcpy(item, "VOLCASEFOLD:");
2292     for (;cf->name; cf++) {
2293         if ( (vol->v_casefold & cf->option) ) {
2294             strlcat(item, cf->name, sizeof(item));
2295             strlcat(item, " ", sizeof(item));
2296         }
2297     }
2298     strlcat(item, "\n", sizeof(item));
2299     strlcat(buf, item, sizeof(buf));
2300
2301     if (strlen(buf) >= sizeof(buf)-1)
2302         LOG(log_debug, logtype_afpd,"Error writing .volinfo file: buffer too small, %s", buf);
2303
2304
2305    if (write( fd, buf, strlen(buf)) < 0) {
2306        LOG(log_debug, logtype_afpd,"Error writing .volinfo file: %s", strerror(errno));
2307        goto done;
2308    }
2309    ftruncate(fd, strlen(buf));
2310
2311 done:
2312    lock.l_type = F_UNLCK;
2313    fcntl(fd, F_SETLK, &lock);
2314    close (fd);
2315    return ret;
2316 }