Remove duplicate CREATE_SGUID_ADMIN_ONLY define
[openafs.git] / src / viced / afsfileprocs.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*  afs_fileprocs.c - Complete File Server request routines              */
11 /*                                                                       */
12 /*  Information Technology Center                                        */
13 /*  Carnegie Mellon University                                           */
14 /*                                                                       */
15 /*  Date: 8/10/88                                                        */
16 /*                                                                       */
17 /*  Function    - A set of routines to handle the various file Server    */
18 /*                  requests; these routines are invoked by rxgen.       */
19 /*                                                                       */
20 /* ********************************************************************** */
21
22 /*
23  * GetVolumePackage disables Rx keepalives; PutVolumePackage re-enables.
24  * If callbacks are to be broken, keepalives should be enabled in the
25  * stub while that occurs; disabled while disk I/O is in process.
26  */
27
28 /*
29  * in Check_PermissionRights, certain privileges are afforded to the owner
30  * of the volume, or the owner of a file.  Are these considered "use of
31  * privilege"?
32  */
33
34 #include <afsconfig.h>
35 #include <afs/param.h>
36 #include <afs/stds.h>
37
38 #include <roken.h>
39
40 #ifdef  AFS_SGI_ENV
41 #undef SHARED                   /* XXX */
42 #endif
43
44 #ifdef HAVE_NET_IF_H
45 #include <net/if.h>
46 #endif
47
48 #ifdef HAVE_NETINET_IF_ETHER_H
49 #include <netinet/if_ether.h>
50 #endif
51
52 #if !defined(AFS_SGI_ENV) && defined(HAVE_SYS_MAP_H)
53 #include <sys/map.h>
54 #endif
55
56 #ifdef HAVE_SYS_STATFS_H
57 #include <sys/statfs.h>
58 #endif
59
60 #ifdef HAVE_SYS_LOCKF_H
61 #include <sys/lockf.h>
62 #endif
63
64 #ifdef HAVE_SYS_DK_H
65 #include <sys/dk.h>
66 #endif
67
68 #ifdef AFS_HPUX_ENV
69 /* included early because of name conflict on IOPEN */
70 #include <sys/inode.h>
71 #ifdef IOPEN
72 #undef IOPEN
73 #endif
74 #endif /* AFS_HPUX_ENV */
75
76 #include <afs/opr.h>
77 #include <rx/rx_queue.h>
78 #include <opr/lock.h>
79 #include <opr/proc.h>
80 #include <afs/nfs.h>
81 #include <afs/afsint.h>
82 #include <afs/vldbint.h>
83 #include <afs/errors.h>
84 #include <afs/ihandle.h>
85 #include <afs/vnode.h>
86 #include <afs/volume.h>
87 #include <afs/ptclient.h>
88 #include <afs/ptuser.h>
89 #include <afs/prs_fs.h>
90 #include <afs/acl.h>
91 #include <rx/rx.h>
92 #include <rx/rx_globals.h>
93
94 #include <afs/cellconfig.h>
95 #include <afs/keys.h>
96
97 #include <afs/partition.h>
98 #include "viced_prototypes.h"
99 #include "viced.h"
100 #include "host.h"
101 #include "callback.h"
102 #include <afs/unified_afs.h>
103 #include <afs/audit.h>
104 #include <afs/afsutil.h>
105 #include <afs/dir.h>
106
107 extern void SetDirHandle(DirHandle * dir, Vnode * vnode);
108 extern void FidZap(DirHandle * file);
109 extern void FidZero(DirHandle * file);
110
111 pthread_mutex_t fileproc_glock_mutex;
112
113 /* Useful local defines used by this module */
114
115 #define DONTCHECK       0
116 #define MustNOTBeDIR    1
117 #define MustBeDIR       2
118
119 #define TVS_SDATA       1
120 #define TVS_SSTATUS     2
121 #define TVS_CFILE       4
122 #define TVS_SLINK       8
123 #define TVS_MKDIR       0x10
124
125 #define CHK_FETCH       0x10
126 #define CHK_FETCHDATA   0x10
127 #define CHK_FETCHACL    0x11
128 #define CHK_FETCHSTATUS 0x12
129 #define CHK_STOREDATA   0x00
130 #define CHK_STOREACL    0x01
131 #define CHK_STORESTATUS 0x02
132
133 #define OWNERREAD       0400
134 #define OWNERWRITE      0200
135 #define OWNEREXEC       0100
136 #ifdef USE_GROUP_PERMS
137 #define GROUPREAD       0040
138 #define GROUPWRITE      0020
139 #define GROUPREXEC      0010
140 #endif
141
142 /* The following errors were not defined in NT. They are given unique
143  * names here to avoid any potential collision.
144  */
145 #define FSERR_ELOOP              90
146 #define FSERR_EOPNOTSUPP        122
147 #define FSERR_ECONNREFUSED      130
148
149 #define NOTACTIVECALL   0
150 #define ACTIVECALL      1
151
152 #define CREATE_SGUID_ADMIN_ONLY 1
153
154 extern struct afsconf_dir *confDir;
155 extern afs_int32 dataVersionHigh;
156
157 extern int SystemId;
158 static struct AFSCallStatistics AFSCallStats;
159 struct fs_stats_FullPerfStats afs_FullPerfStats;
160 extern int AnonymousID;
161 static const char nullString[] = "";
162
163 struct afs_FSStats {
164     afs_int32 NothingYet;
165 };
166
167 struct afs_FSStats afs_fsstats;
168
169 int LogLevel = 0;
170 int supported = 1;
171 int Console = 0;
172 afs_int32 BlocksSpare = 1024;   /* allow 1 MB overruns */
173 afs_int32 PctSpare;
174 extern afs_int32 implicitAdminRights;
175 extern afs_int32 readonlyServer;
176 extern int CopyOnWrite_calls, CopyOnWrite_off0, CopyOnWrite_size0;
177 extern afs_fsize_t CopyOnWrite_maxsize;
178
179 /*
180  * Externals used by the xstat code.
181  */
182 extern VolPkgStats VStats;
183 extern int CEs, CEBlocks;
184
185 extern int HTs, HTBlocks;
186
187 static afs_int32 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
188                                    struct rx_call *Call, afs_sfsize_t Pos,
189                                    afs_sfsize_t Len, afs_int32 Int64Mode,
190                                    afs_sfsize_t * a_bytesToFetchP,
191                                    afs_sfsize_t * a_bytesFetchedP);
192
193 static afs_int32 StoreData_RXStyle(Volume * volptr, Vnode * targetptr,
194                                    struct AFSFid *Fid, struct client *client,
195                                    struct rx_call *Call, afs_fsize_t Pos,
196                                    afs_fsize_t Length, afs_fsize_t FileLength,
197                                    int sync,
198                                    afs_sfsize_t * a_bytesToStoreP,
199                                    afs_sfsize_t * a_bytesStoredP);
200
201 #ifdef AFS_SGI_XFS_IOPS_ENV
202 #include <afs/xfsattrs.h>
203 static int
204 GetLinkCount(Volume * avp, struct stat *astat)
205 {
206     if (!strcmp("xfs", astat->st_fstype)) {
207         return (astat->st_mode & AFS_XFS_MODE_LINK_MASK);
208     } else
209         return astat->st_nlink;
210 }
211 #else
212 #define GetLinkCount(V, S) (S)->st_nlink
213 #endif
214
215 afs_int32
216 SpareComp(Volume * avolp)
217 {
218     afs_int32 temp;
219
220     FS_LOCK;
221     if (PctSpare) {
222         temp = V_maxquota(avolp);
223         if (temp == 0) {
224             /* no matter; doesn't check in this case */
225             FS_UNLOCK;
226             return 0;
227         }
228         temp = (temp * PctSpare) / 100;
229         FS_UNLOCK;
230         return temp;
231     } else {
232         FS_UNLOCK;
233         return BlocksSpare;
234     }
235
236 }                               /*SpareComp */
237
238 /*
239  * Set the volume synchronization parameter for this volume.  If it changes,
240  * the Cache Manager knows that the volume must be purged from the stat cache.
241  */
242 static void
243 SetVolumeSync(struct AFSVolSync *async, Volume * avol)
244 {
245     FS_LOCK;
246     /* date volume instance was created */
247     if (async) {
248         if (avol)
249             async->spare1 = V_creationDate(avol);
250         else
251             async->spare1 = 0;
252         async->spare2 = 0;
253         async->spare3 = 0;
254         async->spare4 = 0;
255         async->spare5 = 0;
256         async->spare6 = 0;
257     }
258     FS_UNLOCK;
259 }                               /*SetVolumeSync */
260
261 /**
262  * Verify that the on-disk size for a vnode matches the length in the vnode
263  * index.
264  *
265  * @param[in] vp   Volume pointer
266  * @param[in] vnp  Vnode pointer
267  * @param[in] alen Size of the vnode on disk, if known. If unknown, give -1,
268  *                 and CheckLength itself will determine the on-disk size.
269  *
270  * @return operation status
271  *  @retval 0 lengths match
272  *  @retval nonzero Error; either the lengths do not match or there was an
273  *                  error determining the on-disk size. The volume should be
274  *                  taken offline and salvaged.
275  */
276 static int
277 CheckLength(struct Volume *vp, struct Vnode *vnp, afs_sfsize_t alen)
278 {
279     afs_sfsize_t vlen;
280     VN_GET_LEN(vlen, vnp);
281
282     if (alen < 0) {
283         FdHandle_t *fdP;
284
285         fdP = IH_OPEN(vnp->handle);
286         if (fdP == NULL) {
287             ViceLog(0, ("CheckLength: cannot open inode for fid %" AFS_VOLID_FMT ".%lu.%lu\n",
288                         afs_printable_VolumeId_lu(vp->hashid),
289                         afs_printable_uint32_lu(Vn_id(vnp)),
290                         afs_printable_uint32_lu(vnp->disk.uniquifier)));
291             return -1;
292         }
293         alen = FDH_SIZE(fdP);
294         FDH_CLOSE(fdP);
295         if (alen < 0) {
296             afs_int64 alen64 = alen;
297             ViceLog(0, ("CheckLength: cannot get size for inode for fid %"
298                         AFS_VOLID_FMT ".%lu.%lu; FDH_SIZE returned %" AFS_INT64_FMT "\n",
299                         afs_printable_VolumeId_lu(vp->hashid),
300                         afs_printable_uint32_lu(Vn_id(vnp)),
301                         afs_printable_uint32_lu(vnp->disk.uniquifier),
302                         alen64));
303             return -1;
304         }
305     }
306
307     if (alen != vlen) {
308         afs_int64 alen64 = alen, vlen64 = vlen;
309         ViceLog(0, ("Fid %" AFS_VOLID_FMT ".%lu.%lu has inconsistent length (index "
310                     "%lld inode %lld ); volume must be salvaged\n",
311                     afs_printable_VolumeId_lu(vp->hashid),
312                     afs_printable_uint32_lu(Vn_id(vnp)),
313                     afs_printable_uint32_lu(vnp->disk.uniquifier),
314                     vlen64, alen64));
315         return -1;
316     }
317     return 0;
318 }
319
320 static void
321 LogClientError(const char *message, struct rx_connection *tcon, afs_int32 viceid, struct AFSFid *Fid)
322 {
323     char hoststr[16];
324     if (Fid) {
325         ViceLog(0, ("%s while handling request from host %s:%d viceid %d "
326                     "fid %" AFS_VOLID_FMT ".%lu.%lu, failing request\n",
327                     message,
328                     afs_inet_ntoa_r(rx_HostOf(rx_PeerOf(tcon)), hoststr),
329                     (int)ntohs(rx_PortOf(rx_PeerOf(tcon))),
330                     viceid,
331                     afs_printable_VolumeId_lu(Fid->Volume),
332                     afs_printable_uint32_lu(Fid->Vnode),
333                     afs_printable_uint32_lu(Fid->Unique)));
334     } else {
335         ViceLog(0, ("%s while handling request from host %s:%d viceid %d "
336                     "fid (none), failing request\n",
337                     message,
338                     afs_inet_ntoa_r(rx_HostOf(rx_PeerOf(tcon)), hoststr),
339                     (int)ntohs(rx_PortOf(rx_PeerOf(tcon))),
340                     viceid));
341     }
342 }
343
344 /*
345  * Note that this function always returns a held host, so
346  * that CallPostamble can block without the host's disappearing.
347  * Call returns rx connection in passed in *tconn
348  *
349  * 'Fid' is optional, and is just used for printing log messages.
350  */
351 static int
352 CallPreamble(struct rx_call *acall, int activecall, struct AFSFid *Fid,
353              struct rx_connection **tconn, struct host **ahostp)
354 {
355     struct host *thost;
356     struct client *tclient;
357     afs_int32 viceid = -1;
358     int retry_flag = 1;
359     int code = 0;
360     char hoststr[16], hoststr2[16];
361     struct ubik_client *uclient;
362     *ahostp = NULL;
363
364     if (!tconn) {
365         ViceLog(0, ("CallPreamble: unexpected null tconn!\n"));
366         return -1;
367     }
368     *tconn = rx_ConnectionOf(acall);
369
370     H_LOCK;
371   retry:
372     tclient = h_FindClient_r(*tconn, &viceid);
373     if (!tclient) {
374         H_UNLOCK;
375         LogClientError("CallPreamble: Couldn't get client", *tconn, viceid, Fid);
376         return VBUSY;
377     }
378     thost = tclient->host;
379     if (tclient->prfail == 1) { /* couldn't get the CPS */
380         if (!retry_flag) {
381             h_ReleaseClient_r(tclient);
382             h_Release_r(thost);
383             H_UNLOCK;
384             LogClientError("CallPreamble: Couldn't get CPS", *tconn, viceid, Fid);
385             return -1001;
386         }
387         retry_flag = 0;         /* Retry once */
388
389         /* Take down the old connection and re-read the key file */
390         ViceLog(0,
391                 ("CallPreamble: Couldn't get CPS. Reconnect to ptserver\n"));
392         uclient = (struct ubik_client *)pthread_getspecific(viced_uclient_key);
393
394         /* Is it still necessary to drop this? We hit the net, we should... */
395         H_UNLOCK;
396         if (uclient) {
397             hpr_End(uclient);
398             uclient = NULL;
399         }
400         code = hpr_Initialize(&uclient);
401
402         if (!code)
403             opr_Verify(pthread_setspecific(viced_uclient_key,
404                                            (void *)uclient) == 0);
405         H_LOCK;
406
407         if (code) {
408             h_ReleaseClient_r(tclient);
409             h_Release_r(thost);
410             H_UNLOCK;
411             LogClientError("CallPreamble: couldn't reconnect to ptserver", *tconn, viceid, Fid);
412             return -1001;
413         }
414
415         tclient->prfail = 2;    /* Means re-eval client's cps */
416         h_ReleaseClient_r(tclient);
417         h_Release_r(thost);
418         goto retry;
419     }
420
421     tclient->LastCall = thost->LastCall = time(NULL);
422     if (activecall)             /* For all but "GetTime", "GetStats", and "GetCaps" calls */
423         thost->ActiveCall = thost->LastCall;
424
425     h_Lock_r(thost);
426     if (thost->hostFlags & HOSTDELETED) {
427         ViceLog(3,
428                 ("Discarded a packet for deleted host %s:%d\n",
429                  afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port)));
430         code = VBUSY;           /* raced, so retry */
431     } else if ((thost->hostFlags & VENUSDOWN)
432                || (thost->hostFlags & HFE_LATER)) {
433         if (BreakDelayedCallBacks_r(thost)) {
434             ViceLog(0,
435                     ("BreakDelayedCallbacks FAILED for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
436                      afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2),
437                      ntohs(rxr_PortOf(*tconn))));
438             if (MultiProbeAlternateAddress_r(thost)) {
439                 ViceLog(0,
440                         ("MultiProbe failed to find new address for host %s:%d\n",
441                          afs_inet_ntoa_r(thost->host, hoststr),
442                          ntohs(thost->port)));
443                 code = -1;
444             } else {
445                 ViceLog(0,
446                         ("MultiProbe found new address for host %s:%d\n",
447                          afs_inet_ntoa_r(thost->host, hoststr),
448                          ntohs(thost->port)));
449                 if (BreakDelayedCallBacks_r(thost)) {
450                     ViceLog(0,
451                             ("BreakDelayedCallbacks FAILED AGAIN for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
452                               afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2),
453                               ntohs(rxr_PortOf(*tconn))));
454                     code = -1;
455                 }
456             }
457         }
458     } else {
459         code = 0;
460     }
461
462     h_ReleaseClient_r(tclient);
463     h_Unlock_r(thost);
464     H_UNLOCK;
465     *ahostp = thost;
466     return code;
467
468 }                               /*CallPreamble */
469
470
471 static afs_int32
472 CallPostamble(struct rx_connection *aconn, afs_int32 ret,
473               struct host *ahost)
474 {
475     struct host *thost;
476     struct client *tclient;
477     int translate = 0;
478
479     H_LOCK;
480     tclient = h_FindClient_r(aconn, NULL);
481     if (!tclient)
482         goto busyout;
483     thost = tclient->host;
484     if (thost->hostFlags & HERRORTRANS)
485         translate = 1;
486     h_ReleaseClient_r(tclient);
487
488     if (ahost) {
489             if (ahost != thost) {
490                     /* host/client recycle */
491                     char hoststr[16], hoststr2[16];
492                     ViceLog(0, ("CallPostamble: ahost %s:%d (%p) != thost "
493                                 "%s:%d (%p)\n",
494                                 afs_inet_ntoa_r(ahost->host, hoststr),
495                                 ntohs(ahost->port),
496                                 ahost,
497                                 afs_inet_ntoa_r(thost->host, hoststr2),
498                                 ntohs(thost->port),
499                                 thost));
500             }
501             /* return the reference taken in CallPreamble */
502             h_Release_r(ahost);
503     } else {
504             char hoststr[16];
505             ViceLog(0, ("CallPostamble: null ahost for thost %s:%d (%p)\n",
506                         afs_inet_ntoa_r(thost->host, hoststr),
507                         ntohs(thost->port),
508                         thost));
509     }
510
511     /* return the reference taken in local h_FindClient_r--h_ReleaseClient_r
512      * does not decrement refcount on client->host */
513     h_Release_r(thost);
514
515  busyout:
516     H_UNLOCK;
517     return (translate ? sys_error_to_et(ret) : ret);
518 }                               /*CallPostamble */
519
520 /*
521  * Returns the volume and vnode pointers associated with file Fid; the lock
522  * type on the vnode is set to lock. Note that both volume/vnode's ref counts
523  * are incremented and they must be eventualy released.
524  */
525 static afs_int32
526 CheckVnodeWithCall(AFSFid * fid, Volume ** volptr, struct VCallByVol *cbv,
527                    Vnode ** vptr, int lock)
528 {
529     Error fileCode = 0;
530     Error local_errorCode, errorCode = -1;
531     static struct timeval restartedat = { 0, 0 };
532
533     if (fid->Volume == 0 || fid->Vnode == 0)    /* not: || fid->Unique == 0) */
534         return (EINVAL);
535     if ((*volptr) == 0) {
536         extern int VInit;
537
538         while (1) {
539             int restarting =
540 #ifdef AFS_DEMAND_ATTACH_FS
541                 VSALVAGE
542 #else
543                 VRESTARTING
544 #endif
545                 ;
546             static const struct timespec timeout_ts = { 0, 0 };
547             static const struct timespec * const ts = &timeout_ts;
548
549             errorCode = 0;
550             *volptr = VGetVolumeWithCall(&local_errorCode, &errorCode,
551                                                fid->Volume, ts, cbv);
552             if (!errorCode) {
553                 opr_Assert(*volptr);
554                 break;
555             }
556             if ((errorCode == VOFFLINE) && (VInit < 2)) {
557                 /* The volume we want may not be attached yet because
558                  * the volume initialization is not yet complete.
559                  * We can do several things:
560                  *     1.  return -1, which will cause users to see
561                  *         "connection timed out".  This is more or
562                  *         less the same as always, except that the servers
563                  *         may appear to bounce up and down while they
564                  *         are actually restarting.
565                  *     2.  return VBUSY which will cause clients to
566                  *         sleep and retry for 6.5 - 15 minutes, depending
567                  *         on what version of the CM they are running.  If
568                  *         the file server takes longer than that interval
569                  *         to attach the desired volume, then the application
570                  *         will see an ENODEV or EIO.  This approach has
571                  *         the advantage that volumes which have been attached
572                  *         are immediately available, it keeps the server's
573                  *         immediate backlog low, and the call is interruptible
574                  *         by the user.  Users see "waiting for busy volume."
575                  *     3.  sleep here and retry.  Some people like this approach
576                  *         because there is no danger of seeing errors.  However,
577                  *         this approach only works with a bounded number of
578                  *         clients, since the pending queues will grow without
579                  *         stopping.  It might be better to find a way to take
580                  *         this call and stick it back on a queue in order to
581                  *         recycle this thread for a different request.
582                  *     4.  Return a new error code, which new cache managers will
583                  *         know enough to interpret as "sleep and retry", without
584                  *         the upper bound of 6-15 minutes that is imposed by the
585                  *         VBUSY handling.  Users will see "waiting for
586                  *         busy volume," so they know that something is
587                  *         happening.  Old cache managers must be able to do
588                  *         something reasonable with this, for instance, mark the
589                  *         server down.  Fortunately, any error code < 0
590                  *         will elicit that behavior. See #1.
591                  *     5.  Some combination of the above.  I like doing #2 for 10
592                  *         minutes, followed by #4.  3.1b and 3.2 cache managers
593                  *         will be fine as long as the restart period is
594                  *         not longer than 6.5 minutes, otherwise they may
595                  *         return ENODEV to users.  3.3 cache managers will be
596                  *         fine for 10 minutes, then will return
597                  *         ETIMEDOUT.  3.4 cache managers will just wait
598                  *         until the call works or fails definitively.
599                  *  NB. The problem with 2,3,4,5 is that old clients won't
600                  *  fail over to an alternate read-only replica while this
601                  *  server is restarting.  3.4 clients will fail over right away.
602                  */
603                 if (restartedat.tv_sec == 0) {
604                     /* I'm not really worried about when we restarted, I'm   */
605                     /* just worried about when the first VBUSY was returned. */
606                     gettimeofday(&restartedat, 0);
607                     if (busyonrst) {
608                         FS_LOCK;
609                         afs_perfstats.fs_nBusies++;
610                         FS_UNLOCK;
611                     }
612                     return (busyonrst ? VBUSY : restarting);
613                 } else {
614                     struct timeval now;
615                     gettimeofday(&now, 0);
616                     if ((now.tv_sec - restartedat.tv_sec) < (11 * 60)) {
617                         if (busyonrst) {
618                             FS_LOCK;
619                             afs_perfstats.fs_nBusies++;
620                             FS_UNLOCK;
621                         }
622                         return (busyonrst ? VBUSY : restarting);
623                     } else {
624                         return (restarting);
625                     }
626                 }
627             }
628             /* allow read operations on busy volume.
629              * must check local_errorCode because demand attach fs
630              * can have local_errorCode == VSALVAGING, errorCode == VBUSY */
631             else if (local_errorCode == VBUSY && lock == READ_LOCK) {
632 #ifdef AFS_DEMAND_ATTACH_FS
633                 /* DAFS case is complicated by the fact that local_errorCode can
634                  * be VBUSY in cases where the volume is truly offline */
635                 if (!*volptr) {
636                     /* volume is in VOL_STATE_UNATTACHED */
637                     return (errorCode);
638                 }
639 #endif /* AFS_DEMAND_ATTACH_FS */
640                 errorCode = 0;
641                 break;
642             } else if (errorCode)
643                 return (errorCode);
644         }
645     }
646     opr_Assert(*volptr);
647
648     /* get the vnode  */
649     *vptr = VGetVnode(&errorCode, *volptr, fid->Vnode, lock);
650     if (errorCode)
651         return (errorCode);
652     if ((*vptr)->disk.uniquifier != fid->Unique) {
653         VPutVnode(&fileCode, *vptr);
654         opr_Assert(fileCode == 0);
655         *vptr = 0;
656         return (VNOVNODE);      /* return the right error code, at least */
657     }
658     return (0);
659 }                               /*CheckVnode */
660
661 static_inline afs_int32
662 CheckVnode(AFSFid * fid, Volume ** volptr, Vnode ** vptr, int lock)
663 {
664     return CheckVnodeWithCall(fid, volptr, NULL, vptr, lock);
665 }
666
667 /*
668  * This routine returns the ACL associated with the targetptr. If the
669  * targetptr isn't a directory, we access its parent dir and get the ACL
670  * thru the parent; in such case the parent's vnode is returned in
671  * READ_LOCK mode.
672  */
673 static afs_int32
674 SetAccessList(Vnode ** targetptr, Volume ** volume,
675               struct acl_accessList **ACL, int *ACLSize, Vnode ** parent,
676               AFSFid * Fid, int Lock)
677 {
678     if ((*targetptr)->disk.type == vDirectory) {
679         *parent = 0;
680         *ACL = VVnodeACL(*targetptr);
681         *ACLSize = VAclSize(*targetptr);
682         return (0);
683     } else {
684         opr_Assert(Fid != 0);
685         while (1) {
686             VnodeId parentvnode;
687             Error errorCode = 0;
688
689             parentvnode = (*targetptr)->disk.parent;
690             VPutVnode(&errorCode, *targetptr);
691             *targetptr = 0;
692             if (errorCode)
693                 return (errorCode);
694             *parent = VGetVnode(&errorCode, *volume, parentvnode, READ_LOCK);
695             if (errorCode)
696                 return (errorCode);
697             *ACL = VVnodeACL(*parent);
698             *ACLSize = VAclSize(*parent);
699             if ((errorCode = CheckVnode(Fid, volume, targetptr, Lock)) != 0)
700                 return (errorCode);
701             if ((*targetptr)->disk.parent != parentvnode) {
702                 VPutVnode(&errorCode, *parent);
703                 *parent = 0;
704                 if (errorCode)
705                     return (errorCode);
706             } else
707                 return (0);
708         }
709     }
710
711 }                               /*SetAccessList */
712
713 /* Must not be called with H_LOCK held */
714 static void
715 client_CheckRights(struct client *client, struct acl_accessList *ACL,
716                    afs_int32 *rights)
717 {
718     *rights = 0;
719     ObtainReadLock(&client->lock);
720     if (client->CPS.prlist_len > 0 && !client->deleted &&
721         client->host && !(client->host->hostFlags & HOSTDELETED))
722         acl_CheckRights(ACL, &client->CPS, rights);
723     ReleaseReadLock(&client->lock);
724 }
725
726 /* Must not be called with H_LOCK held */
727 static afs_int32
728 client_HasAsMember(struct client *client, afs_int32 id)
729 {
730     afs_int32 code = 0;
731
732     ObtainReadLock(&client->lock);
733     if (client->CPS.prlist_len > 0 && !client->deleted &&
734         client->host && !(client->host->hostFlags & HOSTDELETED))
735         code = acl_IsAMember(id, &client->CPS);
736     ReleaseReadLock(&client->lock);
737     return code;
738 }
739
740 /*
741  * Compare the directory's ACL with the user's access rights in the client
742  * connection and return the user's and everybody else's access permissions
743  * in rights and anyrights, respectively
744  */
745 static afs_int32
746 GetRights(struct client *client, struct acl_accessList *ACL,
747           afs_int32 * rights, afs_int32 * anyrights)
748 {
749     extern prlist SystemAnyUserCPS;
750     afs_int32 hrights = 0;
751
752     if (acl_CheckRights(ACL, &SystemAnyUserCPS, anyrights) != 0) {
753         ViceLog(0, ("CheckRights failed\n"));
754         *anyrights = 0;
755     }
756     *rights = 0;
757
758     client_CheckRights(client, ACL, rights);
759
760     /* wait if somebody else is already doing the getCPS call */
761     H_LOCK;
762     while (client->host->hostFlags & HCPS_INPROGRESS) {
763         client->host->hostFlags |= HCPS_WAITING;        /* I am waiting */
764         opr_cv_wait(&client->host->cond, &host_glock_mutex);
765     }
766
767     if (!client->host->hcps.prlist_len || !client->host->hcps.prlist_val) {
768         char hoststr[16];
769         ViceLog(5,
770                 ("CheckRights: len=%u, for host=%s:%d\n",
771                  client->host->hcps.prlist_len,
772                  afs_inet_ntoa_r(client->host->host, hoststr),
773                  ntohs(client->host->port)));
774     } else
775         acl_CheckRights(ACL, &client->host->hcps, &hrights);
776     H_UNLOCK;
777     /* Allow system:admin the rights given with the -implicit option */
778     if (client_HasAsMember(client, SystemId))
779         *rights |= implicitAdminRights;
780
781     *rights |= hrights;
782     *anyrights |= hrights;
783
784     return (0);
785
786 }                               /*GetRights */
787
788 /*
789  * VanillaUser returns 1 (true) if the user is a vanilla user (i.e., not
790  * a System:Administrator)
791  */
792 static afs_int32
793 VanillaUser(struct client *client)
794 {
795     if (client_HasAsMember(client, SystemId))
796         return (0);             /* not a system administrator, then you're "vanilla" */
797     return (1);
798
799 }                               /*VanillaUser */
800
801
802 /*------------------------------------------------------------------------
803  * GetVolumePackageWithCall
804  *
805  * Description:
806  *      This unusual afs_int32-parameter routine encapsulates all volume
807  *      package related operations together in a single function; it's
808  *      called by almost all AFS interface calls.
809  *
810  * Arguments:
811  *      acall               : Ptr to Rx call on which this request came in.
812  *      cbv                 : struct containing the RX call for offline cancels
813  *      Fid                 : the AFS fid the caller is acting on
814  *      volptr              : returns a pointer to the volume struct
815  *      targetptr           : returns a pointer to the vnode struct
816  *      chkforDir           : whether to check for if vnode is a dir
817  *      parent              : returns a pointer to the parent of this vnode
818  *      client              : returns a pointer to the calling client
819  *      locktype            : indicates what kind of lock to take on vnodes
820  *      rights              : returns a pointer to caller's rights
821  *      anyrights           : returns a pointer to anonymous' rights
822  *      remote              : indicates that the volume is a remote RW replica
823  *
824  * Returns:
825  *      0 on success
826  *      appropriate error based on permission or invalid operation.
827  *
828  * Environment:
829  *      Nothing interesting.
830  *
831  * Side Effects:
832  *      On success, disables keepalives on the call. Caller should re-enable
833  *      after completing disk I/O.
834  *------------------------------------------------------------------------*/
835 static afs_int32
836 GetVolumePackageWithCall(struct rx_call *acall, struct VCallByVol *cbv,
837                          AFSFid * Fid, Volume ** volptr, Vnode ** targetptr,
838                          int chkforDir, Vnode ** parent,
839                          struct client **client, int locktype,
840                          afs_int32 * rights, afs_int32 * anyrights, int remote)
841 {
842     struct acl_accessList *aCL = NULL;  /* Internal access List */
843     int aCLSize;                /* size of the access list */
844     Error errorCode = 0;                /* return code to caller */
845     struct rx_connection *tcon = rx_ConnectionOf(acall);
846
847     rx_KeepAliveOff(acall);
848
849     if ((errorCode = CheckVnodeWithCall(Fid, volptr, cbv, targetptr, locktype)))
850         goto gvpdone;
851
852     if (chkforDir) {
853         if (chkforDir == MustNOTBeDIR
854             && ((*targetptr)->disk.type == vDirectory)) {
855             errorCode = EISDIR;
856             goto gvpdone;
857         }
858         else if (chkforDir == MustBeDIR
859                  && ((*targetptr)->disk.type != vDirectory)) {
860             errorCode = ENOTDIR;
861             goto gvpdone;
862         }
863     }
864     /*
865      * If the remote flag is set, the current call is dealing with a remote RW
866      * replica, and it can be assumed that the appropriate access checks were
867      * done by the calling server hosting the master volume.
868      */
869     if (!remote) {
870         if ((errorCode = SetAccessList(targetptr, volptr, &aCL, &aCLSize, parent,
871                 (chkforDir == MustBeDIR ? (AFSFid *) 0 : Fid),
872                 (chkforDir == MustBeDIR ? 0 : locktype))) != 0)
873             goto gvpdone;
874         if (chkforDir == MustBeDIR)
875             opr_Assert((*parent) == 0);
876         if (!(*client)) {
877             if ((errorCode = GetClient(tcon, client)) != 0)
878                 goto gvpdone;
879             if (!(*client)) {
880                 errorCode = EINVAL;
881                 goto gvpdone;
882             }
883         }
884         GetRights(*client, aCL, rights, anyrights);
885         /* ok, if this is not a dir, set the PRSFS_ADMINISTER bit iff we're the owner */
886         if ((*targetptr)->disk.type != vDirectory) {
887             /* anyuser can't be owner, so only have to worry about rights, not anyrights */
888             if ((*targetptr)->disk.owner == (*client)->ViceId)
889                 (*rights) |= PRSFS_ADMINISTER;
890             else
891                 (*rights) &= ~PRSFS_ADMINISTER;
892         }
893 #ifdef ADMIN_IMPLICIT_LOOKUP
894         /* admins get automatic lookup on everything */
895         if (!VanillaUser(*client))
896             (*rights) |= PRSFS_LOOKUP;
897 #endif /* ADMIN_IMPLICIT_LOOKUP */
898     }
899 gvpdone:
900     if (errorCode)
901         rx_KeepAliveOn(acall);
902     return errorCode;
903
904 }                               /*GetVolumePackage */
905
906 static_inline afs_int32
907 GetVolumePackage(struct rx_call *acall, AFSFid * Fid, Volume ** volptr,
908                  Vnode ** targetptr, int chkforDir, Vnode ** parent,
909                  struct client **client, int locktype, afs_int32 * rights,
910                  afs_int32 * anyrights)
911 {
912     return GetVolumePackageWithCall(acall, NULL, Fid, volptr, targetptr,
913                                     chkforDir, parent, client, locktype,
914                                     rights, anyrights, 0);
915 }
916
917
918 /*------------------------------------------------------------------------
919  * PutVolumePackageWithCall
920  *
921  * Description:
922  *      This is the opposite of GetVolumePackage(), and is always used at
923  *      the end of AFS calls to put back all used vnodes and the volume
924  *      in the proper order!
925  *
926  * Arguments:
927  *      acall               : Ptr to Rx call on which this request came in.
928  *      parentwhentargetnotdir : a pointer to the parent when the target isn't
929  *                            a directory vnode
930  *      targetptr           : a pointer to the vnode struct
931  *      parentptr           : a pointer to the parent of this vnode
932  *      volptr              : a pointer to the volume structure
933  *      client              : a pointer to the calling client
934  *      cbv                 : struct containing the RX call for offline cancels
935  *
936  * Returns:
937  *      Nothing
938  *
939  * Environment:
940  *      Nothing interesting.
941  *
942  * Side Effects:
943  *      Enables keepalives on the call.
944  *------------------------------------------------------------------------*/
945 static void
946 PutVolumePackageWithCall(struct rx_call *acall, Vnode *
947                          parentwhentargetnotdir, Vnode * targetptr,
948                          Vnode * parentptr, Volume * volptr,
949                          struct client **client, struct VCallByVol *cbv)
950 {
951     Error fileCode = 0;         /* Error code returned by the volume package */
952
953     rx_KeepAliveOff(acall);
954     if (parentwhentargetnotdir) {
955         VPutVnode(&fileCode, parentwhentargetnotdir);
956         opr_Assert(!fileCode || (fileCode == VSALVAGE));
957     }
958     if (targetptr) {
959         VPutVnode(&fileCode, targetptr);
960         opr_Assert(!fileCode || (fileCode == VSALVAGE));
961     }
962     if (parentptr) {
963         VPutVnode(&fileCode, parentptr);
964         opr_Assert(!fileCode || (fileCode == VSALVAGE));
965     }
966     if (volptr) {
967         VPutVolumeWithCall(volptr, cbv);
968     }
969     rx_KeepAliveOn(acall);
970
971     if (*client) {
972         PutClient(client);
973     }
974 }                               /*PutVolumePackage */
975
976 static_inline void
977 PutVolumePackage(struct rx_call *acall, Vnode * parentwhentargetnotdir,
978                  Vnode * targetptr, Vnode * parentptr, Volume * volptr,
979                  struct client **client)
980 {
981     PutVolumePackageWithCall(acall, parentwhentargetnotdir, targetptr,
982                              parentptr, volptr, client, NULL);
983 }
984
985 static int
986 VolumeOwner(struct client *client, Vnode * targetptr)
987 {
988     afs_int32 owner = V_owner(targetptr->volumePtr);    /* get volume owner */
989
990     if (owner >= 0)
991         return (client->ViceId == owner);
992     else {
993         /*
994          * We don't have to check for host's cps since only regular
995          * viceid are volume owners.
996          */
997         return (client_HasAsMember(client, owner));
998     }
999
1000 }                               /*VolumeOwner */
1001
1002 static int
1003 VolumeRootVnode(Vnode * targetptr)
1004 {
1005     return ((targetptr->vnodeNumber == ROOTVNODE)
1006             && (targetptr->disk.uniquifier == 1));
1007
1008 }                               /*VolumeRootVnode */
1009
1010 /*
1011  * Check if target file has the proper access permissions for the Fetch
1012  * (FetchData, FetchACL, FetchStatus) and Store (StoreData, StoreACL,
1013  * StoreStatus) related calls
1014  */
1015 /* this code should probably just set a "priv" flag where all the audit events
1016  * are now, and only generate the audit event once at the end of the routine,
1017  * thus only generating the event if all the checks succeed, but only because
1018  * of the privilege       XXX
1019  */
1020 static afs_int32
1021 Check_PermissionRights(Vnode * targetptr, struct client *client,
1022                        afs_int32 rights, int CallingRoutine,
1023                        AFSStoreStatus * InStatus)
1024 {
1025     Error errorCode = 0;
1026 #define OWNSp(client, target) ((client)->ViceId == (target)->disk.owner)
1027 #define CHOWN(i,t) (((i)->Mask & AFS_SETOWNER) &&((i)->Owner != (t)->disk.owner))
1028 #define CHGRP(i,t) (((i)->Mask & AFS_SETGROUP) &&((i)->Group != (t)->disk.group))
1029
1030     if (CallingRoutine & CHK_FETCH) {
1031         if (CallingRoutine == CHK_FETCHDATA || VanillaUser(client)) {
1032             if (targetptr->disk.type == vDirectory
1033                 || targetptr->disk.type == vSymlink) {
1034                 if (!(rights & PRSFS_LOOKUP)
1035 #ifdef ADMIN_IMPLICIT_LOOKUP
1036                     /* grant admins fetch on all directories */
1037                     && VanillaUser(client)
1038 #endif /* ADMIN_IMPLICIT_LOOKUP */
1039                     && !VolumeOwner(client, targetptr))
1040                     return (EACCES);
1041             } else {            /* file */
1042                 /* must have read access, or be owner and have insert access */
1043                 if (!(rights & PRSFS_READ)
1044                     && !((OWNSp(client, targetptr) && (rights & PRSFS_INSERT)
1045                           && (client->ViceId != AnonymousID))))
1046                     return (EACCES);
1047             }
1048             if (CallingRoutine == CHK_FETCHDATA
1049                 && targetptr->disk.type == vFile)
1050 #ifdef USE_GROUP_PERMS
1051                 if (!OWNSp(client, targetptr)
1052                     && !client_HasAsMember(client, targetptr->disk.owner)) {
1053                     errorCode =
1054                         (((GROUPREAD | GROUPEXEC) & targetptr->disk.modeBits)
1055                          ? 0 : EACCES);
1056                 } else {
1057                     errorCode =
1058                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.modeBits)
1059                          ? 0 : EACCES);
1060                 }
1061 #else
1062                 /*
1063                  * The check with the ownership below is a kludge to allow
1064                  * reading of files created with no read permission. The owner
1065                  * of the file is always allowed to read it.
1066                  */
1067                 if ((client->ViceId != targetptr->disk.owner)
1068                     && VanillaUser(client))
1069                     errorCode =
1070                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.
1071                           modeBits) ? 0 : EACCES);
1072 #endif
1073         } else {                /*  !VanillaUser(client) && !FetchData */
1074
1075             osi_audit(PrivilegeEvent, 0, AUD_ID,
1076                       (client ? client->ViceId : 0), AUD_INT, CallingRoutine,
1077                       AUD_END);
1078         }
1079     } else {                    /* a store operation */
1080         if ((rights & PRSFS_INSERT) && OWNSp(client, targetptr)
1081             && (CallingRoutine != CHK_STOREACL)
1082             && (targetptr->disk.type == vFile)) {
1083             /* bypass protection checks on first store after a create
1084              * for the creator; also prevent chowns during this time
1085              * unless you are a system administrator */
1086           /******  InStatus->Owner && UnixModeBits better be SET!! */
1087             if (CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
1088                 if (readonlyServer)
1089                     return (VREADONLY);
1090                 else if (VanillaUser(client))
1091                     return (EPERM);     /* Was EACCES */
1092                 else
1093                     osi_audit(PrivilegeEvent, 0, AUD_ID,
1094                               (client ? client->ViceId : 0), AUD_INT,
1095                               CallingRoutine, AUD_END);
1096             }
1097         } else {
1098             if (CallingRoutine != CHK_STOREDATA && !VanillaUser(client)) {
1099                 osi_audit(PrivilegeEvent, 0, AUD_ID,
1100                           (client ? client->ViceId : 0), AUD_INT,
1101                           CallingRoutine, AUD_END);
1102             } else {
1103                 if (readonlyServer) {
1104                     return (VREADONLY);
1105                 }
1106                 if (CallingRoutine == CHK_STOREACL) {
1107                     if (!(rights & PRSFS_ADMINISTER)
1108                         && !VolumeOwner(client, targetptr))
1109                         return (EACCES);
1110                 } else {        /* store data or status */
1111                     /* watch for chowns and chgrps */
1112                     if (CHOWN(InStatus, targetptr)
1113                         || CHGRP(InStatus, targetptr)) {
1114                         if (readonlyServer)
1115                             return (VREADONLY);
1116                         else if (VanillaUser(client))
1117                             return (EPERM);     /* Was EACCES */
1118                         else
1119                             osi_audit(PrivilegeEvent, 0, AUD_ID,
1120                                       (client ? client->ViceId : 0), AUD_INT,
1121                                       CallingRoutine, AUD_END);
1122                     }
1123                     /* must be sysadmin to set suid/sgid bits */
1124                     if ((InStatus->Mask & AFS_SETMODE) &&
1125 #ifdef AFS_NT40_ENV
1126                         (InStatus->UnixModeBits & 0xc00) != 0) {
1127 #else
1128                         (InStatus->UnixModeBits & (S_ISUID | S_ISGID)) != 0) {
1129 #endif
1130                         if (readonlyServer)
1131                             return (VREADONLY);
1132                         if (VanillaUser(client))
1133                             return (EACCES);
1134                         else
1135                             osi_audit(PrivSetID, 0, AUD_ID,
1136                                       (client ? client->ViceId : 0), AUD_INT,
1137                                       CallingRoutine, AUD_END);
1138                     }
1139                     if (CallingRoutine == CHK_STOREDATA) {
1140                         if (readonlyServer)
1141                             return (VREADONLY);
1142                         if (!(rights & PRSFS_WRITE))
1143                             return (EACCES);
1144                         /* Next thing is tricky.  We want to prevent people
1145                          * from writing files sans 0200 bit, but we want
1146                          * creating new files with 0444 mode to work.  We
1147                          * don't check the 0200 bit in the "you are the owner"
1148                          * path above, but here we check the bit.  However, if
1149                          * you're a system administrator, we ignore the 0200
1150                          * bit anyway, since you may have fchowned the file,
1151                          * too */
1152 #ifdef USE_GROUP_PERMS
1153                         if ((targetptr->disk.type == vFile)
1154                             && VanillaUser(client)) {
1155                             if (!OWNSp(client, targetptr)
1156                                 && !client_HasAsMember(client, targetptr->disk.owner)) {
1157                                 errorCode =
1158                                     ((GROUPWRITE & targetptr->disk.modeBits)
1159                                      ? 0 : EACCES);
1160                             } else {
1161                                 errorCode =
1162                                     ((OWNERWRITE & targetptr->disk.modeBits)
1163                                      ? 0 : EACCES);
1164                             }
1165                         } else
1166 #endif
1167                             if ((targetptr->disk.type != vDirectory)
1168                                 && (!(targetptr->disk.modeBits & OWNERWRITE))) {
1169                             if (readonlyServer)
1170                                 return (VREADONLY);
1171                             if (VanillaUser(client))
1172                                 return (EACCES);
1173                             else
1174                                 osi_audit(PrivilegeEvent, 0, AUD_ID,
1175                                           (client ? client->ViceId : 0),
1176                                           AUD_INT, CallingRoutine, AUD_END);
1177                         }
1178                     } else {    /* a status store */
1179                         if (readonlyServer)
1180                             return (VREADONLY);
1181                         if (targetptr->disk.type == vDirectory) {
1182                             if (!(rights & PRSFS_DELETE)
1183                                 && !(rights & PRSFS_INSERT))
1184                                 return (EACCES);
1185                         } else {        /* a file  or symlink */
1186                             if (!(rights & PRSFS_WRITE))
1187                                 return (EACCES);
1188                         }
1189                     }
1190                 }
1191             }
1192         }
1193     }
1194     return (errorCode);
1195
1196 }                               /*Check_PermissionRights */
1197
1198
1199 /*
1200  * The Access List information is converted from its internal form in the
1201  * target's vnode buffer (or its parent vnode buffer if not a dir), to an
1202  * external form and returned back to the caller, via the AccessList
1203  * structure
1204  */
1205 static afs_int32
1206 RXFetch_AccessList(Vnode * targetptr, Vnode * parentwhentargetnotdir,
1207                    struct AFSOpaque *AccessList)
1208 {
1209     char *eACL;                 /* External access list placeholder */
1210
1211     if (acl_Externalize_pr
1212         (hpr_IdToName, (targetptr->disk.type ==
1213           vDirectory ? VVnodeACL(targetptr) :
1214           VVnodeACL(parentwhentargetnotdir)), &eACL) != 0) {
1215         return EIO;
1216     }
1217     if ((strlen(eACL) + 1) > AFSOPAQUEMAX) {
1218         acl_FreeExternalACL(&eACL);
1219         return (E2BIG);
1220     } else {
1221         strcpy((char *)(AccessList->AFSOpaque_val), (char *)eACL);
1222         AccessList->AFSOpaque_len = strlen(eACL) + 1;
1223     }
1224     acl_FreeExternalACL(&eACL);
1225     return (0);
1226
1227 }                               /*RXFetch_AccessList */
1228
1229
1230 /*
1231  * The Access List information is converted from its external form in the
1232  * input AccessList structure to the internal representation and copied into
1233  * the target dir's vnode storage.
1234  */
1235 static afs_int32
1236 RXStore_AccessList(Vnode * targetptr, struct AFSOpaque *AccessList)
1237 {
1238     struct acl_accessList *newACL;      /* PlaceHolder for new access list */
1239
1240     if (acl_Internalize_pr(hpr_NameToId, AccessList->AFSOpaque_val, &newACL)
1241         != 0)
1242         return (EINVAL);
1243     if ((newACL->size + 4) > VAclSize(targetptr))
1244         return (E2BIG);
1245     memcpy((char *)VVnodeACL(targetptr), (char *)newACL, (int)(newACL->size));
1246     acl_FreeACL(&newACL);
1247     return (0);
1248
1249 }                               /*RXStore_AccessList */
1250
1251 static int
1252 CheckLink(Volume *volptr, FdHandle_t *fdP, const char *descr)
1253 {
1254     int code;
1255     afs_ino_str_t ino;
1256
1257     code = FDH_ISUNLINKED(fdP);
1258     if (code < 0) {
1259         ViceLog(0, ("CopyOnWrite: error fstating volume %u inode %s (%s), errno %d\n",
1260                     V_id(volptr), PrintInode(ino, fdP->fd_ih->ih_ino), descr, errno));
1261         return -1;
1262     }
1263     if (code) {
1264         ViceLog(0, ("CopyOnWrite corruption prevention: detected zero nlink for "
1265                     "volume %u inode %s (%s), forcing volume offline\n",
1266                     V_id(volptr), PrintInode(ino, fdP->fd_ih->ih_ino), descr));
1267         return -1;
1268     }
1269     return 0;
1270 }
1271
1272 /* In our current implementation, each successive data store (new file
1273  * data version) creates a new inode. This function creates the new
1274  * inode, copies the old inode's contents to the new one, remove the old
1275  * inode (i.e. decrement inode count -- if it's currently used the delete
1276  * will be delayed), and modify some fields (i.e. vnode's
1277  * disk.inodeNumber and cloned)
1278  */
1279 #define COPYBUFFSIZE    8192
1280 #define MAXFSIZE (~(afs_fsize_t) 0)
1281 static int
1282 CopyOnWrite(Vnode * targetptr, Volume * volptr, afs_foff_t off, afs_fsize_t len)
1283 {
1284     Inode ino;
1285     Inode nearInode AFS_UNUSED;
1286     ssize_t rdlen;
1287     ssize_t wrlen;
1288     afs_fsize_t size;
1289     afs_foff_t done;
1290     size_t length;
1291     char *buff;
1292     int rc;                     /* return code */
1293     IHandle_t *newH;            /* Use until finished copying, then cp to vnode. */
1294     FdHandle_t *targFdP;        /* Source Inode file handle */
1295     FdHandle_t *newFdP;         /* Dest Inode file handle */
1296
1297     if (targetptr->disk.type == vDirectory)
1298         DFlush();               /* just in case? */
1299
1300     VN_GET_LEN(size, targetptr);
1301     if (size > off)
1302         size -= off;
1303     else
1304         size = 0;
1305     if (size > len)
1306         size = len;
1307
1308     buff = malloc(COPYBUFFSIZE);
1309     if (buff == NULL) {
1310         return EIO;
1311     }
1312
1313     ino = VN_GET_INO(targetptr);
1314     if (!VALID_INO(ino)) {
1315         free(buff);
1316         VTakeOffline(volptr);
1317         ViceLog(0, ("Volume %" AFS_VOLID_FMT " now offline, must be salvaged.\n",
1318                     afs_printable_VolumeId_lu(volptr->hashid)));
1319         return EIO;
1320     }
1321     targFdP = IH_OPEN(targetptr->handle);
1322     if (targFdP == NULL) {
1323         rc = errno;
1324         ViceLog(0,
1325                 ("CopyOnWrite failed: Failed to open target vnode %u in volume %" AFS_VOLID_FMT " (errno = %d)\n",
1326                  targetptr->vnodeNumber, afs_printable_VolumeId_lu(V_id(volptr)), rc));
1327         free(buff);
1328         VTakeOffline(volptr);
1329         return rc;
1330     }
1331
1332     nearInode = VN_GET_INO(targetptr);
1333     ino =
1334         IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1335                   VPartitionPath(V_partition(volptr)), nearInode,
1336                   V_id(volptr), targetptr->vnodeNumber,
1337                   targetptr->disk.uniquifier,
1338                   (int)targetptr->disk.dataVersion);
1339     if (!VALID_INO(ino)) {
1340         ViceLog(0,
1341                 ("CopyOnWrite failed: Partition %s that contains volume %" AFS_VOLID_FMT " may be out of free inodes(errno = %d)\n",
1342                  volptr->partition->name, afs_printable_VolumeId_lu(V_id(volptr)), errno));
1343         FDH_CLOSE(targFdP);
1344         free(buff);
1345         return ENOSPC;
1346     }
1347     IH_INIT(newH, V_device(volptr), V_id(volptr), ino);
1348     newFdP = IH_OPEN(newH);
1349     opr_Assert(newFdP != NULL);
1350
1351     rc = CheckLink(volptr, targFdP, "source");
1352     if (!rc) {
1353         rc = CheckLink(volptr, newFdP, "dest");
1354     }
1355     if (rc) {
1356         FDH_REALLYCLOSE(newFdP);
1357         IH_RELEASE(newH);
1358         FDH_REALLYCLOSE(targFdP);
1359         IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1360         free(buff);
1361         VTakeOffline(volptr);
1362         return VSALVAGE;
1363     }
1364
1365     done = off;
1366     while (size > 0) {
1367         if (size > COPYBUFFSIZE) {      /* more than a buffer */
1368             length = COPYBUFFSIZE;
1369             size -= COPYBUFFSIZE;
1370         } else {
1371             length = size;
1372             size = 0;
1373         }
1374         rdlen = FDH_PREAD(targFdP, buff, length, done);
1375         if (rdlen == length) {
1376             wrlen = FDH_PWRITE(newFdP, buff, length, done);
1377             done += rdlen;
1378         } else
1379             wrlen = 0;
1380         /*  Callers of this function are not prepared to recover
1381          *  from error that put the filesystem in an inconsistent
1382          *  state. Make sure that we force the volume off-line if
1383          *  we some error other than ENOSPC - 4.29.99)
1384          *
1385          *  In case we are unable to write the required bytes, and the
1386          *  error code indicates that the disk is full, we roll-back to
1387          *  the initial state.
1388          */
1389         if ((rdlen != length) || (wrlen != length)) {
1390             if ((wrlen < 0) && (errno == ENOSPC)) {     /* disk full */
1391                 ViceLog(0,
1392                         ("CopyOnWrite failed: Partition %s containing volume %" AFS_VOLID_FMT " is full\n",
1393                          volptr->partition->name, afs_printable_VolumeId_lu(V_id(volptr))));
1394                 /* remove destination inode which was partially copied till now */
1395                 FDH_REALLYCLOSE(newFdP);
1396                 IH_RELEASE(newH);
1397                 FDH_REALLYCLOSE(targFdP);
1398                 rc = IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1399                 if (rc) {
1400                     ViceLog(0,
1401                             ("CopyOnWrite failed: error %u after i_dec on disk full, volume %" AFS_VOLID_FMT " in partition %s needs salvage\n",
1402                              rc, afs_printable_VolumeId_lu(V_id(volptr)), volptr->partition->name));
1403                     VTakeOffline(volptr);
1404                 }
1405                 free(buff);
1406                 return ENOSPC;
1407             } else {
1408                 /* length, rdlen, and wrlen may or may not be 64-bits wide;
1409                  * since we never do any I/O anywhere near 2^32 bytes at a
1410                  * time, just case to an unsigned int for printing */
1411
1412                 ViceLog(0,
1413                         ("CopyOnWrite failed: volume %" AFS_VOLID_FMT " in partition %s  (tried reading %u, read %u, wrote %u, errno %u) volume needs salvage\n",
1414                          afs_printable_VolumeId_lu(V_id(volptr)), volptr->partition->name, (unsigned)length, (unsigned)rdlen,
1415                          (unsigned)wrlen, errno));
1416 #if defined(AFS_DEMAND_ATTACH_FS)
1417                 ViceLog(0, ("CopyOnWrite failed: requesting salvage\n"));
1418 #else
1419                 ViceLog(0, ("CopyOnWrite failed: taking volume offline\n"));
1420 #endif
1421                 /* Decrement this inode so salvager doesn't find it. */
1422                 FDH_REALLYCLOSE(newFdP);
1423                 IH_RELEASE(newH);
1424                 FDH_REALLYCLOSE(targFdP);
1425                 IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1426                 free(buff);
1427                 VTakeOffline(volptr);
1428                 return EIO;
1429             }
1430         }
1431     }
1432     FDH_REALLYCLOSE(targFdP);
1433     rc = IH_DEC(V_linkHandle(volptr), VN_GET_INO(targetptr),
1434                 V_parentId(volptr));
1435     opr_Assert(!rc);
1436     IH_RELEASE(targetptr->handle);
1437
1438     rc = FDH_SYNC(newFdP);
1439     opr_Assert(rc == 0);
1440     FDH_CLOSE(newFdP);
1441     targetptr->handle = newH;
1442     VN_SET_INO(targetptr, ino);
1443     targetptr->disk.cloned = 0;
1444     /* Internal change to vnode, no user level change to volume - def 5445 */
1445     targetptr->changed_oldTime = 1;
1446     free(buff);
1447     return 0;                   /* success */
1448 }                               /*CopyOnWrite */
1449
1450 /*
1451  * Common code to handle with removing the Name (file when it's called from
1452  * SAFS_RemoveFile() or an empty dir when called from SAFS_rmdir()) from a
1453  * given directory, parentptr.
1454  */
1455 int DT1 = 0, DT0 = 0;
1456 static afs_int32
1457 DeleteTarget(Vnode * parentptr, Volume * volptr, Vnode ** targetptr,
1458              DirHandle * dir, AFSFid * fileFid, char *Name, int ChkForDir)
1459 {
1460     DirHandle childdir;         /* Handle for dir package I/O */
1461     Error errorCode = 0;
1462     int code;
1463     afs_ino_str_t stmp;
1464
1465     /* watch for invalid names */
1466     if (!strcmp(Name, ".") || !strcmp(Name, ".."))
1467         return (EINVAL);
1468
1469     if (CheckLength(volptr, parentptr, -1)) {
1470         VTakeOffline(volptr);
1471         return VSALVAGE;
1472     }
1473
1474     if (parentptr->disk.cloned) {
1475         ViceLog(25, ("DeleteTarget : CopyOnWrite called\n"));
1476         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE))) {
1477             ViceLog(20,
1478                     ("DeleteTarget %s: CopyOnWrite failed %d\n", Name,
1479                      errorCode));
1480             return errorCode;
1481         }
1482     }
1483
1484     /* check that the file is in the directory */
1485     SetDirHandle(dir, parentptr);
1486     if (afs_dir_Lookup(dir, Name, fileFid))
1487         return (ENOENT);
1488     fileFid->Volume = V_id(volptr);
1489
1490     /* just-in-case check for something causing deadlock */
1491     if (fileFid->Vnode == parentptr->vnodeNumber)
1492         return (EINVAL);
1493
1494     *targetptr = VGetVnode(&errorCode, volptr, fileFid->Vnode, WRITE_LOCK);
1495     if (errorCode) {
1496         return (errorCode);
1497     }
1498     if (ChkForDir == MustBeDIR) {
1499         if ((*targetptr)->disk.type != vDirectory)
1500             return (ENOTDIR);
1501     } else if ((*targetptr)->disk.type == vDirectory)
1502         return (EISDIR);
1503
1504     /*osi_Assert((*targetptr)->disk.uniquifier == fileFid->Unique); */
1505     /**
1506       * If the uniquifiers dont match then instead of asserting
1507       * take the volume offline and return VSALVAGE
1508       */
1509     if ((*targetptr)->disk.uniquifier != fileFid->Unique) {
1510         VTakeOffline(volptr);
1511         ViceLog(0,
1512                 ("Volume %" AFS_VOLID_FMT " now offline, must be salvaged.\n",
1513                  afs_printable_VolumeId_lu(volptr->hashid)));
1514         errorCode = VSALVAGE;
1515         return errorCode;
1516     }
1517
1518     if (ChkForDir == MustBeDIR) {
1519         SetDirHandle(&childdir, *targetptr);
1520         if (afs_dir_IsEmpty(&childdir) != 0)
1521             return (EEXIST);
1522         DZap(&childdir);
1523         FidZap(&childdir);
1524         (*targetptr)->delete = 1;
1525     } else if ((--(*targetptr)->disk.linkCount) == 0)
1526         (*targetptr)->delete = 1;
1527     if ((*targetptr)->delete) {
1528         if (VN_GET_INO(*targetptr)) {
1529             DT0++;
1530             IH_REALLYCLOSE((*targetptr)->handle);
1531             errorCode =
1532                 IH_DEC(V_linkHandle(volptr), VN_GET_INO(*targetptr),
1533                        V_parentId(volptr));
1534             IH_RELEASE((*targetptr)->handle);
1535             if (errorCode == -1) {
1536                 ViceLog(0,
1537                         ("DT: inode=%s, name=%s, errno=%d\n",
1538                          PrintInode(stmp, VN_GET_INO(*targetptr)), Name,
1539                          errno));
1540                 if (errno != ENOENT)
1541                 {
1542                     VTakeOffline(volptr);
1543                     ViceLog(0,
1544                             ("Volume %" AFS_VOLID_FMT " now offline, must be salvaged.\n",
1545                              afs_printable_VolumeId_lu(volptr->hashid)));
1546                     return (EIO);
1547                 }
1548                 DT1++;
1549                 errorCode = 0;
1550             }
1551         }
1552         VN_SET_INO(*targetptr, (Inode) 0);
1553         {
1554             afs_fsize_t adjLength;
1555             VN_GET_LEN(adjLength, *targetptr);
1556             VAdjustDiskUsage(&errorCode, volptr, -(int)nBlocks(adjLength), 0);
1557         }
1558     }
1559
1560     (*targetptr)->changed_newTime = 1;  /* Status change of deleted file/dir */
1561
1562     code = afs_dir_Delete(dir, Name);
1563     if (code) {
1564         ViceLog(0,
1565                 ("Error %d deleting %s\n", code,
1566                  (((*targetptr)->disk.type ==
1567                    Directory) ? "directory" : "file")));
1568         VTakeOffline(volptr);
1569         ViceLog(0,
1570                 ("Volume %" AFS_VOLID_FMT " now offline, must be salvaged.\n",
1571                  afs_printable_VolumeId_lu(volptr->hashid)));
1572         if (!errorCode)
1573             errorCode = code;
1574     }
1575
1576     DFlush();
1577     return (errorCode);
1578
1579 }                               /*DeleteTarget */
1580
1581
1582 /*
1583  * This routine updates the parent directory's status block after the
1584  * specified operation (i.e. RemoveFile(), CreateFile(), Rename(),
1585  * SymLink(), Link(), MakeDir(), RemoveDir()) on one of its children has
1586  * been performed.
1587  */
1588 static void
1589 Update_ParentVnodeStatus(Vnode * parentptr, Volume * volptr, DirHandle * dir,
1590                          int author, int linkcount, char a_inSameNetwork)
1591 {
1592     afs_fsize_t newlength;      /* Holds new directory length */
1593     afs_fsize_t parentLength;
1594     Error errorCode;
1595     Date currDate;              /*Current date */
1596     int writeIdx;               /*Write index to bump */
1597     int timeIdx;                /*Authorship time index to bump */
1598     time_t now;
1599
1600     parentptr->disk.dataVersion++;
1601     newlength = (afs_fsize_t) afs_dir_Length(dir);
1602     /*
1603      * This is a called on both dir removals (i.e. remove, removedir, rename) but also in dir additions
1604      * (create, symlink, link, makedir) so we need to check if we have enough space
1605      * XXX But we still don't check the error since we're dealing with dirs here and really the increase
1606      * of a new entry would be too tiny to worry about failures (since we have all the existing cushion)
1607      */
1608     VN_GET_LEN(parentLength, parentptr);
1609     if (nBlocks(newlength) != nBlocks(parentLength)) {
1610         VAdjustDiskUsage(&errorCode, volptr,
1611                          (nBlocks(newlength) - nBlocks(parentLength)),
1612                          (nBlocks(newlength) - nBlocks(parentLength)));
1613     }
1614     VN_SET_LEN(parentptr, newlength);
1615
1616     /*
1617      * Update directory write stats for this volume.  Note that the auth
1618      * counter is located immediately after its associated ``distance''
1619      * counter.
1620      */
1621     if (a_inSameNetwork)
1622         writeIdx = VOL_STATS_SAME_NET;
1623     else
1624         writeIdx = VOL_STATS_DIFF_NET;
1625     V_stat_writes(volptr, writeIdx)++;
1626     if (author != AnonymousID) {
1627         V_stat_writes(volptr, writeIdx + 1)++;
1628     }
1629
1630     /*
1631      * Update the volume's authorship information in response to this
1632      * directory operation.  Get the current time, decide to which time
1633      * slot this operation belongs, and bump the appropriate slot.
1634      */
1635     now = time(NULL);
1636     currDate = (now - parentptr->disk.unixModifyTime);
1637     timeIdx =
1638         (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 : currDate <
1639          VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 : currDate <
1640          VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 : currDate <
1641          VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 : currDate <
1642          VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 : VOL_STATS_TIME_IDX_5);
1643     if (parentptr->disk.author == author) {
1644         V_stat_dirSameAuthor(volptr, timeIdx)++;
1645     } else {
1646         V_stat_dirDiffAuthor(volptr, timeIdx)++;
1647     }
1648
1649     parentptr->disk.author = author;
1650     parentptr->disk.linkCount = linkcount;
1651     parentptr->disk.unixModifyTime = now;       /* This should be set from CLIENT!! */
1652     parentptr->disk.serverModifyTime = now;
1653     parentptr->changed_newTime = 1;     /* vnode changed, write it back. */
1654 }
1655
1656
1657 /*
1658  * Update the target file's (or dir's) status block after the specified
1659  * operation is complete. Note that some other fields maybe updated by
1660  * the individual module.
1661  * If remote is set, the volume is a RW replica and access checks can
1662  * be skipped.
1663  */
1664
1665 /* XXX INCOMPLETE - More attention is needed here! */
1666 static void
1667 Update_TargetVnodeStatus(Vnode * targetptr, afs_uint32 Caller,
1668                          struct client *client, AFSStoreStatus * InStatus,
1669                          Vnode * parentptr, Volume * volptr,
1670                          afs_fsize_t length, int remote)
1671 {
1672     Date currDate;              /*Current date */
1673     int writeIdx;               /*Write index to bump */
1674     int timeIdx;                /*Authorship time index to bump */
1675
1676     if (Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR)) { /* initialize new file */
1677         targetptr->disk.parent = parentptr->vnodeNumber;
1678         VN_SET_LEN(targetptr, length);
1679         /* targetptr->disk.group =      0;  save some cycles */
1680         targetptr->disk.modeBits = 0777;
1681         targetptr->disk.owner = client->ViceId;
1682         targetptr->disk.dataVersion = 0;        /* consistent with the client */
1683         targetptr->disk.linkCount = (Caller & TVS_MKDIR ? 2 : 1);
1684         /* the inode was created in Alloc_NewVnode() */
1685     }
1686     /*
1687      * Update file write stats for this volume.  Note that the auth
1688      * counter is located immediately after its associated ``distance''
1689      * counter.
1690      */
1691     if (client->InSameNetwork)
1692         writeIdx = VOL_STATS_SAME_NET;
1693     else
1694         writeIdx = VOL_STATS_DIFF_NET;
1695     V_stat_writes(volptr, writeIdx)++;
1696     if (client->ViceId != AnonymousID) {
1697         V_stat_writes(volptr, writeIdx + 1)++;
1698     }
1699
1700     /*
1701      * We only count operations that DON'T involve creating new objects
1702      * (files, symlinks, directories) or simply setting status as
1703      * authorship-change operations.
1704      */
1705     if (!(Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR | TVS_SSTATUS))) {
1706         /*
1707          * Update the volume's authorship information in response to this
1708          * file operation.  Get the current time, decide to which time
1709          * slot this operation belongs, and bump the appropriate slot.
1710          */
1711         currDate = (time(NULL) - targetptr->disk.unixModifyTime);
1712         timeIdx =
1713             (currDate <
1714              VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 : currDate <
1715              VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 : currDate <
1716              VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 : currDate <
1717              VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 : currDate <
1718              VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1719              VOL_STATS_TIME_IDX_5);
1720         if (targetptr->disk.author == client->ViceId) {
1721             V_stat_fileSameAuthor(volptr, timeIdx)++;
1722         } else {
1723             V_stat_fileDiffAuthor(volptr, timeIdx)++;
1724         }
1725     }
1726
1727     if (!(Caller & TVS_SSTATUS))
1728         targetptr->disk.author = client->ViceId;
1729     if (Caller & TVS_SDATA) {
1730         targetptr->disk.dataVersion++;
1731         if (!remote && VanillaUser(client)) {
1732             /* turn off suid */
1733             targetptr->disk.modeBits = targetptr->disk.modeBits & ~04000;
1734 #ifdef CREATE_SGUID_ADMIN_ONLY
1735             /* turn off sgid */
1736             targetptr->disk.modeBits = targetptr->disk.modeBits & ~02000;
1737 #endif
1738         }
1739     }
1740     if (Caller & TVS_SSTATUS) { /* update time on non-status change */
1741         /* store status, must explicitly request to change the date */
1742         if (InStatus->Mask & AFS_SETMODTIME)
1743             targetptr->disk.unixModifyTime = InStatus->ClientModTime;
1744     } else {                    /* other: date always changes, but perhaps to what is specified by caller */
1745         targetptr->disk.unixModifyTime =
1746             (InStatus->Mask & AFS_SETMODTIME ? InStatus->
1747              ClientModTime : time(NULL));
1748     }
1749     if (InStatus->Mask & AFS_SETOWNER) {
1750         /* admin is allowed to do chmod, chown as well as chown, chmod. */
1751         if (!remote && VanillaUser(client)) {
1752             /* turn off suid */
1753             targetptr->disk.modeBits = targetptr->disk.modeBits & ~04000;
1754 #ifdef CREATE_SGUID_ADMIN_ONLY
1755             /* turn off sgid */
1756             targetptr->disk.modeBits = targetptr->disk.modeBits & ~02000;
1757 #endif
1758         }
1759         targetptr->disk.owner = InStatus->Owner;
1760         if (VolumeRootVnode(targetptr)) {
1761             Error errorCode = 0;        /* what should be done with this? */
1762
1763             V_owner(targetptr->volumePtr) = InStatus->Owner;
1764             VUpdateVolume(&errorCode, targetptr->volumePtr);
1765         }
1766     }
1767     if (InStatus->Mask & AFS_SETMODE) {
1768         int modebits = InStatus->UnixModeBits;
1769 #ifdef CREATE_SGUID_ADMIN_ONLY
1770         if (!remote && VanillaUser(client))
1771             modebits = modebits & 0777;
1772 #endif
1773         if (!remote && VanillaUser(client)) {
1774             targetptr->disk.modeBits = modebits;
1775         } else {
1776             targetptr->disk.modeBits = modebits;
1777             switch (Caller) {
1778             case TVS_SDATA:
1779                 osi_audit(PrivSetID, 0, AUD_ID, client->ViceId, AUD_INT,
1780                           CHK_STOREDATA, AUD_END);
1781                 break;
1782             case TVS_CFILE:
1783             case TVS_SSTATUS:
1784                 osi_audit(PrivSetID, 0, AUD_ID, client->ViceId, AUD_INT,
1785                           CHK_STORESTATUS, AUD_END);
1786                 break;
1787             default:
1788                 break;
1789             }
1790         }
1791     }
1792     targetptr->disk.serverModifyTime = time(NULL);
1793     if (InStatus->Mask & AFS_SETGROUP)
1794         targetptr->disk.group = InStatus->Group;
1795     /* vnode changed : to be written back by VPutVnode */
1796     targetptr->changed_newTime = 1;
1797
1798 }                               /*Update_TargetVnodeStatus */
1799
1800
1801 /*
1802  * Fills the CallBack structure with the expiration time and type of callback
1803  * structure. Warning: this function is currently incomplete.
1804  */
1805 static void
1806 SetCallBackStruct(afs_uint32 CallBackTime, struct AFSCallBack *CallBack)
1807 {
1808     /* CallBackTime could not be 0 */
1809     if (CallBackTime == 0) {
1810         ViceLog(0, ("WARNING: CallBackTime == 0!\n"));
1811         CallBack->ExpirationTime = 0;
1812     } else
1813         CallBack->ExpirationTime = CallBackTime - time(NULL);
1814     CallBack->CallBackVersion = CALLBACK_VERSION;
1815     CallBack->CallBackType = CB_SHARED; /* The default for now */
1816
1817 }                               /*SetCallBackStruct */
1818
1819
1820 /*
1821  * Adjusts (Subtract) "length" number of blocks from the volume's disk
1822  * allocation; if some error occured (exceeded volume quota or partition
1823  * was full, or whatever), it frees the space back and returns the code.
1824  * We usually pre-adjust the volume space to make sure that there's
1825  * enough space before consuming some.
1826  */
1827 static afs_int32
1828 AdjustDiskUsage(Volume * volptr, afs_sfsize_t length,
1829                 afs_sfsize_t checkLength)
1830 {
1831     Error rc;
1832     Error nc;
1833
1834     VAdjustDiskUsage(&rc, volptr, length, checkLength);
1835     if (rc) {
1836         VAdjustDiskUsage(&nc, volptr, -length, 0);
1837         if (rc == VOVERQUOTA) {
1838             ViceLog(2,
1839                     ("Volume %" AFS_VOLID_FMT " (%s) is full\n",
1840                      afs_printable_VolumeId_lu(V_id(volptr)),
1841                      V_name(volptr)));
1842             return (rc);
1843         }
1844         if (rc == VDISKFULL) {
1845             ViceLog(0,
1846                     ("Partition %s that contains volume %" AFS_VOLID_FMT " is full\n",
1847                      volptr->partition->name,
1848                      afs_printable_VolumeId_lu(V_id(volptr))));
1849             return (rc);
1850         }
1851         ViceLog(0, ("Got error return %d from VAdjustDiskUsage\n", rc));
1852         return (rc);
1853     }
1854     return (0);
1855
1856 }                               /*AdjustDiskUsage */
1857
1858 /*
1859  * Common code that handles the creation of a new file (SAFS_CreateFile and
1860  * SAFS_Symlink) or a new dir (SAFS_MakeDir)
1861  */
1862 static afs_int32
1863 Alloc_NewVnode(Vnode * parentptr, DirHandle * dir, Volume * volptr,
1864                Vnode ** targetptr, char *Name, struct AFSFid *OutFid,
1865                int FileType, afs_sfsize_t BlocksPreallocatedForVnode)
1866 {
1867     Error errorCode = 0;                /* Error code returned back */
1868     Error temp;
1869     Inode inode = 0;
1870     Inode nearInode AFS_UNUSED;  /* hint for inode allocation in solaris */
1871     afs_ino_str_t stmp;
1872
1873     if ((errorCode =
1874          AdjustDiskUsage(volptr, BlocksPreallocatedForVnode,
1875                          BlocksPreallocatedForVnode))) {
1876         ViceLog(25,
1877                 ("Insufficient space to allocate %lld blocks\n",
1878                  (afs_intmax_t) BlocksPreallocatedForVnode));
1879         return (errorCode);
1880     }
1881
1882     if (CheckLength(volptr, parentptr, -1)) {
1883         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1884         VTakeOffline(volptr);
1885         return VSALVAGE;
1886     }
1887
1888     *targetptr = VAllocVnode(&errorCode, volptr, FileType, 0, 0);
1889     if (errorCode != 0) {
1890         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1891         return (errorCode);
1892     }
1893     OutFid->Volume = V_id(volptr);
1894     OutFid->Vnode = (*targetptr)->vnodeNumber;
1895     OutFid->Unique = (*targetptr)->disk.uniquifier;
1896
1897     nearInode = VN_GET_INO(parentptr);  /* parent is also in same vol */
1898
1899     /* create the inode now itself */
1900     inode =
1901         IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1902                   VPartitionPath(V_partition(volptr)), nearInode,
1903                   V_id(volptr), (*targetptr)->vnodeNumber,
1904                   (*targetptr)->disk.uniquifier, 1);
1905
1906     /* error in creating inode */
1907     if (!VALID_INO(inode)) {
1908         ViceLog(0,
1909                 ("Volume : %" AFS_VOLID_FMT " vnode = %u Failed to create inode: errno = %d\n",
1910                  afs_printable_VolumeId_lu(V_id((*targetptr)->volumePtr)),
1911                  (*targetptr)->vnodeNumber, errno));
1912         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1913         (*targetptr)->delete = 1;       /* delete vnode */
1914         return ENOSPC;
1915     }
1916     VN_SET_INO(*targetptr, inode);
1917     IH_INIT(((*targetptr)->handle), V_device(volptr), V_id(volptr), inode);
1918
1919     /* copy group from parent dir */
1920     (*targetptr)->disk.group = parentptr->disk.group;
1921
1922     if (parentptr->disk.cloned) {
1923         ViceLog(25, ("Alloc_NewVnode : CopyOnWrite called\n"));
1924         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE))) {        /* disk full */
1925             ViceLog(25, ("Alloc_NewVnode : CopyOnWrite failed\n"));
1926             /* delete the vnode previously allocated */
1927             (*targetptr)->delete = 1;
1928             VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1929             IH_REALLYCLOSE((*targetptr)->handle);
1930             if (IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1931                 ViceLog(0,
1932                         ("Alloc_NewVnode: partition %s idec %s failed\n",
1933                          volptr->partition->name, PrintInode(stmp, inode)));
1934             IH_RELEASE((*targetptr)->handle);
1935
1936             return errorCode;
1937         }
1938     }
1939
1940     /* add the name to the directory */
1941     SetDirHandle(dir, parentptr);
1942     if ((errorCode = afs_dir_Create(dir, Name, OutFid))) {
1943         (*targetptr)->delete = 1;
1944         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1945         IH_REALLYCLOSE((*targetptr)->handle);
1946         if (IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1947             ViceLog(0,
1948                     ("Alloc_NewVnode: partition %s idec %s failed\n",
1949                      volptr->partition->name, PrintInode(stmp, inode)));
1950         IH_RELEASE((*targetptr)->handle);
1951         return (errorCode);
1952     }
1953     DFlush();
1954     return (0);
1955
1956 }                               /*Alloc_NewVnode */
1957
1958
1959 /*
1960  * Handle all the lock-related code (SAFS_SetLock, SAFS_ExtendLock and
1961  * SAFS_ReleaseLock)
1962  */
1963 static afs_int32
1964 HandleLocking(Vnode * targetptr, struct client *client, afs_int32 rights, ViceLockType LockingType)
1965 {
1966     int Time;                   /* Used for time */
1967     int writeVnode = targetptr->changed_oldTime;        /* save original status */
1968
1969     targetptr->changed_oldTime = 1;     /* locking doesn't affect any time stamp */
1970     Time = time(NULL);
1971     switch (LockingType) {
1972     case LockRead:
1973     case LockWrite:
1974         if (Time > targetptr->disk.lock.lockTime)
1975             targetptr->disk.lock.lockTime = targetptr->disk.lock.lockCount =
1976                 0;
1977         Time += AFS_LOCKWAIT;
1978         if (LockingType == LockRead) {
1979             if ( !(rights & PRSFS_LOCK) &&
1980                  !(rights & PRSFS_WRITE) &&
1981                  !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)) )
1982                     return(EACCES);
1983
1984             if (targetptr->disk.lock.lockCount >= 0) {
1985                 ++(targetptr->disk.lock.lockCount);
1986                 targetptr->disk.lock.lockTime = Time;
1987             } else
1988                 return (EAGAIN);
1989         } else if (LockingType == LockWrite) {
1990             if ( !(rights & PRSFS_WRITE) &&
1991                  !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)) )
1992                 return(EACCES);
1993
1994             if (targetptr->disk.lock.lockCount == 0) {
1995                 targetptr->disk.lock.lockCount = -1;
1996                 targetptr->disk.lock.lockTime = Time;
1997             } else
1998                 return (EAGAIN);
1999         }
2000         break;
2001     case LockExtend:
2002         Time += AFS_LOCKWAIT;
2003         if (targetptr->disk.lock.lockCount != 0)
2004             targetptr->disk.lock.lockTime = Time;
2005         else
2006             return (EINVAL);
2007         break;
2008     case LockRelease:
2009         if ((--targetptr->disk.lock.lockCount) <= 0)
2010             targetptr->disk.lock.lockCount = targetptr->disk.lock.lockTime =
2011                 0;
2012         break;
2013     default:
2014         targetptr->changed_oldTime = writeVnode;        /* restore old status */
2015         ViceLog(0, ("Illegal Locking type %d\n", LockingType));
2016     }
2017     return (0);
2018 }                               /*HandleLocking */
2019
2020 /* Checks if caller has the proper AFS and Unix (WRITE) access permission to the target directory; Prfs_Mode refers to the AFS Mode operation while rights contains the caller's access permissions to the directory. */
2021
2022 static afs_int32
2023 CheckWriteMode(Vnode * targetptr, afs_int32 rights, int Prfs_Mode)
2024 {
2025     if (readonlyServer)
2026         return (VREADONLY);
2027     if (!(rights & Prfs_Mode))
2028         return (EACCES);
2029     if ((targetptr->disk.type != vDirectory)
2030         && (!(targetptr->disk.modeBits & OWNERWRITE)))
2031         return (EACCES);
2032     return (0);
2033 }
2034
2035 /*
2036  * If some flags (i.e. min or max quota) are set, the volume's in disk
2037  * label is updated; Name, OfflineMsg, and Motd are also reflected in the
2038  * update, if applicable.
2039  */
2040 static afs_int32
2041 RXUpdate_VolumeStatus(Volume * volptr, AFSStoreVolumeStatus * StoreVolStatus,
2042                       char *Name, char *OfflineMsg, char *Motd)
2043 {
2044     Error errorCode = 0;
2045
2046     if (StoreVolStatus->Mask & AFS_SETMINQUOTA)
2047         V_minquota(volptr) = StoreVolStatus->MinQuota;
2048     if (StoreVolStatus->Mask & AFS_SETMAXQUOTA)
2049         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
2050     if (strlen(OfflineMsg) > 0) {
2051         strcpy(V_offlineMessage(volptr), OfflineMsg);
2052     }
2053     if (strlen(Name) > 0) {
2054         strcpy(V_name(volptr), Name);
2055     }
2056     /*
2057      * We don't overwrite the motd field, since it's now being used
2058      * for stats
2059      */
2060     VUpdateVolume(&errorCode, volptr);
2061     return (errorCode);
2062
2063 }                               /*RXUpdate_VolumeStatus */
2064
2065
2066 static afs_int32
2067 RXGetVolumeStatus(AFSFetchVolumeStatus * status, char **name, char **offMsg,
2068                   char **motd, Volume * volptr)
2069 {
2070
2071     status->Vid = V_id(volptr);
2072     status->ParentId = V_parentId(volptr);
2073     status->Online = V_inUse(volptr);
2074     status->InService = V_inService(volptr);
2075     status->Blessed = V_blessed(volptr);
2076     status->NeedsSalvage = V_needsSalvaged(volptr);
2077     if (VolumeWriteable(volptr))
2078         status->Type = ReadWrite;
2079     else
2080         status->Type = ReadOnly;
2081     status->MinQuota = V_minquota(volptr);
2082     status->MaxQuota = V_maxquota(volptr);
2083     status->BlocksInUse = V_diskused(volptr);
2084     status->PartBlocksAvail = RoundInt64ToInt31(volptr->partition->free);
2085     status->PartMaxBlocks = RoundInt64ToInt31(volptr->partition->totalUsable);
2086
2087     /* now allocate and copy these things; they're freed by the RXGEN stub */
2088     *name = strdup(V_name(volptr));
2089     if (!*name) {
2090         ViceLogThenPanic(0, ("Failed malloc in RXGetVolumeStatus\n"));
2091     }
2092     *offMsg = strdup(V_offlineMessage(volptr));
2093     if (!*offMsg) {
2094         ViceLogThenPanic(0, ("Failed malloc in RXGetVolumeStatus\n"));
2095     }
2096     *motd = malloc(1);
2097     if (!*motd) {
2098         ViceLogThenPanic(0, ("Failed malloc in RXGetVolumeStatus\n"));
2099     }
2100     strcpy(*motd, nullString);
2101     return 0;
2102 }                               /*RXGetVolumeStatus */
2103
2104
2105 static afs_int32
2106 FileNameOK(char *aname)
2107 {
2108     afs_int32 i, tc;
2109     i = strlen(aname);
2110     if (i >= 4) {
2111         /* watch for @sys on the right */
2112         if (strcmp(aname + i - 4, "@sys") == 0)
2113             return 0;
2114     }
2115     while ((tc = *aname++)) {
2116         if (tc == '/')
2117             return 0;           /* very bad character to encounter */
2118     }
2119     return 1;                   /* file name is ok */
2120
2121 }                               /*FileNameOK */
2122
2123
2124 /*
2125  * This variant of symlink is expressly to support the AFS/DFS translator
2126  * and is not supported by the AFS fileserver. We just return EINVAL.
2127  * The cache manager should not generate this call to an AFS cache manager.
2128  */
2129 afs_int32
2130 SRXAFS_DFSSymlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
2131                   char *LinkContents, struct AFSStoreStatus *InStatus,
2132                   struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
2133                   struct AFSFetchStatus *OutDirStatus,
2134                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
2135 {
2136     return EINVAL;
2137 }
2138
2139 afs_int32
2140 SRXAFS_FsCmd(struct rx_call * acall, struct AFSFid * Fid,
2141                     struct FsCmdInputs * Inputs,
2142                     struct FsCmdOutputs * Outputs)
2143 {
2144     afs_int32 code = 0;
2145
2146     switch (Inputs->command) {
2147     default:
2148         code = EINVAL;
2149     }
2150     ViceLog(1,("FsCmd: cmd = %d, code=%d\n",
2151                         Inputs->command, Outputs->code));
2152     return code;
2153 }
2154
2155 #ifndef HAVE_PIOV
2156 static struct afs_buffer {
2157     struct afs_buffer *next;
2158 } *freeBufferList = 0;
2159 static int afs_buffersAlloced = 0;
2160
2161 static int
2162 FreeSendBuffer(struct afs_buffer *adata)
2163 {
2164     FS_LOCK;
2165     afs_buffersAlloced--;
2166     adata->next = freeBufferList;
2167     freeBufferList = adata;
2168     FS_UNLOCK;
2169     return 0;
2170
2171 }                               /*FreeSendBuffer */
2172
2173 /* allocate space for sender */
2174 static char *
2175 AllocSendBuffer(void)
2176 {
2177     struct afs_buffer *tp;
2178
2179     FS_LOCK;
2180     afs_buffersAlloced++;
2181     if (!freeBufferList) {
2182         char *tmp;
2183         FS_UNLOCK;
2184         tmp = malloc(sendBufSize);
2185         if (!tmp) {
2186             ViceLogThenPanic(0, ("Failed malloc in AllocSendBuffer\n"));
2187         }
2188         return tmp;
2189     }
2190     tp = freeBufferList;
2191     freeBufferList = tp->next;
2192     FS_UNLOCK;
2193     return (char *)tp;
2194
2195 }                               /*AllocSendBuffer */
2196 #endif /* HAVE_PIOV */
2197
2198 /*
2199  * This routine returns the status info associated with the targetptr vnode
2200  * in the AFSFetchStatus structure.  Some of the newer fields, such as
2201  * SegSize and Group are not yet implemented
2202  */
2203 static
2204     void
2205 GetStatus(Vnode * targetptr, AFSFetchStatus * status, afs_int32 rights,
2206           afs_int32 anyrights, Vnode * parentptr)
2207 {
2208     int Time = time(NULL);
2209
2210     /* initialize return status from a vnode  */
2211     status->InterfaceVersion = 1;
2212     status->SyncCounter = status->dataVersionHigh = status->lockCount =
2213         status->errorCode = 0;
2214     status->ResidencyMask = 1;  /* means for MR-AFS: file in /vicepr-partition */
2215     if (targetptr->disk.type == vFile)
2216         status->FileType = File;
2217     else if (targetptr->disk.type == vDirectory)
2218         status->FileType = Directory;
2219     else if (targetptr->disk.type == vSymlink)
2220         status->FileType = SymbolicLink;
2221     else
2222         status->FileType = Invalid;     /*invalid type field */
2223     status->LinkCount = targetptr->disk.linkCount;
2224     {
2225         afs_fsize_t targetLen;
2226         VN_GET_LEN(targetLen, targetptr);
2227         SplitOffsetOrSize(targetLen, status->Length_hi, status->Length);
2228     }
2229     status->DataVersion = targetptr->disk.dataVersion;
2230     status->Author = targetptr->disk.author;
2231     status->Owner = targetptr->disk.owner;
2232     status->CallerAccess = rights;
2233     status->AnonymousAccess = anyrights;
2234     status->UnixModeBits = targetptr->disk.modeBits;
2235     status->ClientModTime = targetptr->disk.unixModifyTime;     /* This might need rework */
2236     status->ParentVnode =
2237         (status->FileType ==
2238          Directory ? targetptr->vnodeNumber : parentptr->vnodeNumber);
2239     status->ParentUnique =
2240         (status->FileType ==
2241          Directory ? targetptr->disk.uniquifier : parentptr->disk.uniquifier);
2242     status->ServerModTime = targetptr->disk.serverModifyTime;
2243     status->Group = targetptr->disk.group;
2244     status->lockCount = Time > targetptr->disk.lock.lockTime ? 0 : targetptr->disk.lock.lockCount;
2245     status->errorCode = 0;
2246
2247 }                               /*GetStatus */
2248
2249 static afs_int32
2250 common_FetchData64(struct rx_call *acall, struct AFSFid *Fid,
2251                    afs_sfsize_t Pos, afs_sfsize_t Len,
2252                    struct AFSFetchStatus *OutStatus,
2253                    struct AFSCallBack *CallBack, struct AFSVolSync *Sync,
2254                    int type)
2255 {
2256     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2257     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if vptr is a file */
2258     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2259     Error errorCode = 0;                /* return code to caller */
2260     Error fileCode = 0;         /* return code from vol package */
2261     Volume *volptr = 0;         /* pointer to the volume */
2262     struct client *client = 0;  /* pointer to the client data */
2263     struct rx_connection *tcon; /* the connection we're part of */
2264     struct host *thost;
2265     afs_int32 rights, anyrights;        /* rights for this and any user */
2266     struct client *t_client = NULL;     /* tmp ptr to client data */
2267     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2268     struct VCallByVol tcbv, *cbv = NULL;
2269     static int remainder = 0;   /* shared access protected by FS_LOCK */
2270     struct fsstats fsstats;
2271     afs_sfsize_t bytesToXfer;  /* # bytes to xfer */
2272     afs_sfsize_t bytesXferred; /* # bytes actually xferred */
2273     int readIdx;                /* Index of read stats array to bump */
2274
2275     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_FETCHDATA);
2276
2277     ViceLog(1,
2278             ("SRXAFS_FetchData, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2279              Fid->Unique));
2280     FS_LOCK;
2281     AFSCallStats.FetchData++, AFSCallStats.TotalCalls++;
2282     FS_UNLOCK;
2283     if ((errorCode = CallPreamble(acall, ACTIVECALL, Fid, &tcon, &thost)))
2284         goto Bad_FetchData;
2285
2286     /* Get ptr to client data for user Id for logging */
2287     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2288     logHostAddr.s_addr = rxr_HostOf(tcon);
2289     ViceLog(5,
2290             ("SRXAFS_FetchData, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2291              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2292              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2293
2294     queue_NodeInit(&tcbv);
2295     tcbv.call = acall;
2296     cbv = &tcbv;
2297
2298     /*
2299      * Get volume/vnode for the fetched file; caller's access rights to
2300      * it are also returned
2301      */
2302     if ((errorCode =
2303          GetVolumePackageWithCall(acall, cbv, Fid, &volptr, &targetptr, DONTCHECK,
2304                           &parentwhentargetnotdir, &client, READ_LOCK,
2305                           &rights, &anyrights, 0)))
2306         goto Bad_FetchData;
2307
2308     SetVolumeSync(Sync, volptr);
2309
2310     /*
2311      * Remember that another read operation was performed.
2312      */
2313     FS_LOCK;
2314     if (client->InSameNetwork)
2315         readIdx = VOL_STATS_SAME_NET;
2316     else
2317         readIdx = VOL_STATS_DIFF_NET;
2318     V_stat_reads(volptr, readIdx)++;
2319     if (client->ViceId != AnonymousID) {
2320         V_stat_reads(volptr, readIdx + 1)++;
2321     }
2322     FS_UNLOCK;
2323     /* Check whether the caller has permission access to fetch the data */
2324     if ((errorCode =
2325          Check_PermissionRights(targetptr, client, rights, CHK_FETCHDATA, 0)))
2326         goto Bad_FetchData;
2327
2328     /*
2329      * Drop the read lock on the parent directory after saving the parent
2330      * vnode information we need to pass to GetStatus
2331      */
2332     if (parentwhentargetnotdir != NULL) {
2333         tparentwhentargetnotdir = *parentwhentargetnotdir;
2334         VPutVnode(&fileCode, parentwhentargetnotdir);
2335         opr_Assert(!fileCode || (fileCode == VSALVAGE));
2336         parentwhentargetnotdir = NULL;
2337     }
2338
2339     fsstats_StartXfer(&fsstats, FS_STATS_XFERIDX_FETCHDATA);
2340
2341     /* actually do the data transfer */
2342     errorCode =
2343         FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type,
2344                           &bytesToXfer, &bytesXferred);
2345
2346     fsstats_FinishXfer(&fsstats, errorCode, bytesToXfer, bytesXferred,
2347                        &remainder);
2348
2349     if (errorCode)
2350         goto Bad_FetchData;
2351
2352     /* write back  the OutStatus from the target vnode  */
2353     GetStatus(targetptr, OutStatus, rights, anyrights,
2354               &tparentwhentargetnotdir);
2355
2356     rx_KeepAliveOn(acall); /* I/O done */
2357
2358     /* if a r/w volume, promise a callback to the caller */
2359     if (VolumeWriteable(volptr))
2360         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2361     else {
2362         struct AFSFid myFid;
2363         memset(&myFid, 0, sizeof(struct AFSFid));
2364         myFid.Volume = Fid->Volume;
2365         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2366     }
2367
2368   Bad_FetchData:
2369     /* Update and store volume/vnode and parent vnodes back */
2370     (void)PutVolumePackageWithCall(acall, parentwhentargetnotdir, targetptr,
2371                                    (Vnode *) 0, volptr, &client, cbv);
2372     ViceLog(2, ("SRXAFS_FetchData returns %d\n", errorCode));
2373     errorCode = CallPostamble(tcon, errorCode, thost);
2374
2375     fsstats_FinishOp(&fsstats, errorCode);
2376
2377     osi_auditU(acall, FetchDataEvent, errorCode,
2378                AUD_ID, t_client ? t_client->ViceId : 0,
2379                AUD_FID, Fid, AUD_END);
2380     return (errorCode);
2381
2382 }                               /*SRXAFS_FetchData */
2383
2384 afs_int32
2385 SRXAFS_FetchData(struct rx_call * acall, struct AFSFid * Fid, afs_int32 Pos,
2386                  afs_int32 Len, struct AFSFetchStatus * OutStatus,
2387                  struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2388 {
2389     return common_FetchData64(acall, Fid, Pos, Len, OutStatus, CallBack,
2390                               Sync, 0);
2391 }
2392
2393 afs_int32
2394 SRXAFS_FetchData64(struct rx_call * acall, struct AFSFid * Fid, afs_int64 Pos,
2395                    afs_int64 Len, struct AFSFetchStatus * OutStatus,
2396                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2397 {
2398     int code;
2399     afs_sfsize_t tPos, tLen;
2400
2401     tPos = (afs_sfsize_t) Pos;
2402     tLen = (afs_sfsize_t) Len;
2403
2404     code =
2405         common_FetchData64(acall, Fid, tPos, tLen, OutStatus, CallBack, Sync,
2406                            1);
2407     return code;
2408 }
2409
2410 afs_int32
2411 SRXAFS_FetchACL(struct rx_call * acall, struct AFSFid * Fid,
2412                 struct AFSOpaque * AccessList,
2413                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
2414 {
2415     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2416     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2417     Error errorCode = 0;                /* return error code to caller */
2418     Volume *volptr = 0;         /* pointer to the volume */
2419     struct client *client = 0;  /* pointer to the client data */
2420     afs_int32 rights, anyrights;        /* rights for this and any user */
2421     struct rx_connection *tcon = rx_ConnectionOf(acall);
2422     struct host *thost;
2423     struct client *t_client = NULL;     /* tmp ptr to client data */
2424     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2425     struct fsstats fsstats;
2426
2427     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_FETCHACL);
2428
2429     ViceLog(1,
2430             ("SAFS_FetchACL, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2431              Fid->Unique));
2432     FS_LOCK;
2433     AFSCallStats.FetchACL++, AFSCallStats.TotalCalls++;
2434     FS_UNLOCK;
2435     if ((errorCode = CallPreamble(acall, ACTIVECALL, Fid, &tcon, &thost)))
2436         goto Bad_FetchACL;
2437
2438     /* Get ptr to client data for user Id for logging */
2439     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2440     logHostAddr.s_addr = rxr_HostOf(tcon);
2441     ViceLog(5,
2442             ("SAFS_FetchACL, Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2443              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2444              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2445
2446     AccessList->AFSOpaque_len = 0;
2447     AccessList->AFSOpaque_val = malloc(AFSOPAQUEMAX);
2448     if (!AccessList->AFSOpaque_val) {
2449         ViceLogThenPanic(0, ("Failed malloc in SRXAFS_FetchACL\n"));
2450     }
2451
2452     /*
2453      * Get volume/vnode for the fetched file; caller's access rights to it
2454      * are also returned
2455      */
2456     if ((errorCode =
2457          GetVolumePackage(acall, Fid, &volptr, &targetptr, DONTCHECK,
2458                           &parentwhentargetnotdir, &client, READ_LOCK,
2459                           &rights, &anyrights)))
2460         goto Bad_FetchACL;
2461
2462     SetVolumeSync(Sync, volptr);
2463
2464     /* Check whether we have permission to fetch the ACL */
2465     if ((errorCode =
2466          Check_PermissionRights(targetptr, client, rights, CHK_FETCHACL, 0)))
2467         goto Bad_FetchACL;
2468
2469     /* Get the Access List from the dir's vnode */
2470     if ((errorCode =
2471          RXFetch_AccessList(targetptr, parentwhentargetnotdir, AccessList)))
2472         goto Bad_FetchACL;
2473
2474     /* Get OutStatus back From the target Vnode  */
2475     GetStatus(targetptr, OutStatus, rights, anyrights,
2476               parentwhentargetnotdir);
2477
2478   Bad_FetchACL:
2479     /* Update and store volume/vnode and parent vnodes back */
2480     (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2481                            (Vnode *) 0, volptr, &client);
2482     ViceLog(2,
2483             ("SAFS_FetchACL returns %d (ACL=%s)\n", errorCode,
2484              AccessList->AFSOpaque_val));
2485     errorCode = CallPostamble(tcon, errorCode, thost);
2486
2487     fsstats_FinishOp(&fsstats, errorCode);
2488
2489     osi_auditU(acall, FetchACLEvent, errorCode,
2490                AUD_ID, t_client ? t_client->ViceId : 0,
2491                AUD_FID, Fid,
2492                AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
2493     return errorCode;
2494 }                               /*SRXAFS_FetchACL */
2495
2496
2497 /*
2498  * This routine is called exclusively by SRXAFS_FetchStatus(), and should be
2499  * merged into it when possible.
2500  */
2501 static afs_int32
2502 SAFSS_FetchStatus(struct rx_call *acall, struct AFSFid *Fid,
2503                   struct AFSFetchStatus *OutStatus,
2504                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
2505 {
2506     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2507     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2508     Error errorCode = 0;                /* return code to caller */
2509     Volume *volptr = 0;         /* pointer to the volume */
2510     struct client *client = 0;  /* pointer to the client data */
2511     afs_int32 rights, anyrights;        /* rights for this and any user */
2512     struct client *t_client = NULL;     /* tmp ptr to client data */
2513     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2514     struct rx_connection *tcon = rx_ConnectionOf(acall);
2515
2516     /* Get ptr to client data for user Id for logging */
2517     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2518     logHostAddr.s_addr = rxr_HostOf(tcon);
2519     ViceLog(1,
2520             ("SAFS_FetchStatus,  Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2521              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2522              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2523     FS_LOCK;
2524     AFSCallStats.FetchStatus++, AFSCallStats.TotalCalls++;
2525     FS_UNLOCK;
2526     /*
2527      * Get volume/vnode for the fetched file; caller's rights to it are
2528      * also returned
2529      */
2530     if ((errorCode =
2531          GetVolumePackage(acall, Fid, &volptr, &targetptr, DONTCHECK,
2532                           &parentwhentargetnotdir, &client, READ_LOCK,
2533                           &rights, &anyrights)))
2534         goto Bad_FetchStatus;
2535
2536     rx_KeepAliveOn(acall);
2537
2538     /* set volume synchronization information */
2539     SetVolumeSync(Sync, volptr);
2540
2541     /* Are we allowed to fetch Fid's status? */
2542     if (targetptr->disk.type != vDirectory) {
2543         if ((errorCode =
2544              Check_PermissionRights(targetptr, client, rights,
2545                                     CHK_FETCHSTATUS, 0))) {
2546             if (rx_GetCallAbortCode(acall) == errorCode)
2547                 rx_SetCallAbortCode(acall, 0);
2548             goto Bad_FetchStatus;
2549         }
2550     }
2551
2552     /* set OutStatus From the Fid  */
2553     GetStatus(targetptr, OutStatus, rights, anyrights,
2554               parentwhentargetnotdir);
2555
2556     /* If a r/w volume, also set the CallBack state */
2557     if (VolumeWriteable(volptr))
2558         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2559     else {
2560         struct AFSFid myFid;
2561         memset(&myFid, 0, sizeof(struct AFSFid));
2562         myFid.Volume = Fid->Volume;
2563         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2564     }
2565
2566   Bad_FetchStatus:
2567     /* Update and store volume/vnode and parent vnodes back */
2568     (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2569                            (Vnode *) 0, volptr, &client);
2570     ViceLog(2, ("SAFS_FetchStatus returns %d\n", errorCode));
2571     return errorCode;
2572
2573 }                               /*SAFSS_FetchStatus */
2574
2575
2576 afs_int32
2577 SRXAFS_BulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2578                   struct AFSBulkStats * OutStats, struct AFSCBs * CallBacks,
2579                   struct AFSVolSync * Sync)
2580 {
2581     int i;
2582     afs_int32 nfiles;
2583     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2584     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2585     Error errorCode = 0;                /* return code to caller */
2586     Volume *volptr = 0;         /* pointer to the volume */
2587     struct client *client = 0;  /* pointer to the client data */
2588     afs_int32 rights, anyrights;        /* rights for this and any user */
2589     struct AFSFid *tfid;        /* file id we're dealing with now */
2590     struct rx_connection *tcon = rx_ConnectionOf(acall);
2591     struct host *thost;
2592     struct client *t_client = NULL;     /* tmp pointer to the client data */
2593     struct fsstats fsstats;
2594
2595     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_BULKSTATUS);
2596
2597     ViceLog(1, ("SAFS_BulkStatus\n"));
2598     FS_LOCK;
2599     AFSCallStats.TotalCalls++;
2600     FS_UNLOCK;
2601     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2602     if (nfiles <= 0) {          /* Sanity check */
2603         errorCode = EINVAL;
2604         goto Audit_and_Return;
2605     }
2606
2607     /* allocate space for return output parameters */
2608     OutStats->AFSBulkStats_val = malloc(nfiles * sizeof(struct AFSFetchStatus));
2609     if (!OutStats->AFSBulkStats_val) {
2610         ViceLogThenPanic(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2611     }
2612     OutStats->AFSBulkStats_len = nfiles;
2613     CallBacks->AFSCBs_val = malloc(nfiles * sizeof(struct AFSCallBack));
2614     if (!CallBacks->AFSCBs_val) {
2615         ViceLogThenPanic(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2616     }
2617     CallBacks->AFSCBs_len = nfiles;
2618
2619     tfid = Fids->AFSCBFids_val;
2620
2621     if ((errorCode = CallPreamble(acall, ACTIVECALL, tfid, &tcon, &thost)))
2622         goto Bad_BulkStatus;
2623
2624     for (i = 0; i < nfiles; i++, tfid++) {
2625         /*
2626          * Get volume/vnode for the fetched file; caller's rights to it
2627          * are also returned
2628          */
2629         if ((errorCode =
2630              GetVolumePackage(acall, tfid, &volptr, &targetptr, DONTCHECK,
2631                               &parentwhentargetnotdir, &client, READ_LOCK,
2632                               &rights, &anyrights)))
2633             goto Bad_BulkStatus;
2634
2635         rx_KeepAliveOn(acall);
2636
2637         /* set volume synchronization information, but only once per call */
2638         if (i == 0)
2639             SetVolumeSync(Sync, volptr);
2640
2641         /* Are we allowed to fetch Fid's status? */
2642         if (targetptr->disk.type != vDirectory) {
2643             if ((errorCode =
2644                  Check_PermissionRights(targetptr, client, rights,
2645                                         CHK_FETCHSTATUS, 0))) {
2646                 if (rx_GetCallAbortCode(acall) == errorCode)
2647                     rx_SetCallAbortCode(acall, 0);
2648                 goto Bad_BulkStatus;
2649             }
2650         }
2651
2652         /* set OutStatus From the Fid  */
2653         GetStatus(targetptr, &OutStats->AFSBulkStats_val[i], rights,
2654                   anyrights, parentwhentargetnotdir);
2655
2656         /* If a r/w volume, also set the CallBack state */
2657         if (VolumeWriteable(volptr))
2658             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2659                               &CallBacks->AFSCBs_val[i]);
2660         else {
2661             struct AFSFid myFid;
2662             memset(&myFid, 0, sizeof(struct AFSFid));
2663             myFid.Volume = tfid->Volume;
2664             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2665                               &CallBacks->AFSCBs_val[i]);
2666         }
2667
2668         /* put back the file ID and volume */
2669         (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2670                                (Vnode *) 0, volptr, &client);
2671         parentwhentargetnotdir = (Vnode *) 0;
2672         targetptr = (Vnode *) 0;
2673         volptr = (Volume *) 0;
2674         client = (struct client *)0;
2675     }
2676
2677   Bad_BulkStatus:
2678     /* Update and store volume/vnode and parent vnodes back */
2679     (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2680                            (Vnode *) 0, volptr, &client);
2681     errorCode = CallPostamble(tcon, errorCode, thost);
2682
2683     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2684
2685     fsstats_FinishOp(&fsstats, errorCode);
2686
2687   Audit_and_Return:
2688     ViceLog(2, ("SAFS_BulkStatus        returns %d\n", errorCode));
2689     osi_auditU(acall, BulkFetchStatusEvent, errorCode,
2690                AUD_ID, t_client ? t_client->ViceId : 0,
2691                AUD_FIDS, Fids, AUD_END);
2692     return errorCode;
2693
2694 }                               /*SRXAFS_BulkStatus */
2695
2696
2697 afs_int32
2698 SRXAFS_InlineBulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2699                         struct AFSBulkStats * OutStats,
2700                         struct AFSCBs * CallBacks, struct AFSVolSync * Sync)
2701 {
2702     int i;
2703     afs_int32 nfiles;
2704     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2705     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2706     Error errorCode = 0;                /* return code to caller */
2707     Volume *volptr = 0;         /* pointer to the volume */
2708     struct client *client = 0;  /* pointer to the client data */
2709     afs_int32 rights, anyrights;        /* rights for this and any user */
2710     struct AFSFid *tfid;        /* file id we're dealing with now */
2711     struct rx_connection *tcon;
2712     struct host *thost;
2713     struct client *t_client = NULL;     /* tmp ptr to client data */
2714     AFSFetchStatus *tstatus;
2715     int VolSync_set = 0;
2716     struct fsstats fsstats;
2717
2718     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_BULKSTATUS);
2719
2720     ViceLog(1, ("SAFS_InlineBulkStatus\n"));
2721     FS_LOCK;
2722     AFSCallStats.TotalCalls++;
2723     FS_UNLOCK;
2724     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2725     if (nfiles <= 0) {          /* Sanity check */
2726         errorCode = EINVAL;
2727         goto Audit_and_Return;
2728     }
2729
2730     /* allocate space for return output parameters */
2731     OutStats->AFSBulkStats_val = calloc(nfiles, sizeof(struct AFSFetchStatus));
2732     if (!OutStats->AFSBulkStats_val) {
2733         ViceLogThenPanic(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2734     }
2735     OutStats->AFSBulkStats_len = nfiles;
2736     CallBacks->AFSCBs_val = calloc(nfiles, sizeof(struct AFSCallBack));
2737     if (!CallBacks->AFSCBs_val) {
2738         ViceLogThenPanic(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2739     }
2740     CallBacks->AFSCBs_len = nfiles;
2741
2742     /* Zero out return values to avoid leaking information on partial succes */
2743     memset(Sync, 0, sizeof(*Sync));
2744
2745     tfid = Fids->AFSCBFids_val;
2746
2747     if ((errorCode = CallPreamble(acall, ACTIVECALL, tfid, &tcon, &thost))) {
2748         goto Bad_InlineBulkStatus;
2749     }
2750
2751     for (i = 0; i < nfiles; i++, tfid++) {
2752         /*
2753          * Get volume/vnode for the fetched file; caller's rights to it
2754          * are also returned
2755          */
2756         if ((errorCode =
2757              GetVolumePackage(acall, tfid, &volptr, &targetptr, DONTCHECK,
2758                               &parentwhentargetnotdir, &client, READ_LOCK,
2759                               &rights, &anyrights))) {
2760             tstatus = &OutStats->AFSBulkStats_val[i];
2761
2762             if (thost->hostFlags & HERRORTRANS) {
2763                 tstatus->errorCode = sys_error_to_et(errorCode);
2764             } else {
2765                 tstatus->errorCode = errorCode;
2766             }
2767
2768             PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2769                              (Vnode *) 0, volptr, &client);
2770             parentwhentargetnotdir = (Vnode *) 0;
2771             targetptr = (Vnode *) 0;
2772             volptr = (Volume *) 0;
2773             client = (struct client *)0;
2774             continue;
2775         }
2776
2777         rx_KeepAliveOn(acall);
2778
2779         /* set volume synchronization information, but only once per call */
2780         if (!VolSync_set) {
2781             SetVolumeSync(Sync, volptr);
2782             VolSync_set = 1;
2783         }
2784
2785         /* Are we allowed to fetch Fid's status? */
2786         if (targetptr->disk.type != vDirectory) {
2787             if ((errorCode =
2788                  Check_PermissionRights(targetptr, client, rights,
2789                                         CHK_FETCHSTATUS, 0))) {
2790                 tstatus = &OutStats->AFSBulkStats_val[i];
2791
2792                 if (thost->hostFlags & HERRORTRANS) {
2793                     tstatus->errorCode = sys_error_to_et(errorCode);
2794                 } else {
2795                     tstatus->errorCode = errorCode;
2796                 }
2797
2798                 (void)PutVolumePackage(acall, parentwhentargetnotdir,
2799                                        targetptr, (Vnode *) 0, volptr,
2800                                        &client);
2801                 parentwhentargetnotdir = (Vnode *) 0;
2802                 targetptr = (Vnode *) 0;
2803                 volptr = (Volume *) 0;
2804                 client = (struct client *)0;
2805                 continue;
2806             }
2807         }
2808
2809         /* set OutStatus From the Fid  */
2810         GetStatus(targetptr,
2811                   (struct AFSFetchStatus *)&OutStats->AFSBulkStats_val[i],
2812                   rights, anyrights, parentwhentargetnotdir);
2813
2814         /* If a r/w volume, also set the CallBack state */
2815         if (VolumeWriteable(volptr))
2816             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2817                               &CallBacks->AFSCBs_val[i]);
2818         else {
2819             struct AFSFid myFid;
2820             memset(&myFid, 0, sizeof(struct AFSFid));
2821             myFid.Volume = tfid->Volume;
2822             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2823                               &CallBacks->AFSCBs_val[i]);
2824         }
2825
2826         /* put back the file ID and volume */
2827         (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2828                                (Vnode *) 0, volptr, &client);
2829         parentwhentargetnotdir = (Vnode *) 0;
2830         targetptr = (Vnode *) 0;
2831         volptr = (Volume *) 0;
2832         client = (struct client *)0;
2833     }
2834     errorCode = 0;
2835
2836   Bad_InlineBulkStatus:
2837     /* Update and store volume/vnode and parent vnodes back */
2838     (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
2839                            (Vnode *) 0, volptr, &client);
2840     errorCode = CallPostamble(tcon, errorCode, thost);
2841
2842     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2843
2844     fsstats_FinishOp(&fsstats, errorCode);
2845
2846   Audit_and_Return:
2847     ViceLog(2, ("SAFS_InlineBulkStatus  returns %d\n", errorCode));
2848     osi_auditU(acall, InlineBulkFetchStatusEvent, errorCode,
2849                AUD_ID, t_client ? t_client->ViceId : 0,
2850                AUD_FIDS, Fids, AUD_END);
2851     return errorCode;
2852
2853 }                               /*SRXAFS_InlineBulkStatus */
2854
2855
2856 afs_int32
2857 SRXAFS_FetchStatus(struct rx_call * acall, struct AFSFid * Fid,
2858                    struct AFSFetchStatus * OutStatus,
2859                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2860 {
2861     afs_int32 code;
2862     struct rx_connection *tcon;
2863     struct host *thost;
2864     struct client *t_client = NULL;     /* tmp ptr to client data */
2865     struct fsstats fsstats;
2866
2867     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_FETCHSTATUS);
2868
2869     if ((code = CallPreamble(acall, ACTIVECALL, Fid, &tcon, &thost)))
2870         goto Bad_FetchStatus;
2871
2872     code = SAFSS_FetchStatus(acall, Fid, OutStatus, CallBack, Sync);
2873
2874   Bad_FetchStatus:
2875     code = CallPostamble(tcon, code, thost);
2876
2877     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2878
2879     fsstats_FinishOp(&fsstats, code);
2880
2881     osi_auditU(acall, FetchStatusEvent, code,
2882                AUD_ID, t_client ? t_client->ViceId : 0,
2883                AUD_FID, Fid, AUD_END);
2884     return code;
2885
2886 }                               /*SRXAFS_FetchStatus */
2887
2888 static
2889   afs_int32
2890 common_StoreData64(struct rx_call *acall, struct AFSFid *Fid,
2891                    struct AFSStoreStatus *InStatus, afs_fsize_t Pos,
2892                    afs_fsize_t Length, afs_fsize_t FileLength,
2893                    struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
2894 {
2895     Vnode *targetptr = 0;       /* pointer to input fid */
2896     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
2897     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2898     Error errorCode = 0;                /* return code for caller */
2899     Error fileCode = 0;         /* return code from vol package */
2900     Volume *volptr = 0;         /* pointer to the volume header */
2901     struct client *client = 0;  /* pointer to client structure */
2902     afs_int32 rights, anyrights;        /* rights for this and any user */
2903     struct client *t_client = NULL;     /* tmp ptr to client data */
2904     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2905     struct rx_connection *tcon;
2906     struct host *thost;
2907     struct fsstats fsstats;
2908     afs_sfsize_t bytesToXfer;
2909     afs_sfsize_t bytesXferred;
2910     static int remainder = 0;
2911
2912     ViceLog(1,
2913             ("StoreData: Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2914              Fid->Unique));
2915
2916     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_STOREDATA);
2917
2918     FS_LOCK;
2919     AFSCallStats.StoreData++, AFSCallStats.TotalCalls++;
2920     FS_UNLOCK;
2921     if ((errorCode = CallPreamble(acall, ACTIVECALL, Fid, &tcon, &thost)))
2922         goto Bad_StoreData;
2923
2924     /* Get ptr to client data for user Id for logging */
2925     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2926     logHostAddr.s_addr = rxr_HostOf(tcon);
2927     ViceLog(5,
2928             ("StoreData: Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2929              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2930              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2931
2932     /*
2933      * Get associated volume/vnode for the stored file; caller's rights
2934      * are also returned
2935      */
2936     if ((errorCode =
2937          GetVolumePackage(acall, Fid, &volptr, &targetptr, MustNOTBeDIR,
2938                           &parentwhentargetnotdir, &client, WRITE_LOCK,
2939                           &rights, &anyrights))) {
2940         goto Bad_StoreData;
2941     }
2942
2943     rx_KeepAliveOn(acall);
2944
2945     /* set volume synchronization information */
2946     SetVolumeSync(Sync, volptr);
2947
2948     if (targetptr->disk.type == vSymlink) {
2949         /* Should we return a better error code here??? */
2950         errorCode = EISDIR;
2951         goto Bad_StoreData;
2952     }
2953
2954     /* Check if we're allowed to store the data */
2955     if ((errorCode =
2956          Check_PermissionRights(targetptr, client, rights, CHK_STOREDATA,
2957                                 InStatus))) {
2958         goto Bad_StoreData;
2959     }
2960
2961     /*
2962      * Drop the read lock on the parent directory after saving the parent
2963      * vnode information we need to pass to GetStatus
2964      */
2965     if (parentwhentargetnotdir != NULL) {
2966         tparentwhentargetnotdir = *parentwhentargetnotdir;
2967         rx_KeepAliveOff(acall);
2968         VPutVnode(&fileCode, parentwhentargetnotdir);
2969         rx_KeepAliveOn(acall);
2970         opr_Assert(!fileCode || (fileCode == VSALVAGE));
2971         parentwhentargetnotdir = NULL;
2972     }
2973
2974     fsstats_StartXfer(&fsstats, FS_STATS_XFERIDX_STOREDATA);
2975
2976     errorCode =
2977         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
2978                           FileLength, (InStatus->Mask & AFS_FSYNC),
2979                           &bytesToXfer, &bytesXferred);
2980
2981     fsstats_FinishXfer(&fsstats, errorCode, bytesToXfer, bytesXferred,
2982                        &remainder);
2983
2984     if (errorCode && (!targetptr->changed_newTime))
2985         goto Bad_StoreData;
2986
2987     rx_KeepAliveOff(acall);
2988     /* Update the status of the target's vnode */
2989     Update_TargetVnodeStatus(targetptr, TVS_SDATA, client, InStatus,
2990                              targetptr, volptr, 0, 0);
2991     rx_KeepAliveOn(acall);
2992
2993     /* Get the updated File's status back to the caller */
2994     GetStatus(targetptr, OutStatus, rights, anyrights,
2995               &tparentwhentargetnotdir);
2996
2997   Bad_StoreData:
2998     /* Update and store volume/vnode and parent vnodes back */
2999     (void)PutVolumePackage(acall, parentwhentargetnotdir, targetptr,
3000                            (Vnode *) 0, volptr, &client);
3001     ViceLog(2, ("SAFS_StoreData returns %d\n", errorCode));
3002
3003     errorCode = CallPostamble(tcon, errorCode, thost);
3004
3005     fsstats_FinishOp(&fsstats, errorCode);
3006
3007     osi_auditU(acall, StoreDataEvent, errorCode,
3008                AUD_ID, t_client ? t_client->ViceId : 0,
3009                AUD_FID, Fid, AUD_END);
3010     return (errorCode);
3011 }                               /*common_StoreData64 */
3012
3013 afs_int32
3014 SRXAFS_StoreData(struct rx_call * acall, struct AFSFid * Fid,
3015                  struct AFSStoreStatus * InStatus, afs_uint32 Pos,
3016                  afs_uint32 Length, afs_uint32 FileLength,
3017                  struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3018 {
3019     if (FileLength > 0x7fffffff || Pos > 0x7fffffff ||
3020         (0x7fffffff - Pos) < Length)
3021         return EFBIG;
3022
3023     return common_StoreData64(acall, Fid, InStatus, Pos, Length, FileLength,
3024                               OutStatus, Sync);
3025 }                               /*SRXAFS_StoreData */
3026
3027 afs_int32
3028 SRXAFS_StoreData64(struct rx_call * acall, struct AFSFid * Fid,
3029                    struct AFSStoreStatus * InStatus, afs_uint64 Pos,
3030                    afs_uint64 Length, afs_uint64 FileLength,
3031                    struct AFSFetchStatus * OutStatus,
3032                    struct AFSVolSync * Sync)
3033 {
3034     int code;
3035     afs_fsize_t tPos;
3036     afs_fsize_t tLength;
3037     afs_fsize_t tFileLength;
3038
3039     tPos = (afs_fsize_t) Pos;
3040     tLength = (afs_fsize_t) Length;
3041     tFileLength = (afs_fsize_t) FileLength;
3042
3043     code =
3044         common_StoreData64(acall, Fid, InStatus, tPos, tLength, tFileLength,
3045                            OutStatus, Sync);
3046     return code;
3047 }
3048
3049 afs_int32
3050 SRXAFS_StoreACL(struct rx_call * acall, struct AFSFid * Fid,
3051                 struct AFSOpaque * AccessList,
3052                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3053 {
3054     Vnode *targetptr = 0;       /* pointer to input fid */
3055     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3056     Error errorCode = 0;                /* return code for caller */
3057     struct AFSStoreStatus InStatus;     /* Input status for fid */
3058     Volume *volptr = 0;         /* pointer to the volume header */
3059     struct client *client = 0;  /* pointer to client structure */
3060     afs_int32 rights, anyrights;        /* rights for this and any user */
3061     struct rx_connection *tcon;
3062     struct host *thost;
3063     struct client *t_client = NULL;     /* tmp ptr to client data */
3064     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3065     struct fsstats fsstats;
3066
3067     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_STOREACL);
3068
3069     if ((errorCode = CallPreamble(acall, ACTIVECALL, Fid, &tcon, &thost)))
3070         goto Bad_StoreACL;
3071
3072     /* Get ptr to client data for user Id for logging */
3073     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3074     logHostAddr.s_addr = rxr_HostOf(tcon);
3075     ViceLog(1,
3076             ("SAFS_StoreACL, Fid = %u.%u.%u, ACL=%s, Host %s:%d, Id %d\n",
3077              Fid->Volume, Fid->Vnode, Fid->Unique, AccessList->AFSOpaque_val,
3078              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3079     FS_LOCK;
3080     AFSCallStats.StoreACL++, AFSCallStats.TotalCalls++;
3081     FS_UNLOCK;
3082     InStatus.Mask = 0;          /* not storing any status */
3083
3084     /*
3085      * Get associated volume/vnode for the target dir; caller's rights
3086      * are also returned.
3087      */
3088     if ((errorCode =
3089          GetVolumePackage(acall, Fid, &volptr, &targetptr, MustBeDIR,
3090                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3091                           &rights, &anyrights))) {
3092         goto Bad_StoreACL;
3093     }
3094
3095     /* set volume synchronization information */
3096     SetVolumeSync(Sync, volptr);
3097
3098     /* Check if we have permission to change the dir's ACL */
3099     if ((errorCode =
3100          Check_PermissionRights(targetptr, client, rights, CHK_STOREACL,
3101                                 &InStatus))) {
3102         goto Bad_StoreACL;
3103     }
3104
3105     /* Build and store the new Access List for the dir */
3106     if ((errorCode = RXStore_AccessList(targetptr, AccessList))) {
3107         goto Bad_StoreACL;
3108     }
3109
3110     targetptr->changed_newTime = 1;     /* status change of directory */
3111
3112     /* convert the write lock to a read lock before breaking callbacks */
3113     VVnodeWriteToRead(&errorCode, targetptr);
3114     opr_Assert(!errorCode || errorCode == VSALVAGE);
3115
3116     rx_KeepAliveOn(acall);
3117
3118     /* break call backs on the directory  */
3119     BreakCallBack(client->host, Fid, 0);
3120
3121     /* Get the updated dir's status back to the caller */
3122     GetStatus(targetptr, OutStatus, rights, anyrights, 0);
3123
3124   Bad_StoreACL:
3125     /* Update and store volume/vnode and parent vnodes back */
3126     PutVolumePackage(acall, parentwhentargetnotdir, targetptr, (Vnode *) 0,
3127                      volptr, &client);
3128     ViceLog(2, ("SAFS_StoreACL returns %d\n", errorCode));
3129     errorCode = CallPostamble(tcon, errorCode, thost);
3130
3131     fsstats_FinishOp(&fsstats, errorCode);
3132
3133     osi_auditU(acall, StoreACLEvent, errorCode,
3134                AUD_ID, t_client ? t_client->ViceId : 0,
3135                AUD_FID, Fid, AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
3136     return errorCode;
3137
3138 }                               /*SRXAFS_StoreACL */
3139
3140
3141 /*
3142  * Note: This routine is called exclusively from SRXAFS_StoreStatus(), and
3143  * should be merged when possible.
3144  */
3145 static afs_int32
3146 SAFSS_StoreStatus(struct rx_call *acall, struct AFSFid *Fid,
3147                   struct AFSStoreStatus *InStatus,
3148                   struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
3149 {
3150     Vnode *targetptr = 0;       /* pointer to input fid */
3151     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3152     Error errorCode = 0;                /* return code for caller */
3153     Volume *volptr = 0;         /* pointer to the volume header */
3154     struct client *client = 0;  /* pointer to client structure */
3155     afs_int32 rights, anyrights;        /* rights for this and any user */
3156     struct client *t_client = NULL;     /* tmp ptr to client data */
3157     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3158     struct rx_connection *tcon = rx_ConnectionOf(acall);
3159
3160     /* Get ptr to client data for user Id for logging */
3161     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3162     logHostAddr.s_addr = rxr_HostOf(tcon);
3163     ViceLog(1,
3164             ("SAFS_StoreStatus,  Fid    = %u.%u.%u, Host %s:%d, Id %d\n",
3165              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
3166              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3167     FS_LOCK;
3168     AFSCallStats.StoreStatus++, AFSCallStats.TotalCalls++;
3169     FS_UNLOCK;
3170     /*
3171      * Get volume/vnode for the target file; caller's rights to it are
3172      * also returned
3173      */
3174     if ((errorCode =
3175          GetVolumePackage(acall, Fid, &volptr, &targetptr, DONTCHECK,
3176                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3177                           &rights, &anyrights))) {
3178         goto Bad_StoreStatus;
3179     }
3180
3181     /* set volume synchronization information */
3182     SetVolumeSync(Sync, volptr);
3183
3184     /* Check if the caller has proper permissions to store status to Fid */
3185     if ((errorCode =
3186          Check_PermissionRights(targetptr, client, rights, CHK_STORESTATUS,
3187                                 InStatus))) {
3188         goto Bad_StoreStatus;
3189     }
3190     /*
3191      * Check for a symbolic link; we can't chmod these (otherwise could
3192      * change a symlink to a mt pt or vice versa)
3193      */
3194     if (targetptr->disk.type == vSymlink && (InStatus->Mask & AFS_SETMODE)) {
3195         errorCode = EINVAL;
3196         goto Bad_StoreStatus;
3197     }
3198
3199     /* Update the status of the target's vnode */
3200     Update_TargetVnodeStatus(targetptr, TVS_SSTATUS, client, InStatus,
3201                              (parentwhentargetnotdir ? parentwhentargetnotdir
3202                               : targetptr), volptr, 0, 0);
3203
3204     rx_KeepAliveOn(acall);
3205
3206     /* convert the write lock to a read lock before breaking callbacks */
3207     VVnodeWriteToRead(&errorCode, targetptr);
3208     opr_Assert(!errorCode || errorCode == VSALVAGE);
3209
3210     /* Break call backs on Fid */
3211     BreakCallBack(client->host, Fid, 0);
3212
3213     /* Return the updated status back to caller */
3214     GetStatus(targetptr, OutStatus, rights, anyrights,
3215               parentwhentargetnotdir);
3216
3217   Bad_StoreStatus:
3218     /* Update and store volume/vnode and parent vnodes back */
3219     PutVolumePackage(acall, parentwhentargetnotdir, targetptr, (Vnode *) 0,
3220                      volptr, &client);
3221     ViceLog(2, ("SAFS_StoreStatus returns %d\n", errorCode));
3222     return errorCode;
3223
3224 }                               /*SAFSS_StoreStatus */
3225
3226
3227 afs_int32
3228 SRXAFS_StoreStatus(struct rx_call * acall, struct AFSFid * Fid,
3229                    struct AFSStoreStatus * InStatus,
3230                    struct AFSFetchStatus * OutStatus,
3231                    struct AFSVolSync * Sync)
3232 {
3233     afs_int32 code;
3234     struct rx_connection *tcon;
3235     struct host *thost;
3236     struct client *t_client = NULL;     /* tmp ptr to client data */
3237     struct fsstats fsstats;
3238
3239     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_STORESTATUS);
3240
3241     if ((code = CallPreamble(acall, ACTIVECALL, Fid, &tcon, &thost)))
3242         goto Bad_StoreStatus;
3243
3244     code = SAFSS_StoreStatus(acall, Fid, InStatus, OutStatus, Sync);
3245
3246   Bad_StoreStatus:
3247     code = CallPostamble(tcon, code, thost);
3248
3249     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3250
3251     fsstats_FinishOp(&fsstats, code);
3252
3253     osi_auditU(acall, StoreStatusEvent, code,
3254                AUD_ID, t_client ? t_client->ViceId : 0,
3255                AUD_FID, Fid, AUD_END);
3256     return code;
3257
3258 }                               /*SRXAFS_StoreStatus */
3259
3260
3261 /*
3262  * This routine is called exclusively by SRXAFS_RemoveFile(), and should be
3263  * merged in when possible.
3264  */
3265 static afs_int32
3266 SAFSS_RemoveFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3267                  struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
3268 {
3269     Vnode *parentptr = 0;       /* vnode of input Directory */
3270     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3271     Vnode *targetptr = 0;       /* file to be deleted */
3272     Volume *volptr = 0;         /* pointer to the volume header */
3273     AFSFid fileFid;             /* area for Fid from the directory */
3274     Error errorCode = 0;                /* error code */
3275     DirHandle dir;              /* Handle for dir package I/O */
3276     struct client *client = 0;  /* pointer to client structure */
3277     afs_int32 rights, anyrights;        /* rights for this and any user */
3278     struct client *t_client;    /* tmp ptr to client data */
3279     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3280     struct rx_connection *tcon = rx_ConnectionOf(acall);
3281
3282     FidZero(&dir);
3283     /* Get ptr to client data for user Id for logging */
3284     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3285     logHostAddr.s_addr = rxr_HostOf(tcon);
3286     ViceLog(1,
3287             ("SAFS_RemoveFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3288              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3289              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3290     FS_LOCK;
3291     AFSCallStats.RemoveFile++, AFSCallStats.TotalCalls++;
3292     FS_UNLOCK;
3293     /*
3294      * Get volume/vnode for the parent dir; caller's access rights are
3295      * also returned
3296      */
3297     if ((errorCode =
3298          GetVolumePackage(acall, DirFid, &volptr, &parentptr, MustBeDIR,
3299                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3300                           &rights, &anyrights))) {
3301         goto Bad_RemoveFile;
3302     }
3303     /* set volume synchronization information */
3304     SetVolumeSync(Sync, volptr);
3305
3306     /* Does the caller has delete (& write) access to the parent directory? */
3307     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
3308         goto Bad_RemoveFile;
3309     }
3310
3311     /* Actually delete the desired file */
3312     if ((errorCode =
3313          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
3314                       MustNOTBeDIR))) {
3315         goto Bad_RemoveFile;
3316     }
3317
3318     /* Update the vnode status of the parent dir */
3319     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3320                              parentptr->disk.linkCount,
3321                              client->InSameNetwork);
3322
3323     rx_KeepAliveOn(acall);
3324
3325     /* Return the updated parent dir's status back to caller */
3326     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3327
3328     /* Handle internal callback state for the parent and the deleted file */
3329     if (targetptr->disk.linkCount == 0) {
3330         /* no references left, discard entry */
3331         DeleteFileCallBacks(&fileFid);
3332         /* convert the parent lock to a read lock before breaking callbacks */
3333         VVnodeWriteToRead(&errorCode, parentptr);
3334         opr_Assert(!errorCode || errorCode == VSALVAGE);
3335     } else {
3336         /* convert the parent lock to a read lock before breaking callbacks */
3337         VVnodeWriteToRead(&errorCode, parentptr);
3338         opr_Assert(!errorCode || errorCode == VSALVAGE);
3339         /* convert the target lock to a read lock before breaking callbacks */
3340         VVnodeWriteToRead(&errorCode, targetptr);
3341         opr_Assert(!errorCode || errorCode == VSALVAGE);
3342         /* tell all the file has changed */
3343         BreakCallBack(client->host, &fileFid, 1);
3344     }
3345
3346     /* break call back on the directory */
3347     BreakCallBack(client->host, DirFid, 0);
3348
3349   Bad_RemoveFile:
3350     /* Update and store volume/vnode and parent vnodes back */
3351     PutVolumePackage(acall, parentwhentargetnotdir, targetptr, parentptr,
3352                      volptr, &client);
3353     FidZap(&dir);
3354     ViceLog(2, ("SAFS_RemoveFile returns %d\n", errorCode));
3355     return errorCode;
3356
3357 }                               /*SAFSS_RemoveFile */
3358
3359
3360 afs_int32
3361 SRXAFS_RemoveFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3362                   struct AFSFetchStatus * OutDirStatus,
3363                   struct AFSVolSync * Sync)
3364 {
3365     afs_int32 code;
3366     struct rx_connection *tcon;
3367     struct host *thost;
3368     struct client *t_client = NULL;     /* tmp ptr to client data */
3369     struct fsstats fsstats;
3370
3371     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_REMOVEFILE);
3372
3373     if ((code = CallPreamble(acall, ACTIVECALL, DirFid, &tcon, &thost)))
3374         goto Bad_RemoveFile;
3375
3376     code = SAFSS_RemoveFile(acall, DirFid, Name, OutDirStatus, Sync);
3377
3378   Bad_RemoveFile:
3379     code = CallPostamble(tcon, code, thost);
3380
3381     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3382
3383     fsstats_FinishOp(&fsstats, code);
3384
3385     osi_auditU(acall, RemoveFileEvent, code,
3386                AUD_ID, t_client ? t_client->ViceId : 0,
3387                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
3388     return code;
3389
3390 }                               /*SRXAFS_RemoveFile */
3391
3392
3393 /*
3394  * This routine is called exclusively from SRXAFS_CreateFile(), and should
3395  * be merged in when possible.
3396  */
3397 static afs_int32
3398 SAFSS_CreateFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3399                  struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
3400                  struct AFSFetchStatus *OutFidStatus,
3401                  struct AFSFetchStatus *OutDirStatus,
3402                  struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
3403 {
3404     Vnode *parentptr = 0;       /* vnode of input Directory */
3405     Vnode *targetptr = 0;       /* vnode of the new file */
3406     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3407     Volume *volptr = 0;         /* pointer to the volume header */
3408     Error errorCode = 0;                /* error code */
3409     DirHandle dir;              /* Handle for dir package I/O */
3410     struct client *client = 0;  /* pointer to client structure */
3411     afs_int32 rights, anyrights;        /* rights for this and any user */
3412     struct client *t_client;    /* tmp ptr to client data */
3413     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3414     struct rx_connection *tcon = rx_ConnectionOf(acall);
3415
3416     FidZero(&dir);
3417
3418     /* Get ptr to client data for user Id for logging */
3419     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3420     logHostAddr.s_addr = rxr_HostOf(tcon);
3421     ViceLog(1,
3422             ("SAFS_CreateFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3423              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3424              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3425     FS_LOCK;
3426     AFSCallStats.CreateFile++, AFSCallStats.TotalCalls++;
3427     FS_UNLOCK;
3428     if (!FileNameOK(Name)) {
3429         errorCode = EINVAL;
3430         goto Bad_CreateFile;
3431     }
3432
3433     /*
3434      * Get associated volume/vnode for the parent dir; caller long are
3435      * also returned