vlserver: Refactor auditing
[openafs.git] / src / vlserver / vlprocs.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 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 #include <roken.h>
14
15 #include <lock.h>
16 #include <afs/afsutil.h>
17 #include <ubik.h>
18 #include <rx/xdr.h>
19 #include <rx/rx.h>
20 #include <rx/rxkad.h>
21 #include <afs/keys.h>
22 #include <afs/cellconfig.h>
23
24 #include "vlserver.h"
25 #include "vlserver_internal.h"
26 #include "afs/audit.h"
27
28 #ifdef HAVE_POSIX_REGEX         /* use POSIX regexp library */
29 #include <regex.h>
30 #endif
31
32 extern int smallMem;
33 extern int restrictedQueryLevel;
34 extern int extent_mod;
35 extern struct afsconf_dir *vldb_confdir;
36 extern struct ubik_dbase *VL_dbase;
37 int maxnservers;
38 #define ABORT(c) do { \
39     code = (c); \
40     goto abort; \
41 } while (0)
42
43 #define VLDBALLOCLIMIT  10000
44 #define VLDBALLOCINCR   2048
45
46 static int put_attributeentry(struct vl_ctx *ctx,
47                               struct vldbentry **, struct vldbentry **,
48                               struct vldbentry **, bulkentries *,
49                               struct nvlentry *, afs_int32 *, afs_int32 *);
50 static int put_nattributeentry(struct vl_ctx *ctx,
51                                struct nvldbentry **, struct nvldbentry **,
52                                struct nvldbentry **, nbulkentries *,
53                                struct nvlentry *, afs_int32, afs_int32,
54                                afs_int32 *, afs_int32 *);
55 static int RemoveEntry(struct vl_ctx *ctx, afs_int32 entryptr,
56                        struct nvlentry *tentry);
57 static void ReleaseEntry(struct nvlentry *tentry, afs_int32 releasetype);
58 static int check_vldbentry(struct vldbentry *aentry);
59 static int check_nvldbentry(struct nvldbentry *aentry);
60 static int vldbentry_to_vlentry(struct vl_ctx *ctx,
61                                 struct vldbentry *VldbEntry,
62                                 struct nvlentry *VlEntry);
63 static int nvldbentry_to_vlentry(struct vl_ctx *ctx,
64                                  struct nvldbentry *VldbEntry,
65                                  struct nvlentry *VlEntry);
66 static int get_vldbupdateentry(struct vl_ctx *ctx, afs_int32 blockindex,
67                                struct VldbUpdateEntry *updateentry,
68                                struct nvlentry *VlEntry);
69 static int repsite_exists(struct nvlentry *VlEntry, int server, int partition);
70 static void repsite_compress(struct nvlentry *VlEntry, int offset);
71 static int vlentry_to_vldbentry(struct vl_ctx *ctx,
72                                 struct nvlentry *VlEntry,
73                                 struct vldbentry *VldbEntry);
74 static int vlentry_to_nvldbentry(struct vl_ctx *ctx,
75                                  struct nvlentry *VlEntry,
76                                  struct nvldbentry *VldbEntry);
77 static int vlentry_to_uvldbentry(struct vl_ctx *ctx,
78                                  struct nvlentry *VlEntry,
79                                  struct uvldbentry *VldbEntry);
80 static int InvalidVolname(char *volname);
81 static int InvalidVoltype(afs_int32 voltype);
82 static int InvalidOperation(afs_int32 voloper);
83 static int InvalidReleasetype(afs_int32 releasetype);
84 static int IpAddrToRelAddr(struct vl_ctx *ctx, afs_uint32 ipaddr, int create);
85 static int ChangeIPAddr(struct vl_ctx *ctx, afs_uint32 ipaddr1,
86                         afs_uint32 ipaddr2);
87
88 static_inline void
89 countRequest(int opcode)
90 {
91     if (opcode != 0) {
92         dynamic_statistics.requests[opcode - VL_LOWEST_OPCODE]++;
93     }
94 }
95
96 static_inline void
97 countAbort(int opcode)
98 {
99     if (opcode != 0) {
100         dynamic_statistics.aborts[opcode - VL_LOWEST_OPCODE]++;
101     }
102 }
103
104
105 static_inline int
106 multiHomedExtentBase(struct vl_ctx *ctx, int srvidx, struct extentaddr **exp,
107                      int *basePtr)
108 {
109     int base;
110     int index;
111
112     *exp = NULL;
113     *basePtr = 0;
114
115     if ((ctx->hostaddress[srvidx] & 0xff000000) == 0xff000000) {
116         base = (ctx->hostaddress[srvidx] >> 16) & 0xff;
117         index = ctx->hostaddress[srvidx] & 0x0000ffff;
118         if (base >= VL_MAX_ADDREXTBLKS) {
119             VLog(0, ("Internal error: Multihome extent base is too large. "
120                      "Base %d index %d\n", base, index));
121             return VL_IO;
122         }
123         if (index >= VL_MHSRV_PERBLK) {
124             VLog(0, ("Internal error: Multihome extent index is too large. "
125                      "Base %d index %d\n", base, index));
126             return VL_IO;
127         }
128         if (!ctx->ex_addr[base]) {
129             VLog(0, ("Internal error: Multihome extent does not exist. "
130                      "Base %d\n", base));
131             return VL_IO;
132         }
133
134         *basePtr = base;
135         *exp = &ctx->ex_addr[base][index];
136     }
137
138     return 0;
139 }
140
141 static_inline int
142 multiHomedExtent(struct vl_ctx *ctx, int srvidx, struct extentaddr **exp)
143 {
144     int base;
145
146     return multiHomedExtentBase(ctx, srvidx, exp, &base);
147 }
148
149 #define AFS_RXINFO_LEN 128
150 static char *
151 rxkadInfo(char *str, struct rx_connection *conn, struct in_addr hostAddr)
152 {
153     int code;
154     char tname[64] = "";
155     char tinst[64] = "";
156     char tcell[64] = "";
157     afs_uint32 exp;
158
159     code = rxkad_GetServerInfo(conn, NULL, &exp, tname, tinst, tcell,
160                                NULL);
161     if (!code)
162         snprintf(str, AFS_RXINFO_LEN,
163                  "%s rxkad:%s%s%s%s%s", inet_ntoa(hostAddr), tname,
164                 (tinst[0] == '\0') ? "" : ".",
165                 (tinst[0] == '\0') ? "" : tinst,
166                 (tcell[0] == '\0') ? "" : "@",
167                 (tcell[0] == '\0') ? "" : tcell);
168     else
169         snprintf(str, AFS_RXINFO_LEN, "%s noauth", inet_ntoa(hostAddr));
170     return (str);
171 }
172
173 static char *
174 rxinfo(char *str, struct rx_call *rxcall)
175 {
176     struct rx_connection *conn;
177     struct in_addr hostAddr;
178     rx_securityIndex authClass;
179
180     conn = rx_ConnectionOf(rxcall);
181     authClass = rx_SecurityClassOf(conn);
182     hostAddr.s_addr = rx_HostOf(rx_PeerOf(conn));
183
184     switch(authClass) {
185     case RX_SECIDX_KAD:
186         return rxkadInfo(str, conn, hostAddr);
187     default:
188         ;
189     }
190
191     snprintf(str, AFS_RXINFO_LEN, "%s noauth", inet_ntoa(hostAddr));
192     return str;
193 }
194
195
196 /* This is called to initialize the database, set the appropriate locks and make sure that the vldb header is valid */
197 int
198 Init_VLdbase(struct vl_ctx *ctx,
199              int locktype,      /* indicate read or write transaction */
200              int opcode)
201 {
202     int code = 0, pass, wl;
203
204     for (pass = 1; pass <= 3; pass++) {
205         if (pass == 2) {        /* take write lock to rebuild the db */
206             code = ubik_BeginTrans(VL_dbase, UBIK_WRITETRANS, &ctx->trans);
207             wl = 1;
208         } else if (locktype == LOCKREAD) {
209             code =
210                 ubik_BeginTransReadAnyWrite(VL_dbase, UBIK_READTRANS, &ctx->trans);
211             wl = 0;
212         } else {
213             code = ubik_BeginTrans(VL_dbase, UBIK_WRITETRANS, &ctx->trans);
214             wl = 1;
215         }
216         if (code)
217             return code;
218
219         code = ubik_SetLock(ctx->trans, 1, 1, locktype);
220         if (code) {
221             countAbort(opcode);
222             ubik_AbortTrans(ctx->trans);
223             return code;
224         }
225
226         /* check that dbase is initialized and setup cheader */
227         /* 2nd pass we try to rebuild the header */
228         code = CheckInit(ctx->trans, ((pass == 2) ? 1 : 0));
229         if (!code && wl && extent_mod)
230             code = readExtents(ctx->trans);     /* Fix the mh extent blocks */
231         if (code) {
232             countAbort(opcode);
233             ubik_AbortTrans(ctx->trans);
234             /* Only rebuld if the database is empty */
235             /* Exit if can't rebuild */
236             if ((pass == 1) && (code != VL_EMPTY))
237                 return code;
238             if (pass == 2)
239                 return code;
240         } else {                /* No code */
241             if (pass == 2) {
242                 /* The database header was rebuilt; end the write transaction.
243                  * This will call vlsynccache() to copy the write header buffers
244                  * to the read header buffers, before calling vlsetache().
245                  * Do a third pass to re-acquire the original lock, which
246                  * may be a read lock. */
247                 ubik_EndTrans(ctx->trans);
248             } else {
249                 break;          /* didn't rebuild and successful - exit */
250             }
251         }
252     }
253     if (code == 0) {
254         code = vlsetcache(ctx, locktype);
255     }
256     return code;
257 }
258
259
260 /* Create a new vldb entry; both new volume id and name must be unique
261  * (non-existant in vldb).
262  */
263
264 static afs_int32
265 CreateEntry(struct rx_call *rxcall, struct vldbentry *newentry)
266 {
267     int this_op = VLCREATEENTRY;
268     struct vl_ctx ctx;
269     afs_int32 code, blockindex;
270     struct nvlentry tentry;
271     char rxstr[AFS_RXINFO_LEN];
272
273     countRequest(this_op);
274     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL)) {
275         return VL_PERM;
276     }
277
278     /* Do some validity tests on new entry */
279     if ((code = check_vldbentry(newentry))
280         || (code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
281         return code;
282
283     VLog(1,
284          ("OCreate Volume %d %s\n", newentry->volumeId[RWVOL],
285           rxinfo(rxstr, rxcall)));
286     if (EntryIDExists(&ctx, newentry->volumeId, MAXTYPES, &code)) {
287         /* at least one of the specified IDs already exists; we fail */
288         code = VL_IDEXIST;
289         goto abort;
290     } else if (code) {
291         goto abort;
292     }
293
294     /* Is this following check (by volume name) necessary?? */
295     /* If entry already exists, we fail */
296     if (FindByName(&ctx, newentry->name, &tentry, &code)) {
297         code = VL_NAMEEXIST;
298         goto abort;
299     } else if (code) {
300         goto abort;
301     }
302
303     blockindex = AllocBlock(&ctx, &tentry);
304     if (blockindex == 0) {
305         code = VL_CREATEFAIL;
306         goto abort;
307     }
308
309     memset(&tentry, 0, sizeof(struct nvlentry));
310     /* Convert to its internal representation; both in host byte order */
311     if ((code = vldbentry_to_vlentry(&ctx, newentry, &tentry))) {
312         FreeBlock(&ctx, blockindex);
313         goto abort;
314     }
315
316     /* Actually insert the entry in vldb */
317     code = ThreadVLentry(&ctx, blockindex, &tentry);
318     if (code) {
319         FreeBlock(&ctx, blockindex);
320         goto abort;
321     } else {
322         return ubik_EndTrans(ctx.trans);
323     }
324
325   abort:
326     countAbort(this_op);
327     ubik_AbortTrans(ctx.trans);
328     return code;
329 }
330
331 afs_int32
332 SVL_CreateEntry(struct rx_call *rxcall, struct vldbentry *newentry)
333 {
334     afs_int32 code;
335
336     code = CreateEntry(rxcall, newentry);
337     osi_auditU(rxcall, VLCreateEntryEvent, code, AUD_STR,
338                (newentry ? newentry->name : NULL), AUD_END);
339     return code;
340 }
341
342 static afs_int32
343 CreateEntryN(struct rx_call *rxcall, struct nvldbentry *newentry)
344 {
345     int this_op = VLCREATEENTRYN;
346     struct vl_ctx ctx;
347     afs_int32 code, blockindex;
348     struct nvlentry tentry;
349     char rxstr[AFS_RXINFO_LEN];
350
351     countRequest(this_op);
352     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL)) {
353         return VL_PERM;
354     }
355
356     /* Do some validity tests on new entry */
357     if ((code = check_nvldbentry(newentry))
358         || (code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
359         return code;
360
361     VLog(1,
362          ("Create Volume %d %s\n", newentry->volumeId[RWVOL],
363           rxinfo(rxstr, rxcall)));
364     if (EntryIDExists(&ctx, newentry->volumeId, MAXTYPES, &code)) {
365         /* at least one of the specified IDs already exists; we fail */
366         code = VL_IDEXIST;
367         goto abort;
368     } else if (code) {
369         goto abort;
370     }
371
372     /* Is this following check (by volume name) necessary?? */
373     /* If entry already exists, we fail */
374     if (FindByName(&ctx, newentry->name, &tentry, &code)) {
375         code = VL_NAMEEXIST;
376         goto abort;
377     } else if (code) {
378         goto abort;
379     }
380
381     blockindex = AllocBlock(&ctx, &tentry);
382     if (blockindex == 0) {
383         code = VL_CREATEFAIL;
384         goto abort;
385     }
386
387     memset(&tentry, 0, sizeof(struct nvlentry));
388     /* Convert to its internal representation; both in host byte order */
389     if ((code = nvldbentry_to_vlentry(&ctx, newentry, &tentry))) {
390         FreeBlock(&ctx, blockindex);
391         goto abort;
392     }
393
394     /* Actually insert the entry in vldb */
395     code = ThreadVLentry(&ctx, blockindex, &tentry);
396     if (code) {
397         FreeBlock(&ctx, blockindex);
398         goto abort;
399     } else {
400         return ubik_EndTrans(ctx.trans);
401     }
402
403   abort:
404     countAbort(this_op);
405     ubik_AbortTrans(ctx.trans);
406     return code;
407 }
408
409 afs_int32
410 SVL_CreateEntryN(struct rx_call *rxcall, struct nvldbentry *newentry)
411 {
412     afs_int32 code;
413
414     code = CreateEntryN(rxcall, newentry);
415     osi_auditU(rxcall, VLCreateEntryEvent, code, AUD_STR,
416                (newentry ? newentry->name : NULL), AUD_END);
417     return code;
418 }
419
420 static afs_int32
421 ChangeAddr(struct rx_call *rxcall, afs_uint32 ip1, afs_uint32 ip2)
422 {
423     int this_op = VLCHANGEADDR;
424     struct vl_ctx ctx;
425     afs_int32 code;
426     char rxstr[AFS_RXINFO_LEN];
427
428     countRequest(this_op);
429     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL)) {
430         return VL_PERM;
431     }
432
433     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
434         return code;
435
436     VLog(1, ("Change Addr %u -> %u %s\n", ip1, ip2, rxinfo(rxstr, rxcall)));
437     if ((code = ChangeIPAddr(&ctx, ip1, ip2)))
438         goto abort;
439     else {
440         code = ubik_EndTrans(ctx.trans);
441         return code;
442     }
443
444   abort:
445     countAbort(this_op);
446     ubik_AbortTrans(ctx.trans);
447     return code;
448 }
449
450 afs_int32
451 SVL_ChangeAddr(struct rx_call *rxcall, afs_uint32 ip1, afs_uint32 ip2)
452 {
453     afs_int32 code;
454
455     code = ChangeAddr(rxcall, ip1, ip2);
456     osi_auditU(rxcall, VLChangeAddrEvent, code, AUD_LONG, ip1, AUD_LONG,
457                ip2, AUD_END);
458     return code;
459 }
460
461 /* Delete a vldb entry given the volume id. */
462 static afs_int32
463 DeleteEntry(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype)
464 {
465     int this_op = VLDELETEENTRY;
466     struct vl_ctx ctx;
467     afs_int32 blockindex, code;
468     struct nvlentry tentry;
469     char rxstr[AFS_RXINFO_LEN];
470
471     countRequest(this_op);
472     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
473         return VL_PERM;
474
475     if ((voltype != -1) && (InvalidVoltype(voltype)))
476         return VL_BADVOLTYPE;
477
478     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
479         return code;
480
481     VLog(1, ("Delete Volume %u %s\n", volid, rxinfo(rxstr, rxcall)));
482     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
483     if (blockindex == 0) {      /* volid not found */
484         if (!code)
485             code = VL_NOENT;
486         goto abort;
487     }
488
489     if (tentry.flags & VLDELETED) {     /* Already deleted; return */
490         ABORT(VL_ENTDELETED);
491     }
492     if ((code = RemoveEntry(&ctx, blockindex, &tentry))) {
493         goto abort;
494     }
495     return ubik_EndTrans(ctx.trans);
496
497   abort:
498     countAbort(this_op);
499     ubik_AbortTrans(ctx.trans);
500     return code;
501 }
502
503 afs_int32
504 SVL_DeleteEntry(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype)
505 {
506     afs_int32 code;
507
508     code = DeleteEntry(rxcall, volid, voltype);
509     osi_auditU(rxcall, VLDeleteEntryEvent, code, AUD_LONG, volid,
510                AUD_END);
511     return code;
512 }
513
514
515 /* Get a vldb entry given its volume id; make sure it's not a deleted entry. */
516 static int
517 GetEntryByID(struct rx_call *rxcall,
518              afs_uint32 volid,
519              afs_int32 voltype,
520              char *aentry,      /* entry data copied here */
521              afs_int32 new,
522              afs_int32 this_op)
523 {
524     struct vl_ctx ctx;
525     afs_int32 blockindex, code;
526     struct nvlentry tentry;
527     char rxstr[AFS_RXINFO_LEN];
528
529     countRequest(this_op);
530
531     if ((voltype != -1) && (InvalidVoltype(voltype)))
532         return VL_BADVOLTYPE;
533     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
534         return code;
535
536     VLog(5, ("GetVolumeByID %u (%d) %s\n", volid, new,
537              rxinfo(rxstr, rxcall)));
538     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
539     if (blockindex == 0) {      /* entry not found */
540         if (!code)
541             code = VL_NOENT;
542         goto abort;
543     }
544     if (tentry.flags & VLDELETED) {     /* Entry is deleted! */
545         code = VL_ENTDELETED;
546         goto abort;
547     }
548     /* Convert from the internal to external form */
549     if (new == 1)
550         code = vlentry_to_nvldbentry(&ctx, &tentry, (struct nvldbentry *)aentry);
551     else if (new == 2)
552         code = vlentry_to_uvldbentry(&ctx, &tentry, (struct uvldbentry *)aentry);
553     else
554         code = vlentry_to_vldbentry(&ctx, &tentry, (struct vldbentry *)aentry);
555
556     if (code)
557         goto abort;
558
559     return (ubik_EndTrans(ctx.trans));
560
561 abort:
562     countAbort(this_op);
563     ubik_AbortTrans(ctx.trans);
564     return code;
565 }
566
567 afs_int32
568 SVL_GetEntryByID(struct rx_call *rxcall,
569                  afs_uint32 volid,
570                  afs_int32 voltype,
571                  vldbentry *aentry)             /* entry data copied here */
572 {
573     return (GetEntryByID(rxcall, volid, voltype, (char *)aentry, 0,
574                          VLGETENTRYBYID));
575 }
576
577 afs_int32
578 SVL_GetEntryByIDN(struct rx_call *rxcall,
579                   afs_uint32 volid,
580                   afs_int32 voltype,
581                   nvldbentry *aentry)   /* entry data copied here */
582 {
583     return (GetEntryByID(rxcall, volid, voltype, (char *)aentry, 1,
584                          VLGETENTRYBYIDN));
585 }
586
587 afs_int32
588 SVL_GetEntryByIDU(struct rx_call *rxcall,
589                   afs_uint32 volid,
590                   afs_int32 voltype,
591                   uvldbentry *aentry)   /* entry data copied here */
592 {
593     return (GetEntryByID(rxcall, volid, voltype, (char *)aentry, 2,
594                          VLGETENTRYBYIDU));
595 }
596
597 /* returns true if the id is a decimal integer, in which case we interpret
598  * it as an id.  make the cache manager much simpler */
599 static int
600 NameIsId(char *aname)
601 {
602     int tc;
603     while ((tc = *aname++)) {
604         if (tc > '9' || tc < '0')
605             return 0;
606     }
607     return 1;
608 }
609
610 /* Get a vldb entry given the volume's name; of course, very similar to
611  * VLGetEntryByID() above. */
612 static afs_int32
613 GetEntryByName(struct rx_call *rxcall,
614                char *volname,
615                char *aentry,            /* entry data copied here */
616                int new,
617                int this_op)
618 {
619     struct vl_ctx ctx;
620     afs_int32 blockindex, code;
621     struct nvlentry tentry;
622     char rxstr[AFS_RXINFO_LEN];
623
624     if (NameIsId(volname)) {
625         return GetEntryByID(rxcall, strtoul(volname, NULL, 10), -1, aentry, new, this_op);
626     }
627     if (InvalidVolname(volname))
628         return VL_BADNAME;
629     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
630         return code;
631     VLog(5, ("GetVolumeByName %s (%d) %s\n", volname, new, rxinfo(rxstr, rxcall)));
632     blockindex = FindByName(&ctx, volname, &tentry, &code);
633     if (blockindex == 0) {      /* entry not found */
634         if (!code)
635             code = VL_NOENT;
636         goto abort;
637     }
638     if (tentry.flags & VLDELETED) {     /* Entry is deleted */
639         code = VL_ENTDELETED;
640         goto abort;
641     }
642     /* Convert to external entry representation */
643     if (new == 1)
644         code = vlentry_to_nvldbentry(&ctx, &tentry, (struct nvldbentry *)aentry);
645     else if (new == 2)
646         code = vlentry_to_uvldbentry(&ctx, &tentry, (struct uvldbentry *)aentry);
647     else
648         code = vlentry_to_vldbentry(&ctx, &tentry, (struct vldbentry *)aentry);
649
650     if (code)
651         goto abort;
652
653     return (ubik_EndTrans(ctx.trans));
654
655 abort:
656     countAbort(this_op);
657     ubik_AbortTrans(ctx.trans);
658     return code;
659
660 }
661
662 afs_int32
663 SVL_GetEntryByNameO(struct rx_call *rxcall,
664                     char *volname,
665                     struct vldbentry *aentry)   /* entry data copied here */
666 {
667     return (GetEntryByName(rxcall, volname, (char *)aentry, 0,
668                            VLGETENTRYBYNAME));
669 }
670
671 afs_int32
672 SVL_GetEntryByNameN(struct rx_call *rxcall,
673                     char *volname,
674                     struct nvldbentry *aentry)  /* entry data copied here */
675 {
676     return (GetEntryByName(rxcall, volname, (char *)aentry, 1,
677                            VLGETENTRYBYNAMEN));
678 }
679
680 afs_int32
681 SVL_GetEntryByNameU(struct rx_call *rxcall,
682                     char *volname,
683                     struct uvldbentry *aentry)  /* entry data copied here */
684 {
685     return (GetEntryByName(rxcall, volname, (char *)aentry, 2,
686                            VLGETENTRYBYNAMEU));
687 }
688
689 /* Get the current value of the maximum volume id and bump the volume id counter by Maxvolidbump. */
690 static afs_int32
691 getNewVolumeId(struct rx_call *rxcall, afs_uint32 Maxvolidbump,
692                    afs_uint32 *newvolumeid)
693 {
694     int this_op = VLGETNEWVOLUMEID;
695     afs_int32 code;
696     afs_uint32 maxvolumeid;
697     struct vl_ctx ctx;
698     char rxstr[AFS_RXINFO_LEN];
699
700     countRequest(this_op);
701     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
702         return VL_PERM;
703
704     if (Maxvolidbump > MAXBUMPCOUNT)
705         return VL_BADVOLIDBUMP;
706
707     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
708         return code;
709
710     *newvolumeid = maxvolumeid = NextUnusedID(&ctx,
711         ntohl(ctx.cheader->vital_header.MaxVolumeId), Maxvolidbump, &code);
712     if (code) {
713         goto abort;
714     }
715
716     maxvolumeid += Maxvolidbump;
717     VLog(1, ("GetNewVolid newmax=%u %s\n", maxvolumeid, rxinfo(rxstr, rxcall)));
718     ctx.cheader->vital_header.MaxVolumeId = htonl(maxvolumeid);
719     if (write_vital_vlheader(&ctx)) {
720         ABORT(VL_IO);
721     }
722     return ubik_EndTrans(ctx.trans);
723
724   abort:
725     countAbort(this_op);
726     ubik_AbortTrans(ctx.trans);
727     return code;
728 }
729
730 afs_int32
731 SVL_GetNewVolumeId(struct rx_call *rxcall, afs_uint32 Maxvolidbump,
732                    afs_uint32 *newvolumeid)
733 {
734     afs_int32 code;
735
736     code = getNewVolumeId(rxcall, Maxvolidbump, newvolumeid);
737     osi_auditU(rxcall, VLGetNewVolumeIdEvent, code, AUD_END);
738     return code;
739 }
740
741
742 /* Simple replace the contents of the vldb entry, volid, with
743  * newentry. No individual checking/updating per field (alike
744  * VLUpdateEntry) is done. */
745
746 static afs_int32
747 ReplaceEntry(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
748                  struct vldbentry *newentry, afs_int32 releasetype)
749 {
750     int this_op = VLREPLACEENTRY;
751     struct vl_ctx ctx;
752     afs_int32 blockindex, code, typeindex;
753     int hashnewname;
754     int hashVol[MAXTYPES];
755     struct nvlentry tentry;
756     afs_uint32 checkids[MAXTYPES];
757     char rxstr[AFS_RXINFO_LEN];
758
759     countRequest(this_op);
760     for (typeindex = 0; typeindex < MAXTYPES; typeindex++)
761         hashVol[typeindex] = 0;
762     hashnewname = 0;
763     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
764         return VL_PERM;
765
766     if ((code = check_vldbentry(newentry)))
767         return code;
768
769     if (voltype != -1 && InvalidVoltype(voltype))
770         return VL_BADVOLTYPE;
771
772     if (releasetype && InvalidReleasetype(releasetype))
773         return VL_BADRELLOCKTYPE;
774     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
775         return code;
776
777     VLog(1, ("OReplace Volume %u %s\n", volid, rxinfo(rxstr, rxcall)));
778     /* find vlentry we're changing */
779     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
780     if (blockindex == 0) {      /* entry not found */
781         if (!code)
782             code = VL_NOENT;
783         goto abort;
784     }
785
786     /* check that we're not trying to change the RW vol ID */
787     if (newentry->volumeId[RWVOL] != tentry.volumeId[RWVOL]) {
788         ABORT(VL_BADENTRY);
789     }
790
791     /* make sure none of the IDs we are changing to are already in use */
792     memset(&checkids, 0, sizeof(checkids));
793     for (typeindex = ROVOL; typeindex < MAXTYPES; typeindex++) {
794         if (tentry.volumeId[typeindex] != newentry->volumeId[typeindex]) {
795             checkids[typeindex] = newentry->volumeId[typeindex];
796         }
797     }
798     if (EntryIDExists(&ctx, checkids, MAXTYPES, &code)) {
799         ABORT(VL_IDEXIST);
800     } else if (code) {
801         goto abort;
802     }
803
804     /* make sure the name we're changing to doesn't already exist */
805     if (strcmp(newentry->name, tentry.name)) {
806         struct nvlentry tmp_entry;
807         if (FindByName(&ctx, newentry->name, &tmp_entry, &code)) {
808             ABORT(VL_NAMEEXIST);
809         } else if (code) {
810             goto abort;
811         }
812     }
813
814     /* unhash volid entries if they're disappearing or changing.
815      * Remember if we need to hash in the new value (we don't have to
816      * rehash if volid stays same */
817     for (typeindex = ROVOL; typeindex <= BACKVOL; typeindex++) {
818         if (tentry.volumeId[typeindex] != newentry->volumeId[typeindex]) {
819             if (tentry.volumeId[typeindex])
820                 if ((code =
821                     UnhashVolid(&ctx, typeindex, blockindex, &tentry))) {
822                     goto abort;
823                 }
824             /* we must rehash new id if the id is different and the ID is nonzero */
825             hashVol[typeindex] = 1;     /* must rehash this guy if he exists */
826         }
827     }
828
829     /* Rehash volname if it changes */
830     if (strcmp(newentry->name, tentry.name)) {  /* Name changes; redo hashing */
831         if ((code = UnhashVolname(&ctx, blockindex, &tentry))) {
832             goto abort;
833         }
834         hashnewname = 1;
835     }
836
837     /* after this, tentry is new entry, not old one.  vldbentry_to_vlentry
838      * doesn't touch hash chains */
839     if ((code = vldbentry_to_vlentry(&ctx, newentry, &tentry))) {
840         goto abort;
841     }
842
843     for (typeindex = ROVOL; typeindex <= BACKVOL; typeindex++) {
844         if (hashVol[typeindex] && tentry.volumeId[typeindex]) {
845             if ((code = HashVolid(&ctx, typeindex, blockindex, &tentry))) {
846                 goto abort;
847             }
848         }
849     }
850
851     if (hashnewname)
852         HashVolname(&ctx, blockindex, &tentry);
853
854     if (releasetype)
855         ReleaseEntry(&tentry, releasetype);     /* Unlock entry if necessary */
856     if (vlentrywrite(ctx.trans, blockindex, &tentry, sizeof(tentry))) {
857         ABORT(VL_IO);
858     }
859
860     return ubik_EndTrans(ctx.trans);
861
862   abort:
863     countAbort(this_op);
864     ubik_AbortTrans(ctx.trans);
865     return code;
866 }
867
868 afs_int32
869 SVL_ReplaceEntry(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
870                  struct vldbentry *newentry, afs_int32 releasetype)
871 {
872     afs_int32 code;
873
874     code = ReplaceEntry(rxcall, volid, voltype, newentry, releasetype);
875     osi_auditU(rxcall, VLReplaceVLEntryEvent, code, AUD_LONG, volid, AUD_END);
876     return code;
877 }
878
879 static afs_int32
880 ReplaceEntryN(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
881                   struct nvldbentry *newentry, afs_int32 releasetype)
882 {
883     int this_op = VLREPLACEENTRYN;
884     struct vl_ctx ctx;
885     afs_int32 blockindex, code, typeindex;
886     int hashnewname;
887     int hashVol[MAXTYPES];
888     struct nvlentry tentry;
889     char rxstr[AFS_RXINFO_LEN];
890
891     countRequest(this_op);
892     for (typeindex = 0; typeindex < MAXTYPES; typeindex++)
893         hashVol[typeindex] = 0;
894     hashnewname = 0;
895     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
896         return VL_PERM;
897
898     if ((code = check_nvldbentry(newentry)))
899         return code;
900
901     if (voltype != -1 && InvalidVoltype(voltype))
902         return VL_BADVOLTYPE;
903
904     if (releasetype && InvalidReleasetype(releasetype))
905         return VL_BADRELLOCKTYPE;
906     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
907         return code;
908
909     VLog(1, ("Replace Volume %u %s\n", volid, rxinfo(rxstr, rxcall)));
910     /* find vlentry we're changing */
911     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
912     if (blockindex == 0) {      /* entry not found */
913         if (!code)
914             code = VL_NOENT;
915         goto abort;
916     }
917
918     /* check that we're not trying to change the RW vol ID */
919     if (newentry->volumeId[RWVOL] != tentry.volumeId[RWVOL]) {
920         ABORT(VL_BADENTRY);
921     }
922
923     /* unhash volid entries if they're disappearing or changing.
924      * Remember if we need to hash in the new value (we don't have to
925      * rehash if volid stays same */
926     for (typeindex = ROVOL; typeindex <= BACKVOL; typeindex++) {
927         if (tentry.volumeId[typeindex] != newentry->volumeId[typeindex]) {
928             if (tentry.volumeId[typeindex])
929                 if ((code =
930                     UnhashVolid(&ctx, typeindex, blockindex, &tentry))) {
931                     goto abort;
932                 }
933             /* we must rehash new id if the id is different and the ID is nonzero */
934             hashVol[typeindex] = 1;     /* must rehash this guy if he exists */
935         }
936     }
937
938     /* Rehash volname if it changes */
939     if (strcmp(newentry->name, tentry.name)) {  /* Name changes; redo hashing */
940         if ((code = UnhashVolname(&ctx, blockindex, &tentry))) {
941             goto abort;
942         }
943         hashnewname = 1;
944     }
945
946     /* after this, tentry is new entry, not old one.  vldbentry_to_vlentry
947      * doesn't touch hash chains */
948     if ((code = nvldbentry_to_vlentry(&ctx, newentry, &tentry))) {
949         goto abort;
950     }
951
952     for (typeindex = ROVOL; typeindex <= BACKVOL; typeindex++) {
953         if (hashVol[typeindex] && tentry.volumeId[typeindex]) {
954             if ((code = HashVolid(&ctx, typeindex, blockindex, &tentry))) {
955                 goto abort;
956             }
957         }
958     }
959
960     if (hashnewname)
961         HashVolname(&ctx, blockindex, &tentry);
962
963     if (releasetype)
964         ReleaseEntry(&tentry, releasetype);     /* Unlock entry if necessary */
965     if (vlentrywrite(ctx.trans, blockindex, &tentry, sizeof(tentry))) {
966         ABORT(VL_IO);
967     }
968
969     return ubik_EndTrans(ctx.trans);
970
971   abort:
972     countAbort(this_op);
973     ubik_AbortTrans(ctx.trans);
974     return code;
975 }
976
977 afs_int32
978 SVL_ReplaceEntryN(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
979                   struct nvldbentry *newentry, afs_int32 releasetype)
980 {
981     afs_int32 code;
982
983     code = ReplaceEntryN(rxcall, volid, voltype, newentry, releasetype);
984     osi_auditU(rxcall, VLReplaceVLEntryEvent, code, AUD_LONG, volid, AUD_END);
985     return code;
986 }
987
988
989 /* Update a vldb entry (accessed thru its volume id). Almost all of the
990  * entry's fields can be modified in a single call by setting the
991  * appropriate bits in the Mask field in VldbUpdateentry. */
992 /* this routine may never have been tested; use replace entry instead
993  * unless you're brave */
994 static afs_int32
995 UpdateEntry(struct rx_call *rxcall,
996             afs_uint32 volid,
997             afs_int32 voltype,
998             struct VldbUpdateEntry *updateentry,        /* Update entry copied here */
999             afs_int32 releasetype)
1000 {
1001     int this_op = VLUPDATEENTRY;
1002     struct vl_ctx ctx;
1003     afs_int32 blockindex, code;
1004     struct nvlentry tentry;
1005     char rxstr[AFS_RXINFO_LEN];
1006
1007     countRequest(this_op);
1008     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
1009         return VL_PERM;
1010     if ((voltype != -1) && (InvalidVoltype(voltype)))
1011         return VL_BADVOLTYPE;
1012     if (releasetype && InvalidReleasetype(releasetype))
1013         return VL_BADRELLOCKTYPE;
1014     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
1015         return code;
1016
1017     VLog(1, ("Update Volume %u %s\n", volid, rxinfo(rxstr, rxcall)));
1018     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
1019     if (blockindex == 0) {      /* entry not found */
1020         if (!code)
1021             code = VL_NOENT;
1022         goto abort;
1023     }
1024
1025     /* Do the actual updating of the entry, tentry. */
1026     if ((code =
1027         get_vldbupdateentry(&ctx, blockindex, updateentry, &tentry))) {
1028         goto abort;
1029     }
1030     if (releasetype)
1031         ReleaseEntry(&tentry, releasetype);     /* Unlock entry if necessary */
1032     if (vlentrywrite(ctx.trans, blockindex, &tentry, sizeof(tentry))) {
1033         ABORT(VL_IO);
1034     }
1035     return ubik_EndTrans(ctx.trans);
1036
1037   abort:
1038     countAbort(this_op);
1039     ubik_AbortTrans(ctx.trans);
1040     return code;
1041 }
1042
1043 afs_int32
1044 SVL_UpdateEntry(struct rx_call *rxcall,
1045                 afs_uint32 volid,
1046                 afs_int32 voltype,
1047                 struct VldbUpdateEntry *updateentry,
1048                 afs_int32 releasetype)
1049 {
1050     afs_int32 code;
1051
1052     code = UpdateEntry(rxcall, volid, voltype, updateentry, releasetype);
1053     osi_auditU(rxcall, VLUpdateEntryEvent, code, AUD_LONG, volid, AUD_END);
1054     return code;
1055 }
1056
1057 static afs_int32
1058 UpdateEntryByName(struct rx_call *rxcall,
1059                   char *volname,
1060                   struct VldbUpdateEntry *updateentry, /* Update entry copied here */
1061                   afs_int32 releasetype)
1062 {
1063     int this_op = VLUPDATEENTRYBYNAME;
1064     struct vl_ctx ctx;
1065     afs_int32 blockindex, code;
1066     struct nvlentry tentry;
1067
1068     countRequest(this_op);
1069     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
1070         return VL_PERM;
1071     if (releasetype && InvalidReleasetype(releasetype))
1072         return VL_BADRELLOCKTYPE;
1073     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
1074         return code;
1075
1076     blockindex = FindByName(&ctx, volname, &tentry, &code);
1077     if (blockindex == 0) {      /* entry not found */
1078         if (!code)
1079             code = VL_NOENT;
1080         goto abort;
1081     }
1082
1083     /* Do the actual updating of the entry, tentry. */
1084     if ((code =
1085         get_vldbupdateentry(&ctx, blockindex, updateentry, &tentry))) {
1086         goto abort;
1087     }
1088     if (releasetype)
1089         ReleaseEntry(&tentry, releasetype);     /* Unlock entry if necessary */
1090     if (vlentrywrite(ctx.trans, blockindex, &tentry, sizeof(tentry))) {
1091         ABORT(VL_IO);
1092     }
1093     return ubik_EndTrans(ctx.trans);
1094
1095   abort:
1096     countAbort(this_op);
1097     ubik_AbortTrans(ctx.trans);
1098     return code;
1099 }
1100
1101 afs_int32
1102 SVL_UpdateEntryByName(struct rx_call *rxcall,
1103                       char *volname,
1104                       struct VldbUpdateEntry *updateentry, /* Update entry copied here */
1105                       afs_int32 releasetype)
1106 {
1107     afs_int32 code;
1108
1109     code = UpdateEntryByName(rxcall, volname, updateentry, releasetype);
1110     osi_auditU(rxcall, VLUpdateEntryEvent, code, AUD_LONG, -1, AUD_END);
1111     return code;
1112 }
1113
1114 /* Set a lock to the vldb entry for volid (of type voltype if not -1). */
1115 static afs_int32
1116 SetLock(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
1117         afs_int32 voloper)
1118 {
1119     int this_op = VLSETLOCK;
1120     afs_int32 timestamp, blockindex, code;
1121     struct vl_ctx ctx;
1122     struct nvlentry tentry;
1123     char rxstr[AFS_RXINFO_LEN];
1124
1125     countRequest(this_op);
1126     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
1127         return VL_PERM;
1128     if ((voltype != -1) && (InvalidVoltype(voltype)))
1129         return VL_BADVOLTYPE;
1130     if (InvalidOperation(voloper))
1131         return VL_BADVOLOPER;
1132     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
1133         return code;
1134
1135     VLog(1, ("SetLock Volume %u %s\n", volid, rxinfo(rxstr, rxcall)));
1136     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
1137     if (blockindex == NULLO) {
1138         if (!code)
1139             code = VL_NOENT;
1140         goto abort;
1141     }
1142     if (tentry.flags & VLDELETED) {
1143         ABORT(VL_ENTDELETED);
1144     }
1145     timestamp = FT_ApproxTime();
1146
1147     /* Check if entry is already locked; note that we unlock any entry
1148      * locked more than MAXLOCKTIME seconds */
1149     if ((tentry.LockTimestamp)
1150         && ((timestamp - tentry.LockTimestamp) < MAXLOCKTIME)) {
1151         ABORT(VL_ENTRYLOCKED);
1152     }
1153
1154     /* Consider it an unlocked entry: set current timestamp, caller
1155      * and active vol operation */
1156     tentry.LockTimestamp = timestamp;
1157     tentry.LockAfsId = 0;       /* Not implemented yet */
1158     if (tentry.flags & VLOP_RELEASE) {
1159         ABORT(VL_RERELEASE);
1160     }
1161     tentry.flags &= ~VLOP_ALLOPERS;     /* Clear any possible older operation bit */
1162     tentry.flags |= voloper;
1163
1164     if (vlentrywrite(ctx.trans, blockindex, &tentry, sizeof(tentry))) {
1165         ABORT(VL_IO);
1166     }
1167     return ubik_EndTrans(ctx.trans);
1168
1169   abort:
1170     countAbort(this_op);
1171     ubik_AbortTrans(ctx.trans);
1172     return code;
1173 }
1174
1175 afs_int32
1176 SVL_SetLock(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
1177             afs_int32 voloper)
1178 {
1179     afs_int32 code;
1180
1181     code = SetLock(rxcall, volid, voltype, voloper);
1182     osi_auditU(rxcall, VLSetLockEvent, code, AUD_LONG, volid, AUD_END);
1183     return code;
1184 }
1185
1186 /* Release an already locked vldb entry. Releasetype determines what
1187  * fields (afsid and/or volume operation) will be cleared along with
1188  * the lock time stamp. */
1189
1190 static afs_int32
1191 ReleaseLock(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
1192             afs_int32 releasetype)
1193 {
1194     int this_op = VLRELEASELOCK;
1195     afs_int32 blockindex, code;
1196     struct vl_ctx ctx;
1197     struct nvlentry tentry;
1198     char rxstr[AFS_RXINFO_LEN];
1199
1200     countRequest(this_op);
1201     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
1202         return VL_PERM;
1203     if ((voltype != -1) && (InvalidVoltype(voltype)))
1204         return VL_BADVOLTYPE;
1205     if (releasetype && InvalidReleasetype(releasetype))
1206         return VL_BADRELLOCKTYPE;
1207     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
1208         return code;
1209
1210     VLog(1, ("ReleaseLock Volume %u %s\n", volid, rxinfo(rxstr, rxcall)));
1211     blockindex = FindByID(&ctx, volid, voltype, &tentry, &code);
1212     if (blockindex == NULLO) {
1213         if (!code)
1214             code = VL_NOENT;
1215         goto abort;
1216     }
1217     if (tentry.flags & VLDELETED) {
1218         ABORT(VL_ENTDELETED);
1219     }
1220     if (releasetype)
1221         ReleaseEntry(&tentry, releasetype);     /* Unlock the appropriate fields */
1222     if (vlentrywrite(ctx.trans, blockindex, &tentry, sizeof(tentry))) {
1223         ABORT(VL_IO);
1224     }
1225     return ubik_EndTrans(ctx.trans);
1226
1227   abort:
1228     countAbort(this_op);
1229     ubik_AbortTrans(ctx.trans);
1230     return code;
1231 }
1232
1233 afs_int32
1234 SVL_ReleaseLock(struct rx_call *rxcall, afs_uint32 volid, afs_int32 voltype,
1235                 afs_int32 releasetype)
1236 {
1237     afs_int32 code;
1238
1239     code = ReleaseLock(rxcall, volid, voltype, releasetype);
1240     osi_auditU(rxcall, VLReleaseLockEvent, code, AUD_LONG, volid, AUD_END);
1241     return code;
1242 }
1243
1244 /* ListEntry returns a single vldb entry, aentry, with offset previous_index;
1245  * the remaining parameters (i.e. next_index) are used so that sequential
1246  * calls to this routine will get the next (all) vldb entries.
1247  */
1248 static afs_int32
1249 ListEntry(struct rx_call *rxcall, afs_int32 previous_index,
1250           afs_int32 *count, afs_int32 *next_index,
1251           struct vldbentry *aentry)
1252 {
1253     int this_op = VLLISTENTRY;
1254     int code;
1255     struct vl_ctx ctx;
1256     struct nvlentry tentry;
1257     char rxstr[AFS_RXINFO_LEN];
1258
1259     countRequest(this_op);
1260
1261     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
1262                                       restrictedQueryLevel))
1263         return VL_PERM;
1264
1265     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
1266         return code;
1267     VLog(25, ("OListEntry index=%d %s\n", previous_index,
1268               rxinfo(rxstr, rxcall)));
1269     *next_index = NextEntry(&ctx, previous_index, &tentry, count);
1270     if (*next_index) {
1271         code = vlentry_to_vldbentry(&ctx, &tentry, aentry);
1272         if (code) {
1273             countAbort(this_op);
1274             ubik_AbortTrans(ctx.trans);
1275             return code;
1276         }
1277     }
1278     return ubik_EndTrans(ctx.trans);
1279 }
1280
1281 afs_int32
1282 SVL_ListEntry(struct rx_call *rxcall, afs_int32 previous_index,
1283               afs_int32 *count, afs_int32 *next_index,
1284               struct vldbentry *aentry)
1285 {
1286     afs_int32 code;
1287
1288     code = ListEntry(rxcall, previous_index, count, next_index, aentry);
1289     osi_auditU(rxcall, VLListEntryEvent, code, AUD_LONG, previous_index, AUD_END);
1290     return code;
1291 }
1292
1293 /* ListEntry returns a single vldb entry, aentry, with offset previous_index;
1294  * the remaining parameters (i.e. next_index) are used so that sequential
1295  * calls to this routine will get the next (all) vldb entries.
1296  */
1297 static afs_int32
1298 ListEntryN(struct rx_call *rxcall, afs_int32 previous_index,
1299            afs_int32 *count, afs_int32 *next_index,
1300            struct nvldbentry *aentry)
1301 {
1302     int this_op = VLLISTENTRYN;
1303     int code;
1304     struct vl_ctx ctx;
1305     struct nvlentry tentry;
1306     char rxstr[AFS_RXINFO_LEN];
1307
1308     countRequest(this_op);
1309
1310     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
1311                                       restrictedQueryLevel))
1312         return VL_PERM;
1313
1314     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
1315         return code;
1316     VLog(25, ("ListEntry index=%d %s\n", previous_index, rxinfo(rxstr, rxcall)));
1317     *next_index = NextEntry(&ctx, previous_index, &tentry, count);
1318     if (*next_index) {
1319         code = vlentry_to_nvldbentry(&ctx, &tentry, aentry);
1320         if (code) {
1321             countAbort(this_op);
1322             ubik_AbortTrans(ctx.trans);
1323             return code;
1324         }
1325     }
1326
1327     return ubik_EndTrans(ctx.trans);
1328 }
1329
1330 afs_int32
1331 SVL_ListEntryN(struct rx_call *rxcall, afs_int32 previous_index,
1332                afs_int32 *count, afs_int32 *next_index,
1333                struct nvldbentry *aentry)
1334 {
1335     afs_int32 code;
1336
1337     code = ListEntryN(rxcall, previous_index, count, next_index, aentry);
1338     osi_auditU(rxcall, VLListEntryEventN, code, AUD_LONG, previous_index, AUD_END);
1339     return code;
1340 }
1341
1342 /* Retrieves in vldbentries all vldb entries that match the specified
1343  * attributes (by server number, partition, volume type, and flag); if volume
1344  * id is specified then the associated list for that entry is returned.
1345  * CAUTION: This could be a very expensive call since in most cases
1346  * sequential search of all vldb entries is performed.
1347  */
1348 static afs_int32
1349 ListAttributes(struct rx_call *rxcall,
1350                struct VldbListByAttributes *attributes,
1351                afs_int32 *nentries,
1352                bulkentries *vldbentries)
1353 {
1354     int this_op = VLLISTATTRIBUTES;
1355     int code, allocCount = 0;
1356     struct vl_ctx ctx;
1357     struct nvlentry tentry;
1358     struct vldbentry *Vldbentry = 0, *VldbentryFirst = 0, *VldbentryLast = 0;
1359     int pollcount = 0;
1360     char rxstr[AFS_RXINFO_LEN];
1361
1362     countRequest(this_op);
1363
1364     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
1365                                       restrictedQueryLevel))
1366         return VL_PERM;
1367
1368     vldbentries->bulkentries_val = 0;
1369     vldbentries->bulkentries_len = *nentries = 0;
1370     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
1371         return code;
1372     allocCount = VLDBALLOCCOUNT;
1373     Vldbentry = VldbentryFirst = vldbentries->bulkentries_val =
1374         malloc(allocCount * sizeof(vldbentry));
1375     if (Vldbentry == NULL) {
1376         code = VL_NOMEM;
1377         goto abort;
1378     }
1379     VldbentryLast = VldbentryFirst + allocCount;
1380     /* Handle the attribute by volume id totally separate of the rest
1381      * (thus additional Mask values are ignored if VLLIST_VOLUMEID is set!) */
1382     if (attributes->Mask & VLLIST_VOLUMEID) {
1383         afs_int32 blockindex;
1384
1385         blockindex =
1386             FindByID(&ctx, attributes->volumeid, -1, &tentry, &code);
1387         if (blockindex == 0) {
1388             if (!code)
1389                 code = VL_NOENT;
1390             goto abort;
1391         }
1392
1393         code = put_attributeentry(&ctx, &Vldbentry, &VldbentryFirst,
1394                                   &VldbentryLast, vldbentries, &tentry,
1395                                   nentries, &allocCount);
1396         if (code)
1397             goto abort;
1398     } else {
1399         afs_int32 nextblockindex = 0, count = 0, k = 0, match = 0;
1400         while ((nextblockindex =
1401                NextEntry(&ctx, nextblockindex, &tentry, &count))) {
1402             if (++pollcount > 50) {
1403 #ifndef AFS_PTHREAD_ENV
1404                 IOMGR_Poll();
1405 #endif
1406                 pollcount = 0;
1407             }
1408             match = 0;
1409             if (attributes->Mask & VLLIST_SERVER) {
1410                 int serverindex;
1411                 if ((serverindex =
1412                      IpAddrToRelAddr(&ctx, attributes->server, 0)) == -1)
1413                     continue;
1414                 for (k = 0; k < OMAXNSERVERS; k++) {
1415                     if (tentry.serverNumber[k] == BADSERVERID)
1416                         break;
1417                     if (tentry.serverNumber[k] == serverindex) {
1418                         match = 1;
1419                         break;
1420                     }
1421                 }
1422                 if (!match)
1423                     continue;
1424             }
1425             if (attributes->Mask & VLLIST_PARTITION) {
1426                 if (match) {
1427                     if (tentry.serverPartition[k] != attributes->partition)
1428                         continue;
1429                 } else {
1430                     for (k = 0; k < OMAXNSERVERS; k++) {
1431                         if (tentry.serverNumber[k] == BADSERVERID)
1432                             break;
1433                         if (tentry.serverPartition[k] ==
1434                             attributes->partition) {
1435                             match = 1;
1436                             break;
1437                         }
1438                     }
1439                     if (!match)
1440                         continue;
1441                 }
1442             }
1443
1444             if (attributes->Mask & VLLIST_FLAG) {
1445                 if (!(tentry.flags & attributes->flag))
1446                     continue;
1447             }
1448             code = put_attributeentry(&ctx, &Vldbentry, &VldbentryFirst,
1449                                       &VldbentryLast, vldbentries, &tentry,
1450                                       nentries, &allocCount);
1451             if (code)
1452                 goto abort;
1453         }
1454     }
1455     if (vldbentries->bulkentries_len
1456         && (allocCount > vldbentries->bulkentries_len)) {
1457
1458         vldbentries->bulkentries_val =
1459             realloc(vldbentries->bulkentries_val,
1460                     vldbentries->bulkentries_len * sizeof(vldbentry));
1461         if (vldbentries->bulkentries_val == NULL) {
1462             code = VL_NOMEM;
1463             goto abort;
1464         }
1465     }
1466     VLog(5,
1467          ("ListAttrs nentries=%d %s\n", vldbentries->bulkentries_len,
1468           rxinfo(rxstr, rxcall)));
1469     return ubik_EndTrans(ctx.trans);
1470
1471 abort:
1472     if (vldbentries->bulkentries_val)
1473         free(vldbentries->bulkentries_val);
1474     vldbentries->bulkentries_val = 0;
1475     vldbentries->bulkentries_len = 0;
1476
1477     countAbort(this_op);
1478     ubik_AbortTrans(ctx.trans);
1479     return code;
1480 }
1481
1482 afs_int32
1483 SVL_ListAttributes(struct rx_call *rxcall,
1484                    struct VldbListByAttributes *attributes,
1485                    afs_int32 *nentries,
1486                    bulkentries *vldbentries)
1487 {
1488     afs_int32 code;
1489
1490     code = ListAttributes(rxcall, attributes, nentries, vldbentries);
1491     osi_auditU(rxcall, VLListAttributesEvent, code, AUD_END);
1492     return code;
1493 }
1494
1495 static afs_int32
1496 ListAttributesN(struct rx_call *rxcall,
1497                 struct VldbListByAttributes *attributes,
1498                 afs_int32 *nentries,
1499                 nbulkentries *vldbentries)
1500 {
1501     int this_op = VLLISTATTRIBUTESN;
1502     int code, allocCount = 0;
1503     struct vl_ctx ctx;
1504     struct nvlentry tentry;
1505     struct nvldbentry *Vldbentry = 0, *VldbentryFirst = 0, *VldbentryLast = 0;
1506     int pollcount = 0;
1507     char rxstr[AFS_RXINFO_LEN];
1508
1509     countRequest(this_op);
1510
1511     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
1512                                       restrictedQueryLevel))
1513         return VL_PERM;
1514
1515     vldbentries->nbulkentries_val = 0;
1516     vldbentries->nbulkentries_len = *nentries = 0;
1517     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
1518         return code;
1519     allocCount = VLDBALLOCCOUNT;
1520     Vldbentry = VldbentryFirst = vldbentries->nbulkentries_val =
1521         malloc(allocCount * sizeof(nvldbentry));
1522     if (Vldbentry == NULL) {
1523         code = VL_NOMEM;
1524         goto abort;
1525     }
1526     VldbentryLast = VldbentryFirst + allocCount;
1527     /* Handle the attribute by volume id totally separate of the rest
1528      * (thus additional Mask values are ignored if VLLIST_VOLUMEID is set!) */
1529     if (attributes->Mask & VLLIST_VOLUMEID) {
1530         afs_int32 blockindex;
1531
1532         blockindex =
1533             FindByID(&ctx, attributes->volumeid, -1, &tentry, &code);
1534         if (blockindex == 0) {
1535             if (!code)
1536                 code = VL_NOENT;
1537             goto abort;
1538         }
1539
1540         code = put_nattributeentry(&ctx, &Vldbentry, &VldbentryFirst,
1541                                    &VldbentryLast, vldbentries, &tentry,
1542                                    0, 0, nentries, &allocCount);
1543         if (code)
1544             goto abort;
1545     } else {
1546         afs_int32 nextblockindex = 0, count = 0, k = 0, match = 0;
1547         while ((nextblockindex =
1548                NextEntry(&ctx, nextblockindex, &tentry, &count))) {
1549             if (++pollcount > 50) {
1550 #ifndef AFS_PTHREAD_ENV
1551                 IOMGR_Poll();
1552 #endif
1553                 pollcount = 0;
1554             }
1555
1556             match = 0;
1557             if (attributes->Mask & VLLIST_SERVER) {
1558                 int serverindex;
1559                 if ((serverindex =
1560                      IpAddrToRelAddr(&ctx, attributes->server, 0)) == -1)
1561                     continue;
1562                 for (k = 0; k < NMAXNSERVERS; k++) {
1563                     if (tentry.serverNumber[k] == BADSERVERID)
1564                         break;
1565                     if (tentry.serverNumber[k] == serverindex) {
1566                         match = 1;
1567                         break;
1568                     }
1569                 }
1570                 if (!match)
1571                     continue;
1572             }
1573             if (attributes->Mask & VLLIST_PARTITION) {
1574                 if (match) {
1575                     if (tentry.serverPartition[k] != attributes->partition)
1576                         continue;
1577                 } else {
1578                     for (k = 0; k < NMAXNSERVERS; k++) {
1579                         if (tentry.serverNumber[k] == BADSERVERID)
1580                             break;
1581                         if (tentry.serverPartition[k] ==
1582                             attributes->partition) {
1583                             match = 1;
1584                             break;
1585                         }
1586                     }
1587                     if (!match)
1588                         continue;
1589                 }
1590             }
1591
1592             if (attributes->Mask & VLLIST_FLAG) {
1593                 if (!(tentry.flags & attributes->flag))
1594                     continue;
1595             }
1596             code = put_nattributeentry(&ctx, &Vldbentry, &VldbentryFirst,
1597                                        &VldbentryLast, vldbentries,
1598                                        &tentry, 0, 0, nentries, &allocCount);
1599             if (code)
1600                 goto abort;
1601         }
1602     }
1603     if (vldbentries->nbulkentries_len
1604         && (allocCount > vldbentries->nbulkentries_len)) {
1605
1606         vldbentries->nbulkentries_val =
1607             realloc(vldbentries->nbulkentries_val,
1608                     vldbentries->nbulkentries_len * sizeof(nvldbentry));
1609         if (vldbentries->nbulkentries_val == NULL) {
1610             code = VL_NOMEM;
1611             goto abort;
1612         }
1613     }
1614     VLog(5,
1615          ("NListAttrs nentries=%d %s\n", vldbentries->nbulkentries_len,
1616           rxinfo(rxstr, rxcall)));
1617     return ubik_EndTrans(ctx.trans);
1618
1619 abort:
1620     countAbort(this_op);
1621     ubik_AbortTrans(ctx.trans);
1622     if (vldbentries->nbulkentries_val)
1623         free(vldbentries->nbulkentries_val);
1624     vldbentries->nbulkentries_val = 0;
1625     vldbentries->nbulkentries_len = 0;
1626     return code;
1627 }
1628
1629 afs_int32
1630 SVL_ListAttributesN(struct rx_call *rxcall,
1631                     struct VldbListByAttributes *attributes,
1632                     afs_int32 *nentries,
1633                     nbulkentries *vldbentries)
1634 {
1635     afs_int32 code;
1636
1637     code = ListAttributesN(rxcall, attributes, nentries, vldbentries);
1638     osi_auditU(rxcall, VLListAttributesNEvent, code, AUD_END);
1639     return code;
1640 }
1641
1642 static afs_int32
1643 ListAttributesN2(struct rx_call *rxcall,
1644                  struct VldbListByAttributes *attributes,
1645                  char *name,            /* Wildcarded volume name */
1646                  afs_int32 startindex,
1647                  afs_int32 *nentries,
1648                  nbulkentries *vldbentries,
1649                  afs_int32 *nextstartindex)
1650 {
1651     int this_op = VLLISTATTRIBUTESN2;
1652     int code = 0, maxCount = VLDBALLOCCOUNT;
1653     struct vl_ctx ctx;
1654     struct nvlentry tentry;
1655     struct nvldbentry *Vldbentry = 0, *VldbentryFirst = 0, *VldbentryLast = 0;
1656     afs_int32 blockindex = 0, count = 0, k, match;
1657     afs_int32 matchindex = 0;
1658     int serverindex = -1;       /* no server found */
1659     int findserver = 0, findpartition = 0, findflag = 0, findname = 0;
1660     int pollcount = 0;
1661     int namematchRWBK, namematchRO, thismatch;
1662     int matchtype = 0;
1663     char volumename[VL_MAXNAMELEN+2]; /* regex anchors */
1664     char rxstr[AFS_RXINFO_LEN];
1665 #ifdef HAVE_POSIX_REGEX
1666     regex_t re;
1667     int need_regfree = 0;
1668 #else
1669     char *t;
1670 #endif
1671
1672     countRequest(this_op);
1673
1674     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
1675                                       restrictedQueryLevel))
1676         return VL_PERM;
1677
1678     vldbentries->nbulkentries_val = 0;
1679     vldbentries->nbulkentries_len = 0;
1680     *nentries = 0;
1681     *nextstartindex = -1;
1682
1683     code = Init_VLdbase(&ctx, LOCKREAD, this_op);
1684     if (code)
1685         return code;
1686
1687     Vldbentry = VldbentryFirst = vldbentries->nbulkentries_val =
1688         malloc(maxCount * sizeof(nvldbentry));
1689     if (Vldbentry == NULL) {
1690         countAbort(this_op);
1691         ubik_AbortTrans(ctx.trans);
1692         return VL_NOMEM;
1693     }
1694
1695     VldbentryLast = VldbentryFirst + maxCount;
1696
1697     /* Handle the attribute by volume id totally separate of the rest
1698      * (thus additional Mask values are ignored if VLLIST_VOLUMEID is set!)
1699      */
1700     if (attributes->Mask & VLLIST_VOLUMEID) {
1701         blockindex =
1702             FindByID(&ctx, attributes->volumeid, -1, &tentry, &code);
1703         if (blockindex == 0) {
1704             if (!code)
1705                 code = VL_NOENT;
1706         } else {
1707             code =
1708                 put_nattributeentry(&ctx, &Vldbentry, &VldbentryFirst,
1709                                     &VldbentryLast, vldbentries, &tentry, 0,
1710                                     0, nentries, &maxCount);
1711             if (code)
1712                 goto done;
1713         }
1714     }
1715
1716     /* Search each entry in the database and return all entries
1717      * that match the request. It checks volumename (with
1718      * wildcarding), entry flags, server, and partition.
1719      */
1720     else {
1721         /* Get the server index for matching server address */
1722         if (attributes->Mask & VLLIST_SERVER) {
1723             serverindex =
1724                 IpAddrToRelAddr(&ctx, attributes->server, 0);
1725             if (serverindex == -1)
1726                 goto done;
1727             findserver = 1;
1728         }
1729         findpartition = ((attributes->Mask & VLLIST_PARTITION) ? 1 : 0);
1730         findflag = ((attributes->Mask & VLLIST_FLAG) ? 1 : 0);
1731         if (name && (strcmp(name, ".*") != 0) && (strcmp(name, "") != 0)) {
1732             sprintf(volumename, "^%s$", name);
1733 #ifdef HAVE_POSIX_REGEX
1734             if (regcomp(&re, volumename, REG_NOSUB) != 0) {
1735                 code = VL_BADNAME;
1736                 goto done;
1737             }
1738             need_regfree = 1;
1739 #else
1740             t = (char *)re_comp(volumename);
1741             if (t) {
1742                 code = VL_BADNAME;
1743                 goto done;
1744             }
1745 #endif
1746             findname = 1;
1747         }
1748
1749         /* Read each entry and see if it is the one we want */
1750         blockindex = startindex;
1751         while ((blockindex = NextEntry(&ctx, blockindex, &tentry, &count))) {
1752             if (++pollcount > 50) {
1753 #ifndef AFS_PTHREAD_ENV
1754                 IOMGR_Poll();
1755 #endif
1756                 pollcount = 0;
1757             }
1758
1759             /* Step through each server index searching for a match.
1760              * Match to an existing RW, BK, or RO volume name (preference
1761              * is in this order). Remember which index we matched against.
1762              */
1763             namematchRWBK = namematchRO = 0;    /* 0->notTried; 1->match; 2->noMatch */
1764             match = 0;
1765             for (k = 0;
1766                  (k < NMAXNSERVERS
1767                   && (tentry.serverNumber[k] != BADSERVERID)); k++) {
1768                 thismatch = 0;  /* does this index match */
1769
1770                 /* Match against the RW or BK volume name. Remember
1771                  * results in namematchRWBK. Prefer RW over BK.
1772                  */
1773                 if (tentry.serverFlags[k] & VLSF_RWVOL) {
1774                     /* Does the name match the RW name */
1775                     if (tentry.flags & VLF_RWEXISTS) {
1776                         if (findname) {
1777                             sprintf(volumename, "%s", tentry.name);
1778 #ifdef HAVE_POSIX_REGEX
1779                             if (regexec(&re, volumename, 0, NULL, 0) == 0) {
1780                                 thismatch = VLSF_RWVOL;
1781                             }
1782 #else
1783                             if (re_exec(volumename)) {
1784                                 thismatch = VLSF_RWVOL;
1785                             }
1786 #endif
1787                         } else {
1788                             thismatch = VLSF_RWVOL;
1789                         }
1790                     }
1791
1792                     /* Does the name match the BK name */
1793                     if (!thismatch && (tentry.flags & VLF_BACKEXISTS)) {
1794                         if (findname) {
1795                             sprintf(volumename, "%s.backup", tentry.name);
1796 #ifdef HAVE_POSIX_REGEX
1797                             if (regexec(&re, volumename, 0, NULL, 0) == 0) {
1798                                 thismatch = VLSF_BACKVOL;
1799                             }
1800 #else
1801                             if (re_exec(volumename)) {
1802                                 thismatch = VLSF_BACKVOL;
1803                             }
1804 #endif
1805                         } else {
1806                             thismatch = VLSF_BACKVOL;
1807                         }
1808                     }
1809
1810                     namematchRWBK = (thismatch ? 1 : 2);
1811                 }
1812
1813                 /* Match with the RO volume name. Compare once and
1814                  * remember results in namematchRO. Note that this will
1815                  * pick up entries marked NEWREPSITEs and DONTUSE.
1816                  */
1817                 else {
1818                     if (tentry.flags & VLF_ROEXISTS) {
1819                         if (findname) {
1820                             if (namematchRO) {
1821                                 thismatch =
1822                                     ((namematchRO == 1) ? VLSF_ROVOL : 0);
1823                             } else {
1824                                 sprintf(volumename, "%s.readonly",
1825                                         tentry.name);
1826 #ifdef HAVE_POSIX_REGEX
1827                             if (regexec(&re, volumename, 0, NULL, 0) == 0) {
1828                                 thismatch = VLSF_ROVOL;
1829                             }
1830 #else
1831                                 if (re_exec(volumename))
1832                                     thismatch = VLSF_ROVOL;
1833 #endif
1834                             }
1835                         } else {
1836                             thismatch = VLSF_ROVOL;
1837                         }
1838                     }
1839                     namematchRO = (thismatch ? 1 : 2);
1840                 }
1841
1842                 /* Is there a server match */
1843                 if (thismatch && findserver
1844                     && (tentry.serverNumber[k] != serverindex))
1845                     thismatch = 0;
1846
1847                 /* Is there a partition match */
1848                 if (thismatch && findpartition
1849                     && (tentry.serverPartition[k] != attributes->partition))
1850                     thismatch = 0;
1851
1852                 /* Is there a flag match */
1853                 if (thismatch && findflag
1854                     && !(tentry.flags & attributes->flag))
1855                     thismatch = 0;
1856
1857                 /* We found a match. Remember the index, and type */
1858                 if (thismatch) {
1859                     match = 1;
1860                     matchindex = k;
1861                     matchtype = thismatch;
1862                 }
1863
1864                 /* Since we prefer RW and BK volume matches over RO matches,
1865                  * if we have already checked the RWBK name, then we already
1866                  * found the best match and so end the search.
1867                  *
1868                  * If we tried matching against the RW, BK, and RO volume names
1869                  * and both failed, then we end the search (none will match).
1870                  */
1871                 if ((match && namematchRWBK)
1872                     || ((namematchRWBK == 2) && (namematchRO == 2)))
1873                     break;
1874             }
1875
1876             /* Passed all the tests. Take it */
1877             if (match) {
1878                 code =
1879                     put_nattributeentry(&ctx, &Vldbentry, &VldbentryFirst,
1880                                         &VldbentryLast, vldbentries, &tentry,
1881                                         matchtype, matchindex, nentries,
1882                                         &maxCount);
1883                 if (code)
1884                     goto done;
1885
1886                 if (*nentries >= maxCount)
1887                     break;      /* collected the max */
1888             }
1889         }
1890         *nextstartindex = (blockindex ? blockindex : -1);
1891     }
1892
1893   done:
1894 #ifdef HAVE_POSIX_REGEX
1895     if (need_regfree)
1896         regfree(&re);
1897 #endif
1898
1899     if (code) {
1900         countAbort(this_op);
1901         ubik_AbortTrans(ctx.trans);
1902         if (vldbentries->nbulkentries_val)
1903             free(vldbentries->nbulkentries_val);
1904         vldbentries->nbulkentries_val = 0;
1905         vldbentries->nbulkentries_len = 0;
1906         *nextstartindex = -1;
1907     } else {
1908         VLog(5,
1909              ("N2ListAttrs nentries=%d %s\n", vldbentries->nbulkentries_len,
1910               rxinfo(rxstr, rxcall)));
1911         code = ubik_EndTrans(ctx.trans);
1912     }
1913
1914     return code;
1915 }
1916
1917 afs_int32
1918 SVL_ListAttributesN2(struct rx_call *rxcall,
1919                      struct VldbListByAttributes *attributes,
1920                      char *name,                /* Wildcarded volume name */
1921                      afs_int32 startindex,
1922                      afs_int32 *nentries,
1923                      nbulkentries *vldbentries,
1924                      afs_int32 *nextstartindex)
1925 {
1926     afs_int32 code;
1927
1928     code = ListAttributesN2(rxcall, attributes, name, startindex,
1929                             nentries, vldbentries, nextstartindex);
1930     osi_auditU(rxcall, VLListAttributesN2Event, code, AUD_END);
1931     return code;
1932 }
1933
1934 /* Retrieves in vldbentries all vldb entries that match the specified
1935  * attributes (by server number, partition, volume type, and flag); if
1936  * volume id is specified then the associated list for that entry is
1937  * returned. CAUTION: This could be a very expensive call since in most
1938  * cases sequential search of all vldb entries is performed.
1939  */
1940 static afs_int32
1941 LinkedList(struct rx_call *rxcall,
1942            struct VldbListByAttributes *attributes,
1943            afs_int32 *nentries,
1944            vldb_list *vldbentries)
1945 {
1946     int this_op = VLLINKEDLIST;
1947     int code;
1948     struct vl_ctx ctx;
1949     struct nvlentry tentry;
1950     vldblist vllist, *vllistptr;
1951     afs_int32 blockindex, count, match;
1952     afs_int32 k = 0;
1953     int serverindex;
1954     int pollcount = 0;
1955
1956     countRequest(this_op);
1957
1958     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
1959                                       restrictedQueryLevel))
1960         return VL_PERM;
1961
1962     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
1963         return code;
1964
1965     *nentries = 0;
1966     vldbentries->node = NULL;
1967     vllistptr = &vldbentries->node;
1968
1969     /* List by volumeid */
1970     if (attributes->Mask & VLLIST_VOLUMEID) {
1971         blockindex =
1972             FindByID(&ctx, attributes->volumeid, -1, &tentry, &code);
1973         if (!blockindex) {
1974             if (!code)
1975                 code = VL_NOENT;
1976             goto abort;
1977         }
1978
1979         vllist = malloc(sizeof(single_vldbentry));
1980         if (vllist == NULL) {
1981             code = VL_NOMEM;
1982             goto abort;
1983         }
1984         code = vlentry_to_vldbentry(&ctx, &tentry, &vllist->VldbEntry);
1985         if (code)
1986             goto abort;
1987
1988         vllist->next_vldb = NULL;
1989
1990         *vllistptr = vllist;    /* Thread onto list */
1991         vllistptr = &vllist->next_vldb;
1992         (*nentries)++;
1993     }
1994
1995     /* Search by server, partition, and flags */
1996     else {
1997         for (blockindex = NextEntry(&ctx, 0, &tentry, &count); blockindex;
1998              blockindex = NextEntry(&ctx, blockindex, &tentry, &count)) {
1999             match = 0;
2000
2001             if (++pollcount > 50) {
2002 #ifndef AFS_PTHREAD_ENV
2003                 IOMGR_Poll();
2004 #endif
2005                 pollcount = 0;
2006             }
2007
2008             /* Does this volume exist on the desired server */
2009             if (attributes->Mask & VLLIST_SERVER) {
2010                 serverindex =
2011                     IpAddrToRelAddr(&ctx, attributes->server, 0);
2012                 if (serverindex == -1)
2013                     continue;
2014                 for (k = 0; k < OMAXNSERVERS; k++) {
2015                     if (tentry.serverNumber[k] == BADSERVERID)
2016                         break;
2017                     if (tentry.serverNumber[k] == serverindex) {
2018                         match = 1;
2019                         break;
2020                     }
2021                 }
2022                 if (!match)
2023                     continue;
2024             }
2025
2026             /* Does this volume exist on the desired partition */
2027             if (attributes->Mask & VLLIST_PARTITION) {
2028                 if (match) {
2029                     if (tentry.serverPartition[k] != attributes->partition)
2030                         match = 0;
2031                 } else {
2032                     for (k = 0; k < OMAXNSERVERS; k++) {
2033                         if (tentry.serverNumber[k] == BADSERVERID)
2034                             break;
2035                         if (tentry.serverPartition[k] ==
2036                             attributes->partition) {
2037                             match = 1;
2038                             break;
2039                         }
2040                     }
2041                 }
2042                 if (!match)
2043                     continue;
2044             }
2045
2046             /* Does this volume have the desired flags */
2047             if (attributes->Mask & VLLIST_FLAG) {
2048                 if (!(tentry.flags & attributes->flag))
2049                     continue;
2050             }
2051
2052             vllist = malloc(sizeof(single_vldbentry));
2053             if (vllist == NULL) {
2054                 code = VL_NOMEM;
2055                 goto abort;
2056             }
2057             code = vlentry_to_vldbentry(&ctx, &tentry, &vllist->VldbEntry);
2058             if (code)
2059                 goto abort;
2060
2061             vllist->next_vldb = NULL;
2062
2063             *vllistptr = vllist;        /* Thread onto list */
2064             vllistptr = &vllist->next_vldb;
2065             (*nentries)++;
2066             if (smallMem && (*nentries >= VLDBALLOCCOUNT)) {
2067                 code = VL_SIZEEXCEEDED;
2068                 goto abort;
2069             }
2070         }
2071     }
2072     *vllistptr = NULL;
2073     return ubik_EndTrans(ctx.trans);
2074
2075 abort:
2076     countAbort(this_op);
2077     ubik_AbortTrans(ctx.trans);
2078     return code;
2079 }
2080
2081 afs_int32
2082 SVL_LinkedList(struct rx_call *rxcall,
2083                struct VldbListByAttributes *attributes,
2084                afs_int32 *nentries,
2085                vldb_list *vldbentries)
2086 {
2087     afs_int32 code;
2088
2089     code = LinkedList(rxcall, attributes, nentries, vldbentries);
2090     osi_auditU(rxcall, VLLinkedListEvent, code, AUD_END);
2091     return code;
2092 }
2093
2094 static afs_int32
2095 LinkedListN(struct rx_call *rxcall,
2096             struct VldbListByAttributes *attributes,
2097             afs_int32 *nentries,
2098             nvldb_list *vldbentries)
2099 {
2100     int this_op = VLLINKEDLISTN;
2101     int code;
2102     struct vl_ctx ctx;
2103     struct nvlentry tentry;
2104     nvldblist vllist, *vllistptr;
2105     afs_int32 blockindex, count, match;
2106     afs_int32 k = 0;
2107     int serverindex;
2108     int pollcount = 0;
2109
2110     countRequest(this_op);
2111
2112     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
2113                                       restrictedQueryLevel))
2114         return VL_PERM;
2115
2116     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
2117         return code;
2118
2119     *nentries = 0;
2120     vldbentries->node = NULL;
2121     vllistptr = &vldbentries->node;
2122
2123     /* List by volumeid */
2124     if (attributes->Mask & VLLIST_VOLUMEID) {
2125         blockindex =
2126             FindByID(&ctx, attributes->volumeid, -1, &tentry, &code);
2127         if (!blockindex) {
2128             if (!code)
2129                 code = VL_NOENT;
2130             goto abort;
2131         }
2132
2133         vllist = malloc(sizeof(single_nvldbentry));
2134         if (vllist == NULL) {
2135             code = VL_NOMEM;
2136             goto abort;
2137         }
2138         code = vlentry_to_nvldbentry(&ctx, &tentry, &vllist->VldbEntry);
2139         if (code)
2140             goto abort;
2141
2142         vllist->next_vldb = NULL;
2143
2144         *vllistptr = vllist;    /* Thread onto list */
2145         vllistptr = &vllist->next_vldb;
2146         (*nentries)++;
2147     }
2148
2149     /* Search by server, partition, and flags */
2150     else {
2151         for (blockindex = NextEntry(&ctx, 0, &tentry, &count); blockindex;
2152              blockindex = NextEntry(&ctx, blockindex, &tentry, &count)) {
2153             match = 0;
2154
2155             if (++pollcount > 50) {
2156 #ifndef AFS_PTHREAD_ENV
2157                 IOMGR_Poll();
2158 #endif
2159                 pollcount = 0;
2160             }
2161
2162             /* Does this volume exist on the desired server */
2163             if (attributes->Mask & VLLIST_SERVER) {
2164                 serverindex =
2165                     IpAddrToRelAddr(&ctx, attributes->server, 0);
2166                 if (serverindex == -1)
2167                     continue;
2168                 for (k = 0; k < NMAXNSERVERS; k++) {
2169                     if (tentry.serverNumber[k] == BADSERVERID)
2170                         break;
2171                     if (tentry.serverNumber[k] == serverindex) {
2172                         match = 1;
2173                         break;
2174                     }
2175                 }
2176                 if (!match)
2177                     continue;
2178             }
2179
2180             /* Does this volume exist on the desired partition */
2181             if (attributes->Mask & VLLIST_PARTITION) {
2182                 if (match) {
2183                     if (tentry.serverPartition[k] != attributes->partition)
2184                         match = 0;
2185                 } else {
2186                     for (k = 0; k < NMAXNSERVERS; k++) {
2187                         if (tentry.serverNumber[k] == BADSERVERID)
2188                             break;
2189                         if (tentry.serverPartition[k] ==
2190                             attributes->partition) {
2191                             match = 1;
2192                             break;
2193                         }
2194                     }
2195                 }
2196                 if (!match)
2197                     continue;
2198             }
2199
2200             /* Does this volume have the desired flags */
2201             if (attributes->Mask & VLLIST_FLAG) {
2202                 if (!(tentry.flags & attributes->flag))
2203                     continue;
2204             }
2205
2206             vllist = malloc(sizeof(single_nvldbentry));
2207             if (vllist == NULL) {
2208                 code = VL_NOMEM;
2209                 goto abort;
2210             }
2211             code = vlentry_to_nvldbentry(&ctx, &tentry, &vllist->VldbEntry);
2212             if (code)
2213                 goto abort;
2214
2215             vllist->next_vldb = NULL;
2216
2217             *vllistptr = vllist;        /* Thread onto list */
2218             vllistptr = &vllist->next_vldb;
2219             (*nentries)++;
2220             if (smallMem && (*nentries >= VLDBALLOCCOUNT)) {
2221                 code = VL_SIZEEXCEEDED;
2222                 goto abort;
2223             }
2224         }
2225     }
2226     *vllistptr = NULL;
2227     return ubik_EndTrans(ctx.trans);
2228
2229 abort:
2230     countAbort(this_op);
2231     ubik_AbortTrans(ctx.trans);
2232     return code;
2233 }
2234
2235 afs_int32
2236 SVL_LinkedListN(struct rx_call *rxcall,
2237                 struct VldbListByAttributes *attributes,
2238                 afs_int32 *nentries,
2239                 nvldb_list *vldbentries)
2240 {
2241     afs_int32 code;
2242
2243     code = LinkedListN(rxcall, attributes, nentries, vldbentries);
2244     osi_auditU(rxcall, VLLinkedListNEvent, code, AUD_END);
2245     return code;
2246 }
2247
2248 /* Get back vldb header statistics (allocs, frees, maxvolumeid,
2249  * totalentries, etc) and dynamic statistics (number of requests and/or
2250  * aborts per remote procedure call, etc)
2251  */
2252 static afs_int32
2253 GetStats(struct rx_call *rxcall,
2254          vldstats *stats,
2255          vital_vlheader *vital_header)
2256 {
2257     int this_op = VLGETSTATS;
2258     afs_int32 code;
2259     struct vl_ctx ctx;
2260     char rxstr[AFS_RXINFO_LEN];
2261
2262     countRequest(this_op);
2263
2264     if (!afsconf_CheckRestrictedQuery(vldb_confdir, rxcall,
2265                                       restrictedQueryLevel))
2266         return VL_PERM;
2267
2268     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
2269         return code;
2270     VLog(5, ("GetStats %s\n", rxinfo(rxstr, rxcall)));
2271     memcpy((char *)vital_header, (char *)&ctx.cheader->vital_header,
2272            sizeof(vital_vlheader));
2273     memcpy((char *)stats, (char *)&dynamic_statistics, sizeof(vldstats));
2274     return ubik_EndTrans(ctx.trans);
2275 }
2276
2277 afs_int32
2278 SVL_GetStats(struct rx_call *rxcall,
2279              vldstats *stats,
2280              vital_vlheader *vital_header)
2281 {
2282     afs_int32 code;
2283
2284     code = GetStats(rxcall, stats, vital_header);
2285     osi_auditU(rxcall, VLGetStatsEvent, code, AUD_END);
2286     return code;
2287 }
2288
2289 /* Get the list of file server addresses from the VLDB.  Currently it's pretty
2290  * easy to do.  In the future, it might require a little bit of grunging
2291  * through the VLDB, but that's life.
2292  */
2293 afs_int32
2294 SVL_GetAddrs(struct rx_call *rxcall,
2295              afs_int32 Handle,
2296              afs_int32 spare2,
2297              struct VLCallBack *spare3,
2298              afs_int32 *nentries,
2299              bulkaddrs *addrsp)
2300 {
2301     int this_op = VLGETADDRS;
2302     afs_int32 code;
2303     struct vl_ctx ctx;
2304     int nservers, i;
2305     afs_uint32 *taddrp;
2306
2307     countRequest(this_op);
2308     addrsp->bulkaddrs_len = *nentries = 0;
2309     addrsp->bulkaddrs_val = 0;
2310     memset(spare3, 0, sizeof(struct VLCallBack));
2311
2312     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
2313         return code;
2314
2315     VLog(5, ("GetAddrs\n"));
2316     addrsp->bulkaddrs_val = taddrp =
2317         malloc(sizeof(afs_uint32) * (MAXSERVERID + 1));
2318     nservers = *nentries = addrsp->bulkaddrs_len = 0;
2319
2320     if (!taddrp) {
2321         code = VL_NOMEM;
2322         goto abort;
2323     }
2324
2325     for (i = 0; i <= MAXSERVERID; i++) {
2326         if ((*taddrp = ntohl(ctx.cheader->IpMappedAddr[i]))) {
2327             taddrp++;
2328             nservers++;
2329         }
2330     }
2331
2332     addrsp->bulkaddrs_len = *nentries = nservers;
2333     return (ubik_EndTrans(ctx.trans));
2334
2335 abort:
2336     countAbort(this_op);
2337     ubik_AbortTrans(ctx.trans);
2338     return code;
2339 }
2340
2341 static_inline void
2342 append_addr(char *buffer, afs_uint32 addr, size_t buffer_size)
2343 {
2344     int n = strlen(buffer);
2345     if (buffer_size > n) {
2346         snprintf(buffer + n, buffer_size - n, "%u.%u.%u.%u",
2347                  (addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff,
2348                  addr & 0xff);
2349     }
2350 }
2351
2352 afs_int32
2353 SVL_RegisterAddrs(struct rx_call *rxcall, afsUUID *uuidp, afs_int32 spare1,
2354                   bulkaddrs *addrsp)
2355 {
2356     int this_op = VLREGADDR;
2357     afs_int32 code;
2358     struct vl_ctx ctx;
2359     int cnt, h, i, j, k, m;
2360     struct extentaddr *exp = 0, *tex;
2361     char addrbuf[256];
2362     afsUUID tuuid;
2363     afs_uint32 addrs[VL_MAXIPADDRS_PERMH];
2364     int base;
2365     int count, willChangeEntry, foundUuidEntry, willReplaceCnt;
2366     int WillReplaceEntry, WillChange[MAXSERVERID + 1];
2367     int FoundUuid = 0;
2368     int ReplaceEntry = 0;
2369     int srvidx, mhidx;
2370
2371     countRequest(this_op);
2372     if (!afsconf_SuperUser(vldb_confdir, rxcall, NULL))
2373         return (VL_PERM);
2374     if ((code = Init_VLdbase(&ctx, LOCKWRITE, this_op)))
2375         return code;
2376
2377     /* Eliminate duplicates from IP address list */
2378     for (k = 0, cnt = 0; k < addrsp->bulkaddrs_len; k++) {
2379         if (addrsp->bulkaddrs_val[k] == 0)
2380             continue;
2381         for (m = 0; m < cnt; m++) {
2382             if (addrs[m] == addrsp->bulkaddrs_val[k])
2383                 break;
2384         }
2385         if (m == cnt) {
2386             if (m == VL_MAXIPADDRS_PERMH) {
2387                 VLog(0,
2388                      ("Number of addresses exceeds %d. Cannot register IP addr 0x%x in VLDB\n",
2389                       VL_MAXIPADDRS_PERMH, addrsp->bulkaddrs_val[k]));
2390             } else {
2391                 addrs[m] = addrsp->bulkaddrs_val[k];
2392                 cnt++;
2393             }
2394         }
2395     }
2396     if (cnt <= 0) {
2397         code = VL_INDEXERANGE;
2398         goto abort;
2399     }
2400
2401     count = 0;
2402     willReplaceCnt = 0;
2403     foundUuidEntry = 0;
2404     /* For each server registered within the VLDB */
2405     for (srvidx = 0; srvidx <= MAXSERVERID; srvidx++) {
2406         willChangeEntry = 0;
2407         WillReplaceEntry = 1;
2408         code = multiHomedExtent(&ctx, srvidx, &exp);
2409         if (code)
2410              continue;
2411
2412         if (exp) {
2413             /* See if the addresses to register will change this server entry */
2414             tuuid = exp->ex_hostuuid;
2415             afs_ntohuuid(&tuuid);
2416             if (afs_uuid_equal(uuidp, &tuuid)) {
2417                 foundUuidEntry = 1;
2418                 FoundUuid = srvidx;
2419             } else {
2420                 for (mhidx = 0; mhidx < VL_MAXIPADDRS_PERMH; mhidx++) {
2421                     if (!exp->ex_addrs[mhidx])
2422                         continue;
2423                     for (k = 0; k < cnt; k++) {
2424                         if (ntohl(exp->ex_addrs[mhidx]) == addrs[k]) {
2425                             willChangeEntry = 1;
2426                             WillChange[count] = srvidx;
2427                             break;
2428                         }
2429                     }
2430                     if (k >= cnt)
2431                         WillReplaceEntry = 0;
2432                 }
2433             }
2434         } else {
2435             /* The server is not registered as a multihomed.
2436              * See if the addresses to register will replace this server entry.
2437              */
2438             for (k = 0; k < cnt; k++) {
2439                 if (ctx.hostaddress[srvidx] == addrs[k]) {
2440                     willChangeEntry = 1;
2441                     WillChange[count] = srvidx;
2442                     WillReplaceEntry = 1;
2443                     break;
2444                 }
2445             }
2446         }
2447         if (willChangeEntry) {
2448             if (WillReplaceEntry) {
2449                 willReplaceCnt++;
2450                 ReplaceEntry = srvidx;
2451             }
2452             count++;
2453         }
2454     }
2455
2456     /* If we found the uuid in the VLDB and if we are replacing another
2457      * entire entry, then complain and fail. Also, if we did not find
2458      * the uuid in the VLDB and the IP addresses being registered was
2459      * found in more than one other entry, then we don't know which one
2460      * to replace and will complain and fail.
2461      */
2462     if ((foundUuidEntry && (willReplaceCnt > 0))
2463         || (!foundUuidEntry && (count > 1))) {
2464         VLog(0,
2465              ("The following fileserver is being registered in the VLDB:\n"));
2466         for (addrbuf[0] = '\0', k = 0; k < cnt; k++) {
2467             if (k > 0)
2468                 strlcat(addrbuf, " ", sizeof(addrbuf));
2469             append_addr(addrbuf, addrs[k], sizeof(addrbuf));
2470         }
2471         VLog(0, ("      [%s]\n", addrbuf));
2472
2473         if (foundUuidEntry) {
2474             code = multiHomedExtent(&ctx, FoundUuid, &exp);
2475             if (code == 0) {
2476                 VLog(0, ("   It would have replaced the existing VLDB server "
2477                          "entry:\n"));
2478                 for (addrbuf[0] = '\0', mhidx = 0; mhidx < VL_MAXIPADDRS_PERMH; mhidx++) {
2479                     if (!exp->ex_addrs[mhidx])
2480                         continue;
2481                     if (mhidx > 0)
2482                         strlcat(addrbuf, " ", sizeof(addrbuf));
2483                     append_addr(addrbuf, ntohl(exp->ex_addrs[mhidx]), sizeof(addrbuf));
2484                 }
2485                 VLog(0, ("      entry %d: [%s]\n", FoundUuid, addrbuf));
2486             }
2487         }
2488
2489         if (count == 1)
2490             VLog(0, ("   Yet another VLDB server entry exists:\n"));
2491         else
2492             VLog(0, ("   Yet other VLDB server entries exist:\n"));
2493         for (j = 0; j < count; j++) {
2494             srvidx = WillChange[j];
2495             VLog(0, ("      entry %d: ", srvidx));
2496
2497             code = multiHomedExtent(&ctx, srvidx, &exp);
2498             if (code)
2499                 goto abort;
2500
2501             addrbuf[0] = '\0';
2502             if (exp) {
2503                 for (mhidx = 0; mhidx < VL_MAXIPADDRS_PERMH; mhidx++) {
2504                     if (!exp->ex_addrs[mhidx])
2505                         continue;
2506                     if (mhidx > 0)
2507                         strlcat(addrbuf, " ", sizeof(addrbuf));
2508                     append_addr(addrbuf, ntohl(exp->ex_addrs[mhidx]), sizeof(addrbuf));
2509                 }
2510             } else {
2511                 append_addr(addrbuf, ctx.hostaddress[srvidx], sizeof(addrbuf));
2512             }
2513             VLog(0, ("      entry %d: [%s]\n", srvidx, addrbuf));
2514         }
2515
2516         if (count == 1)
2517             VLog(0, ("   You must 'vos changeaddr' this other server entry\n"));
2518         else
2519             VLog(0,
2520                 ("   You must 'vos changeaddr' these other server entries\n"));
2521         if (foundUuidEntry)
2522             VLog(0,
2523                 ("   and/or remove the sysid file from the registering fileserver\n"));
2524         VLog(0, ("   before the fileserver can be registered in the VLDB.\n"));
2525
2526         code = VL_MULTIPADDR;
2527         goto abort;
2528     }
2529
2530     /* Passed the checks. Now find and update the existing mh entry, or create
2531      * a new mh entry.
2532      */
2533     if (foundUuidEntry) {
2534         /* Found the entry with same uuid. See if we need to change it */
2535         int change = 0;
2536
2537         code = multiHomedExtentBase(&ctx, FoundUuid, &exp, &base);
2538         if (code)
2539             goto abort;
2540
2541         /* Determine if the entry has changed */
2542         for (k = 0; ((k < cnt) && !change); k++) {
2543             if (ntohl(exp->ex_addrs[k]) != addrs[k])
2544                 change = 1;
2545         }
2546         for (; ((k < VL_MAXIPADDRS_PERMH) && !change); k++) {
2547             if (exp->ex_addrs[k] != 0)
2548                 change = 1;
2549         }
2550         if (!change) {
2551             return (ubik_EndTrans(ctx.trans));
2552         }
2553     }
2554
2555     VLog(0, ("The following fileserver is being registered in the VLDB:\n"));
2556     for (addrbuf[0] = '\0', k = 0; k < cnt; k++) {
2557         if (k > 0)
2558             strlcat(addrbuf, " ", sizeof(addrbuf));
2559         append_addr(addrbuf, addrs[k], sizeof(addrbuf));
2560     }
2561     VLog(0, ("      [%s]\n", addrbuf));
2562
2563     if (foundUuidEntry) {
2564         VLog(0,
2565             ("   It will replace the following existing entry in the VLDB (same uuid):\n"));
2566         for (addrbuf[0] = '\0', k = 0; k < VL_MAXIPADDRS_PERMH; k++) {
2567             if (exp->ex_addrs[k] == 0)
2568                 continue;
2569             if (k > 0)
2570                 strlcat(addrbuf, " ", sizeof(addrbuf));
2571             append_addr(addrbuf, ntohl(exp->ex_addrs[k]), sizeof(addrbuf));
2572         }
2573         VLog(0, ("      entry %d: [%s]\n", FoundUuid, addrbuf));
2574     } else if (willReplaceCnt || (count == 1)) {
2575         /* If we are not replacing an entry and there is only one entry to change,
2576          * then we will replace that entry.
2577          */
2578         if (!willReplaceCnt) {
2579             ReplaceEntry = WillChange[0];
2580             willReplaceCnt++;
2581         }
2582
2583         /* Have an entry that needs to be replaced */
2584         code = multiHomedExtentBase(&ctx, ReplaceEntry, &exp, &base);
2585         if (code)
2586             goto abort;
2587
2588         if (exp) {
2589             VLog(0,
2590                 ("   It will replace the following existing entry in the VLDB (new uuid):\n"));
2591             for (addrbuf[0] = '\0', k = 0; k < VL_MAXIPADDRS_PERMH; k++) {
2592                 if (exp->ex_addrs[k] == 0)
2593                     continue;
2594                 if (k > 0)
2595                     strlcat(addrbuf, " ", sizeof(addrbuf));
2596                 append_addr(addrbuf, ntohl(exp->ex_addrs[k]), sizeof(addrbuf));
2597             }
2598             VLog(0, ("      entry %d: [%s]\n", ReplaceEntry, addrbuf));
2599         } else {
2600             /* Not a mh entry. So we have to create a new mh entry and
2601              * put it on the ReplaceEntry slot of the ctx.hostaddress array.
2602              */
2603             addrbuf[0] = '\0';
2604             append_addr(addrbuf, ctx.hostaddress[ReplaceEntry], sizeof(addrbuf));
2605             VLog(0, ("   It will replace existing entry %d, %s,"
2606                      " in the VLDB (new uuid):\n", ReplaceEntry, addrbuf));
2607             code =
2608                 FindExtentBlock(&ctx, uuidp, 1, ReplaceEntry, &exp, &base);
2609             if (code || !exp) {
2610                 if (!code)
2611                     code = VL_IO;
2612                 goto abort;
2613             }
2614         }
2615     } else {
2616         /* There is no entry for this server, must create a new mh entry as
2617          * well as use a new slot of the ctx.hostaddress array.
2618          */
2619         VLog(0, ("   It will create a new entry in the VLDB.\n"));
2620         code = FindExtentBlock(&ctx, uuidp, 1, -1, &exp, &base);
2621         if (code || !exp) {
2622             if (!code)
2623                 code = VL_IO;
2624             goto abort;
2625         }
2626     }
2627
2628     /* Now we have a mh entry to fill in. Update the uuid, bump the
2629      * uniquifier, and fill in its IP addresses.
2630      */
2631     tuuid = *uuidp;
2632     afs_htonuuid(&tuuid);
2633     exp->ex_hostuuid = tuuid;
2634     exp->ex_uniquifier = htonl(ntohl(exp->ex_uniquifier) + 1);
2635     for (k = 0; k < cnt; k++) {
2636         exp->ex_addrs[k] = htonl(addrs[k]);
2637     }
2638     for (; k < VL_MAXIPADDRS_PERMH; k++) {
2639         exp->ex_addrs[k] = 0;
2640     }
2641
2642     /* Write the new mh entry out */
2643     if (vlwrite
2644         (ctx.trans,
2645          DOFFSET(ntohl(ctx.ex_addr[0]->ex_contaddrs[base]),
2646                  (char *)ctx.ex_addr[base], (char *)exp), (char *)exp,
2647          sizeof(*exp))) {
2648         code = VL_IO;
2649         goto abort;
2650     }
2651
2652     /* Remove any common addresses from other mh entres. We know these entries
2653      * are being changed and not replaced so they are mh entries.
2654      */
2655     m = 0;
2656     for (i = 0; i < count; i++) {
2657         afs_int32 doff;
2658
2659         /* Skip the entry we replaced */
2660         if (willReplaceCnt && (WillChange[i] == ReplaceEntry))
2661             continue;
2662
2663         code = multiHomedExtentBase(&ctx, WillChange[i], &tex, &base);
2664         if (code)
2665             goto abort;
2666
2667         if (++m == 1)
2668             VLog(0,
2669                 ("   The following existing entries in the VLDB will be updated:\n"));
2670
2671         for (addrbuf[0] = '\0', h = j = 0; j < VL_MAXIPADDRS_PERMH; j++) {
2672             if (tex->ex_addrs[j]) {
2673                 if (j > 0)
2674                     strlcat(addrbuf, " ", sizeof(addrbuf));
2675                 append_addr(addrbuf, ntohl(tex->ex_addrs[j]), sizeof(addrbuf));
2676             }
2677
2678             for (k = 0; k < cnt; k++) {
2679                 if (ntohl(tex->ex_addrs[j]) == addrs[k])
2680                     break;
2681             }
2682             if (k >= cnt) {
2683                 /* Not found, so we keep it */
2684                 tex->ex_addrs[h] = tex->ex_addrs[j];
2685                 h++;
2686             }
2687         }
2688         for (j = h; j < VL_MAXIPADDRS_PERMH; j++) {
2689             tex->ex_addrs[j] = 0;       /* zero rest of mh entry */
2690         }
2691         VLog(0, ("      entry %d: [%s]\n", WillChange[i], addrbuf));
2692
2693         /* Write out the modified mh entry */
2694         tex->ex_uniquifier = htonl(ntohl(tex->ex_uniquifier) + 1);
2695         doff =
2696             DOFFSET(ntohl(ctx.ex_addr[0]->ex_contaddrs[base]),
2697                     (char *)ctx.ex_addr[base], (char *)tex);
2698         if (vlwrite(ctx.trans, doff, (char *)tex, sizeof(*tex))) {
2699             code = VL_IO;
2700             goto abort;
2701         }
2702     }
2703
2704     return (ubik_EndTrans(ctx.trans));
2705
2706 abort:
2707     countAbort(this_op);
2708     ubik_AbortTrans(ctx.trans);
2709     return code;
2710 }
2711
2712 afs_int32
2713 SVL_GetAddrsU(struct rx_call *rxcall,
2714               struct ListAddrByAttributes *attributes,
2715               afsUUID *uuidpo,
2716               afs_int32 *uniquifier,
2717               afs_int32 *nentries,
2718               bulkaddrs *addrsp)
2719 {
2720     int this_op = VLGETADDRSU;
2721     afs_int32 code, index;
2722     struct vl_ctx ctx;
2723     int nservers, i, j, base = 0;
2724     struct extentaddr *exp = 0;
2725     afsUUID tuuid;
2726     afs_uint32 *taddrp, taddr;
2727     char rxstr[AFS_RXINFO_LEN];
2728
2729     countRequest(this_op);
2730     addrsp->bulkaddrs_len = *nentries = 0;
2731     addrsp->bulkaddrs_val = 0;
2732     VLog(5, ("GetAddrsU %s\n", rxinfo(rxstr, rxcall)));
2733     if ((code = Init_VLdbase(&ctx, LOCKREAD, this_op)))
2734         return code;
2735
2736     if (attributes->Mask & VLADDR_IPADDR) {
2737         if (attributes->Mask & (VLADDR_INDEX | VLADDR_UUID)) {
2738             code = VL_BADMASK;
2739             goto abort;
2740         }
2741         /* Search for a server registered with the VLDB with this ip address. */
2742         for (index = 0; index <= MAXSERVERID; index++) {
2743             code = multiHomedExtent(&ctx, index, &exp);
2744             if (code)
2745                 continue;
2746
2747             if (exp) {
2748                 for (j = 0; j < VL_MAXIPADDRS_PERMH; j++) {
2749                     if (exp->ex_addrs[j]
2750                         && (ntohl(exp->ex_addrs[j]) == attributes->ipaddr)) {
2751                         break;
2752                     }
2753                 }
2754                 if (j < VL_MAXIPADDRS_PERMH)
2755                     break;
2756             }
2757         }
2758         if (index > MAXSERVERID) {
2759             code = VL_NOENT;
2760             goto abort;
2761         }
2762     } else if (attributes->Mask & VLADDR_INDEX) {
2763         if (attributes->Mask & (VLADDR_IPADDR | VLADDR_UUID)) {
2764             code = VL_BADMASK;
2765             goto abort;
2766         }
2767         /* VLADDR_INDEX index is one based */
2768         if (attributes->index < 1 || attributes->index > MAXSERVERID) {
2769             code = VL_INDEXERANGE;
2770             goto abort;
2771         }
2772         index = attributes->index - 1;
2773         code = multiHomedExtent(&ctx, index, &exp);
2774         if (code) {
2775             code = VL_NOENT;
2776             goto abort;
2777         }
2778     } else if (attributes->Mask & VLADDR_UUID) {
2779         if (attributes->Mask & (VLADDR_IPADDR | VLADDR_INDEX)) {
2780             code = VL_BADMASK;
2781             goto abort;
2782         }
2783         if (!ctx.ex_addr[0]) {  /* mh servers probably aren't setup on this vldb */
2784             code = VL_NOENT;
2785             goto abort;
2786         }
2787         code = FindExtentBlock(&ctx, &attributes->uuid, 0, -1, &exp, &base);
2788         if (code)
2789             goto abort;
2790     } else {
2791         code = VL_BADMASK;
2792         goto abort;
2793     }
2794
2795     if (exp == NULL) {
2796         code = VL_NOENT;
2797         goto abort;
2798     }
2799     addrsp->bulkaddrs_val = taddrp =
2800         malloc(sizeof(afs_uint32) * (MAXSERVERID + 1));
2801     nservers = *nentries = addrsp->bulkaddrs_len = 0;
2802     if (!taddrp) {
2803         code = VL_NOMEM;
2804         goto abort;
2805     }
2806     tuuid = exp->ex_hostuuid;
2807     afs_ntohuuid(&tuuid);
2808     if (afs_uuid_is_nil(&tuuid)) {
2809         code = VL_NOENT;
2810         goto abort;
2811     }
2812     if (uuidpo)
2813         *uuidpo = tuuid;
2814     if (uniquifier)
2815         *uniquifier = ntohl(exp->ex_uniquifier);
2816     for (i = 0; i < VL_MAXIPADDRS_PERMH; i++) {
2817         if (exp->ex_addrs[i]) {
2818             taddr = ntohl(exp->ex_addrs[i]);
2819             /* Weed out duplicates */
2820             for (j = 0; j < nservers; j++) {
2821                 if (taddrp[j] == taddr)
2822                     break;
2823             }
2824             if ((j == nservers) && (j <= MAXSERVERID)) {
2825                 taddrp[nservers] = taddr;
2826                 nservers++;
2827             }
2828         }
2829     }
2830     addrsp->bulkaddrs_len = *nentries = nservers;
2831     return (ubik_EndTrans(ctx.trans));
2832
2833 abort:
2834     countAbort(this_op);
2835     ubik_AbortTrans(ctx.trans);
2836     return code;
2837 }
2838
2839 /* ============> End of Exported vldb RPC functions <============= */
2840
2841
2842 /* Routine that copies the given vldb entry to the output buffer, vldbentries. */
2843 static int
2844 put_attributeentry(struct vl_ctx *ctx,
2845                    struct vldbentry **Vldbentry,
2846                    struct vldbentry **VldbentryFirst,
2847                    struct vldbentry **VldbentryLast,
2848                    bulkentries *vldbentries,
2849                    struct nvlentry *entry,
2850                    afs_int32 *nentries,
2851                    afs_int32 *alloccnt)
2852 {
2853     vldbentry *reall;
2854     afs_int32 allo;
2855     int code;
2856
2857     if (*Vldbentry == *VldbentryLast) {
2858         if (smallMem)
2859             return VL_SIZEEXCEEDED;     /* no growing if smallMem defined */
2860
2861         /* Allocate another set of memory; each time allocate twice as
2862          * many blocks as the last time. When we reach VLDBALLOCLIMIT,
2863          * then grow in increments of VLDBALLOCINCR.
2864          */
2865         allo = (*alloccnt > VLDBALLOCLIMIT) ? VLDBALLOCINCR : *alloccnt;
2866         reall = realloc(*VldbentryFirst,
2867                         (*alloccnt + allo) * sizeof(vldbentry));
2868         if (reall == NULL)
2869             return VL_NOMEM;
2870
2871         *VldbentryFirst = vldbentries->bulkentries_val = reall;
2872         *Vldbentry = *VldbentryFirst + *alloccnt;
2873         *VldbentryLast = *Vldbentry + allo;
2874         *alloccnt += allo;
2875     }
2876
2877     code = vlentry_to_vldbentry(ctx, entry, *Vldbentry);
2878     if (code)
2879         return code;
2880
2881     (*Vldbentry)++;
2882     (*nentries)++;
2883     vldbentries->bulkentries_len++;
2884     return 0;
2885 }
2886
2887 static int
2888 put_nattributeentry(struct vl_ctx *ctx,
2889                     struct nvldbentry **Vldbentry,
2890                     struct nvldbentry **VldbentryFirst,
2891                     struct nvldbentry **VldbentryLast,
2892                     nbulkentries *vldbentries,
2893                     struct nvlentry *entry,
2894                     afs_int32 matchtype,
2895                     afs_int32 matchindex,
2896                     afs_int32 *nentries,
2897                     afs_int32 *alloccnt)
2898 {
2899     nvldbentry *reall;
2900     afs_int32 allo;
2901     int code;
2902
2903     if (*Vldbentry == *VldbentryLast) {
2904         if (smallMem)
2905             return VL_SIZEEXCEEDED;     /* no growing if smallMem defined */
2906
2907         /* Allocate another set of memory; each time allocate twice as
2908          * many blocks as the last time. When we reach VLDBALLOCLIMIT,
2909          * then grow in increments of VLDBALLOCINCR.
2910          */
2911         allo = (*alloccnt > VLDBALLOCLIMIT) ? VLDBALLOCINCR : *alloccnt;
2912         reall = realloc(*VldbentryFirst,
2913                         (*alloccnt + allo) * sizeof(nvldbentry));
2914         if (reall == NULL)
2915             return VL_NOMEM;
2916
2917         *VldbentryFirst = vldbentries->nbulkentries_val = reall;
2918         *Vldbentry = *VldbentryFirst + *alloccnt;
2919         *VldbentryLast = *Vldbentry + allo;
2920         *alloccnt += allo;
2921     }
2922     code = vlentry_to_nvldbentry(ctx, entry, *Vldbentry);
2923     if (code)
2924         return code;
2925
2926     (*Vldbentry)->matchindex = (matchtype << 16) + matchindex;
2927     (*Vldbentry)++;
2928     (*nentries)++;
2929     vldbentries->nbulkentries_len++;
2930     return 0;
2931 }
2932
2933
2934 /* Common code to actually remove a vldb entry from the database. */
2935 static int
2936 RemoveEntry(struct vl_ctx *ctx, afs_int32 entryptr,
2937             struct nvlentry *tentry)
2938 {
2939     int code;
2940
2941     if ((code = UnthreadVLentry(ctx, entryptr, tentry)))
2942         return code;
2943     if ((code = FreeBlock(ctx, entryptr)))
2944         return code;
2945     return 0;
2946 }
2947
2948 static void
2949 ReleaseEntry(struct nvlentry *tentry, afs_int32 releasetype)
2950 {
2951     if (releasetype & LOCKREL_TIMESTAMP)
2952         tentry->LockTimestamp = 0;
2953     if (releasetype & LOCKREL_OPCODE)
2954         tentry->flags &= ~VLOP_ALLOPERS;
2955     if (releasetype & LOCKREL_AFSID)
2956         tentry->LockAfsId = 0;
2957 }
2958
2959
2960 /* Verify that the incoming vldb entry is valid; multi type of error codes
2961  * are returned. */
2962 static int
2963 check_vldbentry(struct vldbentry *aentry)
2964 {
2965     afs_int32 i;
2966
2967     if (InvalidVolname(aentry->name))
2968         return VL_BADNAME;
2969     if (aentry->nServers <= 0 || aentry->nServers > OMAXNSERVERS)
2970         return VL_BADSERVER;
2971     for (i = 0; i < aentry->nServers; i++) {
2972 /*      if (aentry->serverNumber[i] < 0 || aentry->serverNumber[i] > MAXSERVERID)
2973             return VL_BADSERVER;        */
2974         if (aentry->serverPartition[i] < 0
2975             || aentry->serverPartition[i] > MAXPARTITIONID)
2976             return VL_BADPARTITION;
2977         if (aentry->serverFlags[i] < 0
2978             || aentry->serverFlags[i] > MAXSERVERFLAG)
2979             return VL_BADSERVERFLAG;
2980     }
2981     return 0;
2982 }
2983
2984 static int
2985 check_nvldbentry(struct nvldbentry *aentry)
2986 {
2987     afs_int32 i;
2988
2989     if (InvalidVolname(aentry->name))
2990         return VL_BADNAME;
2991     if (aentry->nServers <= 0 || aentry->nServers > NMAXNSERVERS)
2992         return VL_BADSERVER;
2993     for (i = 0; i < aentry->nServers; i++) {
2994 /*      if (aentry->serverNumber[i] < 0 || aentry->serverNumber[i] > MAXSERVERID)
2995             return VL_BADSERVER;        */
2996         if (aentry->serverPartition[i] < 0
2997             || aentry->serverPartition[i] > MAXPARTITIONID)
2998             return VL_BADPARTITION;
2999         if (aentry->serverFlags[i] < 0
3000             || aentry->serverFlags[i] > MAXSERVERFLAG)
3001             return VL_BADSERVERFLAG;
3002     }
3003     return 0;
3004 }
3005
3006
3007 /* Convert from the external vldb entry representation to its internal
3008    (more compact) form.  This call should not change the hash chains! */
3009 static int
3010 vldbentry_to_vlentry(struct vl_ctx *ctx,
3011                      struct vldbentry *VldbEntry,
3012                      struct nvlentry *VlEntry)
3013 {
3014     int i, serverindex;
3015
3016     if (strcmp(VlEntry->name, VldbEntry->name))
3017         strncpy(VlEntry->name, VldbEntry->name, sizeof(VlEntry->name));
3018     for (i = 0; i < VldbEntry->nServers; i++) {
3019         serverindex = IpAddrToRelAddr(ctx, VldbEntry->serverNumber[i], 1);
3020         if (serverindex == -1)
3021             return VL_BADSERVER;
3022         VlEntry->serverNumber[i] = serverindex;
3023         VlEntry->serverPartition[i] = VldbEntry->serverPartition[i];
3024         VlEntry->serverFlags[i] = VldbEntry->serverFlags[i];
3025     }
3026     for (; i < OMAXNSERVERS; i++)
3027         VlEntry->serverNumber[i] = VlEntry->serverPartition[i] =
3028             VlEntry->serverFlags[i] = BADSERVERID;
3029     for (i = 0; i < MAXTYPES; i++)
3030         VlEntry->volumeId[i] = VldbEntry->volumeId[i];
3031     VlEntry->cloneId = VldbEntry->cloneId;
3032     VlEntry->flags = VldbEntry->flags;
3033     return 0;
3034 }
3035
3036 static int
3037 nvldbentry_to_vlentry(struct vl_ctx *ctx,
3038                       struct nvldbentry *VldbEntry,
3039                       struct nvlentry *VlEntry)
3040 {
3041     int i, serverindex;
3042
3043     if (strcmp(VlEntry->name, VldbEntry->name))
3044         strncpy(VlEntry->name, VldbEntry->name, sizeof(VlEntry->name));
3045     for (i = 0; i < VldbEntry->nServers; i++) {
3046         serverindex = IpAddrToRelAddr(ctx, VldbEntry->serverNumber[i], 1);
3047         if (serverindex == -1)
3048             return VL_BADSERVER;
3049         VlEntry->serverNumber[i] = serverindex;
3050         VlEntry->serverPartition[i] = VldbEntry->serverPartition[i];
3051         VlEntry->serverFlags[i] = VldbEntry->serverFlags[i];
3052     }
3053     for (; i < NMAXNSERVERS; i++)
3054         VlEntry->serverNumber[i] = VlEntry->serverPartition[i] =
3055             VlEntry->serverFlags[i] = BADSERVERID;
3056     for (i = 0; i < MAXTYPES; i++)
3057         VlEntry->volumeId[i] = VldbEntry->volumeId[i];
3058     VlEntry->cloneId = VldbEntry->cloneId;
3059     VlEntry->flags = VldbEntry->flags;
3060     return 0;
3061 }
3062
3063
3064 /* Update the vldb entry with the new fields as indicated by the value of
3065  * the Mask entry in the updateentry structure. All necessary validation
3066  * checks are performed.
3067  */
3068 static int
3069 get_vldbupdateentry(struct vl_ctx *ctx,
3070                     afs_int32 blockindex,
3071                     struct VldbUpdateEntry *updateentry,
3072                     struct nvlentry *VlEntry)
3073 {
3074     int i, j, code, serverindex;
3075     afs_uint32 checkids[MAXTYPES];
3076
3077     /* check if any specified new IDs are already present in the db. Do
3078      * this check before doing anything else, so we don't get a half-
3079      * updated entry. */
3080     memset(&checkids, 0, sizeof(checkids));
3081     if (updateentry->Mask & VLUPDATE_RWID) {
3082         checkids[RWVOL] = updateentry->spares3; /* rw id */
3083     }
3084     if (updateentry->Mask & VLUPDATE_READONLYID) {
3085         checkids[ROVOL] = updateentry->ReadOnlyId;
3086     }
3087     if (updateentry->Mask & VLUPDATE_BACKUPID) {
3088         checkids[BACKVOL] = updateentry->BackupId;
3089     }
3090
3091     if (EntryIDExists(ctx, checkids, MAXTYPES, &code)) {
3092         return VL_IDEXIST;
3093     } else if (code) {
3094         return code;
3095     }
3096
3097     if (updateentry->Mask & VLUPDATE_VOLUMENAME) {
3098         struct nvlentry tentry;
3099
3100         if (InvalidVolname(updateentry->name))
3101             return VL_BADNAME;
3102
3103         if (FindByName(ctx, updateentry->name, &tentry, &code)) {
3104             return VL_NAMEEXIST;
3105         } else if (code) {
3106             return code;
3107         }
3108
3109         if ((code = UnhashVolname(ctx, blockindex, VlEntry)))
3110             return code;
3111         strncpy(VlEntry->name, updateentry->name, sizeof(VlEntry->name));
3112         HashVolname(ctx, blockindex, VlEntry);
3113     }
3114
3115     if (updateentry->Mask & VLUPDATE_VOLNAMEHASH) {
3116         if ((code = UnhashVolname(ctx, blockindex, VlEntry))) {
3117             if (code != VL_NOENT)
3118                 return code;
3119         }
3120         HashVolname(ctx, blockindex, VlEntry);
3121     }
3122
3123     if (updateentry->Mask & VLUPDATE_FLAGS) {
3124         VlEntry->flags = updateentry->flags;
3125     }
3126     if (updateentry->Mask & VLUPDATE_CLONEID) {
3127         VlEntry->cloneId = updateentry->cloneId;
3128     }
3129     if (updateentry->Mask & VLUPDATE_RWID) {
3130         if ((code = UnhashVolid(ctx, RWVOL, blockindex, VlEntry))) {
3131             if (code != VL_NOENT)
3132                 return code;
3133         }
3134         VlEntry->volumeId[RWVOL] = updateentry->spares3;        /* rw id */
3135         if ((code = HashVolid(ctx, RWVOL, blockindex, VlEntry)))
3136             return code;
3137     }
3138     if (updateentry->Mask & VLUPDATE_READONLYID) {
3139         if ((code = UnhashVolid(ctx, ROVOL, blockindex, VlEntry))) {
3140             if (code != VL_NOENT)
3141                 return code;
3142         }
3143         VlEntry->volumeId[ROVOL] = updateentry->ReadOnlyId;
3144         if ((code = HashVolid(ctx, ROVOL, blockindex, VlEntry)))
3145             return code;
3146     }
3147     if (updateentry->Mask & VLUPDATE_BACKUPID) {
3148         if ((code = UnhashVolid(ctx, BACKVOL, blockindex, VlEntry))) {
3149             if (code != VL_NOENT)
3150                 return code;
3151         }
3152         VlEntry->volumeId[BACKVOL] = updateentry->BackupId;
3153         if ((code = HashVolid(ctx, BACKVOL, blockindex, VlEntry)))
3154             return code;
3155     }
3156     if (updateentry->Mask & VLUPDATE_REPSITES) {
3157         if (updateentry->nModifiedRepsites <= 0
3158             || updateentry->nModifiedRepsites > OMAXNSERVERS)
3159             return VL_BADSERVER;
3160         for (i = 0; i < updateentry->nModifiedRepsites; i++) {
3161 /*          if (updateentry->RepsitesTargetServer[i] < 0 || updateentry->RepsitesTargetServer[i] > MAXSERVERID)
3162                 return VL_BADSERVER;    */
3163             if (updateentry->RepsitesTargetPart[i] < 0
3164                 || updateentry->RepsitesTargetPart[i] > MAXPARTITIONID)
3165                 return VL_BADPARTITION;
3166             if (updateentry->RepsitesMask[i] & VLUPDATE_REPS_DELETE) {
3167                 if ((j =
3168                      repsite_exists(VlEntry,
3169                                     IpAddrToRelAddr(ctx, updateentry->
3170                                                     RepsitesTargetServer[i],
3171                                                     1),
3172                                     updateentry->RepsitesTargetPart[i])) !=
3173                     -1)
3174                     repsite_compress(VlEntry, j);
3175                 else
3176                     return VL_NOREPSERVER;
3177             }
3178             if (updateentry->RepsitesMask[i] & VLUPDATE_REPS_ADD) {
3179 /*              if (updateentry->RepsitesNewServer[i] < 0 || updateentry->RepsitesNewServer[i] > MAXSERVERID)
3180                     return VL_BADSERVER;                */
3181                 if (updateentry->RepsitesNewPart[i] < 0
3182                     || updateentry->RepsitesNewPart[i] > MAXPARTITIONID)
3183                     return VL_BADPARTITION;
3184                 if (repsite_exists
3185                     (VlEntry,
3186                      IpAddrToRelAddr(ctx, updateentry->RepsitesNewServer[i], 1),
3187                      updateentry->RepsitesNewPart[i]) != -1)
3188                     return VL_DUPREPSERVER;
3189                 for (j = 0;
3190                      VlEntry->serverNumber[j] != BADSERVERID
3191                      && j < OMAXNSERVERS; j++);
3192                 if (j >= OMAXNSERVERS)
3193                     return VL_REPSFULL;
3194                 if ((serverindex =
3195                      IpAddrToRelAddr(ctx, updateentry->RepsitesNewServer[i],
3196                                      1)) == -1)
3197                     return VL_BADSERVER;
3198                 VlEntry->serverNumber[j] = serverindex;
3199                 VlEntry->serverPartition[j] = updateentry->RepsitesNewPart[i];
3200                 if (updateentry->RepsitesNewFlags[i] < 0
3201                     || updateentry->RepsitesNewFlags[i] > MAXSERVERFLAG)
3202                     return VL_BADSERVERFLAG;
3203                 VlEntry->serverFlags[j] = updateentry->RepsitesNewFlags[i];
3204             }
3205             if (updateentry->RepsitesMask[i] & VLUPDATE_REPS_MODSERV) {
3206 /*n             if (updateentry->RepsitesNewServer[i] < 0 || updateentry->RepsitesNewServer[i] > MAXSERVERID)
3207                     return VL_BADSERVER;            */
3208                 if ((j =
3209                      repsite_exists(VlEntry,
3210                                     IpAddrToRelAddr(ctx, updateentry->
3211                                                     RepsitesTargetServer[i],
3212                                                     1),
3213                                     updateentry->RepsitesTargetPart[i])) !=
3214                     -1) {
3215                     VlEntry->serverNumber[j] =
3216                         IpAddrToRelAddr(ctx, updateentry->RepsitesNewServer[i],
3217                                         1);
3218                 } else
3219                     return VL_NOREPSERVER;
3220             }
3221             if (updateentry->RepsitesMask[i] & VLUPDATE_REPS_MODPART) {
3222                 if (updateentry->RepsitesNewPart[i] < 0
3223                     || updateentry->RepsitesNewPart[i] > MAXPARTITIONID)
3224                     return VL_BADPARTITION;
3225                 if ((j =
3226                      repsite_exists(VlEntry,
3227                                     IpAddrToRelAddr(ctx, updateentry->
3228                                                     RepsitesTargetServer[i],
3229                                                     1),
3230                                     updateentry->RepsitesTargetPart[i])) !=
3231                     -1)
3232                     VlEntry->serverPartition[j] =
3233                         updateentry->RepsitesNewPart[i];
3234                 else
3235                     return VL_NOREPSERVER;
3236             }
3237             if (updateentry->RepsitesMask[i] & VLUPDATE_REPS_MODFLAG) {
3238                 if ((j =
3239                      repsite_exists(VlEntry,
3240                                     IpAddrToRelAddr(ctx, updateentry->
3241                                                     RepsitesTargetServer[i],
3242                                                     1),
3243                                     updateentry->RepsitesTargetPart[i])) !=
3244                     -1) {
3245                     if (updateentry->RepsitesNewFlags[i] < 0
3246                         || updateentry->RepsitesNewFlags[i] > MAXSERVERFLAG)
3247                         return VL_BADSERVERFLAG;
3248                     VlEntry->serverFlags[j] =
3249                         updateentry->RepsitesNewFlags[i];
3250                 } else
3251                     return VL_NOREPSERVER;
3252             }
3253         }
3254     }
3255     return 0;
3256 }
3257
3258
3259 /* Check if the specified [server,partition] entry is found in the vldb
3260  * entry's repsite table; it's offset in the table is returned, if it's
3261  * present there. */
3262 static int
3263 repsite_exists(struct nvlentry *VlEntry, int server, int partition)
3264 {
3265     int i;
3266
3267     for (i = 0; VlEntry->serverNumber[i] != BADSERVERID && i < OMAXNSERVERS;
3268          i++) {
3269         if ((VlEntry->serverNumber[i] == server)
3270             && (VlEntry->serverPartition[i] == partition))
3271             return i;
3272     }
3273     return -1;
3274 }
3275
3276
3277
3278 /* Repsite table compression: used when deleting a repsite entry so that
3279  * all active repsite entries are on the top of the table. */
3280 static void
3281 repsite_compress(struct nvlentry *VlEntry, int offset)
3282 {
3283     int repsite_offset = offset;
3284     for (;
3285          VlEntry->serverNumber[repsite_offset] != BADSERVERID
3286          && repsite_offset < OMAXNSERVERS - 1; repsite_offset++) {
3287         VlEntry->serverNumber[repsite_offset] =
3288             VlEntry->serverNumber[repsite_offset + 1];
3289         VlEntry->serverPartition[repsite_offset] =
3290             VlEntry->serverPartition[repsite_offset + 1];
3291         VlEntry->serverFlags[repsite_offset] =
3292             VlEntry->serverFlags[repsite_offset + 1];
3293     }
3294     VlEntry->serverNumber[repsite_offset] = BADSERVERID;
3295 }
3296
3297
3298 /* Convert from the internal (compacted) vldb entry to the external
3299  * representation used by the interface. */
3300 static int
3301 vlentry_to_vldbentry(struct vl_ctx *ctx, struct nvlentry *VlEntry,
3302                      struct vldbentry *VldbEntry)
3303 {
3304     int i, j, code;
3305     struct extentaddr *exp;
3306
3307     memset(VldbEntry, 0, sizeof(struct vldbentry));
3308     strncpy(VldbEntry->name, VlEntry->name, sizeof(VldbEntry->name));
3309     for (i = 0; i < OMAXNSERVERS; i++) {
3310         if (VlEntry->serverNumber[i] == BADSERVERID)
3311             break;
3312         code = multiHomedExtent(ctx, VlEntry->serverNumber[i], &exp);
3313         if (code)
3314             return code;
3315         if (exp) {
3316             /* For now return the first ip address back */
3317             for (j = 0; j < VL_MAXIPADDRS_PERMH; j++) {
3318                 if (exp->ex_addrs[j]) {
3319                     VldbEntry->serverNumber[i] = ntohl(exp->ex_addrs[j]);
3320                     break;
3321                 }
3322             }
3323         } else
3324             VldbEntry->serverNumber[i] =
3325                 ctx->hostaddress[VlEntry->serverNumber[i]];
3326         VldbEntry->serverPartition[i] = VlEntry->serverPartition[i];
3327         VldbEntry->serverFlags[i] = VlEntry->serverFlags[i];
3328     }
3329     VldbEntry->nServers = i;
3330     for (i = 0; i < MAXTYPES; i++)
3331         VldbEntry->volumeId[i] = VlEntry->volumeId[i];
3332     VldbEntry->cloneId = VlEntry->cloneId;
3333     VldbEntry->flags = VlEntry->flags;
3334
3335     return 0;
3336 }
3337
3338
3339 /* Convert from the internal (compacted) vldb entry to the external
3340  * representation used by the interface. */
3341 static int
3342 vlentry_to_nvldbentry(struct vl_ctx *ctx, struct nvlentry *VlEntry,
3343                       struct nvldbentry *VldbEntry)
3344 {
3345     int i, j, code;
3346     struct extentaddr *exp;
3347
3348     memset(VldbEntry, 0, sizeof(struct nvldbentry));
3349     strncpy(VldbEntry->name, VlEntry->name, sizeof(VldbEntry->name));
3350     for (i = 0; i < NMAXNSERVERS; i++) {
3351         if (VlEntry->serverNumber[i] == BADSERVERID)
3352             break;
3353         code = multiHomedExtent(ctx, VlEntry->serverNumber[i], &exp);
3354         if (code)
3355             return code;
3356
3357         if (exp) {
3358             /* For now return the first ip address back */
3359             for (j = 0; j < VL_MAXIPADDRS_PERMH; j++) {
3360                 if (exp->ex_addrs[j]) {
3361                     VldbEntry->serverNumber[i] = ntohl(exp->ex_addrs[j]);
3362                     break;
3363                 }
3364             }
3365         } else
3366             VldbEntry->serverNumber[i] =
3367                 ctx->hostaddress[VlEntry->serverNumber[i]];
3368         VldbEntry->serverPartition[i] = VlEntry->serverPartition[i];
3369         VldbEntry->serverFlags[i] = VlEntry->serverFlags[i];
3370     }
3371     VldbEntry->nServers = i;
3372     for (i = 0; i < MAXTYPES; i++)
3373         VldbEntry->volumeId[i] = VlEntry->volumeId[i];
3374     VldbEntry->cloneId = VlEntry->cloneId;
3375     VldbEntry->flags = VlEntry->flags;
3376
3377     return 0;
3378 }
3379
3380 static int
3381 vlentry_to_uvldbentry(struct vl_ctx *ctx, struct nvlentry *VlEntry,
3382                       struct uvldbentry *VldbEntry)
3383 {
3384     int i, code;
3385     struct extentaddr *exp;
3386
3387     memset(VldbEntry, 0, sizeof(struct uvldbentry));
3388     strncpy(VldbEntry->name, VlEntry->name, sizeof(VldbEntry->name));
3389     for (i = 0; i < NMAXNSERVERS; i++) {
3390         if (VlEntry->serverNumber[i] == BADSERVERID)
3391             break;
3392         VldbEntry->serverFlags[i] = VlEntry->serverFlags[i];
3393         VldbEntry->serverUnique[i] = 0;
3394         code = multiHomedExtent(ctx, VlEntry->serverNumber[i], &exp);
3395         if (code)
3396             return code;
3397
3398         if (exp) {
3399             afsUUID tuuid;
3400
3401             tuuid = exp->ex_hostuuid;
3402             afs_ntohuuid(&tuuid);
3403             VldbEntry->serverFlags[i] |= VLSF_UUID;
3404             VldbEntry->serverNumber[i] = tuuid;
3405             VldbEntry->serverUnique[i] = ntohl(exp->ex_uniquifier);
3406         } else {
3407             VldbEntry->serverNumber[i].time_low =
3408                 ctx->hostaddress[VlEntry->serverNumber[i]];
3409         }
3410         VldbEntry->serverPartition[i] = VlEntry->serverPartition[i];
3411
3412     }
3413     VldbEntry->nServers = i;
3414     for (i = 0; i < MAXTYPES; i++)
3415         VldbEntry->volumeId[i] = VlEntry->volumeId[i];
3416     VldbEntry->cloneId = VlEntry->cloneId;
3417     VldbEntry->flags = VlEntry->flags;
3418
3419     return 0;
3420 }
3421
3422 #define LEGALCHARS ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
3423
3424
3425 /* Verify that the volname is a valid volume name. */
3426 static int
3427 InvalidVolname(char *volname)
3428 {
3429     char *map;
3430     int slen;
3431
3432     map = LEGALCHARS;
3433     slen = strlen(volname);
3434     if (slen >= VL_MAXNAMELEN)
3435         return 1;
3436     return (slen != strspn(volname, map));
3437 }
3438
3439
3440 /* Verify that the given volume type is valid. */
3441 static int
3442 InvalidVoltype(afs_int32 voltype)
3443 {
3444     if (voltype != RWVOL && voltype != ROVOL && voltype != BACKVOL)
3445         return 1;
3446     return 0;
3447 }
3448
3449
3450 static int
3451 InvalidOperation(afs_int32 voloper)
3452 {
3453     if (voloper != VLOP_MOVE && voloper != VLOP_RELEASE
3454         && voloper != VLOP_BACKUP && voloper != VLOP_DELETE
3455         && voloper != VLOP_DUMP)
3456         return 1;
3457     return 0;
3458 }
3459
3460 static int
3461 InvalidReleasetype(afs_int32 releasetype)
3462 {
3463     if ((releasetype & LOCKREL_TIMESTAMP) || (releasetype & LOCKREL_OPCODE)
3464         || (releasetype & LOCKREL_AFSID))
3465         return 0;
3466     return 1;
3467 }
3468
3469 static int
3470 IpAddrToRelAddr(struct vl_ctx *ctx, afs_uint32 ipaddr, int create)
3471 {
3472     int i, j;
3473     afs_int32 code;
3474     struct extentaddr *exp;
3475
3476     for (i = 0; i <= MAXSERVERID; i++) {
3477         if (ctx->hostaddress[i] == ipaddr)
3478             return i;
3479         code = multiHomedExtent(ctx, i, &exp);
3480         if (code)
3481             return -1;
3482         if (exp) {
3483             for (j = 0; j < VL_MAXIPADDRS_PERMH; j++) {
3484                 if (exp->ex_addrs[j] && (ntohl(exp->ex_addrs[j]) == ipaddr)) {
3485                     return i;
3486                 }
3487             }
3488         }
3489     }
3490
3491     /* allocate the new server a server id pronto */
3492     if (create) {
3493         for (i = 0; i <= MAXSERVERID; i++) {
3494             if (ctx->cheader->IpMappedAddr[i] == 0) {
3495                 ctx->cheader->IpMappedAddr[i] = htonl(ipaddr);
3496                 code =
3497                     vlwrite(ctx->trans,
3498                             DOFFSET(0, ctx->cheader, &ctx->cheader->IpMappedAddr[i]),
3499                             (char *)&ctx->cheader->IpMappedAddr[i],
3500                             sizeof(afs_int32));
3501                 ctx->hostaddress[i] = ipaddr;
3502                 if (code)
3503                     return -1;
3504                 return i;
3505             }
3506         }
3507     }
3508     return -1;
3509 }
3510
3511 static int
3512 ChangeIPAddr(struct vl_ctx *ctx, afs_uint32 ipaddr1, afs_uint32 ipaddr2)
3513 {
3514     int i, j;
3515     afs_int32 code;
3516     struct extentaddr *exp = NULL;
3517     int base;
3518     int mhidx;
3519     afsUUID tuuid;
3520     afs_int32 blockindex, count;
3521     int pollcount = 0;
3522     struct nvlentry tentry;
3523     int ipaddr1_id = -1, ipaddr2_id = -1;
3524     char addrbuf1[256];
3525     char addrbuf2[256];
3526
3527     /* Don't let addr change to 256.*.*.* : Causes internal error below */
3528     if ((ipaddr2 & 0xff000000) == 0xff000000)
3529         return (VL_BADSERVER);
3530
3531     /* If we are removing an address, ip1 will be -1 and ip2 will be
3532      * the original address. This prevents an older revision vlserver
3533      * from removing the IP address (won't find server 0xfffffff in
3534      * the VLDB). An older revision vlserver does not have the check
3535      * to see if any volumes exist on the server being removed.
3536      */
3537     if (ipaddr1 == 0xffffffff) {
3538         ipaddr1 = ipaddr2;
3539         ipaddr2 = 0;
3540     }
3541
3542     for (i = 0; i <= MAXSERVERID; i++) {
3543         code = multiHomedExtentBase(ctx, i, &exp, &base);
3544         if (code)
3545             return code;
3546
3547         if (exp) {
3548             for (mhidx = 0; mhidx < VL_MAXIPADDRS_PERMH; mhidx++) {
3549                 if (!exp->ex_addrs[mhidx])
3550                     continue;
3551                 if (ntohl(exp->ex_addrs[mhidx]) == ipaddr1) {
3552                     ipaddr1_id = i;
3553                 }
3554                 if (ipaddr2 != 0 && ntohl(exp->ex_addrs[mhidx]) == ipaddr2) {
3555                     ipaddr2_id = i;
3556                 }
3557             }
3558         } else {
3559             if (ctx->hostaddress[i] == ipaddr1) {
3560                 exp = NULL;
3561                 ipaddr1_id = i;
3562             }
3563             if (ipaddr2 != 0 && ctx->hostaddress[i] == ipaddr2) {
3564                 ipaddr2_id = i;
3565             }
3566         }
3567
3568         if (ipaddr1_id >= 0 && (ipaddr2 == 0 || ipaddr2_id >= 0)) {
3569             /* we've either found both IPs already in the VLDB, or we found
3570              * ipaddr1, and we're not going to find ipaddr2 because it's 0 */
3571             break;
3572         }
3573     }
3574
3575     if (ipaddr1_id < 0) {
3576         return VL_NOENT;        /* not found */
3577     }
3578
3579     if (ipaddr2_id >= 0 && ipaddr2_id != ipaddr1_id) {
3580         char buf1[16], buf2[16];
3581         VLog(0, ("Cannot change IP address from %s to %s because the latter "
3582                  "is in use by server id %d\n",
3583                  afs_inet_ntoa_r(htonl(ipaddr1), buf1),
3584                  afs_inet_ntoa_r(htonl(ipaddr2), buf2),
3585                  ipaddr2_id));
3586         return VL_MULTIPADDR;
3587     }
3588
3589     /* If we are removing a server entry, a volume cannot
3590      * exist on the server. If one does, don't remove the
3591      * server entry: return error "volume entry exists".
3592      */
3593     if (ipaddr2 == 0) {
3594         for (blockindex = NextEntry(ctx, 0, &tentry, &count); blockindex;
3595              blockindex = NextEntry(ctx, blockindex, &tentry, &count)) {
3596             if (++pollcount > 50) {
3597 #ifndef AFS_PTHREAD_ENV
3598                 IOMGR_Poll();
3599 #endif
3600                 pollcount = 0;
3601             }
3602             for (j = 0; j < NMAXNSERVERS; j++) {
3603                 if (tentry.serverNumber[j] == BADSERVERID)
3604                     break;
3605                 if (tentry.serverNumber[j] == ipaddr1_id) {
3606                     return VL_IDEXIST;
3607                 }
3608             }
3609         }
3610     }
3611
3612     /* Log a message saying we are changing/removing an IP address */
3613     VLog(0,
3614          ("The following IP address is being %s:\n",
3615           (ipaddr2 ? "changed" : "removed")));
3616     addrbuf1[0] = addrbuf2[0] = '\0';
3617     if (exp) {
3618         for (mhidx = 0; mhidx < VL_MAXIPADDRS_PERMH; mhidx++) {
3619             if (!exp->ex_addrs[mhidx])
3620                 continue;
3621             if (mhidx > 0)
3622                 strlcat(addrbuf1, " ", sizeof(addrbuf1));
3623             append_addr(addrbuf1, ntohl(exp->ex_addrs[mhidx]), sizeof(addrbuf1));
3624         }
3625     } else {
3626         append_addr(addrbuf1, ipaddr1, sizeof(addrbuf1));
3627     }
3628     if (ipaddr2) {
3629         append_addr(addrbuf2, ipaddr2, sizeof(addrbuf2));
3630     }
3631     VLog(0, ("      entry %d: [%s] -> [%s]\n", i, addrbuf1, addrbuf2));
3632
3633     /* Change the registered uuuid addresses */
3634     if (exp) {
3635         memset(&tuuid, 0, sizeof(afsUUID));
3636         afs_htonuuid(&tuuid);
3637         exp->ex_hostuuid = tuuid;
3638         code =
3639             vlwrite(ctx->trans,
3640                     DOFFSET(ntohl(ctx->ex_addr[0]->ex_contaddrs[base]),
3641                             (char *)ctx->ex_addr[base], (char *)exp),
3642                     (char *)&tuuid, sizeof(tuuid));
3643         if (code)
3644             return VL_IO;
3645     }
3646
3647     /* Now change the host address entry */
3648     ctx->cheader->IpMappedAddr[ipaddr1_id] = htonl(ipaddr2);
3649     code =
3650         vlwrite(ctx->trans, DOFFSET(0, ctx->cheader, &ctx->cheader->IpMappedAddr[ipaddr1_id]),
3651                 (char *)
3652                 &ctx->cheader->IpMappedAddr[ipaddr1_id], sizeof(afs_int32));
3653     ctx->hostaddress[ipaddr1_id] = ipaddr2;
3654     if (code)
3655         return VL_IO;
3656
3657     return 0;
3658 }
3659
3660 /* see if the vlserver is back yet */
3661 afs_int32
3662 SVL_ProbeServer(struct rx_call *rxcall)
3663 {
3664     return 0;
3665 }