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