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