Add interface to select client security objects
[openafs.git] / src / bucoord / ubik_db_if.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 /* Interface and supporting routines for the backup system's ubik database */
11
12 #include <afsconfig.h>
13 #include <afs/stds.h>
14
15 #ifdef IGNORE_SOME_GCC_WARNINGS
16 # pragma GCC diagnostic warning "-Wstrict-prototypes"
17 #endif
18
19 #include <sys/types.h>
20 #include <fcntl.h>
21 #ifdef AFS_NT40_ENV
22 #include <winsock2.h>
23 #elif defined(AFS_SUN5_ENV)
24 #include <netdb.h>
25 #else
26 #include <sys/param.h>          /* for hostnames etc */
27 #endif
28 #include <afs/auth.h>
29 #include <afs/cellconfig.h>
30 #include <ubik.h>
31 #include <afs/volser.h>
32 #include <afs/volser_prototypes.h>
33 #include <afs/afsutil.h>
34 #include <afs/bubasics.h>
35 #include <afs/budb_client.h>
36 #include <afs/budb.h>
37 #include <afs/com_err.h>
38 #include <errno.h>
39
40 #include "bc.h"
41 #include "error_macros.h"
42 #include "bucoord_internal.h"
43 #include "bucoord_prototypes.h"
44
45 extern char *whoami;
46
47 /* -------------------------------------
48  * Globals 
49  * -------------------------------------
50  */
51
52 struct udbHandleS udbHandle;
53
54 /* -------------------------------------
55  * interface routines (alphabetic)
56  * -------------------------------------
57  */
58
59 afs_int32 bcdb_AddVolume(register struct budb_volumeEntry *veptr)
60 {
61     afs_int32 code;
62
63     code = ubik_BUDB_AddVolume(udbHandle.uh_client, 0, veptr);
64     return (code);
65 }
66
67 afs_int32 bcdb_AddVolumes(register struct budb_volumeEntry *veptr, afs_int32 count)
68 {
69     struct budb_volumeList volumeList;
70     afs_int32 code;
71
72     volumeList.budb_volumeList_len = count;
73     volumeList.budb_volumeList_val = veptr;
74     code = ubik_BUDB_AddVolumes(udbHandle.uh_client, 0, &volumeList);
75     return (code);
76 }
77
78
79 afs_int32 bcdb_CreateDump(register struct budb_dumpEntry *deptr)
80 {
81     afs_int32 code;
82
83     code = ubik_BUDB_CreateDump(udbHandle.uh_client, 0, deptr);
84     return (code);
85 }
86
87 afs_int32 bcdb_deleteDump(afs_int32 dumpID, afs_int32 fromTime, afs_int32 toTime, 
88   budb_dumpsList *dumps)
89 {
90     afs_int32 code;
91     budb_dumpsList dumpsList, *dumpsPtr;
92
93     dumpsList.budb_dumpsList_len = 0;
94     dumpsList.budb_dumpsList_val = 0;
95     dumpsPtr = (dumps ? dumps : &dumpsList);
96
97     code =
98         ubik_BUDB_DeleteDump(udbHandle.uh_client, 0, dumpID, fromTime,
99                   toTime, dumpsPtr);
100     if (dumpsList.budb_dumpsList_val)
101         free(dumpsList.budb_dumpsList_val);
102     return (code);
103 }
104
105 afs_int32 bcdb_listDumps (afs_int32 sflags, afs_int32 groupId,
106                           afs_int32 fromTime, afs_int32 toTime,
107                           budb_dumpsList *dumps, budb_dumpsList *flags)
108 {
109     afs_int32 code;
110     budb_dumpsList dumpsList, *dumpsPtr;
111     budb_dumpsList flagsList, *flagsPtr;
112
113     dumpsList.budb_dumpsList_len = 0;
114     dumpsList.budb_dumpsList_val = 0;
115     dumpsPtr = (dumps ? dumps : &dumpsList);
116
117     flagsList.budb_dumpsList_len = 0;
118     flagsList.budb_dumpsList_val = 0;
119     flagsPtr = (flags ? flags : &flagsList);
120
121     code =
122         ubik_BUDB_ListDumps(udbHandle.uh_client, 0, sflags, "", groupId,
123                   fromTime, toTime, dumpsPtr, flagsPtr);
124
125     if (dumpsList.budb_dumpsList_val)
126         free(dumpsList.budb_dumpsList_val);
127     if (flagsList.budb_dumpsList_val)
128         free(flagsList.budb_dumpsList_val);
129     return (code);
130 }
131
132
133 afs_int32 bcdb_DeleteVDP(char *dumpSetName, char *dumpPath, afs_int32 dumpID)
134 {
135     afs_int32 code;
136
137     code =
138         ubik_BUDB_DeleteVDP(udbHandle.uh_client, 0, dumpSetName,
139                   dumpPath, dumpID);
140     return (code);
141 }
142
143 /* bcdb_FindClone
144  *      Returns the clone time of a volume by going up the parent chain.
145  *      If no clone time is found, a clone time of 0 is returned, forcing
146  *      a full dump.
147  * entry:
148  *      dumpID - of the first dump to examine.
149  *      volName - name of the volume for whom a clone time is required
150  *      clonetime - ptr to vbl for returning result
151  * exit:
152  *      0 - clonetime set appropriately
153  *      -1 - error occured in traversing chain, clone time set to 0.
154  *      -2 - no clone times found, clone time set to 0
155  */
156
157 afs_int32 bcdb_FindClone(afs_int32 dumpID, char *volName, afs_int32 *clonetime)
158 {
159     afs_int32 code;
160     code =
161         ubik_BUDB_FindClone(udbHandle.uh_client, 0, dumpID, volName,
162                   clonetime);
163     return (code);
164 }
165
166 /* bcdb_FindDump
167  *      scan entire database for latest volume dump before adate.  Optimize
168  *      further by reading only the first line of the dump and if it is older
169  *      than the oldest acceptable dump we've found so far, we don't bother
170  *      scanning the dump file we've just opened
171  *
172  *      Used by restore code when restoring a user requested volume(s)
173  * entry:
174  *      volumeName - name of volume to match on
175  *      beforeDate - look for dumps older than this date
176  * exit:
177  *      deptr - desciptor of most recent dump
178  * notes:
179  *      should be able to implement this in a single call rather than
180  *      the current multiple bcdb_ call algorithm.
181  */
182
183 int
184 bcdb_FindDump(char *volumeName, afs_int32 beforeDate, 
185               struct budb_dumpEntry *deptr)
186 {
187     afs_int32 code;
188     code =
189         ubik_BUDB_FindDump(udbHandle.uh_client, 0, volumeName,
190                   beforeDate, deptr);
191     return (code);
192 }
193
194 /* bcdb_FindDumpByID
195  *      find a dump by id. Currently insists on a single return value.
196  * entry:
197  *      dumpID - id to lookup
198  * exit:
199  */
200 int
201 bcdb_FindDumpByID(afs_int32 dumpID, struct budb_dumpEntry *deptr)
202 {
203     register afs_int32 code;
204     afs_int32 nextindex;
205     afs_int32 dbTime;
206     budb_dumpList dl;
207
208     /* initialize the dump list */
209     dl.budb_dumpList_len = 0;
210     dl.budb_dumpList_val = 0;
211
212     /* outline algorithm */
213     code = ubik_BUDB_GetDumps(udbHandle.uh_client, 0, BUDB_MAJORVERSION, BUDB_OP_DUMPID, "",    /* no name */
214                      dumpID,    /* start */
215                      0,         /* end */
216                      0,         /* index */
217                      &nextindex, &dbTime, &dl);
218
219     if ((code != 0)
220         || (dl.budb_dumpList_len != 1)  /* single retn val expected */
221         ) {
222 /*      printf("bcdb_FindDumpByID: code %d, nvalues %d\n",
223                code, dl.budb_dumpList_len); */
224         if (code == 0)
225             code = 1;           /* multiple id's */
226         goto error;
227     }
228
229     memcpy(deptr, dl.budb_dumpList_val, sizeof(*deptr));
230
231   exit:
232     if (dl.budb_dumpList_val) {
233         /* free any allocated structures */
234         free(dl.budb_dumpList_val);
235     }
236     return (code);
237
238   error:
239     memset(deptr, 0, sizeof(*deptr));
240     goto exit;
241 }
242
243 /* bcdb_FindLastVolClone
244  *      Returns the clone time, from the most recent dump of volName, when
245  *      dumped in the volume set volSetName, with dump schedule dumpName.
246  *      The clone time can be used to check if the volume has been correctly
247  *      re-cloned, and also is used as the time from which to do the current
248  *      incremental dump.
249  * entry:
250  *      volSetName - name of volume set
251  *      dumpName - full path of dump node
252  *      volName - name of volume for whom a clone time is required
253  *      clonetime - ptr to vbl for result
254  * exit:
255  *      0 - clonetime set appropriately
256  * notes:
257  *      used only for warning generation. Suggest that this be omitted.
258  */
259
260 afs_int32
261 bcdb_FindLastVolClone(char *volSetName, char *dumpName, char *volName, 
262                       afs_int32 *clonetime)
263 {
264     /* server notes
265      * search by dumpName
266      * match on volumeset and dump path
267      * search for the volume name
268      */
269     return (0);
270 }
271
272 /* bcdb_FindLatestDump
273  *      find the latest dump with volume set component avname and the
274  *      specified dump pathname. Used to find a dump, relative to which an
275  *      incremental dump can be done. Defines the parent <-> child relations
276  *      for restores.
277  * entry:
278  *      avname: volume set name
279  *      dumpPath: full path of dump node
280  * exit:
281  *      0:  adentry: dump entry structure filled in.
282  *      -1: probably an internal error
283  *      2: no such entry
284  * Notes for 4.0:
285  *      Need to store volumeset name in dump in order to implement this.
286  *      Need new routine since params are two strings
287  */
288
289 int
290 bcdb_FindLatestDump(char *volSetName, char *dumpPath, 
291                     struct budb_dumpEntry *deptr)
292 {
293     afs_int32 code;
294     code =
295         ubik_BUDB_FindLatestDump(udbHandle.uh_client, 0, volSetName,
296                   dumpPath, deptr);
297     return (code);
298 }
299
300
301 /* bcdb_FindTape
302  *      find a tape
303  * entry:
304  *      dumpid: dump id to which tape beint32s
305  *      tapeName: name of tape
306  */
307
308 int
309 bcdb_FindTape(afs_int32 dumpid, char *tapeName, 
310               struct budb_tapeEntry *teptr)
311 {
312     budb_tapeList tl;
313     afs_int32 next;
314     afs_int32 dbTime;
315     afs_int32 code = 0;
316
317     memset(teptr, 0, sizeof(*teptr));
318     tl.budb_tapeList_len = 0;
319     tl.budb_tapeList_val = 0;
320
321     code =
322         ubik_BUDB_GetTapes(udbHandle.uh_client, 0, BUDB_MAJORVERSION,
323                   BUDB_OP_TAPENAME | BUDB_OP_DUMPID, tapeName, dumpid, 0, 0,
324                   &next, &dbTime, &tl);
325
326     if (code)
327         ERROR(code);
328
329     if (tl.budb_tapeList_len != 1)
330         ERROR(BC_NOTUNIQUE);    /* expecting a single descriptor */
331
332     memcpy(teptr, tl.budb_tapeList_val, sizeof(*teptr));
333
334   error_exit:
335     if (tl.budb_tapeList_val)
336         free(tl.budb_tapeList_val);
337     return (code);
338 }
339
340 int
341 bcdb_FindTapeSeq(afs_int32 dumpid, afs_int32 tapeSeq, 
342                  struct budb_tapeEntry *teptr)
343 {
344     budb_tapeList tl;
345     afs_int32 next;
346     afs_int32 dbTime;
347     afs_int32 code = 0;
348
349     memset(teptr, 0, sizeof(*teptr));
350     tl.budb_tapeList_len = 0;
351     tl.budb_tapeList_val = 0;
352
353     code =
354         ubik_BUDB_GetTapes(udbHandle.uh_client, 0, BUDB_MAJORVERSION,
355                   BUDB_OP_TAPESEQ | BUDB_OP_DUMPID, "", dumpid, tapeSeq, 0,
356                   &next, &dbTime, &tl);
357     if (code)
358         ERROR(code);
359
360     if (tl.budb_tapeList_len != 1)
361         ERROR(BC_NOTUNIQUE);    /* expecting a single descriptor */
362
363     memcpy(teptr, tl.budb_tapeList_val, sizeof(*teptr));
364
365   error_exit:
366     if (tl.budb_tapeList_val)
367         free(tl.budb_tapeList_val);
368     return (code);
369 }
370
371 /* bcdb_FindVolumes
372  * notes: 
373  *      - this is part of dblookup. The existing semantics will not work since
374  *      they do lookups based on dump id.
375  *      - in the restore code, it uses this to extract information about
376  *      the volume. Need current semantics. Could filter the output, selecting
377  *      on the dumpid.
378  *      - Suggest that the lookup be based on volume name only, with optional
379  *      match on backup, and readonly volumes.
380  *      - Further, need to check if the volume structure returns enough
381  *      information
382  */
383
384 afs_int32
385 bcdb_FindVolumes(afs_int32 dumpID, char *volumeName, 
386                  struct budb_volumeEntry *returnArray, 
387                  afs_int32 last, afs_int32 *next, afs_int32 maxa, 
388                  afs_int32 *nEntries)
389 {
390     budb_volumeList vl;
391     afs_int32 dbTime;
392     afs_int32 code;
393
394     vl.budb_volumeList_len = maxa;
395     vl.budb_volumeList_val = returnArray;
396
397     /* outline algorithm */
398     code = ubik_BUDB_GetVolumes(udbHandle.uh_client, 0, BUDB_MAJORVERSION, BUDB_OP_VOLUMENAME | BUDB_OP_DUMPID, volumeName,     /* name */
399                      dumpID,    /* start */
400                      0,         /* end */
401                      last,      /* index */
402                      next,      /* nextindex */
403                      &dbTime, &vl);
404
405     *nEntries = vl.budb_volumeList_len;
406     return (code);
407 }
408
409 int
410 bcdb_FinishDump(register struct budb_dumpEntry *deptr)
411 {
412     afs_int32 code;
413     code = ubik_BUDB_FinishDump(udbHandle.uh_client, 0, deptr);
414     return (code);
415 }
416
417 int
418 bcdb_FinishTape(register struct budb_tapeEntry *teptr)
419 {
420     afs_int32 code;
421     code = ubik_BUDB_FinishTape(udbHandle.uh_client, 0, teptr);
422     return (code);
423
424 }
425
426 /* bcdb_LookupVolumes
427  */
428
429 afs_int32
430 bcdb_LookupVolume(char *volumeName, struct budb_volumeEntry *returnArray, 
431                   afs_int32 last, afs_int32 *next, afs_int32 maxa, 
432                   afs_int32 *nEntries)
433 {
434     budb_volumeList vl;
435     afs_int32 dbTime;
436     afs_int32 code;
437
438     vl.budb_volumeList_len = maxa;
439     vl.budb_volumeList_val = returnArray;
440
441     /* outline algorithm */
442     code = ubik_BUDB_GetVolumes(udbHandle.uh_client, 0, BUDB_MAJORVERSION, BUDB_OP_VOLUMENAME, volumeName,      /* name */
443                      0,         /* start */
444                      0,         /* end */
445                      last,      /* index */
446                      next,      /* nextindex */
447                      &dbTime, &vl);
448     if (code) {
449         *nEntries = 0;
450         return (code);
451     }
452     *nEntries = vl.budb_volumeList_len;
453     return (0);
454 }
455
456 int
457 bcdb_UseTape(struct budb_tapeEntry *teptr, afs_int32 *newFlag)
458 {
459     afs_int32 code;
460     code = ubik_BUDB_UseTape(udbHandle.uh_client, 0, teptr, newFlag);
461     return (code);
462 }
463
464
465 /* ---- text configuration handling routines ----
466  * 
467  * notes: 
468  *      The caller should pass in/out a fid for an unlinked, open file to prevent
469  *      tampering with the files contents; 
470  */
471
472 /* bcdb_GetTextFile
473  *      extract the specified textType and put it in a temporary, local
474  *      file.
475  * entry:
476  *      ctPtr - ptr to client structure with all the required information
477  */
478
479 int
480 bcdb_GetTextFile(register udbClientTextP ctPtr)
481 {
482     afs_int32 bufferSize;
483     afs_int32 offset, nextOffset;
484     charListT charList;
485     afs_int32 code = 0;
486
487     /* Initialize charlistT_val. We try to deallocate this structure based on
488      * this */
489     memset((void *)&charList, 0, sizeof(charList));
490
491     /* check params and cleanup any previous state */
492     if (ctPtr->lockHandle == 0)
493         ERROR(BUDB_INTERNALERROR);
494
495     if (ctPtr->textStream == NULL)      /* Should have an open stream */
496         ERROR(BUDB_INTERNALERROR);
497
498     /* allocate a buffer */
499     bufferSize = 1024;
500     charList.charListT_val = (char *)malloc(bufferSize);
501     if (charList.charListT_val == 0)
502         ERROR(BUDB_INTERNALERROR);
503     charList.charListT_len = bufferSize;
504
505     offset = 0;
506     nextOffset = 0;
507     ctPtr->textSize = 0;
508     while (nextOffset != -1) {
509         offset = nextOffset;
510         charList.charListT_len = bufferSize;
511         code =
512             ubik_BUDB_GetText(udbHandle.uh_client, 0, ctPtr->lockHandle,
513                       ctPtr->textType, bufferSize, offset, &nextOffset,
514                       &charList);
515
516         if (code)
517             ERROR(code);
518
519         code =
520             fwrite(charList.charListT_val, sizeof(char),
521                    charList.charListT_len, ctPtr->textStream);
522         if (ferror(ctPtr->textStream))
523             ERROR(BUDB_INTERNALERROR);
524
525         ctPtr->textSize += charList.charListT_len;
526     }
527
528     /* get text version */
529     code =
530         ubik_BUDB_GetTextVersion(udbHandle.uh_client, 0,
531                   ctPtr->textType, &ctPtr->textVersion);
532     if (code)
533         ERROR(code);
534
535   normal_exit:
536     fflush(ctPtr->textStream);  /* debug */
537
538     /* exit, leaving the configuration text file open */
539     if (charList.charListT_val)
540         free(charList.charListT_val);
541     return (code);
542
543   error_exit:
544     if (ctPtr->textStream != NULL) {
545         fclose(ctPtr->textStream);
546         ctPtr->textStream = NULL;
547     }
548     goto normal_exit;
549 }
550
551
552 /* bcdb_SaveTextFile
553  *      save the text file in ubik database
554  * entry:
555  *      textType - identifies type of configuration file
556  *      filename - where to get the text from
557  */
558
559 int
560 bcdb_SaveTextFile(udbClientTextP ctPtr)
561 {
562     afs_int32 bufferSize;
563     afs_int32 offset, chunkSize, fileSize;
564     charListT charList;
565     afs_int32 code = 0;
566
567     /* allocate a buffer */
568     bufferSize = 1024;
569     charList.charListT_val = (char *)malloc(bufferSize);
570     if (charList.charListT_val == 0)
571         ERROR(BUDB_INTERNALERROR);
572     charList.charListT_len = bufferSize;
573
574     if (ctPtr->textStream == NULL)
575         ERROR(BUDB_INTERNALERROR);
576     rewind(ctPtr->textStream);
577
578     fileSize = (afs_int32) filesize(ctPtr->textStream);
579
580     afs_dprintf(("filesize is %d\n", fileSize));
581
582     rewind(ctPtr->textStream);
583
584     /* special case empty files */
585     if (fileSize == 0) {
586         charList.charListT_len = 0;
587         code =
588             ubik_BUDB_SaveText(udbHandle.uh_client, 0,
589                       ctPtr->lockHandle, ctPtr->textType, 0,
590                       BUDB_TEXT_COMPLETE, &charList);
591         goto error_exit;
592     }
593
594     offset = 0;
595     while (fileSize != 0) {
596         chunkSize = MIN(fileSize, bufferSize);
597         code =
598             fread(charList.charListT_val, sizeof(char), chunkSize,
599                   ctPtr->textStream);
600
601         if (code != chunkSize)
602             printf("code = %d\n", code);
603         if (ferror(ctPtr->textStream))
604             ERROR(BUDB_INTERNALERROR);
605
606         charList.charListT_len = chunkSize;
607         code =
608             ubik_BUDB_SaveText(udbHandle.uh_client, 0,
609                       ctPtr->lockHandle, ctPtr->textType, offset,
610                       (chunkSize == fileSize) ? BUDB_TEXT_COMPLETE : 0,
611                       &charList);
612         if (code)
613             ERROR(code);
614
615         fileSize -= chunkSize;
616         offset += chunkSize;
617     }
618
619   error_exit:
620     /* if ( ctPtr->textStream >= 0 )
621      * close(ctPtr->textStream); */
622     if (charList.charListT_val)
623         free(charList.charListT_val);
624     return (code);
625 }
626
627 int
628 bcdb_FindLastTape(afs_int32 dumpID, struct budb_dumpEntry *dumpEntry,
629                   struct budb_tapeEntry *tapeEntry,
630                   struct budb_volumeEntry *volEntry)
631 {
632     return (ubik_BUDB_FindLastTape(udbHandle.uh_client, 0, dumpID, dumpEntry,
633              tapeEntry, volEntry));
634 }
635
636 int
637 bcdb_MakeDumpAppended(afs_int32 appendedDumpID, afs_int32 initialDumpID,
638                       afs_int32 startTapeSeq)
639 {
640     return (ubik_BUDB_MakeDumpAppended(udbHandle.uh_client, 0, appendedDumpID,
641              initialDumpID, startTapeSeq));
642 }
643
644
645 /* -------------------------------------
646  * misc. support routines
647  * -------------------------------------
648  */
649
650 afs_int32
651 filesize(FILE *stream)
652 {
653     afs_int32 offset;
654     afs_int32 size;
655
656     offset = ftell(stream);
657     fseek(stream, (afs_int32) 0, 2);    /* end of file */
658     size = ftell(stream);
659     fseek(stream, offset, 0);
660     return (size);
661 }
662
663
664 /* ------------------------------------
665  * misc. support routines - general text management
666  * ------------------------------------
667  */
668
669
670 /* bc_LockText
671  *      locks the text described by the ctPtr
672  * entry:
673  *      ctptr - client text ptr
674  * exit:
675  *      0 - success
676  *      n - fail
677  */
678
679 int
680 bc_LockText(udbClientTextP ctPtr)
681 {
682     afs_int32 code;
683     afs_int32 timeout, j = 0;
684
685     if (ctPtr->lockHandle != 0)
686         return (1);             /* already locked */
687
688     timeout =
689         ((ctPtr->textSize == 0) ? 30 : ((ctPtr->textSize / 50000) + 10));
690
691     while (1) {
692         code =
693             ubik_BUDB_GetLock(udbHandle.uh_client, 0,
694                       udbHandle.uh_instanceId, ctPtr->textType, timeout,
695                       &ctPtr->lockHandle);
696         if ((code != BUDB_LOCKED) && (code != BUDB_SELFLOCKED)) {
697             break;
698         }
699
700         /* Mention something every 30 seconds */
701         if (++j >= 30) {
702             afs_com_err(whoami, code,
703                     "; Waiting for db configuration text unlock");
704             j = 0;
705         }
706 #ifdef AFS_PTHREAD_ENV
707         sleep(1);
708 #else
709         IOMGR_Sleep(1);
710 #endif
711     }
712
713     /* cleanup */
714     if (code)
715         ctPtr->lockHandle = 0;
716     return (code);
717 }
718
719 /* bc_UnlockText
720  *      unlocks the text described by the ctPtr
721  * entry:
722  *      ctptr - client text ptr
723  * exit:
724  *      0 - success
725  *      n - fail
726  */
727
728 int
729 bc_UnlockText(udbClientTextP ctPtr)
730 {
731     afs_int32 code = 0;
732
733     if (ctPtr->lockHandle == 0)
734         return (0);
735
736     code =
737         ubik_BUDB_FreeLock(udbHandle.uh_client, 0, ctPtr->lockHandle);
738     ctPtr->lockHandle = 0;
739
740     /* Don't try to analyse the error. Let the lock timeout */
741     return (code);
742 }
743
744 /* bc_CheckTextVersion
745  * exit:
746  *      0 - version # ok
747  *      n - out of date or error
748  */
749
750 int
751 bc_CheckTextVersion(udbClientTextP ctPtr)
752 {
753     afs_int32 code;
754     afs_uint32 tversion;
755
756     if (ctPtr->textVersion == -1)
757         return (BC_VERSIONMISMATCH);
758
759     code =
760         ubik_BUDB_GetTextVersion(udbHandle.uh_client, 0,
761                   ctPtr->textType, &tversion);
762     if (code)
763         return (code);
764     if (tversion != ctPtr->textVersion)
765         return (BC_VERSIONMISMATCH);
766     return (0);
767 }
768
769 /* -------------------------------------
770  * initialization routines
771  * -------------------------------------
772  */
773
774 static afsconf_secflags
775 parseSecFlags(int noAuthFlag, int localauth, const char **confdir) {
776     afsconf_secflags secFlags;
777
778     secFlags = 0;
779     if (noAuthFlag)
780         secFlags |= AFSCONF_SECOPTS_NOAUTH;
781
782     if (localauth) {
783         secFlags |= AFSCONF_SECOPTS_LOCALAUTH;
784         *confdir = AFSDIR_SERVER_ETC_DIRPATH;
785     } else {
786         *confdir = AFSDIR_CLIENT_ETC_DIRPATH;
787     }
788     return secFlags;
789 }
790
791 /* vldbClientInit 
792  *      Initialize a client for the vl ubik database.
793  */
794 int
795 vldbClientInit(int noAuthFlag, int localauth, char *cellName, 
796                struct ubik_client **cstruct, 
797                time_t *expires)
798 {
799     afs_int32 code = 0;
800     struct afsconf_dir *acdir;
801     struct rx_securityClass *sc;
802     afs_int32 i, scIndex = 0;   /* Index of Rx security object - noauth */
803     struct afsconf_cell info;
804     struct rx_connection *serverconns[VLDB_MAXSERVERS];
805     afsconf_secflags secFlags;
806     const char *confdir;
807
808     secFlags = parseSecFlags(noAuthFlag, localauth, &confdir);
809     secFlags |= AFSCONF_SECOPTS_FALLBACK_NULL;
810
811     /* This just preserves old behaviour of using the default cell when
812      * passed an empty string */
813     if (cellName && cellName[0] == '\0')
814         cellName = NULL;
815
816     /* Find out about the given cell */
817     acdir = afsconf_Open(confdir);
818     if (!acdir) {
819         afs_com_err(whoami, 0, "Can't open configuration directory '%s'", confdir);
820         ERROR(BC_NOCELLCONFIG);
821     }
822
823     code = afsconf_GetCellInfo(acdir, cellName, AFSCONF_VLDBSERVICE, &info);
824     if (code) {
825         afs_com_err(whoami, code, "; Can't find cell %s's hosts in %s/%s",
826                     cellName, confdir, AFSDIR_CELLSERVDB_FILE);
827         ERROR(BC_NOCELLCONFIG);
828     }
829
830     code = afsconf_PickClientSecObj(acdir, secFlags, &info, cellName,
831                                     &sc, &scIndex, expires);
832     if (code) {
833         afs_com_err(whoami, code, "(configuring connection security)");
834         ERROR(BC_NOCELLCONFIG);
835     }
836     if (scIndex == 0 && !noAuthFlag)
837         afs_com_err(whoami, 0, "Can't get tokens - running unauthenticated");
838
839     /* tell UV module about default authentication */
840     UV_SetSecurity(sc, scIndex);
841
842     if (info.numServers > VLDB_MAXSERVERS) {
843         afs_com_err(whoami, 0,
844                 "Warning: %d VLDB servers exist for cell '%s', can only remember the first %d",
845                 info.numServers, cellName, VLDB_MAXSERVERS);
846         info.numServers = VLDB_MAXSERVERS;
847     }
848
849     for (i = 0; i < info.numServers; i++)
850         serverconns[i] =
851             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
852                              info.hostAddr[i].sin_port, USER_SERVICE_ID, sc,
853                              scIndex);
854     serverconns[i] = 0;
855
856     *cstruct = 0;
857     code = ubik_ClientInit(serverconns, cstruct);
858     if (code) {
859         afs_com_err(whoami, code, "; Can't initialize ubik connection to vldb");
860         ERROR(code);
861     }
862
863   error_exit:
864     if (acdir)
865         afsconf_Close(acdir);
866     return (code);
867 }
868
869 /* udbClientInit
870  *      initialize a client for the backup systems ubik database.
871  */
872
873 afs_int32
874 udbClientInit(int noAuthFlag, int localauth, char *cellName)
875 {
876     struct afsconf_cell info;
877     struct afsconf_dir *acdir;
878     const char *confdir;
879     int i;
880     afs_int32 secFlags;
881     afs_int32 code = 0;
882
883     secFlags = parseSecFlags(noAuthFlag, localauth, &confdir);
884     secFlags |= AFSCONF_SECOPTS_FALLBACK_NULL;
885
886     if (cellName && cellName[0] == '\0')
887         cellName = NULL;
888
889     acdir = afsconf_Open(confdir);
890     if (!acdir) {
891         afs_com_err(whoami, 0, "Can't open configuration directory '%s'",
892                     confdir);
893         ERROR(BC_NOCELLCONFIG);
894     }
895
896     code = afsconf_GetCellInfo(acdir, cellName, 0, &info);
897     if (code) {
898         afs_com_err(whoami, code, "; Can't find cell %s's hosts in %s/%s",
899                     cellName, confdir, AFSDIR_CELLSERVDB_FILE);
900         ERROR(BC_NOCELLCONFIG);
901     }
902
903     code = afsconf_PickClientSecObj(acdir, secFlags, &info, cellName,
904                                     &udbHandle.uh_secobj,
905                                     &udbHandle.uh_scIndex, NULL);
906     if (code) {
907         afs_com_err(whoami, code, "(configuring connection security)");
908         ERROR(BC_NOCELLCONFIG);
909     }
910     if (&udbHandle.uh_scIndex == 0 && !noAuthFlag)
911         afs_com_err(whoami, 0, "Can't get tokens - running unauthenticated");
912
913     if (info.numServers > MAXSERVERS) {
914         afs_com_err(whoami, 0,
915                 "Warning: %d BDB servers exist for cell '%s', can only remember the first %d",
916                 info.numServers, cellName, MAXSERVERS);
917         info.numServers = MAXSERVERS;
918     }
919
920     /* establish connections to the servers. Check for failed connections? */
921     for (i = 0; i < info.numServers; i++) {
922         udbHandle.uh_serverConn[i] =
923             rx_NewConnection(info.hostAddr[i].sin_addr.s_addr,
924                              htons(AFSCONF_BUDBPORT), BUDB_SERVICE,
925                              udbHandle.uh_secobj, udbHandle.uh_scIndex);
926     }
927     udbHandle.uh_serverConn[i] = 0;
928
929     code = ubik_ClientInit(udbHandle.uh_serverConn, &udbHandle.uh_client);
930     if (code) {
931         afs_com_err(whoami, code,
932                 "; Can't initialize ubik connection to backup database");
933         ERROR(code);
934     }
935
936     /* Try to quickly find a good site by setting deadtime low */
937     for (i = 0; i < info.numServers; i++)
938         rx_SetConnDeadTime(udbHandle.uh_client->conns[i], 1);
939     code =
940         ubik_BUDB_GetInstanceId(udbHandle.uh_client, 0,
941                   &udbHandle.uh_instanceId);
942
943     /* Reset dead time back up to default */
944     for (i = 0; i < info.numServers; i++)
945         rx_SetConnDeadTime(udbHandle.uh_client->conns[i], 60);
946
947     /* If did not find a site on first quick pass, try again */
948     if (code == -1)
949         code =
950             ubik_BUDB_GetInstanceId(udbHandle.uh_client, 0,
951                       &udbHandle.uh_instanceId);
952     if (code) {
953         afs_com_err(whoami, code, "; Can't access backup database");
954         ERROR(code);
955     }
956
957   error_exit:
958     if (acdir)
959         afsconf_Close(acdir);
960     return (code);
961 }
962
963 /* -------------------------------------
964  * specialized ubik support
965  * -------------------------------------
966  */
967
968 #include <rx/xdr.h>
969 #include <rx/rx.h>
970 #include <lock.h>
971
972 /* notes
973  *      1) first call with SINGLESERVER set, record the server to be used.
974  *      2) subsequent calls use that server. If a failure is encountered,
975  *         the state is cleaned up and the error returned back to the caller.
976  *      3) upon completion, the user must make a dummy call with
977  *         END_SINGLESERVER set, to clean up state.
978  *      4) if the vanilla ubik_Call is ever modified, the END_SINGLESERVER
979  *         flag can be discarded. The first call without SINGLESERVER set
980  *         can clean up the state.
981  */
982
983 struct ubikCallState {
984     afs_int32 ucs_flags;        /* state flags */
985     afs_int32 ucs_selectedServer;       /* which server selected */
986 };
987
988 static struct ubikCallState uServer;
989
990 /* ubik_Call_SingleServer
991  *      variant of ubik_Call. This is used by the backup system to initiate
992  *      a series of calls to a single ubik server. The first call sets up
993  *      process state (not recorded in ubik) that requires all further calls
994  *      of that group to be made to the same server process.
995  *
996  *      call this instead of stub and we'll guarantee to find a host that's up.
997  *      in the future, we should also put in a protocol to find the sync site
998  */
999
1000 afs_int32
1001 ubik_Call_SingleServer(int (*aproc) (), struct ubik_client *aclient, 
1002                        afs_int32 aflags, char *p1, char *p2, char *p3, 
1003                        char *p4, char *p5, char *p6, char *p7, char *p8,
1004                        char *p9, char *p10, char *p11, char *p12, char *p13, 
1005                        char *p14, char *p15, char *p16)
1006 {
1007     register afs_int32 code;
1008     afs_int32 someCode, newHost, thisHost;
1009     register afs_int32 i;
1010     register afs_int32 count;
1011     int chaseCount;
1012     int pass;
1013     struct rx_connection *tc;
1014     struct rx_peer *rxp;
1015
1016     if ((aflags & (UF_SINGLESERVER | UF_END_SINGLESERVER)) != 0) {
1017         if (((aflags & UF_SINGLESERVER) != 0)
1018             && ((uServer.ucs_flags & UF_SINGLESERVER) != 0)
1019             ) {
1020
1021             /* have a selected server */
1022             tc = aclient->conns[uServer.ucs_selectedServer];
1023
1024             code =
1025                 (*aproc) (tc, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11,
1026                           p12, p13, p14, p15, p16);
1027             if (code) {
1028                 /* error. Clean up single server state */
1029                 memset(&uServer, 0, sizeof(uServer));
1030             }
1031             return (code);
1032         } else if ((aflags & UF_END_SINGLESERVER) != 0) {
1033             memset(&uServer, 0, sizeof(uServer));
1034             return (0);
1035         }
1036     }
1037
1038     someCode = UNOSERVERS;
1039     chaseCount = 0;
1040     pass = 0;
1041     count = 0;
1042     while (1) {                 /*w */
1043
1044         /* tc is the next conn to try */
1045         tc = aclient->conns[count];
1046         if (tc == 0) {
1047             if (pass == 0) {
1048                 pass = 1;       /* in pass 1, we look at down hosts, too */
1049                 count = 0;
1050                 continue;
1051             } else
1052                 break;          /* nothing left to try */
1053         }
1054         if (pass == 0 && (aclient->states[count] & CFLastFailed)) {
1055             count++;
1056             continue;           /* this guy's down, try someone else first */
1057         }
1058
1059         code =
1060             (*aproc) (tc, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12,
1061                       p13, p14, p15, p16);
1062
1063         /* note that getting a UNOTSYNC error code back does *not* guarantee
1064          * that there is a sync site yet elected.  However, if there is a
1065          * sync site out there somewhere, and you're trying an operation that
1066          * requires a sync site, ubik will return UNOTSYNC, indicating the
1067          * operation won't work until you find a sync site
1068          */
1069         if (code == UNOTSYNC) { /*ns */
1070             /* means that this requires a sync site to work */
1071             someCode = code;    /* remember an error, if this fails */
1072
1073             /* now see if we can find the sync site host */
1074             code = VOTE_GetSyncSite(tc, &newHost);
1075             if (code == 0 && newHost != 0) {
1076                 newHost = htonl(newHost);       /* convert back to network order */
1077
1078                 /* position count at the appropriate slot in the client
1079                  * structure and retry. If we can't find in slot, we'll just
1080                  * continue through the whole list
1081                  */
1082                 for (i = 0; i < MAXSERVERS; i++) {      /*f */
1083                     rxp = rx_PeerOf(aclient->conns[i]);
1084                     if (!(thisHost = rx_HostOf(rxp))) {
1085                         count++;        /* host not found, try the next dude */
1086                         break;
1087                     }
1088                     if (thisHost == newHost) {
1089                         /* avoid asking in a loop */
1090                         if (chaseCount++ > 2)
1091                             break;
1092                         count = i;      /* we were told to use this one */
1093                         break;
1094                     }
1095                 }               /*f */
1096             } else
1097                 count++;        /* not directed, keep looking for a sync site */
1098             continue;
1099         } /*ns */
1100         else if (code == UNOQUORUM) {   /* this guy is still recovering */
1101             someCode = code;
1102             count++;
1103             continue;
1104         } else if (code < 0) {  /* network errors */
1105             someCode = code;
1106             aclient->states[count] |= CFLastFailed;
1107             count++;
1108             continue;
1109         } else {
1110             /* ok, operation worked */
1111             aclient->states[count] &= ~CFLastFailed;
1112             /* either misc ubik code, or misc application code (incl success)
1113              */
1114
1115             /* if the call succeeded, setup connection state for subsequent
1116              * calls
1117              */
1118             if ((code == 0)
1119                 && ((aflags & UF_SINGLESERVER) != 0)
1120                 ) {
1121                 /* need to save state */
1122                 uServer.ucs_flags = UF_SINGLESERVER;
1123                 uServer.ucs_selectedServer = count;
1124             }
1125
1126             return code;
1127         }
1128     }                           /*w */
1129     return someCode;
1130 }
1131
1132
1133 /* -------------------------------------
1134  * debug and test routines 
1135  * -------------------------------------
1136  */
1137
1138 /* udbLocalInit
1139  *      For testing only. Open a connect to the database server running on
1140  *      the local host
1141  * exit:
1142  *      0 - ubik connection established in the global udbHandle structure
1143  *      n - error.
1144  */
1145
1146 int
1147 udbLocalInit(void)
1148 {
1149     afs_int32 serverList[MAXSERVERS];
1150     char hostname[256];
1151     char *args[3];
1152     int i;
1153     afs_int32 code;
1154
1155     /* get our host name */
1156     gethostname(hostname, sizeof(hostname));
1157     /* strcpy(hostname, "hops"); */
1158
1159     args[0] = "";
1160     args[1] = "-servers";
1161     args[2] = hostname;
1162
1163     code = ubik_ParseClientList(3, args, serverList);
1164     if (code) {
1165         afs_com_err(whoami, code, "; udbLocalInit: parsing ubik server list");
1166         return (-1);
1167     }
1168
1169     udbHandle.uh_scIndex = RX_SCINDEX_NULL;
1170     udbHandle.uh_secobj = (struct rx_securityClass *)
1171         rxnull_NewClientSecurityObject();
1172
1173     for (i = 0; serverList[i] != 0; i++) {
1174         udbHandle.uh_serverConn[i] =
1175             rx_NewConnection(serverList[i], htons(AFSCONF_BUDBPORT),
1176                              BUDB_SERVICE, udbHandle.uh_secobj,
1177                              udbHandle.uh_scIndex);
1178         if (udbHandle.uh_serverConn[i] == 0) {
1179             afs_com_err(whoami, 0, "connection %d failed", i);
1180             continue;
1181         }
1182     }
1183     udbHandle.uh_serverConn[i] = 0;
1184     code = ubik_ClientInit(udbHandle.uh_serverConn, &udbHandle.uh_client);
1185     if (code) {
1186         afs_com_err(whoami, code, "; in ubik_ClientInit");
1187         return (code);
1188     }
1189
1190     code =
1191         ubik_BUDB_GetInstanceId(udbHandle.uh_client, 0,
1192                   &udbHandle.uh_instanceId);
1193     if (code) {
1194         afs_com_err(whoami, code, "; Can't estblish instance Id");
1195         return (code);
1196     }
1197
1198    /* abort: */
1199     return (0);
1200 }
1201
1202 /* bc_openTextFile - This function opens a temp file to read in the
1203  * config text recd from the bu server. On Unix, an unlink() is done on
1204  * the file as soon as it is opened, so when the program exits, the file will
1205  * be removed automatically, while being invisible while in use.
1206  * On NT, however, the file must be explicitly deleted after use with an unlink()
1207  * Input:
1208  *  Pointer to a udhClientTextP struct. The open stream ptr is stored in
1209  *           the udbClientTextP.textStream member.
1210  * Output: The temp file name is returned in tmpFileName. This should be used
1211  *   to delete the file when done with it.
1212  * Return Values: 
1213  *     !0: error code
1214  *     0: Success.
1215  */
1216 int
1217 bc_openTextFile(udbClientTextP ctPtr, char *tmpFileName)
1218 {
1219     int code = 0;
1220
1221     if (ctPtr->textStream != NULL)
1222         fclose(ctPtr->textStream);
1223
1224     sprintf(tmpFileName, "%s/bu_XXXXXX", gettmpdir());
1225 #ifdef AFS_LINUX20_ENV
1226     mkstemp(tmpFileName);
1227 #else
1228     mktemp(tmpFileName);
1229 #endif
1230     ctPtr->textStream = fopen(tmpFileName, "w+");
1231     if (ctPtr->textStream == NULL)
1232         ERROR(BUDB_INTERNALERROR);
1233
1234 #ifndef AFS_NT40_ENV            /* This can't be done on NT */
1235     /* make the file invisible to others */
1236     code = unlink(tmpFileName);
1237     if (code)
1238         ERROR(errno);
1239 #endif
1240
1241     afs_dprintf(("file is %s\n", tmpFileName));
1242
1243   normal_exit:
1244     return code;
1245
1246   error_exit:
1247     if (ctPtr->textStream != NULL) {
1248         fclose(ctPtr->textStream);
1249         ctPtr->textStream = NULL;
1250     }
1251     goto normal_exit;
1252 }
1253
1254
1255 /* bc_closeTextFile: This function closes any actual temp files associated with
1256  * a udbClientText structure. 
1257  * Input: ctPtr->textStream - stream to close
1258  *        tmpFileName - temp file name to delete
1259  * RetVal: 
1260  *    0  - Success
1261  *    !0 - error code
1262  */
1263 int
1264 bc_closeTextFile(udbClientTextP ctPtr, char *tmpFileName)
1265 {
1266     int code = 0;
1267
1268     if (ctPtr->textStream)
1269         fclose(ctPtr->textStream);
1270
1271     if (*tmpFileName) {         /* we have a valid name */
1272         code = unlink(tmpFileName);
1273         if (code < 0)
1274             code = errno;
1275     }
1276     return code;
1277 }