butc: Remove dead loop pointer allocations
[openafs.git] / src / butc / tcudbprocs.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 <afs/procmgmt.h>
14 #include <roken.h>
15
16 #ifdef IGNORE_SOME_GCC_WARNINGS
17 # pragma GCC diagnostic warning "-Wimplicit-function-declaration"
18 #endif
19
20 #include <afs/opr.h>
21 #include <rx/rx.h>
22 #include <afs/afsint.h>
23 #include <afs/prs_fs.h>
24 #include <afs/nfs.h>
25 #include <lwp.h>
26 #include <lock.h>
27 #include <afs/cellconfig.h>
28 #include <afs/keys.h>
29 #include <ubik.h>
30 #include <afs/acl.h>
31 #include <afs/volser.h>
32 #include <afs/vlserver.h>
33 #include <afs/tcdata.h>
34 #include <afs/budb.h>
35 #include <afs/budb_client.h>
36 #include <afs/bubasics.h>
37 #include <afs/bucoord_prototypes.h>
38 #include <afs/butm_prototypes.h>
39 #include <afs/budb_prototypes.h>
40 #include <afs/afsutil.h>
41
42 #include "butc_internal.h"
43 #include "error_macros.h"
44
45 /* GLOBAL CONFIGURATION PARAMETERS */
46 #define BIGCHUNK 102400
47
48 extern int dump_namecheck;
49 extern int autoQuery;
50
51 struct rstTapeInfo {
52     afs_int32 taskId;
53     afs_int32 tapeSeq;
54     afs_uint32 dumpid;
55 };
56
57 static void initTapeBuffering(void);
58 static int writeDbDump(struct butm_tapeInfo *, afs_uint32, Date, afs_uint32);
59 static int restoreDbEntries(struct butm_tapeInfo *, struct rstTapeInfo *);
60
61 int getTapeData(struct butm_tapeInfo *, struct rstTapeInfo *, void *,
62                 afs_int32);
63 int restoreDbHeader(struct butm_tapeInfo *, struct rstTapeInfo *,
64                     struct structDumpHeader *);
65 int restoreDbDump(struct butm_tapeInfo *, struct rstTapeInfo *,
66                   struct structDumpHeader *);
67 int restoreText(struct butm_tapeInfo *, struct rstTapeInfo *,
68                 struct structDumpHeader *);
69
70
71
72 void * KeepAlive(void *);
73 /* CreateDBDump
74  *      create a dump entry for a saved database
75  */
76
77 afs_int32
78 CreateDBDump(struct budb_dumpEntry *dumpEntryPtr)
79 {
80     afs_int32 code = 0;
81
82     memset(dumpEntryPtr, 0, sizeof(struct budb_dumpEntry));
83
84     strcpy(dumpEntryPtr->name, DUMP_TAPE_NAME);
85     strcpy(dumpEntryPtr->tapes.format, DUMP_TAPE_NAME);
86     strcat(dumpEntryPtr->tapes.format, ".%d");
87     strcpy(dumpEntryPtr->volumeSetName, "");
88     strcpy(dumpEntryPtr->dumpPath, "");
89     dumpEntryPtr->created = 0;  /* let database assign it */
90     dumpEntryPtr->incTime = 0;
91     dumpEntryPtr->nVolumes = 0;
92     dumpEntryPtr->initialDumpID = 0;
93     dumpEntryPtr->parent = 0;
94     dumpEntryPtr->level = 0;
95     dumpEntryPtr->tapes.maxTapes = 0;
96     dumpEntryPtr->tapes.b = 1;
97
98     /* now call the database to create the entry */
99     code = bcdb_CreateDump(dumpEntryPtr);
100     return (code);
101 }
102
103 struct tapeEntryList {
104     struct tapeEntryList *next;
105     afs_uint32 oldDumpId;
106     struct budb_tapeEntry tapeEnt;
107 };
108 struct tapeEntryList *listEntryHead;
109 struct tapeEntryList *listEntryPtr;
110 #define tapeEntryPtr (&listEntryPtr->tapeEnt)
111 struct budb_dumpEntry lastDump; /* the last dump of this volset */
112
113 /* GetDBTape
114  *      Load a DB tape, read and over write its label.
115  *      Leave the tape mounted.
116  */
117 afs_int32
118 GetDBTape(afs_int32 taskId, Date expires, struct butm_tapeInfo *tapeInfoPtr,
119           afs_uint32 dumpid, afs_int32 sequence, int queryFlag,
120           int *wroteLabel)
121 {
122     afs_int32 code = 0;
123     int interactiveFlag;
124     char tapeName[BU_MAXTAPELEN];
125     char strlevel[5];
126     struct timeval tp;
127     afs_int32 curTime;
128     int tapecount = 1;
129
130     struct butm_tapeLabel oldTapeLabel, newLabel;
131     struct tapeEntryList *endList;
132
133     /* construct the name of the tape */
134     sprintf(tapeName, "%s.%-d", DUMP_TAPE_NAME, sequence);
135
136     interactiveFlag = queryFlag;
137     *wroteLabel = 0;
138
139     while (!*wroteLabel) {      /*w */
140         if (interactiveFlag) {  /* need a tape to write */
141             code =
142                 PromptForTape(SAVEDBOPCODE, tapeName, dumpid, taskId,
143                               tapecount);
144             if (code)
145                 ERROR_EXIT(code);
146         }
147         interactiveFlag = 1;
148         tapecount++;
149
150         code = butm_Mount(tapeInfoPtr, tapeName);
151         if (code) {
152             TapeLog(0, taskId, code, tapeInfoPtr->error, "Can't open tape\n");
153             goto getNewTape;
154         }
155
156         memset(&oldTapeLabel, 0, sizeof(oldTapeLabel));
157         code = butm_ReadLabel(tapeInfoPtr, &oldTapeLabel, 1);   /* rewind tape */
158         if (code) {
159             oldTapeLabel.useCount = 0;  /* no label exists */
160             oldTapeLabel.structVersion = 0;
161             strcpy(oldTapeLabel.pName, "");
162         } else {
163             /* If tape has a name, it must be null or database tape name */
164             if (dump_namecheck && strcmp(oldTapeLabel.AFSName, "")
165                 && !databaseTape(oldTapeLabel.AFSName)) {
166                 char gotName[BU_MAXTAPELEN + 32];
167
168                 LABELNAME(gotName, &oldTapeLabel);
169                 TLog(taskId,
170                      "This tape %s must be a database tape or NULL tape\n",
171                      gotName);
172
173               getNewTape:
174                 unmountTape(taskId, tapeInfoPtr);
175                 continue;
176             }
177
178             /* Do not overwrite a tape that belongs to this dump */
179             if (oldTapeLabel.dumpid && (oldTapeLabel.dumpid == dumpid)) {
180                 ErrorLog(0, taskId, 0, 0,
181                          "Can't overwrite tape containing the dump in progress\n");
182                 goto getNewTape;
183             }
184
185             /* On first tape, the savedb has not started yet, so the database is not locked
186              * and we can therefore, access information from it. This is easier to do because
187              * database dumps don't have appended dumps (nor appended).
188              */
189             if (sequence == 1) {
190                 afs_uint32 dmp;
191                 struct budb_dumpEntry de, de2;
192
193                 /* Verify the tape has not expired
194                  * Early database dumps don't have a dumpid
195                  */
196                 if (!tapeExpired(&oldTapeLabel)) {
197                     TLog(taskId, "This tape has not expired\n");
198                     goto getNewTape;
199                 }
200
201                 /* Since the dumpset on this tape will be deleted from database, check if
202                  * any of the dumps in this dumpset are most-recent-dumps.
203                  */
204                 for (dmp = oldTapeLabel.dumpid; dmp; dmp = de.appendedDumpID) {
205                     if (dmp == lastDump.id) {
206                         memcpy(&de, &lastDump, sizeof(de));
207                         memcpy(&de2, &lastDump, sizeof(de2));
208                     } else {
209                         code = bcdb_FindDumpByID(dmp, &de);
210                         if (code)
211                             break;
212                         sprintf(strlevel, "%d", de.level);
213                         code =
214                             bcdb_FindLatestDump(de.volumeSetName, strlevel,
215                                                 &de2);
216                         if (code)
217                             continue;
218                     }
219
220                     if (de.id == de2.id) {
221                         if (strcmp(DUMP_TAPE_NAME, de2.name) == 0) {
222                             ErrorLog(0, taskId, 0, 0,
223                                      "Warning: Overwriting most recent dump %s (DumpID %u)\n",
224                                      de.name, de.id);
225                         } else {
226                             ErrorLog(0, taskId, 0, 0,
227                                      "Warning: Overwriting most recent dump of the '%s' volumeset: %s (DumpID %u)\n",
228                                      de.volumeSetName, de.name, de.id);
229                         }
230                     }
231                 }
232             }
233
234             /* Otherwise, the savedb is in progress and we can't
235              * access the database (it's locked). So we rely on the
236              * information available (and not the backup database).
237              */
238             else {
239                 /* Check the tape's expiration date. Use the expiration on the label */
240                 gettimeofday(&tp, NULL);
241                 curTime = tp.tv_sec;
242                 if (curTime < oldTapeLabel.expirationDate) {
243                     TLog(taskId, "This tape has not expired\n");
244                     goto getNewTape;
245                 }
246
247                 /* Check if this previous-dump of the dump-in-progress is on this tape */
248                 if (oldTapeLabel.dumpid
249                     && (oldTapeLabel.dumpid == lastDump.id)) {
250                     ErrorLog(0, taskId, 0, 0,
251                              "Warning: Overwriting most recent dump %s (DumpID %u)\n",
252                              lastDump.name, lastDump.id);
253                 }
254
255             }
256         }
257
258         GetNewLabel(tapeInfoPtr, oldTapeLabel.pName, tapeName, &newLabel);
259         newLabel.expirationDate = expires;
260         newLabel.useCount = oldTapeLabel.useCount + 1;
261         newLabel.dumpid = dumpid;
262         newLabel.size = tapeInfoPtr->tapeSize;
263
264         code = butm_Create(tapeInfoPtr, &newLabel, 1);  /* rewind tape */
265         if (code) {
266             TapeLog(0, taskId, code, tapeInfoPtr->error,
267                     "Can't label tape\n");
268             goto getNewTape;
269         }
270
271         *wroteLabel = 1;
272
273         /* Initialize a tapeEntry for later inclusion into the database */
274         listEntryPtr = calloc(1, sizeof(struct tapeEntryList));
275         if (!listEntryPtr)
276             ERROR_EXIT(TC_NOMEMORY);
277
278         /* Remember dumpid so we can delete it later */
279         if ((oldTapeLabel.structVersion >= TAPE_VERSION_3)
280             && oldTapeLabel.dumpid)
281             listEntryPtr->oldDumpId = oldTapeLabel.dumpid;
282
283         /* Fill in tape entry so we can save it later */
284         strcpy(tapeEntryPtr->name, TNAME(&newLabel));
285         tapeEntryPtr->flags = BUDB_TAPE_BEINGWRITTEN;
286         tapeEntryPtr->written = newLabel.creationTime;
287         tapeEntryPtr->expires = expires;
288         tapeEntryPtr->seq = sequence;
289         tapeEntryPtr->useCount = oldTapeLabel.useCount + 1;
290         tapeEntryPtr->dump = dumpid;
291         tapeEntryPtr->useKBytes = 0;
292         tapeEntryPtr->labelpos = 0;
293
294         /* Thread onto end of single-linked list */
295         if (listEntryHead) {
296             endList = listEntryHead;
297             while (endList->next)
298                 endList = endList->next;
299             endList->next = listEntryPtr;
300         } else
301             listEntryHead = listEntryPtr;
302     }                           /*w */
303
304   error_exit:
305     return (code);
306 }
307
308 /* freeTapeList
309  *       With the list of tapes, free the structures.
310  */
311
312 afs_int32
313 freeTapeList(void)
314 {
315     struct tapeEntryList *next;
316
317     listEntryPtr = listEntryHead;
318     while (listEntryPtr) {
319         next = listEntryPtr->next;
320         free(listEntryPtr);
321         listEntryPtr = next;
322     }
323
324     listEntryHead = NULL;
325     return (0);
326 }
327
328 /* addTapesToDb
329  *       With the list of tapes, add them to the database.
330  *       Also delete any olddumpids that are around.
331  */
332
333 afs_int32
334 addTapesToDb(afs_int32 taskId)
335 {
336     afs_int32 code = 0;
337     afs_int32 i, new;
338     struct tapeEntryList *next;
339
340     listEntryPtr = listEntryHead;
341     while (listEntryPtr) {
342         next = listEntryPtr->next;
343
344         /* Remove the old database entry */
345         if (listEntryPtr->oldDumpId) {
346             i = bcdb_deleteDump(listEntryPtr->oldDumpId, 0, 0, 0);
347             if (i && (i != BUDB_NOENT)) {
348                 ErrorLog(0, taskId, i, 0,
349                          "Unable to delete old DB entry %u.\n",
350                          listEntryPtr->oldDumpId);
351             }
352         }
353
354         /* Add the tape to the database */
355         code = bcdb_UseTape(tapeEntryPtr, &new);
356         if (code) {
357             ErrorLog(0, taskId, code, 0, "Can't add tape to database: %s\n",
358                      tapeEntryPtr->name);
359             ERROR_EXIT(code);
360         }
361
362         code = bcdb_FinishTape(tapeEntryPtr);
363         if (code) {
364             ErrorLog(0, taskId, code, 0, "Can't finish tape: %s\n",
365                      tapeEntryPtr->name);
366             ERROR_EXIT(code);
367         }
368
369         listEntryPtr = next;
370     }
371
372   error_exit:
373     return (code);
374 }
375
376 /* writeDbDump
377  * notes:
378  *      this code assumes that the blocksize on reads is smaller than
379  *      the blocksize on writes
380  */
381
382 static int
383 writeDbDump(struct butm_tapeInfo *tapeInfoPtr, afs_uint32 taskId,
384             Date expires, afs_uint32 dumpid)
385 {
386     afs_int32 blockSize;
387     afs_int32 writeBufNbytes = 0;
388     char *writeBlock = 0;
389     char *writeBuffer = 0;
390     char *writeBufPtr;
391     afs_int32 transferSize;
392
393     char *readBufPtr = NULL;
394     afs_int32 maxReadSize;
395
396     charListT charList;
397     afs_int32 done;
398     afs_int32 code;
399     afs_int32 chunksize = 0;
400     afs_int32 tc_EndMargin, tc_KEndMargin, kRemaining;
401     int sequence;
402     int wroteLabel;
403     int firstcall;
404 #ifdef AFS_PTHREAD_ENV
405     pthread_t alivePid;
406     pthread_attr_t tattr;
407     AFS_SIGSET_DECL;
408 #else
409     PROCESS alivePid;
410 #endif
411
412     extern struct tapeConfig globalTapeConfig;
413     extern struct udbHandleS udbHandle;
414
415     charList.charListT_val = 0;
416     charList.charListT_len = 0;
417     blockSize = BUTM_BLKSIZE;
418     writeBlock = malloc(BUTM_BLOCKSIZE);
419     if (!writeBlock)
420         ERROR_EXIT(TC_NOMEMORY);
421
422     writeBuffer = writeBlock + sizeof(struct blockMark);
423     memset(writeBuffer, 0, BUTM_BLKSIZE);
424     maxReadSize = 1024;
425
426     /*
427      * The margin of space to check for end of tape is set to the
428      * amount of space used to write an end-of-tape multiplied by 2.
429      * The amount of space is size of a 16K EODump marker, its EOF
430      * marker, and up to two EOF markers done on close (1 16K blocks +
431      * 3 EOF * markers).
432      */
433     tc_EndMargin = (16384 + 3 * globalTapeConfig.fileMarkSize) * 2;
434     tc_KEndMargin = tc_EndMargin / 1024;
435
436     /* have to write enclose the dump in file marks */
437     code = butm_WriteFileBegin(tapeInfoPtr);
438     if (code) {
439         ErrorLog(0, taskId, code, tapeInfoPtr->error,
440                  "Can't write FileBegin on tape\n");
441         ERROR_EXIT(code);
442     }
443
444     writeBufPtr = &writeBuffer[0];
445     firstcall = 1;
446     sequence = 1;
447
448     while (1) {                 /*w */
449         /* When no data in buffer, read data from the budb_server */
450         if (charList.charListT_len == 0) {
451             /* get more data. let rx allocate space */
452             if (charList.charListT_val) {
453                 free(charList.charListT_val);
454                 charList.charListT_val = 0;
455             }
456
457             /* get the data */
458             code =
459                 ubik_Call_SingleServer(BUDB_DumpDB, udbHandle.uh_client,
460                                        UF_SINGLESERVER, firstcall,
461                                        maxReadSize, &charList, &done);
462             if (code) {
463                 ErrorLog(0, taskId, code, 0, "Can't read database\n");
464                 ERROR_EXIT(code);
465             }
466
467             /* If this if the first call to the budb server, create a thread
468              * that will keep the connection alive (during tape changes).
469              */
470             if (firstcall) {
471 #ifdef AFS_PTHREAD_ENV
472                 code = pthread_attr_init(&tattr);
473                 if (code) {
474                     ErrorLog(0, taskId, code, 0,
475                              "Can't pthread_attr_init Keep-alive process\n");
476                     ERROR_EXIT(code);
477                 }
478
479                 code =
480                     pthread_attr_setdetachstate(&tattr,
481                                                 PTHREAD_CREATE_DETACHED);
482                 if (code) {
483                     ErrorLog(0, taskId, code, 0,
484                              "Can't pthread_attr_setdetachstate Keep-alive process\n");
485                     ERROR_EXIT(code);
486                 }
487
488                 AFS_SIGSET_CLEAR();
489                 code = pthread_create(&alivePid, &tattr, KeepAlive, 0);
490                 AFS_SIGSET_RESTORE();
491 #else
492                 code =
493                     LWP_CreateProcess(KeepAlive, 16384, 1, NULL,
494                                       "Keep-alive process", &alivePid);
495 #endif
496                 /* XXX should we check code here ??? XXX */
497             }
498             firstcall = 0;
499
500             readBufPtr = charList.charListT_val;
501         }
502
503         if ((charList.charListT_len == 0) && done)
504             break;
505
506         /* compute how many bytes and transfer to the write Buffer */
507         transferSize =
508             (charList.charListT_len <
509              (blockSize -
510               writeBufNbytes)) ? charList.charListT_len : (blockSize -
511                                                            writeBufNbytes);
512
513         memcpy(writeBufPtr, readBufPtr, transferSize);
514         charList.charListT_len -= transferSize;
515         writeBufPtr += transferSize;
516         readBufPtr += transferSize;
517         writeBufNbytes += transferSize;
518
519         /* If filled the write buffer, then write it to tape */
520         if (writeBufNbytes == blockSize) {
521             code = butm_WriteFileData(tapeInfoPtr, writeBuffer, 1, blockSize);
522             if (code) {
523                 ErrorLog(0, taskId, code, tapeInfoPtr->error,
524                          "Can't write data on tape\n");
525                 ERROR_EXIT(code);
526             }
527
528             memset(writeBuffer, 0, blockSize);
529             writeBufPtr = &writeBuffer[0];
530             writeBufNbytes = 0;
531
532             /* Every BIGCHUNK bytes check if aborted */
533             chunksize += blockSize;
534             if (chunksize > BIGCHUNK) {
535                 chunksize = 0;
536                 if (checkAbortByTaskId(taskId))
537                     ERROR_EXIT(TC_ABORTEDBYREQUEST);
538             }
539
540             /*
541              * check if tape is full - since we filled a blockSize worth of data
542              * assume that there is more data.
543              */
544             kRemaining = butm_remainingKSpace(tapeInfoPtr);
545             if (kRemaining < tc_KEndMargin) {
546                 code = butm_WriteFileEnd(tapeInfoPtr);
547                 if (code) {
548                     ErrorLog(0, taskId, code, tapeInfoPtr->error,
549                              "Can't write FileEnd on tape\n");
550                     ERROR_EXIT(code);
551                 }
552
553                 code = butm_WriteEOT(tapeInfoPtr);
554                 if (code) {
555                     ErrorLog(0, taskId, code, tapeInfoPtr->error,
556                              "Can't write end-of-dump on tape\n");
557                     ERROR_EXIT(code);
558                 }
559
560                 /* Mark tape as having been written */
561                 tapeEntryPtr->useKBytes =
562                     tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
563                 tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;
564
565                 unmountTape(taskId, tapeInfoPtr);
566
567                 /* Get next tape and writes its label */
568                 sequence++;
569                 code =
570                     GetDBTape(taskId, expires, tapeInfoPtr, dumpid, sequence,
571                               1, &wroteLabel);
572                 if (code)
573                     ERROR_EXIT(code);
574
575                 code = butm_WriteFileBegin(tapeInfoPtr);
576                 if (code) {
577                     ErrorLog(0, taskId, code, tapeInfoPtr->error,
578                              "Can't write FileBegin on tape\n");
579                     ERROR_EXIT(code);
580                 }
581             }
582         }
583     }                           /*w */
584
585     /* no more data to be read - if necessary, flush out the last buffer */
586     if (writeBufNbytes > 0) {
587         code = butm_WriteFileData(tapeInfoPtr, writeBuffer, 1, blockSize);
588         if (code) {
589             ErrorLog(1, taskId, code, tapeInfoPtr->error,
590                      "Can't write data on tape\n");
591             ERROR_EXIT(code);
592         }
593     }
594
595     code = butm_WriteFileEnd(tapeInfoPtr);
596     if (code) {
597         ErrorLog(0, taskId, code, tapeInfoPtr->error,
598                  "Can't write FileEnd on tape\n");
599         ERROR_EXIT(code);
600     }
601
602     /* Mark tape as having been written */
603     tapeEntryPtr->useKBytes =
604         tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
605     tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;
606
607   error_exit:
608     /* Let the KeepAlive process stop on its own */
609     code =
610         ubik_Call_SingleServer(BUDB_DumpDB, udbHandle.uh_client,
611                                UF_END_SINGLESERVER, 0);
612
613     if (writeBlock)
614         free(writeBlock);
615     if (charList.charListT_val)
616         free(charList.charListT_val);
617     return (code);
618 }
619
620 /* saveDbToTape
621  *      dump backup database to tape
622  */
623
624 void *
625 saveDbToTape(void *param)
626 {
627     struct saveDbIf *saveDbIfPtr = (struct saveDbIf *)param;
628     afs_int32 code;
629     afs_int32 i;
630     int wroteLabel;
631     afs_uint32 taskId;
632     Date expires;
633
634     struct butm_tapeInfo tapeInfo;
635     struct budb_dumpEntry dumpEntry;
636
637     extern struct deviceSyncNode *deviceLatch;
638     extern struct tapeConfig globalTapeConfig;
639
640     afs_pthread_setname_self("Db save");
641     expires = (saveDbIfPtr->archiveTime ? NEVERDATE : 0);
642     taskId = saveDbIfPtr->taskId;
643     dumpEntry.id = 0;
644
645     setStatus(taskId, DRIVE_WAIT);
646     EnterDeviceQueue(deviceLatch);      /* lock tape device */
647     clearStatus(taskId, DRIVE_WAIT);
648
649     printf("\n\n");
650     TLog(taskId, "SaveDb\n");
651
652     tapeInfo.structVersion = BUTM_MAJORVERSION;
653     code = butm_file_Instantiate(&tapeInfo, &globalTapeConfig);
654     if (code) {
655         ErrorLog(0, taskId, code, tapeInfo.error,
656                  "Can't initialize tape module\n");
657         ERROR_EXIT(code);
658     }
659
660     /* Determine what the last database dump was */
661     memset(&lastDump, 0, sizeof(lastDump));
662     code = bcdb_FindLatestDump("", "", &lastDump);
663     if (code) {
664         if (code != BUDB_NODUMPNAME) {
665             ErrorLog(0, taskId, code, 0, "Can't read backup database\n");
666             ERROR_EXIT(code);
667         }
668         memset(&lastDump, 0, sizeof(lastDump));
669     }
670
671     code = CreateDBDump(&dumpEntry);    /* Create a dump for this tape */
672     if (code) {
673         ErrorLog(0, taskId, code, 0, "Can't create dump in database\n");
674         ERROR_EXIT(code);
675     }
676
677
678     listEntryHead = NULL;
679
680     /* Get the tape and write a new label to it */
681     code =
682         GetDBTape(taskId, expires, &tapeInfo, dumpEntry.id, 1, autoQuery,
683                   &wroteLabel);
684
685     /*
686      * If did not write the label, remove created dump
687      * Else if wrote the label, remove old dump from db so it's not saved.
688      */
689     if (!wroteLabel) {
690         i = bcdb_deleteDump(dumpEntry.id, 0, 0, 0);
691         dumpEntry.id = 0;
692         if (i && (i != BUDB_NOENT))
693             ErrorLog(0, taskId, i, 0, "Unable to delete DB entry %u.\n",
694                      dumpEntry.id);
695     } else if (listEntryHead->oldDumpId) {
696         i = bcdb_deleteDump(listEntryHead->oldDumpId, 0, 0, 0);
697         listEntryHead->oldDumpId = 0;
698         if (i && (i != BUDB_NOENT)) {
699             ErrorLog(0, taskId, i, 0, "Unable to delete old DB entry %u.\n",
700                      listEntryHead->oldDumpId);
701             ERROR_EXIT(i);
702         }
703     }
704     if (code)
705         ERROR_EXIT(code);
706
707     TapeLog(1, taskId, 0, 0, "Tape accepted - now dumping database\n");
708
709     /* we have a writable tape */
710     code = writeDbDump(&tapeInfo, taskId, expires, dumpEntry.id);
711     if (code)
712         ERROR_EXIT(code);
713
714     /* Now delete the entries between time 0 and archive-time */
715     if (saveDbIfPtr->archiveTime)
716         code = bcdb_deleteDump(0, 0, saveDbIfPtr->archiveTime, 0);
717
718   error_exit:
719     unmountTape(taskId, &tapeInfo);
720
721     /* Add this dump's tapes to the database and mark it finished */
722     if (dumpEntry.id) {
723         i = addTapesToDb(taskId);
724         if (!code)
725             code = i;
726
727         i = bcdb_FinishDump(&dumpEntry);
728         if (!code)
729             code = i;
730     }
731     freeTapeList();
732
733     if (code == TC_ABORTEDBYREQUEST) {
734         TLog(taskId, "SaveDb: Aborted by request\n");
735         clearStatus(taskId, ABORT_REQUEST);
736         setStatus(taskId, ABORT_DONE);
737     } else if (code) {
738         TapeLog(0, taskId, code, 0, "SaveDb: Finished with errors\n");
739         setStatus(taskId, TASK_ERROR);
740     } else {
741         TLog(taskId, "SaveDb: Finished\n");
742     }
743     setStatus(taskId, TASK_DONE);
744
745     free(saveDbIfPtr);
746     LeaveDeviceQueue(deviceLatch);
747     return (void *)(intptr_t)(code);
748 }
749
750
751 /* makeDbDumpEntry()
752  *      Make a database dump entry given a tape label.
753  */
754
755 afs_int32
756 makeDbDumpEntry(struct budb_tapeEntry *tapeEntPtr,
757                 struct budb_dumpEntry *dumpEntryPtr)
758 {
759     memset(dumpEntryPtr, 0, sizeof(struct budb_dumpEntry));
760
761     dumpEntryPtr->id = tapeEntPtr->dump;
762     dumpEntryPtr->initialDumpID = 0;
763     dumpEntryPtr->parent = 0;
764     dumpEntryPtr->level = 0;
765     dumpEntryPtr->flags = 0;
766
767     strcpy(dumpEntryPtr->volumeSetName, "");
768     strcpy(dumpEntryPtr->dumpPath, "");
769     strcpy(dumpEntryPtr->name, DUMP_TAPE_NAME);
770
771     dumpEntryPtr->created = tapeEntPtr->dump;
772     dumpEntryPtr->incTime = 0;
773     dumpEntryPtr->nVolumes = 0;
774
775     strcpy(dumpEntryPtr->tapes.format, DUMP_TAPE_NAME);
776     strcat(dumpEntryPtr->tapes.format, ".%d");
777     dumpEntryPtr->tapes.b = tapeEntPtr->seq;
778     dumpEntryPtr->tapes.maxTapes = 0;
779     return 0;
780 }
781
782 /* readDbTape
783  *      prompt for a specific database tape
784  */
785
786 afs_int32
787 readDbTape(struct butm_tapeInfo *tapeInfoPtr,
788            struct rstTapeInfo *rstTapeInfoPtr, int query)
789 {
790     afs_int32 code = 0;
791     int interactiveFlag;
792     afs_int32 taskId;
793     struct butm_tapeLabel oldTapeLabel;
794     char AFStapeName[BU_MAXTAPELEN], tapeName[BU_MAXTAPELEN];
795     struct tapeEntryList *endList;
796     int tapecount = 1;
797     struct budb_dumpEntry de;
798     struct budb_tapeEntry te;
799
800     taskId = rstTapeInfoPtr->taskId;
801     interactiveFlag = query;
802
803     /* construct the name of the tape */
804     sprintf(AFStapeName, "%s.%-d", DUMP_TAPE_NAME, rstTapeInfoPtr->tapeSeq);
805     strcpy(tapeName, AFStapeName);
806
807     /* Will prompt for the latest saved database tape, but will accept any one */
808     if (rstTapeInfoPtr->tapeSeq == 1) {
809         code = bcdb_FindLatestDump("", "", &de);
810         if (!code)
811             rstTapeInfoPtr->dumpid = de.id;
812     }
813     if (rstTapeInfoPtr->dumpid) {
814         code =
815             bcdb_FindTapeSeq(rstTapeInfoPtr->dumpid, rstTapeInfoPtr->tapeSeq,
816                              &te);
817         if (!code)
818             strcpy(tapeName, te.name);
819     }
820     code = 0;
821
822     while (1) {                 /*w */
823         if (interactiveFlag) {  /* need a tape to read */
824             code =
825                 PromptForTape(RESTOREDBOPCODE, tapeName,
826                               rstTapeInfoPtr->dumpid, taskId, tapecount);
827             if (code)
828                 ERROR_EXIT(code);
829         }
830         interactiveFlag = 1;
831         tapecount++;
832
833         code = butm_Mount(tapeInfoPtr, tapeName);
834         if (code) {
835             TapeLog(0, taskId, code, tapeInfoPtr->error, "Can't open tape\n");
836             goto getNewTape;
837         }
838
839         code = butm_ReadLabel(tapeInfoPtr, &oldTapeLabel, 1);   /* will rewind the tape */
840         if (code) {
841             TapeLog(0, taskId, code, tapeInfoPtr->error,
842                     "Can't read tape label\n");
843             goto getNewTape;
844         }
845
846         /* Check for name of tape and matching dump id (if applicable). */
847         if ((strcmp(oldTapeLabel.AFSName, AFStapeName) != 0)
848             || ((rstTapeInfoPtr->tapeSeq != 1)
849                 && (oldTapeLabel.dumpid != rstTapeInfoPtr->dumpid))) {
850             char expTape[BU_MAXTAPELEN + 32];
851             char gotTape[BU_MAXTAPELEN + 32];
852
853             TAPENAME(expTape, tapeName, rstTapeInfoPtr->dumpid);
854             TAPENAME(gotTape, oldTapeLabel.AFSName, oldTapeLabel.dumpid);
855
856             TLog(taskId, "Tape label expected %s, label seen %s\n", expTape,
857                  gotTape);
858             goto getNewTape;
859         }
860
861         if (rstTapeInfoPtr->tapeSeq == 1)       /* Remember this dumpId */
862             rstTapeInfoPtr->dumpid = oldTapeLabel.dumpid;
863
864         break;
865
866       getNewTape:
867         unmountTape(taskId, tapeInfoPtr);
868     }                           /*w */
869
870
871     /* Initialize a tapeEntry for later inclusion into the database */
872     listEntryPtr = calloc(1, sizeof(struct tapeEntryList));
873     if (!listEntryPtr)
874         ERROR_EXIT(TC_NOMEMORY);
875
876     /* Fill in tape entry so we can save it later */
877     strcpy(tapeEntryPtr->name, TNAME(&oldTapeLabel));
878     tapeEntryPtr->dump = oldTapeLabel.dumpid;
879     tapeEntryPtr->flags = BUDB_TAPE_BEINGWRITTEN;
880     tapeEntryPtr->written = oldTapeLabel.creationTime;
881     tapeEntryPtr->expires = oldTapeLabel.expirationDate;
882     tapeEntryPtr->seq = extractTapeSeq(oldTapeLabel.AFSName);
883     tapeEntryPtr->useCount = oldTapeLabel.useCount;
884     tapeEntryPtr->useKBytes = 0;
885     tapeEntryPtr->labelpos = 0;
886
887     /* Thread onto end of single-linked list */
888     if (listEntryHead) {
889         endList = listEntryHead;
890         while (endList->next)
891             endList = endList->next;
892         endList->next = listEntryPtr;
893     } else
894         listEntryHead = listEntryPtr;
895
896   error_exit:
897     return (code);
898 }
899
900 static afs_int32 nbytes = 0;    /* # bytes left in buffer */
901 static void
902 initTapeBuffering(void)
903 {
904     nbytes = 0;
905 }
906
907
908 /* restoreDbEntries
909  *      restore all the items on the tape
910  * entry:
911  *      tape positioned after tape label
912  */
913
914 static int
915 restoreDbEntries(struct butm_tapeInfo *tapeInfoPtr,
916                  struct rstTapeInfo *rstTapeInfoPtr)
917 {
918     struct structDumpHeader netItemHeader, hostItemHeader;
919     afs_int32 more = 1;
920     afs_int32 taskId, code = 0;
921     int count = 0;
922
923     taskId = rstTapeInfoPtr->taskId;
924
925     /* clear state for the buffer routine(s) */
926     initTapeBuffering();
927
928     code = butm_ReadFileBegin(tapeInfoPtr);
929     if (code) {
930         ErrorLog(0, taskId, code, tapeInfoPtr->error,
931                  "Can't read FileBegin on tape\n");
932         ERROR_EXIT(code);
933     }
934
935     /* get the first item-header */
936     memset(&netItemHeader, 0, sizeof(netItemHeader));
937     code =
938         getTapeData(tapeInfoPtr, rstTapeInfoPtr, &netItemHeader,
939                     sizeof(netItemHeader));
940     if (code)
941         ERROR_EXIT(code);
942     structDumpHeader_ntoh(&netItemHeader, &hostItemHeader);
943
944     while (more) {
945         switch (hostItemHeader.type) {
946         case SD_DBHEADER:
947             code =
948                 restoreDbHeader(tapeInfoPtr, rstTapeInfoPtr, &hostItemHeader);
949             if (code)
950                 ERROR_EXIT(code);
951             break;
952
953         case SD_DUMP:
954             if (++count > 25) { /*every 25 dumps, wait */
955                 waitDbWatcher();
956                 count = 0;
957             }
958             code =
959                 restoreDbDump(tapeInfoPtr, rstTapeInfoPtr, &hostItemHeader);
960             if (code)
961                 ERROR_EXIT(code);
962             break;
963
964         case SD_TAPE:
965         case SD_VOLUME:
966             ERROR_EXIT(-1);
967             break;
968
969         case SD_TEXT_DUMPSCHEDULE:
970         case SD_TEXT_VOLUMESET:
971         case SD_TEXT_TAPEHOSTS:
972             code = restoreText(tapeInfoPtr, rstTapeInfoPtr, &hostItemHeader);
973             if (code)
974                 ERROR_EXIT(code);
975             break;
976
977         case SD_END:
978             more = 0;
979             break;
980
981         default:
982             TLog(taskId, "Unknown database header type %d\n",
983                  hostItemHeader.type);
984             ERROR_EXIT(-1);
985             break;
986         }
987     }
988
989     code = butm_ReadFileEnd(tapeInfoPtr);
990     if (code) {
991         ErrorLog(0, taskId, code, tapeInfoPtr->error,
992                  "Can't read EOF on tape\n");
993         ERROR_EXIT(code);
994     }
995
996     /* Mark tape as having been written */
997     tapeEntryPtr->useKBytes =
998         tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
999     tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;
1000
1001   error_exit:
1002     return (code);
1003 }
1004
1005 /* restoreDbFromTape
1006  *      restore the backup database from tape.
1007  */
1008
1009 void *
1010 restoreDbFromTape(void *param)
1011 {
1012     afs_uint32 taskId = (intptr_t) param;
1013     afs_int32 code = 0;
1014     afs_int32 i;
1015     struct butm_tapeInfo tapeInfo;
1016     struct rstTapeInfo rstTapeInfo;
1017     struct budb_dumpEntry dumpEntry;
1018
1019     extern struct tapeConfig globalTapeConfig;
1020     extern struct deviceSyncNode *deviceLatch;
1021
1022     afs_pthread_setname_self("Db restore");
1023     setStatus(taskId, DRIVE_WAIT);
1024     EnterDeviceQueue(deviceLatch);      /* lock tape device */
1025     clearStatus(taskId, DRIVE_WAIT);
1026
1027     printf("\n\n");
1028     TLog(taskId, "RestoreDb\n");
1029
1030     tapeInfo.structVersion = BUTM_MAJORVERSION;
1031     code = butm_file_Instantiate(&tapeInfo, &globalTapeConfig);
1032     if (code) {
1033         ErrorLog(0, taskId, code, tapeInfo.error,
1034                  "Can't initialize tape module\n");
1035         ERROR_EXIT(code);
1036     }
1037
1038     listEntryHead = NULL;
1039
1040     rstTapeInfo.taskId = taskId;
1041     rstTapeInfo.tapeSeq = 1;
1042     rstTapeInfo.dumpid = 0;
1043
1044     code = readDbTape(&tapeInfo, &rstTapeInfo, autoQuery);
1045     if (code)
1046         ERROR_EXIT(code);
1047
1048     code = restoreDbEntries(&tapeInfo, &rstTapeInfo);
1049     if (code)
1050         ERROR_EXIT(code);
1051
1052   error_exit:
1053     /* Now put this dump into the database */
1054     /* Make a dump entry from first tape   */
1055     listEntryPtr = listEntryHead;
1056     if (listEntryPtr) {
1057         makeDbDumpEntry(tapeEntryPtr, &dumpEntry);
1058         if (dumpEntry.id != 0) {
1059             i = bcdb_CreateDump(&dumpEntry);
1060             if (i) {
1061                 if (i == BUDB_DUMPIDEXISTS)
1062                     fprintf(stderr,
1063                             "Dump id %d not added to database - already exists\n",
1064                             dumpEntry.id);
1065                 else
1066                     TapeLog(0, taskId, i, 0,
1067                             "Dump id %d not added to database\n",
1068                             dumpEntry.id);
1069             } else {
1070                 i = addTapesToDb(taskId);
1071                 if (!code)
1072                     code = i;
1073
1074                 i = bcdb_FinishDump(&dumpEntry);
1075                 if (!code)
1076                     code = i;
1077             }
1078         }
1079         freeTapeList();
1080     }
1081
1082     unmountTape(taskId, &tapeInfo);
1083     waitDbWatcher();
1084
1085     if (code == TC_ABORTEDBYREQUEST) {
1086         TLog(taskId, "RestoreDb: Aborted by request\n");
1087         clearStatus(taskId, ABORT_REQUEST);
1088         setStatus(taskId, ABORT_DONE);
1089     } else if (code) {
1090         TapeLog(0, taskId, code, 0, "RestoreDb: Finished with errors\n");
1091         setStatus(taskId, TASK_ERROR);
1092     } else {
1093         TLog(taskId, "RestoreDb: Finished\n");
1094     }
1095
1096     LeaveDeviceQueue(deviceLatch);
1097     setStatus(taskId, TASK_DONE);
1098
1099     return (void *)(intptr_t)(code);
1100 }
1101
1102 /* KeepAlive
1103  *
1104  *      While dumping the database, keeps the connection alive.
1105  *      Every 10 seconds, wake up and ask to read 0 bytes of the database.
1106  *      This resets the database's internal timer so that it does not
1107  *      prematuraly quit (on asking for new tapes and such).
1108  *
1109  *      Use the same udbHandle as writeDbDump so we go to the same server.
1110  */
1111 void *
1112 KeepAlive(void *unused)
1113 {
1114     charListT charList;
1115     afs_int32 code;
1116     afs_int32 done;
1117
1118     extern struct udbHandleS udbHandle;
1119
1120     afs_pthread_setname_self("Keep-alive");
1121     while (1) {
1122 #ifdef AFS_PTHREAD_ENV
1123         sleep(5);
1124 #else
1125         IOMGR_Sleep(5);
1126 #endif
1127         charList.charListT_val = 0;
1128         charList.charListT_len = 0;
1129         code =
1130             ubik_Call_SingleServer(BUDB_DumpDB, udbHandle.uh_client,
1131                                    UF_SINGLESERVER, 0, 0, &charList, &done);
1132         if (code || done)
1133             break;
1134     }
1135     return 0;
1136 }
1137
1138
1139 /* restoreDbHeader
1140  *      restore special items in the header
1141  */
1142
1143 int
1144 restoreDbHeader(struct butm_tapeInfo *tapeInfo,
1145                 struct rstTapeInfo *rstTapeInfoPtr,
1146                 struct structDumpHeader *nextHeader)
1147 {
1148     struct structDumpHeader netItemHeader;
1149     struct DbHeader netDbHeader, hostDbHeader;
1150     afs_int32 code = 0;
1151
1152     extern struct udbHandleS udbHandle;
1153
1154     /* Read the database header */
1155     memset(&netDbHeader, 0, sizeof(netDbHeader));
1156     code =
1157         getTapeData(tapeInfo, rstTapeInfoPtr, &netDbHeader,
1158                     sizeof(netDbHeader));
1159     if (code)
1160         ERROR_EXIT(code);
1161     DbHeader_ntoh(&netDbHeader, &hostDbHeader);
1162
1163     /* Add the database header to the database */
1164     code =
1165         ubik_BUDB_RestoreDbHeader(udbHandle.uh_client, 0,
1166                   &hostDbHeader);
1167     if (code) {
1168         ErrorLog(0, rstTapeInfoPtr->taskId, code, 0,
1169                  "Can't restore DB Header\n");
1170         ERROR_EXIT(code);
1171     }
1172
1173     /* get the next item-header */
1174     memset(nextHeader, 0, sizeof(*nextHeader));
1175     code =
1176         getTapeData(tapeInfo, rstTapeInfoPtr, &netItemHeader,
1177                     sizeof(netItemHeader));
1178     if (code)
1179         ERROR_EXIT(code);
1180     structDumpHeader_ntoh(&netItemHeader, nextHeader);
1181
1182   error_exit:
1183     return (code);
1184 }
1185
1186
1187 /* restoreDbDump
1188  *      restore a single dump, including all its tapes and volumes, from
1189  *      the tape.
1190  * entry:
1191  *      nextHeader - ptr to structure for return value
1192  * exit:
1193  *      nextHeader - next structure header from tape
1194  * notes:
1195  *      upon entry, the dump structure header has been read confirming that
1196  *      a database dump tree exists on the tape
1197  */
1198
1199 int
1200 restoreDbDump(struct butm_tapeInfo *tapeInfo,
1201               struct rstTapeInfo *rstTapeInfoPtr,
1202               struct structDumpHeader *nextHeader)
1203 {
1204     struct budb_dumpEntry netDumpEntry, hostDumpEntry;
1205     struct budb_tapeEntry netTapeEntry, hostTapeEntry;
1206     struct budb_volumeEntry netVolumeEntry, hostVolumeEntry;
1207     struct structDumpHeader netItemHeader;
1208     int restoreThisDump = 1;
1209     afs_int32 code = 0;
1210
1211     extern struct udbHandleS udbHandle;
1212
1213     /* read dump entry */
1214     memset(&netDumpEntry, 0, sizeof(netDumpEntry));
1215     code =
1216         getTapeData(tapeInfo, rstTapeInfoPtr, &netDumpEntry,
1217                     sizeof(netDumpEntry));
1218     if (code)
1219         ERROR_EXIT(code);
1220
1221     /* If database tape does not have a dumpid (AFS 3.3) then no initial/appended dumps */
1222     if (rstTapeInfoPtr->dumpid == 0) {
1223         netDumpEntry.initialDumpID = 0;
1224         netDumpEntry.appendedDumpID = 0;
1225     }
1226
1227     dumpEntry_ntoh(&netDumpEntry, &hostDumpEntry);
1228
1229     /* The dump entry for this database tape is incomplete, so don't include it */
1230     if (hostDumpEntry.id == rstTapeInfoPtr->dumpid)
1231         restoreThisDump = 0;
1232
1233     /* add the dump to the database */
1234     if (restoreThisDump) {
1235         code =
1236             threadEntryDir(&hostDumpEntry, sizeof(hostDumpEntry),
1237                            DLQ_USEDUMP);
1238         if (code)
1239             ERROR_EXIT(code);
1240     }
1241
1242     /* get the next item-header */
1243     memset(nextHeader, 0, sizeof(*nextHeader));
1244     code =
1245         getTapeData(tapeInfo, rstTapeInfoPtr, &netItemHeader,
1246                     sizeof(netItemHeader));
1247     if (code)
1248         ERROR_EXIT(code);
1249     structDumpHeader_ntoh(&netItemHeader, nextHeader);
1250
1251     /* Add every tape to the db */
1252     while (nextHeader->type == SD_TAPE) {       /*t */
1253
1254         /* read the tape entry */
1255         memset(&netTapeEntry, 0, sizeof(netTapeEntry));
1256         code =
1257             getTapeData(tapeInfo, rstTapeInfoPtr, &netTapeEntry,
1258                         sizeof(netTapeEntry));
1259         if (code)
1260             ERROR_EXIT(code);
1261         tapeEntry_ntoh(&netTapeEntry, &hostTapeEntry);
1262
1263         /* Add the tape to the database */
1264         if (restoreThisDump) {
1265             code =
1266                 threadEntryDir(&hostTapeEntry, sizeof(hostTapeEntry),
1267                                DLQ_USETAPE);
1268             if (code)
1269                 ERROR_EXIT(code);
1270         }
1271
1272         /* get the next item-header */
1273         memset(nextHeader, 0, sizeof(*nextHeader));
1274         code =
1275             getTapeData(tapeInfo, rstTapeInfoPtr, &netItemHeader,
1276                         sizeof(netItemHeader));
1277         if (code)
1278             ERROR_EXIT(code);
1279         structDumpHeader_ntoh(&netItemHeader, nextHeader);
1280
1281         /* Add every volume to the db */
1282         while (nextHeader->type == SD_VOLUME) { /*v */
1283
1284             /* read the volume entry */
1285             memset(&netVolumeEntry, 0, sizeof(netVolumeEntry));
1286             code =
1287                 getTapeData(tapeInfo, rstTapeInfoPtr, &netVolumeEntry,
1288                             sizeof(netVolumeEntry));
1289             if (code)
1290                 ERROR_EXIT(code);
1291             volumeEntry_ntoh(&netVolumeEntry, &hostVolumeEntry);
1292
1293             if (restoreThisDump) {
1294                 code =
1295                     threadEntryDir(&hostVolumeEntry, sizeof(hostVolumeEntry),
1296                                    DLQ_VOLENTRY);
1297                 if (code)
1298                     ERROR_EXIT(code);
1299             }
1300
1301             /* get the next item-header */
1302             memset(nextHeader, 0, sizeof(*nextHeader));
1303             code =
1304                 getTapeData(tapeInfo, rstTapeInfoPtr, &netItemHeader,
1305                             sizeof(netItemHeader));
1306             if (code)
1307                 ERROR_EXIT(code);
1308             structDumpHeader_ntoh(&netItemHeader, nextHeader);
1309         }                       /*v */
1310
1311         /* Finish the tape */
1312         if (restoreThisDump) {
1313             code =
1314                 threadEntryDir(&hostTapeEntry, sizeof(hostTapeEntry),
1315                                DLQ_FINISHTAPE);
1316             if (code)
1317                 ERROR_EXIT(code);
1318         }
1319     }                           /*t */
1320
1321     /* Finish the dump */
1322     if (restoreThisDump) {
1323         code =
1324             threadEntryDir(&hostDumpEntry, sizeof(hostDumpEntry),
1325                            DLQ_FINISHDUMP);
1326         if (code)
1327             ERROR_EXIT(code);
1328     }
1329
1330   error_exit:
1331     return (code);
1332 }
1333
1334 /* saveTextFile
1335  *      Save the specified file as configuration text in the ubik database.
1336  *      Have to setup the client text structure so that we can call
1337  *      the routine to transmit the text to the db.
1338  */
1339
1340 afs_int32
1341 saveTextFile(afs_int32 taskId, afs_int32 textType, char *fileName)
1342 {
1343     udbClientTextP ctPtr = 0;
1344     afs_int32 code = 0;
1345     int tlock = 0;
1346
1347     ctPtr = calloc(1, sizeof(*ctPtr));
1348     if (!ctPtr)
1349         ERROR_EXIT(TC_NOMEMORY);
1350
1351     ctPtr->textType = textType;
1352
1353     /* lock the text in the database */
1354     code = bc_LockText(ctPtr);
1355     if (code) {
1356         ErrorLog(0, taskId, code, 0, "Can't lock text file\n");
1357         ERROR_EXIT(code);
1358     }
1359     tlock = 1;
1360
1361     ctPtr->textStream = fopen(fileName, "r");
1362     if (!ctPtr->textStream) {
1363         ErrorLog(0, taskId, errno, 0, "Can't open text file\n");
1364         ERROR_EXIT(errno);
1365     }
1366
1367     /* now send the text to the database */
1368     code = bcdb_SaveTextFile(ctPtr);
1369     if (code) {
1370         ErrorLog(0, taskId, code, 0, "Can't save text file\n");
1371         ERROR_EXIT(code);
1372     }
1373
1374   error_exit:
1375     if (ctPtr) {
1376         if (ctPtr->textStream)
1377             fclose(ctPtr->textStream);
1378         if (tlock)
1379             bc_UnlockText(ctPtr);
1380         free(ctPtr);
1381     }
1382     return (code);
1383 }
1384
1385 /* restoreText
1386  *      read the text off the tape, and store it in the appropriate
1387  *      text type in the database.
1388  * entry:
1389  *      nextHeader - ptr to struct for return information
1390  * exit:
1391  *      nextHeader - struct header for next item on the tape
1392  */
1393
1394 int
1395 restoreText(struct butm_tapeInfo *tapeInfo,
1396             struct rstTapeInfo *rstTapeInfoPtr,
1397             struct structDumpHeader *nextHeader)
1398 {
1399     char filename[64];
1400     afs_int32 nbytes;
1401     char *readBuffer = 0;
1402     afs_int32 readBlockSize;
1403     afs_int32 transferSize;
1404     struct structDumpHeader netItemHeader;
1405     int fid = -1;
1406     afs_int32 code = 0;
1407
1408     udbClientTextP ctPtr = 0;
1409     afs_int32 textType;
1410
1411     ctPtr = malloc(sizeof(*ctPtr));
1412     if (!ctPtr)
1413         ERROR_EXIT(TC_NOMEMORY);
1414
1415     /* determine the type of text block */
1416     switch (nextHeader->type) {
1417     case SD_TEXT_DUMPSCHEDULE:
1418         textType = TB_DUMPSCHEDULE;
1419         break;
1420
1421     case SD_TEXT_VOLUMESET:
1422         textType = TB_VOLUMESET;
1423         break;
1424
1425     case SD_TEXT_TAPEHOSTS:
1426         textType = TB_TAPEHOSTS;
1427         break;
1428
1429     default:
1430         ErrorLog(0, rstTapeInfoPtr->taskId, TC_INTERNALERROR, 0,
1431                  "Unknown text block\n");
1432         ERROR_EXIT(TC_INTERNALERROR);
1433         break;
1434     }
1435
1436     /* open the text file */
1437     sprintf(filename, "%s/bu_XXXXXX", gettmpdir());
1438     fid = mkstemp(filename);
1439     if (fid < 0) {
1440         ErrorLog(0, rstTapeInfoPtr->taskId, errno, 0,
1441                  "Can't open temporary text file: %s\n", filename);
1442         ERROR_EXIT(errno);
1443     }
1444
1445     /* allocate buffer for text */
1446     readBlockSize = BUTM_BLKSIZE;
1447     readBuffer = malloc(readBlockSize);
1448     if (!readBuffer)
1449         ERROR_EXIT(TC_NOMEMORY);
1450
1451     /* read the text into the temporary file */
1452     nbytes = nextHeader->size;
1453     while (nbytes > 0) {
1454         transferSize = (readBlockSize < nbytes) ? readBlockSize : nbytes;
1455
1456         /* read it from the tape */
1457         code =
1458             getTapeData(tapeInfo, rstTapeInfoPtr, readBuffer, transferSize);
1459         if (code)
1460             ERROR_EXIT(code);
1461
1462         /* write to the file */
1463         if (write(fid, readBuffer, transferSize) != transferSize) {
1464             ErrorLog(0, rstTapeInfoPtr->taskId, errno, 0,
1465                      "Can't write temporary text file: %s\n", filename);
1466             ERROR_EXIT(errno);
1467         }
1468
1469         nbytes -= transferSize;
1470     }
1471
1472     close(fid);
1473     fid = -1;
1474     code = saveTextFile(rstTapeInfoPtr->taskId, textType, filename);
1475     if (code)
1476         ERROR_EXIT(code);
1477     unlink(filename);
1478
1479     /* get the next item-header */
1480     memset(nextHeader, 0, sizeof(*nextHeader));
1481     code =
1482         getTapeData(tapeInfo, rstTapeInfoPtr, &netItemHeader,
1483                     sizeof(netItemHeader));
1484     if (code)
1485         ERROR_EXIT(code);
1486     structDumpHeader_ntoh(&netItemHeader, nextHeader);
1487
1488   error_exit:
1489     if (ctPtr)
1490         free(ctPtr);
1491     if (readBuffer)
1492         free(readBuffer);
1493     if (fid != -1) {
1494         close(fid);
1495         unlink(filename);
1496     }
1497     return (code);
1498 }
1499
1500
1501 /* ----------------------------------
1502  * Tape data buffering - for reading database dumps
1503  * ----------------------------------
1504  */
1505
1506 static char *tapeReadBuffer = 0;        /* input buffer */
1507 static char *tapeReadBufferPtr = 0;     /* position in buffer */
1508
1509 /* getTapeData
1510  *      Read information from tape, and place the requested number of bytes
1511  *      in the buffer supplied
1512  * entry:
1513  *      tapeInfo
1514  *      rstTapeInfoPtr - Info about the dump being restored.
1515  *      buffer - buffer for requested data
1516  *      requestedBytes - no. of bytes requested
1517  * exit:
1518  *      fn retn - 0, ok, n, error
1519  */
1520
1521 int
1522 getTapeData(struct butm_tapeInfo *tapeInfoPtr,
1523             struct rstTapeInfo *rstTapeInfoPtr,
1524             void *out, afs_int32 requestedBytes)
1525 {
1526     char *buffer = (char *) out;
1527     afs_int32 taskId, transferBytes;
1528     afs_int32 code = 0;
1529
1530     taskId = rstTapeInfoPtr->taskId;
1531
1532     if (checkAbortByTaskId(taskId))
1533         ERROR_EXIT(TC_ABORTEDBYREQUEST);
1534
1535     if (!tapeReadBuffer) {
1536         tapeReadBuffer = malloc(BUTM_BLOCKSIZE);
1537         if (!tapeReadBuffer)
1538             ERROR_EXIT(TC_NOMEMORY);
1539     }
1540
1541     while (requestedBytes > 0) {
1542         if (nbytes == 0) {
1543             tapeReadBufferPtr = &tapeReadBuffer[sizeof(struct blockMark)];
1544
1545             /* get more data */
1546             code =
1547                 butm_ReadFileData(tapeInfoPtr, tapeReadBufferPtr,
1548                                   BUTM_BLKSIZE, &nbytes);
1549             if (code) {
1550                 /* detect if we hit the end-of-tape and get next tape */
1551                 if (code == BUTM_ENDVOLUME) {
1552                     /* Update fields in tape entry for this tape */
1553                     tapeEntryPtr->flags = BUDB_TAPE_WRITTEN;
1554                     tapeEntryPtr->useKBytes =
1555                         tapeInfoPtr->kBytes + (tapeInfoPtr->nBytes ? 1 : 0);
1556
1557                     unmountTape(taskId, tapeInfoPtr);
1558
1559                     rstTapeInfoPtr->tapeSeq++;
1560                     code = readDbTape(tapeInfoPtr, rstTapeInfoPtr, 1);
1561                     if (code)
1562                         ERROR_EXIT(code);
1563
1564                     code = butm_ReadFileBegin(tapeInfoPtr);
1565                     if (code) {
1566                         ErrorLog(0, taskId, code, tapeInfoPtr->error,
1567                                  "Can't read FileBegin on tape\n");
1568                         ERROR_EXIT(code);
1569                     }
1570
1571                     continue;
1572                 }
1573
1574                 ErrorLog(0, taskId, code, tapeInfoPtr->error,
1575                          "Can't read FileData on tape\n");
1576                 ERROR_EXIT(code);
1577             }
1578         }
1579
1580         /* copy out data */
1581         transferBytes = (nbytes < requestedBytes) ? nbytes : requestedBytes;
1582         memcpy(buffer, tapeReadBufferPtr, transferBytes);
1583         tapeReadBufferPtr += transferBytes;
1584         buffer += transferBytes;
1585         nbytes -= transferBytes;
1586         requestedBytes -= transferBytes;
1587     }
1588
1589   error_exit:
1590     return (code);
1591 }