openafs-void-star-pointers-20071031
[openafs.git] / src / bucoord / commands.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 RCSID
14     ("$Header$");
15
16 #include <afs/stds.h>
17 #if defined(AFS_LINUX24_ENV)
18 #define _REGEX_RE_COMP
19 #endif
20 #include <sys/types.h>
21 #if defined(AFS_LINUX24_ENV)
22 #include <regex.h>
23 #endif
24 #include <afs/cmd.h>
25 #ifdef AFS_NT40_ENV
26 #include <winsock2.h>
27 #else
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netdb.h>
31 #endif
32 #include <errno.h>
33 #include <afs/com_err.h>
34 #include <afs/budb.h>
35 #include <afs/butc.h>
36 #include <afs/bubasics.h>       /* PA */
37 #include <afs/volser.h>
38 #include <afs/voldefs.h>        /* PA */
39 #include <afs/vldbint.h>        /* PA */
40 #include <afs/ktime.h>          /* PA */
41 #include <time.h>
42
43 #include <lock.h>
44 #include <afs/butc.h>
45 #include <afs/tcdata.h>
46 #include <afs/butx.h>
47 #include "bc.h"
48 #include "error_macros.h"
49
50
51 extern struct bc_config *bc_globalConfig;
52 extern struct bc_dumpSchedule *bc_FindDumpSchedule();
53 extern struct bc_volumeSet *bc_FindVolumeSet(struct bc_config *cfg,
54                                              char *name);
55 extern struct bc_dumpTask bc_dumpTasks[BC_MAXSIMDUMPS];
56 extern struct ubik_client *cstruct;
57 extern int bc_Dumper();         /* function to do dumps */
58 extern int bc_Restorer();       /* function to do restores */
59 extern char *whoami;
60 extern struct ktc_token ttoken;
61 extern char *tailCompPtr();
62 extern statusP createStatusNode();
63
64 char *loadFile;
65 extern afs_int32 lastTaskCode;
66
67 #define HOSTADDR(sockaddr) (sockaddr)->sin_addr.s_addr
68
69 int
70 bc_EvalVolumeSet(aconfig, avs, avols, uclient)
71      struct bc_config *aconfig;
72      register struct bc_volumeSet *avs;
73      struct bc_volumeDump **avols;
74      struct ubik_client *uclient;
75 {                               /*bc_EvalVolumeSet */
76     int code;
77     static afs_int32 use = 2;
78
79     if (use == 2) {             /* Use EvalVolumeSet2() */
80         code = EvalVolumeSet2(aconfig, avs, avols, uclient);
81         if (code == RXGEN_OPCODE)
82             use = 1;
83     }
84     if (use == 1) {             /* Use EvalVolumeSet1() */
85         code = EvalVolumeSet1(aconfig, avs, avols, uclient);
86     }
87     return code;
88 }                               /*bc_EvalVolumeSet */
89
90 struct partitionsort {
91     afs_int32 part;
92     struct bc_volumeDump *vdlist;
93     struct bc_volumeDump *lastvdlist;
94     struct bc_volumeDump *dupvdlist;
95     struct bc_volumeEntry *vole;
96     struct partitionsort *next;
97 };
98 struct serversort {
99     afs_uint32 ipaddr;
100     struct partitionsort *partitions;
101     struct serversort *next;
102 };
103
104 afs_int32
105 getSPEntries(server, partition, serverlist, ss, ps)
106      afs_uint32 server;
107      afs_int32 partition;
108      struct serversort **serverlist, **ss;
109      struct partitionsort **ps;
110 {
111     if (!(*ss) || ((*ss)->ipaddr != server)) {
112         *ps = 0;
113         for ((*ss) = *serverlist; (*ss); *ss = (*ss)->next) {
114             if ((*ss)->ipaddr == server)
115                 break;
116         }
117     }
118     /* No server entry added. Add one */
119     if (!(*ss)) {
120         *ss = (struct serversort *)malloc(sizeof(struct serversort));
121         if (!(*ss)) {
122             afs_com_err(whoami, BC_NOMEM, "");
123             *ss = 0;
124             return (BC_NOMEM);
125         }
126         memset(*ss, 0, sizeof(struct serversort));
127         (*ss)->ipaddr = server;
128         (*ss)->next = *serverlist;
129         *serverlist = *ss;
130     }
131
132
133     if (!(*ps) || ((*ps)->part != partition)) {
134         for (*ps = (*ss)->partitions; *ps; *ps = (*ps)->next) {
135             if ((*ps)->part == partition)
136                 break;
137         }
138     }
139     /* No partition entry added. Add one */
140     if (!(*ps)) {
141         *ps = (struct partitionsort *)malloc(sizeof(struct partitionsort));
142         if (!(*ps)) {
143             afs_com_err(whoami, BC_NOMEM, "");
144             free(*ss);
145             *ps = 0;
146             *ss = 0;
147             return (BC_NOMEM);
148         }
149         memset(*ps, 0, sizeof(struct partitionsort));
150         (*ps)->part = partition;
151         (*ps)->next = (*ss)->partitions;
152         (*ss)->partitions = *ps;
153     }
154     return 0;
155 }
156
157 afs_int32
158 randSPEntries(serverlist, avols)
159      struct serversort *serverlist;
160      struct bc_volumeDump **avols;
161 {
162     struct serversort *ss, **pss;
163     struct partitionsort *ps, **pps;
164     afs_int32 r;
165     afs_int32 scount, pcount;
166
167     *avols = 0;
168
169     /* Seed random number generator */
170     r = time(0) + getpid();
171     srand(r);
172
173     /* Count number of servers, remove one at a time */
174     for (scount = 0, ss = serverlist; ss; ss = ss->next, scount++);
175     for (; scount; scount--) {
176         /* Pick a random server in list and remove it */
177         r = (rand() >> 4) % scount;
178         for (pss = &serverlist, ss = serverlist; r;
179              pss = &ss->next, ss = ss->next, r--);
180         *pss = ss->next;
181
182         /* Count number of partitions, remove one at a time */
183         for (pcount = 0, ps = ss->partitions; ps; ps = ps->next, pcount++);
184         for (; pcount; pcount--) {
185             /* Pick a random parition in list and remove it */
186             r = (rand() >> 4) % pcount;
187             for (pps = &ss->partitions, ps = ss->partitions; r;
188                  pps = &ps->next, ps = ps->next, r--);
189             *pps = ps->next;
190
191             ps->lastvdlist->next = *avols;
192             *avols = ps->vdlist;
193             free(ps);
194         }
195         free(ss);
196     }
197     return 0;
198 }
199
200 int
201 EvalVolumeSet2(aconfig, avs, avols, uclient)
202      struct bc_config *aconfig;
203      struct bc_volumeSet *avs;
204      struct bc_volumeDump **avols;
205      struct ubik_client *uclient;
206 {                               /*EvalVolumeSet2 */
207     struct bc_volumeEntry *tve;
208     struct bc_volumeDump *tavols;
209     struct VldbListByAttributes attributes;
210     afs_int32 si, nsi;          /* startIndex and nextStartIndex */
211     afs_int32 nentries, e, ei, et, add, l;
212     nbulkentries bulkentries;
213     struct nvldbentry *entries = 0;
214     struct bc_volumeDump *tvd;
215     afs_int32 code = 0, tcode;
216     afs_int32 count = 0;
217     struct serversort *servers = 0, *lastserver = 0, *ss = 0;
218     struct partitionsort *ps = 0;
219
220     *avols = (struct bc_volumeDump *)0;
221     bulkentries.nbulkentries_len = 0;
222     bulkentries.nbulkentries_val = 0;
223
224     /* For each of the volume set entries - collect the volumes that match it */
225     for (tve = avs->ventries; tve; tve = tve->next) {
226         /* Put together a call to the vlserver for this vlentry. The 
227          * performance gain is from letting the vlserver expand the
228          * volumeset and not this routine.
229          */
230         attributes.Mask = 0;
231         if (tve->server.sin_addr.s_addr) {      /* The server */
232             attributes.Mask |= VLLIST_SERVER;
233             attributes.server = tve->server.sin_addr.s_addr;
234         }
235         if (tve->partition != -1) {     /* The partition */
236             attributes.Mask |= VLLIST_PARTITION;
237             attributes.partition = tve->partition;
238         }
239
240         /* Now make the call to the vlserver */
241         for (si = 0; si != -1; si = nsi) {
242             nentries = 0;
243             bulkentries.nbulkentries_len = 0;
244             bulkentries.nbulkentries_val = 0;
245             nsi = -1;
246             tcode =
247                 ubik_Call(VL_ListAttributesN2, uclient, 0, &attributes,
248                           tve->name, si, &nentries, &bulkentries, &nsi);
249             if (tcode)
250                 ERROR(tcode);
251
252             /* The 3.4 vlserver has a VL_ListAttributesN2() RPC call, but
253              * it is not complete. The only way to tell if it is not complete
254              * is if et == 0 (which we check for below). Also, if the call didn't
255              * match any entries, then we don't know what version the vlserver
256              * is. In both cases, we return RXGEN_OPCODE and the calling routine
257              * will switch to the EvalVolumeSet1() call.
258              */
259             if (nentries == 0)
260                 ERROR(RXGEN_OPCODE);    /* Use EvalVolumeSet1 */
261
262             /* Step through each entry and add it to the list of volumes */
263             entries = bulkentries.nbulkentries_val;
264             for (e = 0; e < nentries; e++) {
265                 ei = entries[e].matchindex & 0xffff;
266                 et = (entries[e].matchindex >> 16) & 0xffff;
267                 switch (et) {
268                 case ITSRWVOL:{
269                         et = RWVOL;
270                         break;
271                     }
272                 case ITSBACKVOL:{
273                         et = BACKVOL;
274                         break;
275                     }
276                 case ITSROVOL:{
277                         et = ROVOL;
278                         break;
279                     }
280                 default:
281                     ERROR(RXGEN_OPCODE);        /* Use EvalVolumeSet1 */
282                 }
283
284                 /* Find server and partiton structure to hang the entry off of */
285                 tcode =
286                     getSPEntries(entries[e].serverNumber[ei],
287                                  entries[e].serverPartition[ei], &servers,
288                                  &ss, &ps);
289                 if (tcode) {
290                     afs_com_err(whoami, tcode, "");
291                     ERROR(tcode);
292                 }
293
294                 /* Detect if this entry should be added (not a duplicate).
295                  * Use ps->dupvdlist and ps->vole to only search volumes from
296                  * previous volume set entries.
297                  */
298                 add = 1;
299                 if (tve != avs->ventries) {
300                     l = strlen(entries[e].name);
301                     if (ps->vole != tve) {
302                         ps->vole = tve;
303                         ps->dupvdlist = ps->vdlist;
304                     }
305                     for (tavols = ps->dupvdlist; add && tavols;
306                          tavols = tavols->next) {
307                         if (strncmp(tavols->name, entries[e].name, l) == 0) {
308                             if ((strcmp(&entries[e].name[l], ".backup") == 0)
309                                 || (strcmp(&entries[e].name[l], ".readonly")
310                                     == 0)
311                                 || (strcmp(&entries[e].name[l], "") == 0))
312                                 add = 0;
313                         }
314                     }
315                 }
316
317                 if (add) {
318                     /* Allocate a volume dump structure and its name */
319                     tvd = (struct bc_volumeDump *)
320                         malloc(sizeof(struct bc_volumeDump));
321                     if (!tvd) {
322                         afs_com_err(whoami, BC_NOMEM, "");
323                         ERROR(BC_NOMEM);
324                     }
325                     memset(tvd, 0, sizeof(*tvd));
326
327                     tvd->name = (char *)malloc(strlen(entries[e].name) + 10);
328                     if (!(tvd->name)) {
329                         afs_com_err(whoami, BC_NOMEM, "");
330                         free(tvd);
331                         ERROR(BC_NOMEM);
332                     }
333
334                     /* Fill it in and thread onto avols list */
335                     strcpy(tvd->name, entries[e].name);
336                     if (et == BACKVOL)
337                         strcat(tvd->name, ".backup");
338                     else if (et == ROVOL)
339                         strcat(tvd->name, ".readonly");
340                     tvd->vid = entries[e].volumeId[et];
341                     tvd->entry = tve;
342                     tvd->volType = et;
343                     tvd->partition = entries[e].serverPartition[ei];
344                     tvd->server.sin_addr.s_addr = entries[e].serverNumber[ei];
345                     tvd->server.sin_port = 0;   /* default FS port */
346                     tvd->server.sin_family = AF_INET;
347 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
348                     tvd->server.sin_len = sizeof(struct sockaddr_in);
349 #endif
350
351                     /* String tvd off of partition struct */
352                     tvd->next = ps->vdlist;
353                     ps->vdlist = tvd;
354                     if (!tvd->next)
355                         ps->lastvdlist = tvd;
356
357                     count++;
358                 }
359             }
360
361             /* Free memory allocated during VL call */
362             if (bulkentries.nbulkentries_val) {
363                 free((char *)bulkentries.nbulkentries_val);
364                 bulkentries.nbulkentries_val = 0;
365                 entries = 0;
366             }
367         }
368     }
369
370     /* Randomly link the volumedump entries together */
371     randSPEntries(servers, avols);
372     fprintf(stderr, "Total number of volumes : %u\n", count);
373
374   error_exit:
375     if (bulkentries.nbulkentries_val) {
376         free((char *)bulkentries.nbulkentries_val);
377     }
378     return (code);
379 }                               /*EvalVolumeSet2 */
380
381 /*-----------------------------------------------------------------------------
382  * EvalVolumeSetOld
383  *
384  * Description:
385  *      Takes the entries in a volumeset and expands them into a list of 
386  *      volumes. Every VLDB volume entry is looked at and compared to the
387  *      volumeset entries.
388  *
389  *      When matching a VLDB volume entry to a volumeset entry, 
390  *       1. If the RW volume entry matches, that RW volume is used.
391  *       2. Otherwise, if the BK volume entry matches, the BK volume is used.
392  *       3. Finally, if the RO volume entry matches, the RO volume is used.
393  *      For instance: A volumeset entry of ".* .* user.t.*" will match volume 
394  *                    "user.troy" and "user.troy.backup". The rules will use 
395  *                    the RW volume "user.troy".
396  *
397  *      When a VLDB volume entry matches a volumeset entry (be it RW, BK or RO),
398  *      that volume is used and matches against any remaining volumeset entries 
399  *      are not even done.
400  *      For instance: A 1st volumeset entry ".* .* .*.backup" will match with
401  *                    "user.troy.backup". Its 2nd volumeset entry ".* .* .*" 
402  *                    would have matched its RW volume "user.troy", but the first 
403  *                    match is used and the second match isn't even done.
404  *
405  * Arguments:
406  *      aconfig : Global configuration info.
407  *      avs     : 
408  *      avols   : Ptr to linked list of entries describing volumes to dump.
409  *      uclient : Ptr to Ubik client structure.
410  *
411  * Returns:
412  *      0 on successful volume set evaluation,
413  *      Lower-level codes otherwise.
414  *
415  * Environment:
416  *      Expand only the single volume set provided (avs); don't go down its chain.
417  *
418  * Side Effects:
419  *      None.
420  *-----------------------------------------------------------------------------
421  */
422 int
423 EvalVolumeSet1(aconfig, avs, avols, uclient)
424      struct bc_config *aconfig;
425      struct bc_volumeSet *avs;
426      struct bc_volumeDump **avols;
427      struct ubik_client *uclient;
428 {                               /*EvalVolumeSet1 */
429     afs_int32 code;             /*Result of various calls */
430     char *errm;
431     struct bc_volumeDump *tvd;  /*Ptr to new dump instance */
432     struct bc_volumeEntry *tve, *ctve;  /*Ptr to new volume entry instance */
433     char patt[256];             /*Composite regex; also, target string */
434     int volType;                /*Type of volume that worked */
435     afs_int32 index;            /*Current VLDB entry index */
436     afs_int32 count;            /*Needed by VL_ListEntry() */
437     afs_int32 next_index;       /*Next index to list */
438     struct vldbentry entry;     /*VLDB entry */
439     int srvpartpair;            /*Loop counter: server/partition pair */
440     afs_int32 total = 0;
441     int found, foundentry;
442     struct serversort *servers = 0, *ss = 0;
443     struct partitionsort *ps = 0;
444
445     *avols = (struct bc_volumeDump *)0;
446     ctve = (struct bc_volumeEntry *)0;  /* no compiled entry */
447
448     /* For each vldb entry.
449      * Variable next_index is set to the index of the next VLDB entry
450      * in the enumeration.
451      */
452     for (index = 0; 1; index = next_index) {    /*w */
453         memset(&entry, 0, sizeof(entry));
454         code = ubik_Call(VL_ListEntry,  /*Routine to invoke */
455                          uclient,       /*Ubik client structure */
456                          0,     /*Ubik flags */
457                          index, /*Current index */
458                          &count,        /*Ptr to working variable */
459                          &next_index,   /*Ptr to next index value to list */
460                          &entry);       /*Ptr to entry to fill */
461         if (code)
462             return code;
463         if (!next_index)
464             break;              /* If the next index is invalid, bail out now. */
465
466         /* For each entry in the volume set */
467         found = 0;              /* No match in volume set yet */
468         for (tve = avs->ventries; tve; tve = tve->next) {       /*ve */
469             /* for each server in the vldb entry */
470             for (srvpartpair = 0; srvpartpair < entry.nServers; srvpartpair++) {        /*s */
471                 /* On the same server */
472                 if (tve->server.sin_addr.s_addr
473                     && !VLDB_IsSameAddrs(tve->server.sin_addr.s_addr,
474                                          entry.serverNumber[srvpartpair],
475                                          &code)) {
476                     if (code)
477                         return (code);
478                     continue;
479                 }
480
481
482                 /* On the same partition */
483                 if ((tve->partition != -1)
484                     && (tve->partition != entry.serverPartition[srvpartpair]))
485                     continue;
486
487                 /* If the volume entry is not compiled, then compile it */
488                 if (ctve != tve) {
489                     sprintf(patt, "^%s$", tve->name);
490                     errm = (char *)re_comp(patt);
491                     if (errm) {
492                         afs_com_err(whoami, 0,
493                                 "Can't compile regular expression '%s': %s",
494                                 patt, errm);
495                         return (-1);
496                     }
497                     ctve = tve;
498                 }
499
500                 /* If the RW name matches the volume set entry, take
501                  * it and exit. First choice is to use the RW volume.
502                  */
503                 if (entry.serverFlags[srvpartpair] & ITSRWVOL) {
504                     if (entry.flags & RW_EXISTS) {
505                         sprintf(patt, "%s", entry.name);
506                         code = re_exec(patt);
507                         if (code == 1) {
508                             found = 1;
509                             foundentry = srvpartpair;
510                             volType = RWVOL;
511                             break;
512                         }
513                     }
514
515                     /* If the BK name matches the volume set entry, take 
516                      * it and exit. Second choice is to use the BK volume.
517                      */
518                     if (entry.flags & BACK_EXISTS) {
519                         sprintf(patt, "%s.backup", entry.name);
520                         code = re_exec(patt);
521                         if (code == 1) {
522                             found = 1;
523                             foundentry = srvpartpair;
524                             volType = BACKVOL;
525                             break;
526                         }
527                     }
528                 }
529
530                 /* If the RO name matches the volume set entry, remember
531                  * it, but continue searching. Further entries may be
532                  * RW or backup entries that will match.
533                  */
534                 else if (!found && (entry.serverFlags[srvpartpair] & ITSROVOL)
535                          && (entry.flags & RO_EXISTS)) {
536                     sprintf(patt, "%s.readonly", entry.name);
537                     code = re_exec(patt);
538                     if (code == 1) {
539                         found = 1;
540                         foundentry = srvpartpair;
541                         volType = ROVOL;
542                     }
543                 }
544
545                 if (code < 0)
546                     afs_com_err(whoami, 0, "Internal error in regex package");
547             }                   /*s */
548
549             /* If found a match, then create a new volume dump entry */
550             if (found) {        /*f */
551                 /* Find server and partition structure to hang the entry off of */
552                 code =
553                     getSPEntries(entry.serverNumber[foundentry],
554                                  entry.serverPartition[foundentry], &servers,
555                                  &ss, &ps);
556                 if (code) {
557                     afs_com_err(whoami, code, "");
558                     return (code);
559                 }
560
561                 total++;
562                 tvd = (struct bc_volumeDump *)
563                     malloc(sizeof(struct bc_volumeDump));
564                 if (!tvd) {
565                     afs_com_err(whoami, BC_NOMEM, "");
566                     return (BC_NOMEM);
567                 }
568                 memset(tvd, 0, sizeof(*tvd));
569
570                 tvd->name = (char *)malloc(strlen(entry.name) + 10);
571                 if (!(tvd->name)) {
572                     afs_com_err(whoami, BC_NOMEM, "");
573                     free(tvd);
574                     return (BC_NOMEM);
575                 }
576
577                 strcpy(tvd->name, entry.name);
578                 if (volType == BACKVOL)
579                     strcat(tvd->name, ".backup");
580                 else if (volType == ROVOL)
581                     strcat(tvd->name, ".readonly");
582                 tvd->vid = entry.volumeId[volType];
583                 tvd->entry = tve;
584                 tvd->volType = volType;
585                 tvd->partition = entry.serverPartition[foundentry];
586                 tvd->server.sin_addr.s_addr = entry.serverNumber[foundentry];
587                 tvd->server.sin_port = 0;       /* default FS port */
588                 tvd->server.sin_family = AF_INET;
589
590                 /* String tvd off of partition struct */
591                 tvd->next = ps->vdlist;
592                 ps->vdlist = tvd;
593                 if (!tvd->next)
594                     ps->lastvdlist = tvd;
595
596                 break;
597             }                   /*f */
598         }                       /*ve */
599     }                           /*w */
600
601     /* Randomly link the volumedump entries together */
602     randSPEntries(servers, avols);
603
604     fprintf(stderr, "Total number of volumes : %u\n", total);
605     return (0);
606 }                               /*EvalVolumeSet1 */
607
608 /* compactDateString
609  *      print out a date in compact format, 16 chars, format is
610  *      mm/dd/yyyy hh:mm
611  * entry:
612  *      date_long - ptr to a long containing the time
613  * exit:
614  *      ptr to a string containing a representation of the date
615  */
616 char *
617 compactDateString(date_long, string, size)
618      afs_int32 *date_long, size;
619      char *string;
620 {
621     struct tm *ltime;
622
623     if (!string)
624         return 0;
625
626     if (*date_long == NEVERDATE) {
627         sprintf(string, "NEVER");
628     } else {
629         time_t t = *date_long;
630         ltime = localtime(&t);
631         /* prints date in U.S. format of mm/dd/yyyy */
632         strftime(string, size, "%m/%d/%Y %H:%M", ltime);
633     }
634     return (string);
635 }
636
637 afs_int32
638 bc_SafeATOI(anum)
639      char *anum;
640 {
641     afs_int32 total = 0;
642
643     for (; *anum; anum++) {
644         if ((*anum < '0') || (*anum > '9'))
645             return -1;
646         total = (10 * total) + (afs_int32) (*anum - '0');
647     }
648     return total;
649 }
650
651 /* bc_FloatATOI:
652  *    Take a string and parse it for a number (could be float) followed
653  *    by a character representing the units (K,M,G,T). Default is 'K'.
654  *    Return the size in KBytes.
655  */
656 afs_int32
657 bc_FloatATOI(anum)
658      char *anum;
659 {
660     float total = 0;
661     afs_int32 rtotal;
662     afs_int32 fraction = 0;     /* > 0 if past the decimal */
663
664     for (; *anum; anum++) {
665         if ((*anum == 't') || (*anum == 'T')) {
666             total *= 1024 * 1024 * 1024;
667             break;
668         }
669         if ((*anum == 'g') || (*anum == 'G')) {
670             total *= 1024 * 1024;
671             break;
672         }
673         if ((*anum == 'm') || (*anum == 'M')) {
674             total *= 1024;
675             break;
676         }
677         if ((*anum == 'k') || (*anum == 'K')) {
678             break;
679         }
680         if (*anum == '.') {
681             fraction = 10;
682             continue;
683         }
684         if ((*anum < '0') || (*anum > '9'))
685             return -1;
686
687         if (!fraction) {
688             total = (10. * total) + (float)(*anum - '0');
689         } else {
690             total += ((float)(*anum - '0')) / (float)fraction;
691             fraction *= 10;
692         }
693     }
694
695     total += 0.5;               /* Round up */
696     if (total > 0x7fffffff)     /* Don't go over 2G */
697         total = 0x7fffffff;
698     rtotal = (afs_int32) total;
699     return (rtotal);
700 }
701
702 /* make a copy of a string so that it can be freed later */
703 char *
704 bc_CopyString(astring)
705      char *astring;
706 {
707     afs_int32 tlen;
708     char *tp;
709
710     if (!astring)
711         return (NULL);          /* propagate null strings easily */
712     tlen = strlen(astring);
713     tp = (char *)malloc(tlen + 1);      /* don't forget the terminating null */
714     if (!tp) {
715         afs_com_err(whoami, BC_NOMEM, "");
716         return (tp);
717     }
718     strcpy(tp, astring);
719     return tp;
720 }
721
722 /* concatParams
723  * 
724  *    Concatenates the parameters of an option and returns the string.
725  *
726  */
727
728 char *
729 concatParams(itemPtr)
730      struct cmd_item *itemPtr;
731 {
732     struct cmd_item *tempPtr;
733     afs_int32 length = 0;
734     char *string;
735
736     /* compute the length of string required */
737     for (tempPtr = itemPtr; tempPtr; tempPtr = tempPtr->next) {
738         length += strlen(tempPtr->data);
739         length++;               /* space or null terminator */
740     }
741
742     if (length == 0) {          /* no string (0 length) */
743         afs_com_err(whoami, 0, "Can't have zero length date and time string");
744         return (NULL);
745     }
746
747     string = (char *)malloc(length);    /* allocate the string */
748     if (!string) {
749         afs_com_err(whoami, BC_NOMEM, "");
750         return (NULL);
751     }
752     string[0] = 0;
753
754     tempPtr = itemPtr;          /* now assemble the string */
755     while (tempPtr) {
756         strcat(string, tempPtr->data);
757         tempPtr = tempPtr->next;
758         if (tempPtr)
759             strcat(string, " ");
760     }
761
762     return (string);            /* return the string */
763 }
764
765 /* printIfStatus
766  *      print out an interface status node as received from butc
767  */
768
769 printIfStatus(statusPtr)
770      struct tciStatusS *statusPtr;
771 {
772     printf("Task %d: %s: ", statusPtr->taskId, statusPtr->taskName);
773     if (statusPtr->nKBytes)
774         printf("%ld Kbytes transferred", statusPtr->nKBytes);
775     if (strlen(statusPtr->volumeName) != 0) {
776         if (statusPtr->nKBytes)
777             printf(", ");
778         printf("volume %s", statusPtr->volumeName);
779     }
780
781     /* orphan */
782
783     if (statusPtr->flags & ABORT_REQUEST)
784         printf(" [abort request rcvd]");
785
786     if (statusPtr->flags & ABORT_DONE)
787         printf(" [abort complete]");
788
789     if (statusPtr->flags & OPR_WAIT)
790         printf(" [operator wait]");
791
792     if (statusPtr->flags & CALL_WAIT)
793         printf(" [callout in progress]");
794
795     if (statusPtr->flags & DRIVE_WAIT)
796         printf(" [drive wait]");
797
798     if (statusPtr->flags & TASK_DONE)
799         printf(" [done]");
800     printf("\n");
801 }
802
803 afs_int32
804 getPortOffset(port)
805      char *port;
806 {
807     afs_int32 portOffset;
808
809     portOffset = bc_SafeATOI(port);
810
811     if (portOffset < 0) {
812         afs_com_err(whoami, 0, "Can't decode port offset '%s'", port);
813         return (-1);
814     } else if (portOffset > BC_MAXPORTOFFSET) {
815         afs_com_err(whoami, 0, "%u exceeds max port offset %u", portOffset,
816                 BC_MAXPORTOFFSET);
817         return (-1);
818     }
819     return (portOffset);
820 }
821
822 /* bc_GetTapeStatusCmd
823  *      display status of all tasks on a particular tape coordinator
824  */
825 int
826 bc_GetTapeStatusCmd(struct cmd_syndesc *as, void *arock)
827 {
828     afs_int32 code;
829     struct rx_connection *tconn;
830     afs_int32 portOffset = 0;
831
832     int ntasks;
833     afs_uint32 flags;
834     afs_uint32 taskId;
835     struct tciStatusS status;
836
837     code = bc_UpdateHosts();
838     if (code) {
839         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
840         return (code);
841     }
842
843     if (as->parms[0].items) {
844         portOffset = getPortOffset(as->parms[0].items->data);
845         if (portOffset < 0)
846             return (BC_BADARG);
847     }
848
849     code = ConnectButc(bc_globalConfig, portOffset, &tconn);
850     if (code)
851         return (code);
852
853     flags = TSK_STAT_FIRST;
854     taskId = 0;
855     ntasks = 0;
856
857     while ((flags & TSK_STAT_END) == 0) {
858         code = TC_ScanStatus(tconn, &taskId, &status, &flags);
859         if (code) {
860             if (code == TC_NOTASKS)
861                 break;
862             afs_com_err(whoami, code, "; Can't get status from butc");
863             return (-1);
864         }
865         if ((flags & TSK_STAT_NOTFOUND))
866             break;              /* Can't find the task id */
867         flags &= ~TSK_STAT_FIRST;       /* turn off flag */
868
869         printIfStatus(&status);
870         ntasks++;
871     }
872
873     if (ntasks == 0)
874         printf("Tape coordinator is idle\n");
875
876     if (flags & TSK_STAT_ADSM)
877         printf("TSM Tape coordinator\n");
878     else if (flags & TSK_STAT_XBSA)
879         printf("XBSA Tape coordinator\n");
880
881     return (0);
882 }
883
884 extern struct Lock dispatchLock;
885
886 /* bc_WaitForNoJobs
887  *      wait for all jobs to terminate
888  */
889 bc_WaitForNoJobs()
890 {
891     afs_int32 wcode = 0;
892     int i;
893     int waitmsg = 1;
894     int usefulJobRunning = 1;
895
896     extern dlqlinkT statusHead;
897
898     afs_com_err(whoami, 0, "waiting for job termination");
899
900     while (usefulJobRunning) {
901         usefulJobRunning = (dlqEmpty(&statusHead) ? 0 : 1);
902         if (dispatchLock.excl_locked)
903             usefulJobRunning = 1;
904         for (i = 0; (!usefulJobRunning && (i < BC_MAXSIMDUMPS)); i++) {
905             if (bc_dumpTasks[i].flags & BC_DI_INUSE)
906                 usefulJobRunning = 1;
907         }
908
909         /* Wait 5 seconds and check again */
910         if (usefulJobRunning)
911             IOMGR_Sleep(5);
912     }
913     return (lastTaskCode);
914 }
915
916 /* bc_JobsCmd
917  *      print status on running jobs
918  * parameters
919  *      ignored - a null "as" prints only jobs.
920  */
921 int
922 bc_JobsCmd(struct cmd_syndesc *as, void *arock)
923 {
924     afs_int32 prevTime;
925     dlqlinkP ptr;
926     statusP statusPtr;
927     char ds[50];
928
929     statusP youngest;
930     dlqlinkT atJobsHead;
931     extern dlqlinkT statusHead;
932
933     dlqInit(&atJobsHead);
934
935     lock_Status();
936     ptr = (&statusHead)->dlq_next;
937     while (ptr != &statusHead) {
938         statusPtr = (statusP) ptr;
939         ptr = ptr->dlq_next;
940
941         if (statusPtr->scheduledDump) {
942             dlqUnlink((dlqlinkP) statusPtr);
943             dlqLinkb(&atJobsHead, (dlqlinkP) statusPtr);
944         } else {
945             printf("Job %d:", statusPtr->jobNumber);
946
947             printf(" %s", statusPtr->taskName);
948
949             if (statusPtr->dbDumpId)
950                 printf(": DumpID %u", statusPtr->dbDumpId);
951             if (statusPtr->nKBytes)
952                 printf(", %ld Kbytes", statusPtr->nKBytes);
953             if (strlen(statusPtr->volumeName) != 0)
954                 printf(", volume %s", statusPtr->volumeName);
955
956             if (statusPtr->flags & CONTACT_LOST)
957                 printf(" [butc contact lost]");
958
959             if (statusPtr->flags & ABORT_REQUEST)
960                 printf(" [abort request]");
961
962             if (statusPtr->flags & ABORT_SENT)
963                 printf(" [abort sent]");
964
965             if (statusPtr->flags & OPR_WAIT)
966                 printf(" [operator wait]");
967
968             if (statusPtr->flags & CALL_WAIT)
969                 printf(" [callout in progress]");
970
971             if (statusPtr->flags & DRIVE_WAIT)
972                 printf(" [drive wait]");
973             printf("\n");
974         }
975     }
976
977     /* 
978      * Now print the scheduled dumps.
979      */
980     if (!dlqEmpty(&statusHead) && as)
981         printf("\n");           /* blank line between running and scheduled dumps */
982
983     prevTime = 0;
984     while (!dlqEmpty(&atJobsHead)) {
985         ptr = (&atJobsHead)->dlq_next;
986         youngest = (statusP) ptr;
987
988         ptr = ptr->dlq_next;
989         while (ptr != &atJobsHead) {    /* Find the dump that starts the earliest */
990             statusPtr = (statusP) ptr;
991             if (statusPtr->scheduledDump < youngest->scheduledDump)
992                 youngest = statusPtr;
993             ptr = ptr->dlq_next;
994         }
995
996         /* Print token expiration time */
997         if ((ttoken.endTime > prevTime)
998             && (ttoken.endTime <= youngest->scheduledDump) && as
999             && (ttoken.endTime != NEVERDATE)) {
1000             if (ttoken.endTime > time(0)) {
1001                 compactDateString(&ttoken.endTime, ds, 50);
1002                 printf("       %16s: TOKEN EXPIRATION\n", ds);
1003             } else {
1004                 printf("       TOKEN HAS EXPIRED\n");
1005             }
1006         }
1007         prevTime = youngest->scheduledDump;
1008
1009         /* Print the info */
1010         compactDateString(&youngest->scheduledDump, ds, 50);
1011         printf("Job %d:", youngest->jobNumber);
1012         printf(" %16s: %s", ds, youngest->cmdLine);
1013         printf("\n");
1014
1015         /* return to original list */
1016         dlqUnlink((dlqlinkP) youngest);
1017         dlqLinkb(&statusHead, (dlqlinkP) youngest);
1018     }
1019
1020     /* Print token expiration time if havn't already */
1021     if ((ttoken.endTime == NEVERDATE) && as)
1022         printf("     : TOKEN NEVER EXPIRES\n");
1023     else if ((ttoken.endTime > prevTime) && as) {
1024         if (ttoken.endTime > time(0)) {
1025             compactDateString(&ttoken.endTime, ds, 50);
1026             printf("       %16s: TOKEN EXPIRATION\n", ds);
1027         } else {
1028             printf("     : TOKEN HAS EXPIRED\n");
1029         }
1030     }
1031
1032     unlock_Status();
1033     return 0;
1034 }
1035
1036 int
1037 bc_KillCmd(struct cmd_syndesc *as, void *arock)
1038 {
1039     afs_int32 i;
1040     afs_int32 slot;
1041     struct bc_dumpTask *td;
1042     char *tp;
1043     char tbuffer[256];
1044
1045     dlqlinkP ptr;
1046     statusP statusPtr;
1047
1048     extern dlqlinkT statusHead;
1049     extern statusP findStatus();
1050
1051
1052     tp = as->parms[0].items->data;
1053     if (strchr(tp, '.') == 0) {
1054         slot = bc_SafeATOI(tp);
1055         if (slot == -1) {
1056             afs_com_err(whoami, 0, "Bad syntax for number '%s'", tp);
1057             return -1;
1058         }
1059
1060         lock_Status();
1061         ptr = (&statusHead)->dlq_next;
1062         while (ptr != &statusHead) {
1063             statusPtr = (statusP) ptr;
1064             if (statusPtr->jobNumber == slot) {
1065                 statusPtr->flags |= ABORT_REQUEST;
1066                 unlock_Status();
1067                 return (0);
1068             }
1069             ptr = ptr->dlq_next;
1070         }
1071         unlock_Status();
1072
1073         fprintf(stderr, "Job %d not found\n", slot);
1074         return (-1);
1075     } else {
1076         /* vol.dump */
1077         td = bc_dumpTasks;
1078         for (i = 0; i < BC_MAXSIMDUMPS; i++, td++) {
1079             if (td->flags & BC_DI_INUSE) {
1080                 /* compute name */
1081                 strcpy(tbuffer, td->volSetName);
1082                 strcat(tbuffer, ".");
1083                 strcat(tbuffer, tailCompPtr(td->dumpName));
1084                 if (strcmp(tbuffer, tp) == 0)
1085                     break;
1086             }
1087         }
1088         if (i >= BC_MAXSIMDUMPS) {
1089             afs_com_err(whoami, 0, "Can't find job %s", tp);
1090             return -1;
1091         }
1092
1093         lock_Status();
1094         statusPtr = findStatus(td->dumpID);
1095
1096         if (statusPtr == 0) {
1097             afs_com_err(whoami, 0, "Can't locate status - internal error");
1098             unlock_Status();
1099             return (-1);
1100         }
1101         statusPtr->flags |= ABORT_REQUEST;
1102         unlock_Status();
1103         return (0);
1104     }
1105     return 0;
1106 }
1107
1108 /* restore a volume or volumes */
1109 int
1110 bc_VolRestoreCmd(struct cmd_syndesc *as, void *arock)
1111 {
1112     /*
1113      * parm 0 is the new server to restore to
1114      * parm 1 is the new partition to restore to
1115      * parm 2 is volume(s) to restore
1116      * parm 3 is the new extension, if any, for the volume name.
1117      * parm 4 gives the new volume # to restore this volume as (removed).
1118      * parm 4 date is a string representing the date
1119      *
1120      * We handle four types of restores.  If old is set, then we restore the
1121      * volume with the same name and ID.  If old is not set, we allocate
1122      * a new volume ID for the restored volume.  If a new extension is specified,
1123      * we add that extension to the volume name of the restored volume.
1124      */
1125     struct bc_volumeEntry tvolumeEntry; /* entry within the volume set */
1126     struct bc_volumeDump *volsToRestore = (struct bc_volumeDump *)0;
1127     struct bc_volumeDump *lastVol = (struct bc_volumeDump *)0;
1128     struct bc_volumeDump *tvol; /* temp for same */
1129     struct sockaddr_in destServ;        /* machine to which to restore volumes */
1130     afs_int32 destPartition;    /* partition to which to restore volumes */
1131     char *tp;
1132     struct cmd_item *ti;
1133     afs_int32 code;
1134     int oldFlag;
1135     afs_int32 fromDate;
1136     afs_int32 dumpID = 0;
1137     char *newExt, *timeString;
1138     afs_int32 i;
1139     afs_int32 *ports = NULL;
1140     afs_int32 portCount = 0;
1141     int dontExecute;
1142
1143     code = bc_UpdateHosts();
1144     if (code) {
1145         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
1146         return (code);
1147     }
1148
1149     /* specified other destination host */
1150     if (as->parms[0].items) {
1151         tp = as->parms[0].items->data;
1152         if (bc_ParseHost(tp, &destServ)) {
1153             afs_com_err(whoami, 0, "Failed to locate destination host '%s'", tp);
1154             return -1;
1155         }
1156     }
1157
1158     /* specified other destination partition */
1159     if (as->parms[1].items) {
1160         tp = as->parms[1].items->data;
1161         if (bc_GetPartitionID(tp, &destPartition)) {
1162             afs_com_err(whoami, 0, "Can't parse destination partition '%s'", tp);
1163             return -1;
1164         }
1165     }
1166
1167     for (ti = as->parms[2].items; ti; ti = ti->next) {
1168         /* build list of volume items */
1169         tvol = (struct bc_volumeDump *)malloc(sizeof(struct bc_volumeDump));
1170         if (!tvol) {
1171             afs_com_err(whoami, BC_NOMEM, "");
1172             return BC_NOMEM;
1173         }
1174         memset(tvol, 0, sizeof(struct bc_volumeDump));
1175
1176         tvol->name = (char *)malloc(VOLSER_MAXVOLNAME + 1);
1177         if (!tvol->name) {
1178             afs_com_err(whoami, BC_NOMEM, "");
1179             return BC_NOMEM;
1180         }
1181         strncpy(tvol->name, ti->data, VOLSER_OLDMAXVOLNAME);
1182         tvol->entry = &tvolumeEntry;
1183
1184         if (lastVol)
1185             lastVol->next = tvol;       /* thread onto end of list */
1186         else
1187             volsToRestore = tvol;
1188         lastVol = tvol;
1189     }
1190
1191     if (as->parms[4].items) {
1192         timeString = concatParams(as->parms[4].items);
1193         if (!timeString)
1194             return (-1);
1195
1196         code = ktime_DateToLong(timeString, &fromDate);
1197         free(timeString);
1198         if (code) {
1199             afs_com_err(whoami, 0, "Can't parse restore date and time");
1200             afs_com_err(whoami, 0, "%s", ktime_GetDateUsage());
1201             return code;
1202         }
1203     } else {
1204         fromDate = 0x7fffffff;  /* latest one */
1205     }
1206
1207     newExt = (as->parms[3].items ? as->parms[3].items->data : NULL);
1208     oldFlag = 0;
1209
1210     /* Read all the port offsets into the ports array. The first element in the
1211      * array is for full restore and the rest are for incremental restores 
1212      */
1213     if (as->parms[5].items) {
1214         for (ti = as->parms[5].items; ti; ti = ti->next)
1215             portCount++;
1216         ports = (afs_int32 *) malloc(portCount * sizeof(afs_int32));
1217         if (!ports) {
1218             afs_com_err(whoami, BC_NOMEM, "");
1219             return BC_NOMEM;
1220         }
1221
1222         for (ti = as->parms[5].items, i = 0; ti; ti = ti->next, i++) {
1223             ports[i] = getPortOffset(ti->data);
1224             if (ports[i] < 0)
1225                 return (BC_BADARG);
1226         }
1227     }
1228
1229     dontExecute = (as->parms[6].items ? 1 : 0); /* -n */
1230
1231     if (as->parms[7].items)
1232       {
1233         dumpID = atoi(as->parms[7].items->data);
1234         if (dumpID <= 0)
1235           dumpID = 0;
1236       }
1237     
1238     /*
1239      * Perform the call to start the restore.
1240      */
1241     code =
1242         bc_StartDmpRst(bc_globalConfig, "volume", "restore", volsToRestore,
1243                        &destServ, destPartition, fromDate, newExt, oldFlag,
1244                        /*parentDump */ dumpID, /*dumpLevel */ 0,
1245                        bc_Restorer, ports, portCount,
1246                        /*dumpSched */ NULL, /*append */ 0, dontExecute);
1247     if (code)
1248         afs_com_err(whoami, code, "; Failed to queue restore");
1249
1250     return (code);
1251 }
1252
1253 /* restore a whole partition or server */
1254
1255 /* bc_DiskRestoreCmd
1256  *      restore a whole partition
1257  * params:
1258  *      first, reqd - machine (server) to restore
1259  *      second, reqd - partition to restore
1260  *      various optional
1261  */
1262
1263 int
1264 bc_DiskRestoreCmd(struct cmd_syndesc *as, void *arock)
1265 {
1266     struct bc_volumeSet tvolumeSet;     /* temporary volume set for EvalVolumeSet call */
1267     struct bc_volumeEntry tvolumeEntry; /* entry within the volume set */
1268     struct bc_volumeDump *volsToRestore = (struct bc_volumeDump *)0;
1269     struct sockaddr_in destServ;        /* machine to which to restore volumes */
1270     afs_int32 destPartition;    /* partition to which to restore volumes */
1271     char *tp;
1272     afs_int32 code;
1273     int oldFlag;
1274     afs_int32 fromDate;
1275     char *newExt;
1276     afs_int32 *ports = NULL;
1277     afs_int32 portCount = 0;
1278     int dontExecute;
1279     struct bc_volumeDump *prev, *tvol, *nextvol;
1280     struct cmd_item *ti;
1281     afs_int32 i;
1282
1283     /* parm 0 is the server to restore
1284      * parm 1 is the partition to restore
1285      
1286      * parm 8 and above as in VolRestoreCmd:
1287      * parm 8 is the new server to restore to
1288      * parm 9 is the new partition to restore to
1289      */
1290
1291     code = bc_UpdateVolumeSet();
1292     if (code) {
1293         afs_com_err(whoami, code, "; Can't retrieve volume sets");
1294         return (code);
1295     }
1296     code = bc_UpdateHosts();
1297     if (code) {
1298         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
1299         return (code);
1300     }
1301
1302     /* create a volume set corresponding to the volume pattern we've been given */
1303     memset(&tvolumeSet, 0, sizeof(tvolumeSet));
1304     memset(&tvolumeEntry, 0, sizeof(tvolumeEntry));
1305     tvolumeSet.name = "TempVolumeSet";
1306     tvolumeSet.ventries = &tvolumeEntry;
1307     tvolumeEntry.serverName = as->parms[0].items->data;
1308     tvolumeEntry.partname = as->parms[1].items->data;
1309
1310     if (bc_GetPartitionID(tvolumeEntry.partname, &tvolumeEntry.partition)) {
1311         afs_com_err(whoami, 0, "Can't parse partition '%s'",
1312                 tvolumeEntry.partname);
1313         return -1;
1314     }
1315
1316     if (bc_ParseHost(tvolumeEntry.serverName, &tvolumeEntry.server)) {
1317         afs_com_err(whoami, 0, "Can't locate host '%s'", tvolumeEntry.serverName);
1318         return -1;
1319     }
1320
1321     /* specified other destination host */
1322     if (as->parms[8].items) {
1323         tp = as->parms[8].items->data;
1324         if (bc_ParseHost(tp, &destServ)) {
1325             afs_com_err(whoami, 0, "Can't locate destination host '%s'", tp);
1326             return -1;
1327         }
1328     } else                      /* use destination host == original host */
1329         memcpy(&destServ, &tvolumeEntry.server, sizeof(destServ));
1330
1331     /* specified other destination partition */
1332     if (as->parms[9].items) {
1333         tp = as->parms[9].items->data;
1334         if (bc_GetPartitionID(tp, &destPartition)) {
1335             afs_com_err(whoami, 0, "Can't parse destination partition '%s'", tp);
1336             return -1;
1337         }
1338     } else                      /* use original partition */
1339         destPartition = tvolumeEntry.partition;
1340
1341     tvolumeEntry.name = ".*";   /* match all volumes (this should be a parameter) */
1342
1343     if (as->parms[2].items) {
1344         for (ti = as->parms[2].items; ti; ti = ti->next)
1345             portCount++;
1346         ports = (afs_int32 *) malloc(portCount * sizeof(afs_int32));
1347         if (!ports) {
1348             afs_com_err(whoami, BC_NOMEM, "");
1349             return BC_NOMEM;
1350         }
1351
1352         for (ti = as->parms[2].items, i = 0; ti; ti = ti->next, i++) {
1353             ports[i] = getPortOffset(ti->data);
1354             if (ports[i] < 0)
1355                 return (BC_BADARG);
1356         }
1357     }
1358
1359     newExt = (as->parms[10].items ? as->parms[10].items->data : NULL);
1360     dontExecute = (as->parms[11].items ? 1 : 0);        /* -n */
1361
1362     /*
1363      * Expand out the volume set into its component list of volumes, by calling VLDB server.
1364      */
1365     code =
1366         bc_EvalVolumeSet(bc_globalConfig, &tvolumeSet, &volsToRestore,
1367                          cstruct);
1368     if (code) {
1369         afs_com_err(whoami, code, "; Failed to evaluate volume set");
1370         return (-1);
1371     }
1372
1373     /* Since we want only RW volumes, remove any 
1374      * BK or RO volumes from the list.
1375      */
1376     for (prev = 0, tvol = volsToRestore; tvol; tvol = nextvol) {
1377         nextvol = tvol->next;
1378         if (BackupName(tvol->name)) {
1379             if (tvol->name)
1380                 fprintf(stderr,
1381                         "Will not restore volume %s (its RW does not reside on the partition)\n",
1382                         tvol->name);
1383
1384             if (tvol == volsToRestore) {
1385                 volsToRestore = nextvol;
1386             } else {
1387                 prev->next = nextvol;
1388             }
1389             if (tvol->name)
1390                 free(tvol->name);
1391             free(tvol);
1392         } else {
1393             prev = tvol;
1394         }
1395     }
1396
1397     fromDate = 0x7fffffff;      /* last one before this date */
1398     oldFlag = 1;                /* do restore same volid (and name) */
1399
1400     /*
1401      * Perform the call to start the dump.
1402      */
1403     code =
1404         bc_StartDmpRst(bc_globalConfig, "disk", "restore", volsToRestore,
1405                        &destServ, destPartition, fromDate, newExt, oldFlag,
1406                        /*parentDump */ 0, /*dumpLevel */ 0,
1407                        bc_Restorer, ports, portCount,
1408                        /*dumpSched */ NULL, /*append */ 0, dontExecute);
1409     if (code)
1410         afs_com_err(whoami, code, "; Failed to queue restore");
1411
1412     return (code);
1413 }
1414
1415 /* bc_VolsetRestoreCmd
1416  *      restore a volumeset or list of volumes.
1417  */
1418
1419 int
1420 bc_VolsetRestoreCmd(struct cmd_syndesc *as, void *arock)
1421 {
1422     int oldFlag;
1423     long fromDate;
1424     char *newExt;
1425
1426     int dontExecute;
1427     afs_int32 *ports = NULL;
1428     afs_int32 portCount = 0;
1429     afs_int32 code = 0;
1430     afs_int32 portoffset = 0;
1431     char *volsetName;
1432     struct bc_volumeSet *volsetPtr;     /* Ptr to list of generated volume info */
1433     struct bc_volumeDump *volsToRestore = (struct bc_volumeDump *)0;
1434     struct bc_volumeDump *lastVol = (struct bc_volumeDump *)0;
1435     struct sockaddr_in destServer;      /* machine to which to restore volume */
1436     afs_int32 destPartition;    /* partition to which to restore volumes */
1437     struct cmd_item *ti;
1438     afs_int32 i;
1439
1440     code = bc_UpdateVolumeSet();
1441     if (code) {
1442         afs_com_err(whoami, code, "; Can't retrieve volume sets");
1443         return (code);
1444     }
1445     code = bc_UpdateHosts();
1446     if (code) {
1447         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
1448         return (code);
1449     }
1450
1451     if (as->parms[0].items) {
1452         if (as->parms[1].items) {
1453             afs_com_err(whoami, 0, "Can't have both -name and -file options");
1454             return (-1);
1455         }
1456
1457         volsetName = as->parms[0].items->data;
1458         volsetPtr = bc_FindVolumeSet(bc_globalConfig, volsetName);
1459         if (!volsetPtr) {
1460             afs_com_err(whoami, 0,
1461                     "Can't find volume set '%s' in backup database",
1462                     volsetName);
1463             return (-1);
1464         }
1465
1466         /* Expand out the volume set into its component list of volumes. */
1467         code =
1468             bc_EvalVolumeSet(bc_globalConfig, volsetPtr, &volsToRestore,
1469                              cstruct);
1470         if (code) {
1471             afs_com_err(whoami, code, "; Failed to evaluate volume set");
1472             return (-1);
1473         }
1474     } else if (as->parms[1].items) {
1475         FILE *fd;
1476         char line[256];
1477         char server[50], partition[50], volume[50], rest[256];
1478         long count;
1479         struct bc_volumeDump *tvol;
1480
1481         fd = fopen(as->parms[1].items->data, "r");
1482         if (!fd) {
1483             afs_com_err(whoami, errno, "; Cannot open file '%s'",
1484                     as->parms[1].items->data);
1485             return (-1);
1486         }
1487
1488         while (fgets(line, 255, fd)) {
1489             count =
1490                 sscanf(line, "%s %s %s %s", server, partition, volume, rest);
1491
1492             if (count <= 0)
1493                 continue;
1494             if (count < 3) {
1495                 fprintf(stderr,
1496                         "Invalid volumeset file format: Wrong number of arguments: Ignoring\n");
1497                 fprintf(stderr, "     %s", line);
1498                 continue;
1499             }
1500
1501             if (bc_ParseHost(server, &destServer)) {
1502                 afs_com_err(whoami, 0, "Failed to locate host '%s'", server);
1503                 continue;
1504             }
1505
1506             if (bc_GetPartitionID(partition, &destPartition)) {
1507                 afs_com_err(whoami, 0,
1508                         "Failed to parse destination partition '%s'",
1509                         partition);
1510                 continue;
1511             }
1512
1513             /* Allocate a volumeDump structure and link it in */
1514             tvol =
1515                 (struct bc_volumeDump *)malloc(sizeof(struct bc_volumeDump));
1516             memset(tvol, 0, sizeof(struct bc_volumeDump));
1517
1518             tvol->name = (char *)malloc(VOLSER_MAXVOLNAME + 1);
1519             if (!tvol->name) {
1520                 afs_com_err(whoami, BC_NOMEM, "");
1521                 return BC_NOMEM;
1522             }
1523             strncpy(tvol->name, volume, VOLSER_OLDMAXVOLNAME);
1524             memcpy(&tvol->server, &destServer, sizeof(destServer));
1525             tvol->partition = destPartition;
1526
1527             if (lastVol)
1528                 lastVol->next = tvol;   /* thread onto end of list */
1529             else
1530                 volsToRestore = tvol;
1531             lastVol = tvol;
1532         }
1533         fclose(fd);
1534     } else {
1535         afs_com_err(whoami, 0, "-name or -file option required");
1536         return (-1);
1537     }
1538
1539
1540     /* Get the port offset for the restore */
1541     if (as->parms[2].items) {
1542         for (ti = as->parms[2].items; ti; ti = ti->next)
1543             portCount++;
1544         ports = (afs_int32 *) malloc(portCount * sizeof(afs_int32));
1545         if (!ports) {
1546             afs_com_err(whoami, BC_NOMEM, "");
1547             return BC_NOMEM;
1548         }
1549
1550         for (ti = as->parms[2].items, i = 0; ti; ti = ti->next, i++) {
1551             ports[i] = getPortOffset(ti->data);
1552             if (ports[i] < 0)
1553                 return (BC_BADARG);
1554         }
1555     }
1556
1557     newExt = (as->parms[3].items ? as->parms[3].items->data : NULL);
1558     dontExecute = (as->parms[4].items ? 1 : 0);
1559
1560     fromDate = 0x7fffffff;      /* last one before this date */
1561     oldFlag = 1;                /* do restore same volid (and name) */
1562
1563     /* Perform the call to start the restore */
1564     code = bc_StartDmpRst(bc_globalConfig, "disk", "restore", volsToRestore,
1565                           /*destserver */ NULL, /*destpartition */ 0, fromDate,
1566                           newExt, oldFlag,
1567                           /*parentDump */ 0, /*dumpLevel */ 0,
1568                           bc_Restorer, ports, portCount,
1569                           /*dumpSched */ NULL, /*append */ 0, dontExecute);
1570     if (code)
1571         afs_com_err(whoami, code, "; Failed to queue restore");
1572
1573     return code;
1574 }
1575
1576 /*-----------------------------------------------------------------------------
1577  * bc_DumpCmd
1578  *
1579  * Description:
1580  *      Perform a dump of the set of volumes provided.
1581  *      user specifies: -volumeset .. -dump .. [-portoffset ..] [-n]
1582  *
1583  * Arguments:
1584  *      as      : Parsed command line information.
1585  *      arock   : Ptr to misc stuff; not used.
1586  *
1587  * Returns:
1588  *      -1 on errors,
1589  *      The result of bc_StartDump() otherwise
1590  *
1591  * Environment:
1592  *      Nothing special.
1593  *
1594  * Side Effects:
1595  *      As advertised.
1596  *---------------------------------------------------------------------------
1597  */
1598 int dontExecute;
1599
1600 int
1601 bc_DumpCmd(struct cmd_syndesc *as, void *arock)
1602 {                               /*bc_DumpCmd */
1603     static char rn[] = "bc_DumpCmd";    /*Routine name */
1604     char *dumpPath, *vsName;    /*Ptrs to various names */
1605     struct bc_volumeSet *tvs;   /*Ptr to list of generated volume info */
1606     struct bc_dumpSchedule *tds, *baseds;       /*Ptr to dump schedule node */
1607     struct bc_volumeDump *tve, *volsToDump;     /*Ptr to individual vols to be dumped */
1608     struct budb_dumpEntry dumpEntry, de, fde;   /* dump entry */
1609     afs_uint32 d;
1610
1611     afs_int32 parent;           /* parent dump */
1612     afs_int32 level;            /* this dump's level # */
1613     afs_int32 problemFindingDump;       /* can't find parent(s) */
1614
1615     afs_int32 *portp = NULL;
1616     afs_int32 portCount = 0;
1617     afs_int32 doAt, atTime;     /* Time a timed-dump is to start at */
1618     afs_int32 length;
1619     char *timeString;
1620     int doAppend;               /* Append the dump to dump set */
1621     afs_int32 code;             /* Return code */
1622     int loadfile;               /* whether to load a file or not */
1623
1624     statusP statusPtr;
1625
1626     extern struct bc_dumpTask bc_dumpTasks[];
1627     extern afs_int32 bcdb_FindLastVolClone();
1628     extern afs_int32 volImageTime();
1629
1630     code = bc_UpdateDumpSchedule();
1631     if (code) {
1632         afs_com_err(whoami, code, "; Can't retrieve dump schedule");
1633         return (code);
1634     }
1635     code = bc_UpdateVolumeSet();
1636     if (code) {
1637         afs_com_err(whoami, code, "; Can't retrieve volume sets");
1638         return (code);
1639     }
1640     code = bc_UpdateHosts();
1641     if (code) {
1642         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
1643         return (code);
1644     }
1645
1646     /* 
1647      * Some parameters cannot be specified together
1648      * The "-file" option cannot exist with the "-volume", "-dump", 
1649      * "-portoffset", or "-append" option 
1650      */
1651     if (as->parms[6].items) {
1652         loadfile = 1;
1653         if (as->parms[0].items || as->parms[1].items || as->parms[2].items
1654             || as->parms[4].items) {
1655             afs_com_err(whoami, 0, "Invalid option specified with -file option");
1656             return -1;
1657         }
1658     } else {
1659         loadfile = 0;
1660         if (!as->parms[0].items || !as->parms[1].items) {
1661             afs_com_err(whoami, 0,
1662                     "Must specify volume set name and dump level name");
1663             return -1;
1664         }
1665     }
1666
1667     /* 
1668      * Get the time we are to perform this dump
1669      */
1670     if (as->parms[3].items) {
1671         doAt = 1;
1672
1673         timeString = concatParams(as->parms[3].items);
1674         if (!timeString)
1675             return (-1);
1676
1677         /*
1678          * Now parse this string for the time to start.
1679          */
1680         code = ktime_DateToLong(timeString, &atTime);
1681         free(timeString);
1682         if (code) {
1683             afs_com_err(whoami, 0, "Can't parse dump start date and time");
1684             afs_com_err(whoami, 0, "%s", ktime_GetDateUsage());
1685             return (1);
1686         }
1687     } else
1688         doAt = 0;
1689
1690     dontExecute = (as->parms[5].items ? 1 : 0); /* -n */
1691
1692     /* 
1693      * If this dump is not a load file, then check the parameters.
1694      */
1695     if (!loadfile) {            /*6 */
1696         vsName = as->parms[0].items->data;      /* get volume set name */
1697         dumpPath = as->parms[1].items->data;    /* get dump path */
1698
1699         /* get the port number, if one was specified */
1700         if (as->parms[2].items) {
1701             portCount = 1;
1702             portp = (afs_int32 *) malloc(sizeof(afs_int32));
1703             if (!portp) {
1704                 afs_com_err(whoami, BC_NOMEM, "");
1705                 return BC_NOMEM;
1706             }
1707
1708             *portp = getPortOffset(as->parms[2].items->data);
1709             if (*portp < 0)
1710                 return (BC_BADARG);
1711         }
1712
1713         doAppend = (as->parms[4].items ? 1 : 0);        /* -append */
1714
1715         /*
1716          * Get a hold of the given volume set and dump set.
1717          */
1718         tvs = bc_FindVolumeSet(bc_globalConfig, vsName);
1719         if (!tvs) {
1720             afs_com_err(whoami, 0,
1721                     "Can't find volume set '%s' in backup database", vsName);
1722             return (-1);
1723         }
1724         baseds = bc_FindDumpSchedule(bc_globalConfig, dumpPath);
1725         if (!baseds) {
1726             afs_com_err(whoami, 0,
1727                     "Can't find dump schedule '%s' in backup database",
1728                     dumpPath);
1729             return (-1);
1730         }
1731
1732     }
1733
1734     /*6 */
1735     /*
1736      * If given the "-at" option, then add this to the jobs list and return 
1737      * with no error.
1738      *
1739      * Create a status node for this timed dump.
1740      * Fill in the time to dump and the cmd line for the dump leaving off
1741      * the -at option.  If the -n option is there, it is scheduled with 
1742      * the Timed dump as opposed to not scheduling the time dump at all.
1743      */
1744     if (doAt) {
1745         if (atTime < time(0)) {
1746             afs_com_err(whoami, 0,
1747                     "Time of dump is earlier then current time - not added");
1748         } else {
1749             statusPtr = createStatusNode();
1750             lock_Status();
1751             statusPtr->scheduledDump = atTime;
1752
1753             /* Determine length of the dump command */
1754             length = 0;
1755             length += 4;        /* "dump" */
1756             if (loadfile) {
1757                 length += 6;    /* " -file" */
1758                 length += 1 + strlen(as->parms[6].items->data); /* " <file>" */
1759             } else {
1760                 /* length += 11; *//* " -volumeset" */
1761                 length += 1 + strlen(as->parms[0].items->data); /* " <volset> */
1762
1763                 /* length += 6; *//* " -dump" */
1764                 length += 1 + strlen(as->parms[1].items->data); /* " <dumpset> */
1765
1766                 if (as->parms[2].items) {
1767                     /* length += 12; *//* " -portoffset" */
1768                     length += 1 + strlen(as->parms[2].items->data);     /* " <port>" */
1769                 }
1770
1771                 if (as->parms[4].items)
1772                     length += 8;        /* " -append" */
1773             }
1774
1775             if (dontExecute)
1776                 length += 3;    /* " -n" */
1777             length++;           /* end-of-line */
1778
1779             /* Allocate status block for this timed dump */
1780             sprintf(statusPtr->taskName, "Scheduled Dump");
1781             statusPtr->jobNumber = bc_jobNumber();
1782             statusPtr->scheduledDump = atTime;
1783             statusPtr->cmdLine = (char *)malloc(length);
1784             if (!statusPtr->cmdLine) {
1785                 afs_com_err(whoami, BC_NOMEM, "");
1786                 return BC_NOMEM;
1787             }
1788
1789             /* Now reconstruct the dump command */
1790             statusPtr->cmdLine[0] = 0;
1791             strcat(statusPtr->cmdLine, "dump");
1792             if (loadfile) {
1793                 strcat(statusPtr->cmdLine, " -file");
1794                 strcat(statusPtr->cmdLine, " ");
1795                 strcat(statusPtr->cmdLine, as->parms[6].items->data);
1796             } else {
1797                 /* strcat(statusPtr->cmdLine, " -volumeset"); */
1798                 strcat(statusPtr->cmdLine, " ");
1799                 strcat(statusPtr->cmdLine, as->parms[0].items->data);
1800
1801                 /* strcat(statusPtr->cmdLine, " -dump"); */
1802                 strcat(statusPtr->cmdLine, " ");
1803                 strcat(statusPtr->cmdLine, as->parms[1].items->data);
1804
1805                 if (as->parms[2].items) {
1806                     /* strcat(statusPtr->cmdLine, " -portoffset"); */
1807                     strcat(statusPtr->cmdLine, " ");
1808                     strcat(statusPtr->cmdLine, as->parms[2].items->data);
1809                 }
1810
1811                 if (as->parms[4].items)
1812                     strcat(statusPtr->cmdLine, " -append");
1813             }
1814             if (dontExecute)
1815                 strcat(statusPtr->cmdLine, " -n");
1816
1817             printf("Add scheduled dump as job %d\n", statusPtr->jobNumber);
1818             if ((atTime > ttoken.endTime) && (ttoken.endTime != NEVERDATE))
1819                 afs_com_err(whoami, 0,
1820                         "Warning: job %d starts after expiration of AFS token",
1821                         statusPtr->jobNumber);
1822
1823             unlock_Status();
1824         }
1825
1826         return (0);
1827     }
1828
1829     /* 
1830      * Read and execute the load file if specified.  The work of reading is done
1831      * in the main routine prior the dispatch call. loadFile and dontExecute are
1832      * global variables so this can take place in main.
1833      */
1834     if (loadfile) {
1835         loadFile = (char *)malloc(strlen(as->parms[6].items->data) + 1);
1836         if (!loadFile) {
1837             afs_com_err(whoami, BC_NOMEM, "");
1838             return BC_NOMEM;
1839         }
1840         strcpy(loadFile, as->parms[6].items->data);
1841         return 0;
1842     }
1843
1844     /* 
1845      * We are doing a real dump (no load file or timed dump).
1846      */
1847     printf("Starting dump of volume set '%s' (dump level '%s')\n", vsName,
1848            dumpPath);
1849
1850     /* For each dump-level above this one, see if the volumeset was dumped
1851      * at the level. We search all dump-levels since a higher dump-level
1852      * may have actually been done AFTER a lower dump level.
1853      */
1854     parent = level = problemFindingDump = 0;
1855     for (tds = baseds->parent; tds; tds = tds->parent) {
1856         /* Find the most recent dump of the volume-set at this dump-level.
1857          * Raise problem flag if didn't find a dump and a parent not yet found.
1858          */
1859         code = bcdb_FindLatestDump(vsName, tds->name, &dumpEntry);
1860         if (code) {
1861             if (!parent)
1862                 problemFindingDump = 1; /* skipping a dump level */
1863             continue;
1864         }
1865
1866         /* We found the most recent dump at this level. Now check
1867          * if we should use it by seeing if its full dump hierarchy 
1868          * exists. If it doesn't, we don't want to base our incremental
1869          * off of this dump. 
1870          */
1871         if (!parent || (dumpEntry.id > parent)) {
1872             /* Follow the parent dumps to see if they are all there */
1873             for (d = dumpEntry.parent; d; d = de.parent) {
1874                 code = bcdb_FindDumpByID(d, &de);
1875                 if (code)
1876                     break;
1877             }
1878
1879             /* If we found the entire level, remember it. Otherwise raise flag.
1880              * If we had already found a dump, raise the problem flag.
1881              */
1882             if (!d && !code) {
1883                 if (parent)
1884                     problemFindingDump = 1;
1885                 parent = dumpEntry.id;
1886                 level = dumpEntry.level + 1;
1887                 memcpy(&fde, &dumpEntry, sizeof(dumpEntry));
1888             } else {
1889                 /* Dump hierarchy not complete so can't base off the latest */
1890                 problemFindingDump = 1;
1891             }
1892         }
1893     }
1894
1895     /* If the problemflag was raise, it means we are not doing the 
1896      * dump at the level we requested it be done at.
1897      */
1898     if (problemFindingDump) {
1899         afs_com_err(whoami, 0,
1900                 "Warning: Doing level %d dump due to missing higher-level dumps",
1901                 level);
1902         if (parent) {
1903             printf("Parent dump: dump %s (DumpID %u)\n", fde.name, parent);
1904         }
1905     } else if (parent) {
1906         printf("Found parent: dump %s (DumpID %u)\n", fde.name, parent);
1907     }
1908
1909     /* Expand out the volume set into its component list of volumes. */
1910     code = bc_EvalVolumeSet(bc_globalConfig, tvs, &volsToDump, cstruct);
1911     if (code) {
1912         afs_com_err(whoami, code, "; Failed to evaluate volume set");
1913         return (-1);
1914     }
1915     if (!volsToDump) {
1916         printf("No volumes to dump\n");
1917         return (0);
1918     }
1919
1920     /* Determine what the clone time of the volume was when it was
1921      * last dumped (tve->date). This is the time from when an
1922      * incremental should be done (remains zero if a full dump).
1923      */
1924     if (parent) {
1925         for (tve = volsToDump; tve; tve = tve->next) {
1926             code = bcdb_FindClone(parent, tve->name, &tve->date);
1927             if (code)
1928                 tve->date = 0;
1929
1930             /* Get the time the volume was last cloned and see if the volume has
1931              * changed since then. Only do this when the "-n" flag is specified
1932              * because butc will get the cloneDate at time of dump.
1933              */
1934             if (dontExecute) {
1935                 code =
1936                     volImageTime(tve->server.sin_addr.s_addr, tve->partition,
1937                                  tve->vid, tve->volType, &tve->cloneDate);
1938                 if (code)
1939                     tve->cloneDate = 0;
1940
1941                 if (tve->cloneDate && (tve->cloneDate == tve->date)) {
1942                     afs_com_err(whoami, 0,
1943                             "Warning: Timestamp on volume %s unchanged from previous dump",
1944                             tve->name);
1945                 }
1946             }
1947         }
1948     }
1949
1950     if (dontExecute)
1951         printf("Would have dumped the following volumes:\n");
1952     else
1953         printf("Preparing to dump the following volumes:\n");
1954     for (tve = volsToDump; tve; tve = tve->next) {
1955         printf("\t%s (%u)\n", tve->name, tve->vid);
1956     }
1957     if (dontExecute)
1958         return (0);
1959
1960     code = bc_StartDmpRst(bc_globalConfig, dumpPath, vsName, volsToDump,
1961                           /*destServer */ NULL, /*destPartition */ 0,
1962                           /*fromDate */ 0,
1963                           /*newExt */ NULL, /*oldFlag */ 0,
1964                           parent, level, bc_Dumper, portp, /*portCount */ 1,
1965                           baseds, doAppend, dontExecute);
1966     if (code)
1967         afs_com_err(whoami, code, "; Failed to queue dump");
1968
1969     return (code);
1970 }                               /*bc_DumpCmd */
1971
1972
1973 /* bc_QuitCmd
1974  *      terminate the backup process. Insists that that all running backup
1975  *      jobs be terminated before it will quit
1976  * parameters:
1977  *      ignored
1978  */
1979 int
1980 bc_QuitCmd(struct cmd_syndesc *as, void *arock)
1981 {
1982     int i;
1983     struct bc_dumpTask *td;
1984     extern dlqlinkT statusHead;
1985     dlqlinkP ptr;
1986     statusP statusPtr;
1987
1988     /* Check the status list for outstanding jobs */
1989     lock_Status();
1990     for (ptr = (&statusHead)->dlq_next; ptr != &statusHead;
1991          ptr = ptr->dlq_next) {
1992         statusPtr = (statusP) ptr;
1993         if (!(statusPtr->flags & ABORT_REQUEST)) {
1994             unlock_Status();
1995             afs_com_err(whoami, 0, "Job %d still running (and not aborted)",
1996                     statusPtr->jobNumber);
1997             afs_com_err(whoami, 0,
1998                     "You must at least 'kill' all running jobs before quitting");
1999             return -1;
2000         }
2001     }
2002     unlock_Status();
2003
2004     /* A job still being initialized (but no status structure or job number since it
2005      * has not been handed to a butc process yet)
2006      */
2007     for (td = bc_dumpTasks, i = 0; i < BC_MAXSIMDUMPS; i++, td++) {
2008         if (td->flags & BC_DI_INUSE) {
2009             afs_com_err(whoami, 0, "A job is still running");
2010             afs_com_err(whoami, 0,
2011                     "You must at least 'kill' all running jobs before quitting");
2012             return -1;
2013         }
2014     }
2015
2016 #ifdef AFS_NT40_ENV
2017     /* close the all temp text files before quitting */
2018     for (i = 0; i < TB_NUM; i++)
2019         bc_closeTextFile(&bc_globalConfig->configText[i],
2020                          &bc_globalConfig->tmpTextFileNames[i][0]);
2021 #endif
2022     exit(lastTaskCode);
2023 }
2024
2025 /* bc_LabelTapeCmd
2026  *      Labels a tape i.e. request the tape coordinator to perform this
2027  *      operation
2028  */
2029 int
2030 bc_LabelTapeCmd(struct cmd_syndesc *as, void *arock)
2031 {
2032     char *tapename = 0, *pname = 0;
2033     afs_int32 size;
2034     afs_int32 code;
2035     afs_int32 port = 0;
2036
2037     code = bc_UpdateHosts();
2038     if (code) {
2039         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
2040         return (code);
2041     }
2042
2043     if (as->parms[0].items) {   /* -name */
2044         tapename = as->parms[0].items->data;
2045         if (strlen(tapename) >= TC_MAXTAPELEN) {
2046             afs_com_err(whoami, 0, "AFS tape name '%s' is too long", tapename);
2047             return -1;
2048         }
2049     }
2050
2051     if (as->parms[3].items) {   /* -pname */
2052         if (tapename) {
2053             afs_com_err(whoami, 0, "Can only specify -name or -pname");
2054             return -1;
2055         }
2056         pname = as->parms[3].items->data;
2057         if (strlen(pname) >= TC_MAXTAPELEN) {
2058             afs_com_err(whoami, 0, "Permanent tape name '%s' is too long", pname);
2059             return -1;
2060         }
2061     }
2062
2063     if (as->parms[1].items) {
2064         size = bc_FloatATOI(as->parms[1].items->data);
2065         if (size == -1) {
2066             afs_com_err(whoami, 0, "Bad syntax for tape size '%s'",
2067                     as->parms[1].items->data);
2068             return -1;
2069         }
2070     } else
2071         size = 0;
2072
2073     if (as->parms[2].items) {
2074         port = getPortOffset(as->parms[2].items->data);
2075         if (port < 0)
2076             return (BC_BADARG);
2077     }
2078
2079     code = bc_LabelTape(tapename, pname, size, bc_globalConfig, port);
2080     if (code)
2081         return code;
2082     return 0;
2083 }
2084
2085 /* bc_ReadLabelCmd
2086  *      read the label on a tape
2087  * params:
2088  *      optional port number
2089  */
2090 int
2091 bc_ReadLabelCmd(struct cmd_syndesc *as, void *arock)
2092 {
2093     afs_int32 code;
2094     afs_int32 port = 0;
2095
2096     code = bc_UpdateHosts();
2097     if (code) {
2098         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
2099         return (code);
2100     }
2101
2102     if (as->parms[0].items) {
2103         port = getPortOffset(as->parms[0].items->data);
2104         if (port < 0)
2105             return (BC_BADARG);
2106     }
2107
2108     code = bc_ReadLabel(bc_globalConfig, port);
2109     if (code)
2110         return code;
2111     return 0;
2112 }
2113
2114 /* bc_ScanDumpsCmd
2115  *      read content information from dump tapes, and if user desires,
2116  *      add it to the database
2117  */
2118 int
2119 bc_ScanDumpsCmd(struct cmd_syndesc *as, void *arock)
2120 {
2121     afs_int32 port = 0;
2122     afs_int32 dbAddFlag = 0;
2123     afs_int32 code;
2124
2125     code = bc_UpdateHosts();
2126     if (code) {
2127         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
2128         return (code);
2129     }
2130
2131     /* check for flag */
2132     if (as->parms[0].items != 0) {      /* add scan to database */
2133         dbAddFlag++;
2134     }
2135
2136     /* check for port */
2137     if (as->parms[1].items) {
2138         port = getPortOffset(as->parms[1].items->data);
2139         if (port < 0)
2140             return (BC_BADARG);
2141     }
2142
2143     code = bc_ScanDumps(bc_globalConfig, dbAddFlag, port);
2144     return (code);
2145 }
2146
2147 /* bc_ParseExpiration
2148  *
2149  * Notes:
2150  *      dates are specified as absolute or relative, the syntax is:
2151  *      absolute:       at %d/%d/%d [%d:%d]     where [..] is optional
2152  *      relative:       in [%dy][%dm][%dd]      where at least one component
2153  *                                              must be specified
2154  */
2155
2156 afs_int32
2157 bc_ParseExpiration(paramPtr, expType, expDate)
2158      struct cmd_parmdesc *paramPtr;
2159      afs_int32 *expType;
2160      afs_int32 *expDate;
2161 {
2162     struct cmd_item *itemPtr;
2163     struct ktime_date kt;
2164     char *dateString = 0;
2165     afs_int32 code = 0;
2166
2167     *expType = BC_NO_EXPDATE;
2168     *expDate = 0;
2169
2170     if (!paramPtr->items)
2171         ERROR(0);               /* no expiration specified */
2172
2173     /* some form of expiration date specified. First validate the prefix */
2174     itemPtr = paramPtr->items;
2175
2176     if (strcmp(itemPtr->data, "at") == 0) {
2177         *expType = BC_ABS_EXPDATE;
2178
2179         dateString = concatParams(itemPtr->next);
2180         if (!dateString)
2181             ERROR(1);
2182
2183         code = ktime_DateToLong(dateString, expDate);
2184         if (code)
2185             ERROR(1);
2186     } else if (strcmp(itemPtr->data, "in") == 0) {
2187         *expType = BC_REL_EXPDATE;
2188
2189         dateString = concatParams(itemPtr->next);
2190         if (!dateString)
2191             ERROR(1);
2192
2193         code = ParseRelDate(dateString, &kt);
2194         if (code)
2195             ERROR(1);
2196         *expDate = ktimeRelDate_ToLong(&kt);
2197     } else {
2198         dateString = concatParams(itemPtr);
2199         if (!dateString)
2200             ERROR(1);
2201
2202         if (ktime_DateToLong(dateString, expDate) == 0) {
2203             *expType = BC_ABS_EXPDATE;
2204             code = ktime_DateToLong(dateString, expDate);
2205             if (code)
2206                 ERROR(1);
2207         } else if (ParseRelDate(dateString, &kt) == 0) {
2208             *expType = BC_REL_EXPDATE;
2209             *expDate = ktimeRelDate_ToLong(&kt);
2210         } else {
2211             ERROR(1);
2212         }
2213     }
2214
2215   error_exit:
2216     if (dateString)
2217         free(dateString);
2218     return (code);
2219 }
2220
2221 /* database lookup command and routines */
2222
2223 /* bc_dblookupCmd
2224  *      Currently a single option, volumename to search for. Reports
2225  *      all dumps containing the specified volume
2226  */
2227 int
2228 bc_dblookupCmd(struct cmd_syndesc *as, void *arock)
2229 {
2230     struct cmd_item *ciptr;
2231     afs_int32 code;
2232
2233     ciptr = as->parms[0].items;
2234     if (ciptr == 0)             /* no argument specified */
2235         return (-1);
2236
2237     code = DBLookupByVolume(ciptr->data);
2238     return (code);
2239 }
2240
2241
2242
2243 /* for ubik version */
2244 int
2245 bc_dbVerifyCmd(struct cmd_syndesc *as, void *arock)
2246 {
2247     afs_int32 status;
2248     afs_int32 orphans;
2249     afs_int32 host;
2250
2251     struct hostent *hostPtr;
2252     int detail;
2253     afs_int32 code = 0;
2254
2255     extern struct udbHandleS udbHandle;
2256
2257     detail = (as->parms[0].items ? 1 : 0);      /* print more details */
2258
2259     code =
2260         ubik_Call(BUDB_DbVerify, udbHandle.uh_client, 0, &status, &orphans,
2261                   &host);
2262
2263     if (code) {
2264         afs_com_err(whoami, code, "; Unable to verify database");
2265         return (-1);
2266     }
2267
2268     /* verification call succeeded */
2269
2270     if (status == 0)
2271         printf("Database OK\n");
2272     else
2273         afs_com_err(whoami, status, "; Database is NOT_OK");
2274
2275     if (detail) {
2276         printf("Orphan blocks %d\n", orphans);
2277
2278         if (!host)
2279             printf("Unable to lookup host id\n");
2280         else {
2281             hostPtr = gethostbyaddr((char *)&host, sizeof(host), AF_INET);
2282             if (hostPtr == 0)
2283                 printf("Database checker was %d.%d.%d.%d\n",
2284                        ((host & 0xFF000000) >> 24), ((host & 0xFF0000) >> 16),
2285                        ((host & 0xFF00) >> 8), (host & 0xFF));
2286             else
2287                 printf("Database checker was %s\n", hostPtr->h_name);
2288         }
2289     }
2290     return ((status ? -1 : 0));
2291 }
2292
2293 /* deleteDump:
2294  * Delete a dump. If port is >= 0, it means try to delete from XBSA server
2295  */
2296 deleteDump(dumpid, port, force)
2297      afs_uint32 dumpid;         /* The dumpid to delete */
2298      afs_int32 port;            /* port==-1 means don't go to butc */
2299      afs_int32 force;
2300 {
2301     afs_int32 code = 0, tcode;
2302     struct budb_dumpEntry dumpEntry;
2303     struct rx_connection *tconn = 0;
2304     afs_int32 i, taskflag, xbsadump;
2305     statusP statusPtr = 0;
2306     budb_dumpsList dumps;
2307     afs_uint32 taskId;
2308
2309     /* If the port is set, we will try to send a delete request to the butc */
2310     if (port >= 0) {
2311         tcode = bc_UpdateHosts();
2312         if (tcode) {
2313             afs_com_err(whoami, tcode, "; Can't retrieve tape hosts");
2314             ERROR(tcode);
2315         }
2316
2317         /* Find the dump in the backup database */
2318         tcode = bcdb_FindDumpByID(dumpid, &dumpEntry);
2319         if (tcode) {
2320             afs_com_err(whoami, tcode, "; Unable to locate dumpID %u in database",
2321                     dumpid);
2322             ERROR(tcode);
2323         }
2324         xbsadump = (dumpEntry.flags & (BUDB_DUMP_ADSM | BUDB_DUMP_BUTA));
2325
2326         /* If dump is to an XBSA server, connect to butc and send it
2327          * the dump to delete. Butc will contact the XBSA server.
2328          * The dump will not be an appended dump because XBSA butc 
2329          * does not support the append option.
2330          */
2331         if (xbsadump && dumpEntry.nVolumes) {
2332             tcode = ConnectButc(bc_globalConfig, port, &tconn);
2333             if (tcode)
2334                 ERROR(tcode);
2335
2336             tcode = TC_DeleteDump(tconn, dumpid, &taskId);
2337             if (tcode) {
2338                 if (tcode == RXGEN_OPCODE)
2339                     tcode = BC_VERSIONFAIL;
2340                 afs_com_err(whoami, tcode,
2341                         "; Unable to delete dumpID %u via butc", dumpid);
2342                 ERROR(tcode);
2343             }
2344
2345             statusPtr = createStatusNode();
2346             lock_Status();
2347             statusPtr->taskId = taskId;
2348             statusPtr->port = port;
2349             statusPtr->jobNumber = bc_jobNumber();
2350             statusPtr->flags |= (SILENT | NOREMOVE);    /* No msg & keep statusPtr */
2351             statusPtr->flags &= ~STARTING;      /* clearstatus to examine */
2352             sprintf(statusPtr->taskName, "DeleteDump");
2353             unlock_Status();
2354
2355             /* Wait for task to finish */
2356             taskflag = waitForTask(taskId);
2357             if (taskflag & (TASK_ERROR | ABORT_DONE)) {
2358                 afs_com_err(whoami, BUTX_DELETEOBJFAIL,
2359                         "; Unable to delete dumpID %u via butc", dumpid);
2360                 ERROR(BUTX_DELETEOBJFAIL);      /* the task failed */
2361             }
2362         }
2363     }
2364
2365   error_exit:
2366     if (statusPtr)
2367         deleteStatusNode(statusPtr);    /* Clean up statusPtr - because NOREMOVE */
2368     if (tconn)
2369         rx_DestroyConnection(tconn);    /* Destroy the connection */
2370
2371     /* Remove the dump from the backup database */
2372     if (!code || force) {
2373         dumps.budb_dumpsList_len = 0;
2374         dumps.budb_dumpsList_val = 0;
2375
2376         tcode = bcdb_deleteDump(dumpid, 0, 0, &dumps);
2377         if (tcode) {
2378             afs_com_err(whoami, tcode,
2379                     "; Unable to delete dumpID %u from database", dumpid);
2380             dumps.budb_dumpsList_len = 0;
2381             if (!code)
2382                 code = tcode;
2383         }
2384
2385         /* Display the dumps that were deleted - includes appended dumps */
2386         for (i = 0; i < dumps.budb_dumpsList_len; i++)
2387             printf("     %u%s\n", dumps.budb_dumpsList_val[i],
2388                    (i > 0) ? " Appended Dump" : "");
2389         if (dumps.budb_dumpsList_val)
2390             free(dumps.budb_dumpsList_val);
2391     }
2392
2393     return code;
2394 }
2395
2396 /* bc_deleteDumpCmd
2397  *      Delete a specified dump from the database
2398  * entry:
2399  *      dump id - single required arg as param 0.
2400  */
2401 int
2402 bc_deleteDumpCmd(struct cmd_syndesc *as, void *arock)
2403 {
2404     afs_uint32 dumpid;
2405     afs_int32 code = 0;
2406     afs_int32 rcode = 0;
2407     afs_int32 groupId = 0, havegroupid, sflags, noexecute;
2408     struct cmd_item *ti;
2409     afs_uint32 fromTime = 0, toTime = 0, havetime = 0;
2410     char *timeString;
2411     budb_dumpsList dumps, flags;
2412     int i;
2413     afs_int32 port = -1, dbonly = 0, force;
2414
2415     /* Must specify at least one of -dumpid, -from, or -to */
2416     if (!as->parms[0].items && !as->parms[1].items && !as->parms[2].items
2417         && !as->parms[4].items) {
2418         afs_com_err(whoami, 0, "Must specify at least one field");
2419         return (-1);
2420     }
2421
2422     /* Must have -to option with -from option */
2423     if (as->parms[1].items && !as->parms[2].items) {
2424         afs_com_err(whoami, 0, "Must specify '-to' field with '-from' field");
2425         return (-1);
2426     }
2427
2428     /* Get the time to delete from */
2429     if (as->parms[1].items) {   /* -from */
2430         timeString = concatParams(as->parms[1].items);
2431         if (!timeString)
2432             return (-1);
2433
2434         /*
2435          * Now parse this string for the time to start.
2436          */
2437         code = ktime_DateToLong(timeString, &fromTime);
2438         free(timeString);
2439         if (code) {
2440             afs_com_err(whoami, 0, "Can't parse 'from' date and time");
2441             afs_com_err(whoami, 0, "%s", ktime_GetDateUsage());
2442             return (-1);
2443         }
2444         havetime = 1;
2445     }
2446
2447     port = (as->parms[3].items ? getPortOffset(as->parms[3].items->data) : 0);  /* -port */
2448     if (as->parms[5].items)     /* -dbonly */
2449         port = -1;
2450
2451     force = (as->parms[6].items ? 1 : 0);
2452
2453     havegroupid = (as->parms[4].items ? 1 : 0);
2454     if (havegroupid)
2455         groupId = atoi(as->parms[4].items->data);
2456
2457     noexecute = (as->parms[7].items ? 1 : 0);
2458
2459     /* Get the time to delete to */
2460     if (as->parms[2].items) {   /* -to */
2461         timeString = concatParams(as->parms[2].items);
2462         if (!timeString)
2463             return (-1);
2464
2465         /*
2466          * Now parse this string for the time to start. Simce
2467          * times are at minute granularity, add 59 seconds.
2468          */
2469         code = ktime_DateToLong(timeString, &toTime);
2470         free(timeString);
2471         if (code) {
2472             afs_com_err(whoami, 0, "Can't parse 'to' date and time");
2473             afs_com_err(whoami, 0, "%s", ktime_GetDateUsage());
2474             return (-1);
2475         }
2476         toTime += 59;
2477         havetime = 1;
2478     }
2479
2480     if (fromTime > toTime) {
2481         afs_com_err(whoami, 0,
2482                 "'-from' date/time cannot be later than '-to' date/time");
2483         return (-1);
2484     }
2485
2486     /* Remove speicific dump ids - if any */
2487     printf("The following dumps %s deleted:\n",
2488            (noexecute ? "would have been" : "were"));
2489     for (ti = as->parms[0].items; ti != 0; ti = ti->next) {     /* -dumpid */
2490         dumpid = atoi(ti->data);
2491         if (!noexecute) {
2492             code = deleteDump(dumpid, port, force);
2493         } else {
2494             printf("     %u\n", dumpid);
2495         }
2496     }
2497
2498     /*
2499      * Now remove dumps between to and from dates.
2500      */
2501     if (havegroupid || havetime) {
2502         dumps.budb_dumpsList_len = 0;
2503         dumps.budb_dumpsList_val = 0;
2504         flags.budb_dumpsList_len = 0;
2505         flags.budb_dumpsList_val = 0;
2506         sflags = 0;
2507         if (havegroupid)
2508             sflags |= BUDB_OP_GROUPID;
2509         if (havetime)
2510             sflags |= BUDB_OP_DATES;
2511
2512         code =
2513             bcdb_listDumps(sflags, groupId, fromTime, toTime, &dumps, &flags);
2514         if (code) {
2515             afs_com_err(whoami, code,
2516                     "; Error while deleting dumps from %u to %u", fromTime,
2517                     toTime);
2518             rcode = -1;
2519         }
2520
2521         for (i = 0; i < dumps.budb_dumpsList_len; i++) {
2522             if (flags.budb_dumpsList_val[i] & BUDB_OP_DBDUMP)
2523                 continue;
2524
2525             if (!noexecute) {
2526                 if (flags.budb_dumpsList_val[i] & BUDB_OP_APPDUMP)
2527                     continue;
2528                 code = deleteDump(dumps.budb_dumpsList_val[i], port, force);
2529                 /* Ignore code and continue */
2530             } else {
2531                 printf("     %u%s%s\n", dumps.budb_dumpsList_val[i],
2532                        (flags.
2533                         budb_dumpsList_val[i] & BUDB_OP_APPDUMP) ?
2534                        " Appended Dump" : "",
2535                        (flags.
2536                         budb_dumpsList_val[i] & BUDB_OP_DBDUMP) ?
2537                        " Database Dump" : "");
2538
2539             }
2540         }
2541
2542         if (dumps.budb_dumpsList_val)
2543             free(dumps.budb_dumpsList_val);
2544         dumps.budb_dumpsList_len = 0;
2545         dumps.budb_dumpsList_val = 0;
2546         if (flags.budb_dumpsList_val)
2547             free(flags.budb_dumpsList_val);
2548         flags.budb_dumpsList_len = 0;
2549         flags.budb_dumpsList_val = 0;
2550     }
2551
2552     return (rcode);
2553 }
2554
2555 int
2556 bc_saveDbCmd(struct cmd_syndesc *as, void *arock)
2557 {
2558     struct rx_connection *tconn;
2559     afs_int32 portOffset = 0;
2560     statusP statusPtr;
2561     afs_uint32 taskId;
2562     afs_int32 code;
2563     afs_uint32 toTime;
2564     char *timeString;
2565
2566     code = bc_UpdateHosts();
2567     if (code) {
2568         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
2569         return (code);
2570     }
2571
2572     if (as->parms[0].items) {
2573         portOffset = getPortOffset(as->parms[0].items->data);
2574         if (portOffset < 0)
2575             return (BC_BADARG);
2576     }
2577
2578     /* Get the time to delete to */
2579     if (as->parms[1].items) {
2580         timeString = concatParams(as->parms[1].items);
2581         if (!timeString)
2582             return (-1);
2583
2584         /*
2585          * Now parse this string for the time. Since
2586          * times are at minute granularity, add 59 seconds.
2587          */
2588         code = ktime_DateToLong(timeString, &toTime);
2589         free(timeString);
2590         if (code) {
2591             afs_com_err(whoami, 0, "Can't parse '-archive' date and time");
2592             afs_com_err(whoami, 0, "%s", ktime_GetDateUsage());
2593             return (-1);
2594         }
2595         toTime += 59;
2596     } else
2597         toTime = 0;
2598
2599     code = ConnectButc(bc_globalConfig, portOffset, &tconn);
2600     if (code)
2601         return (code);
2602
2603     code = TC_SaveDb(tconn, toTime, &taskId);
2604     if (code) {
2605         afs_com_err(whoami, code, "; Failed to save database");
2606         goto exit;
2607     }
2608
2609     /* create status monitor block */
2610     statusPtr = createStatusNode();
2611     lock_Status();
2612     statusPtr->taskId = taskId;
2613     statusPtr->port = portOffset;
2614     statusPtr->jobNumber = bc_jobNumber();
2615     statusPtr->flags &= ~STARTING;      /* clearstatus to examine */
2616     sprintf(statusPtr->taskName, "SaveDb");
2617     unlock_Status();
2618
2619   exit:
2620     rx_DestroyConnection(tconn);
2621     return (code);
2622 }
2623
2624 int
2625 bc_restoreDbCmd(struct cmd_syndesc *as, void *arock)
2626 {
2627     struct rx_connection *tconn;
2628     afs_int32 portOffset = 0;
2629     statusP statusPtr;
2630     afs_uint32 taskId;
2631     afs_int32 code;
2632
2633     code = bc_UpdateHosts();
2634     if (code) {
2635         afs_com_err(whoami, code, "; Can't retrieve tape hosts");
2636         return (code);
2637     }
2638
2639     if (as->parms[0].items) {
2640         portOffset = getPortOffset(as->parms[0].items->data);
2641         if (portOffset < 0)
2642             return (BC_BADARG);
2643     }
2644
2645     code = ConnectButc(bc_globalConfig, portOffset, &tconn);
2646     if (code)
2647         return (code);
2648
2649     code = TC_RestoreDb(tconn, &taskId);
2650     if (code) {
2651         afs_com_err(whoami, code, "; Failed to restore database");
2652         goto exit;
2653     }
2654
2655     /* create status monitor block */
2656     statusPtr = createStatusNode();
2657     lock_Status();
2658     statusPtr->taskId = taskId;
2659     statusPtr->port = portOffset;
2660     statusPtr->jobNumber = bc_jobNumber();
2661     statusPtr->flags &= ~STARTING;      /* clearstatus to examine */
2662     sprintf(statusPtr->taskName, "RestoreDb");
2663     unlock_Status();
2664
2665   exit:
2666     rx_DestroyConnection(tconn);
2667     return (code);
2668 }
2669
2670 /* ----------------------------------
2671  * supporting routines for database examination 
2672  * ----------------------------------
2673  */
2674
2675 /* structures and defines for DBLookupByVolume */
2676
2677 #define DBL_MAX_VOLUMES 20      /* max. for each dump */
2678
2679 /* dumpedVol - saves interesting information so that we can print it out
2680  *      later
2681  */
2682
2683 struct dumpedVol {
2684     struct dumpedVol *next;
2685     afs_int32 dumpID;
2686     afs_int32 initialDumpID;
2687     char tapeName[BU_MAXTAPELEN];
2688     afs_int32 level;
2689     afs_int32 parent;
2690     afs_int32 createTime;
2691     afs_int32 incTime;          /* actually the clone time */
2692 };
2693
2694 /* -----------------------------------------
2695  * routines for examining the database
2696  * -----------------------------------------
2697  */
2698
2699 /* DBLookupByVolume
2700  *      Lookup the volumename in the backup database and print the results
2701  * entry:
2702  *      volumeName - volume to lookup
2703  */
2704
2705 DBLookupByVolume(volumeName)
2706      char *volumeName;
2707 {
2708     struct budb_dumpEntry dumpEntry;
2709     struct budb_volumeEntry volumeEntry[DBL_MAX_VOLUMES];
2710     afs_int32 numEntries;
2711     afs_int32 tapedumpid;
2712     afs_int32 last, next;
2713
2714     struct dumpedVol *dvptr = 0;
2715     struct dumpedVol *tempPtr = 0;
2716     afs_int32 code = 0;
2717     int i, pass;
2718     char vname[BU_MAXNAMELEN];
2719     char ds[50];
2720
2721     for (pass = 0; pass < 2; pass++) {
2722         /*p */
2723         /* On second pass, search for backup volume */
2724         if (pass == 1) {
2725             if (!BackupName(volumeName)) {
2726                 strcpy(vname, volumeName);
2727                 strcat(vname, ".backup");
2728                 volumeName = vname;
2729             } else {
2730                 continue;
2731             }
2732         }
2733
2734         last = next = 0;
2735         while (next != -1) {    /*w */
2736             code =
2737                 bcdb_LookupVolume(volumeName, &volumeEntry[0], last, &next,
2738                                   DBL_MAX_VOLUMES, &numEntries);
2739             if (code)
2740                 break;
2741
2742             /* add the volumes to the list */
2743             for (i = 0; i < numEntries; i++) {  /*f */
2744                 struct dumpedVol *insPtr, **prevPtr;
2745
2746                 tempPtr =
2747                     (struct dumpedVol *)malloc(sizeof(struct dumpedVol));
2748                 if (!tempPtr)
2749                     ERROR(BC_NOMEM);
2750
2751                 memset(tempPtr, 0, sizeof(*tempPtr));
2752                 tempPtr->incTime = volumeEntry[i].clone;
2753                 tempPtr->dumpID = volumeEntry[i].dump;
2754                 strncpy(tempPtr->tapeName, volumeEntry[i].tape,
2755                         BU_MAXTAPELEN);
2756
2757                 /* check if we need to null terminate it - just for safety */
2758                 if (strlen(volumeEntry[i].tape) >= BU_MAXTAPELEN)
2759                     tempPtr->tapeName[BU_MAXTAPELEN - 1] = 0;
2760
2761                 code = bcdb_FindDumpByID(tempPtr->dumpID, &dumpEntry);
2762                 if (code) {
2763                     free(tempPtr);
2764                     ERROR(code);
2765                 }
2766
2767                 tempPtr->initialDumpID = dumpEntry.initialDumpID;
2768                 tempPtr->parent = dumpEntry.parent;
2769                 tempPtr->level = dumpEntry.level;
2770                 tempPtr->createTime = dumpEntry.created;
2771
2772                 /* add volume to list in reverse chronological order */
2773                 prevPtr = &dvptr;
2774                 insPtr = dvptr;
2775
2776                 while ((insPtr != 0)
2777                        && (insPtr->createTime > tempPtr->createTime)
2778                     ) {
2779                     prevPtr = &insPtr->next;
2780                     insPtr = insPtr->next;
2781                 }
2782
2783                 /* now at the right place - insert the block */
2784                 tempPtr->next = *prevPtr;
2785                 *prevPtr = tempPtr;
2786             }                   /*f */
2787
2788             last = next;
2789         }                       /*w */
2790     }                           /*p */
2791
2792     if (dvptr) {
2793         printf
2794             ("DumpID    lvl parentID creation date     clone date       tape name\n");
2795         for (tempPtr = dvptr; tempPtr; tempPtr = tempPtr->next) {
2796             /* For the user, the tape name is its name and initial dump id */
2797             tapedumpid =
2798                 (tempPtr->initialDumpID ? tempPtr->initialDumpID : tempPtr->
2799                  dumpID);
2800
2801             /* beware the static items in compactDateString */
2802             compactDateString(&tempPtr->createTime, ds, 50);
2803             printf("%-9d %-2d %-9d %16s", tempPtr->dumpID, tempPtr->level,
2804                    tempPtr->parent, ds);
2805             compactDateString(&tempPtr->incTime, ds, 50);
2806             printf("  %16s %s (%u)\n", ds, tempPtr->tapeName, tapedumpid);
2807         }
2808         code = 0;
2809     }
2810
2811   error_exit:
2812     for (tempPtr = dvptr; tempPtr; tempPtr = dvptr) {
2813         dvptr = dvptr->next;
2814         free(tempPtr);
2815     }
2816
2817     if (code)
2818         afs_com_err(whoami, code, "");
2819     return (code);
2820 }
2821
2822 /* structures for dumpInfo */
2823
2824 struct volumeLink {
2825     struct volumeLink *nextVolume;
2826     struct budb_volumeEntry volumeEntry;
2827 };
2828
2829 struct tapeLink {
2830     struct tapeLink *nextTape;
2831     struct budb_tapeEntry tapeEntry;
2832     struct volumeLink *firstVolume;
2833 };
2834
2835
2836 /* dumpInfo
2837  *      print information about a dump and all its tapes and volumes.
2838  */
2839
2840 afs_int32
2841 dumpInfo(dumpid, detailFlag)
2842      afs_int32 dumpid;
2843      afs_int32 detailFlag;
2844 {
2845     struct budb_dumpEntry dumpEntry;
2846     struct tapeLink *head = 0;
2847     struct tapeLink *tapeLinkPtr, *lastTapeLinkPtr;
2848     struct volumeLink **link, *volumeLinkPtr, *lastVolumeLinkPtr;
2849
2850     budb_volumeList vl;
2851     afs_int32 last, next, dbTime;
2852     afs_int32 tapedumpid;
2853
2854     int tapeNumber;
2855     int i;
2856     int dbDump;
2857     afs_int32 code = 0;
2858     char ds[50];
2859
2860     extern struct udbHandleS udbHandle;
2861
2862     tapeLinkPtr = 0;
2863     lastTapeLinkPtr = 0;
2864     volumeLinkPtr = 0;
2865     lastVolumeLinkPtr = 0;
2866
2867     /* first get information about the dump */
2868
2869     code = bcdb_FindDumpByID(dumpid, &dumpEntry);
2870     if (code)
2871         ERROR(code);
2872
2873     /* For the user, the tape name is its name and initial dump id */
2874     tapedumpid = (dumpEntry.initialDumpID ? dumpEntry.initialDumpID : dumpid);
2875
2876     /* Is this a database dump id or not */
2877     if (strcmp(dumpEntry.name, DUMP_TAPE_NAME) == 0)
2878         dbDump = 1;
2879     else
2880         dbDump = 0;
2881
2882     /* print out the information about the dump */
2883     if (detailFlag) {
2884         printf("\nDump\n");
2885         printf("----\n");
2886         printDumpEntry(&dumpEntry);
2887     } else {
2888         time_t t = dumpEntry.created;
2889         if (dbDump)
2890             printf("Dump: id %u, created: %s\n", dumpEntry.id,
2891                    ctime(&t));
2892         else
2893             printf("Dump: id %u, level %d, volumes %d, created: %s\n",
2894                    dumpEntry.id, dumpEntry.level, dumpEntry.nVolumes,
2895                    ctime(&t));
2896     }
2897
2898     if (!detailFlag && (strlen(dumpEntry.tapes.tapeServer) > 0)
2899         && (dumpEntry.flags & (BUDB_DUMP_ADSM | BUDB_DUMP_BUTA))) {
2900         printf("Backup Service: TSM: Server: %s\n",
2901                dumpEntry.tapes.tapeServer);
2902     }
2903
2904     /* now get the list of tapes */
2905     for (tapeNumber = dumpEntry.tapes.b; tapeNumber <= dumpEntry.tapes.maxTapes; tapeNumber++) {        /*f */
2906         tapeLinkPtr = (struct tapeLink *)malloc(sizeof(struct tapeLink));
2907         if (!tapeLinkPtr) {
2908             afs_com_err(whoami, BC_NOMEM, "");
2909             ERROR(BC_NOMEM);
2910         }
2911
2912         memset(tapeLinkPtr, 0, sizeof(*tapeLinkPtr));
2913         code = bcdb_FindTapeSeq(dumpid, tapeNumber, &tapeLinkPtr->tapeEntry);
2914         if (code) {
2915             code = 0;
2916             free(tapeLinkPtr);
2917             continue;
2918         }
2919
2920         /* add this tape to  previous chain */
2921         if (lastTapeLinkPtr) {
2922             lastTapeLinkPtr->nextTape = tapeLinkPtr;
2923             lastTapeLinkPtr = tapeLinkPtr;
2924         }
2925
2926         if (head == 0) {
2927             head = tapeLinkPtr;
2928             lastTapeLinkPtr = head;
2929         }
2930
2931         next = 0;
2932         while (next != -1) {    /*wn */
2933             vl.budb_volumeList_len = 0;
2934             vl.budb_volumeList_val = 0;
2935             last = next;
2936
2937             /* now get all the volumes in this dump. */
2938             code = ubik_Call_SingleServer(BUDB_GetVolumes, udbHandle.uh_client, UF_SINGLESERVER, BUDB_MAJORVERSION, BUDB_OP_DUMPID | BUDB_OP_TAPENAME, tapeLinkPtr->tapeEntry.name,     /* tape name */
2939                                           dumpid,       /* dumpid (not initial dumpid) */
2940                                           0,    /* end */
2941                                           last, /* last */
2942                                           &next,        /* nextindex */
2943                                           &dbTime,      /* update time */
2944                                           &vl);
2945
2946             if (code) {
2947                 if (code == BUDB_ENDOFLIST) {   /* 0 volumes on tape */
2948                     code = 0;
2949                     break;
2950                 }
2951                 ERROR(code);
2952             }
2953
2954             for (i = 0; i < vl.budb_volumeList_len; i++) {
2955                 link = &tapeLinkPtr->firstVolume;
2956
2957                 volumeLinkPtr =
2958                     (struct volumeLink *)malloc(sizeof(struct volumeLink));
2959                 if (!volumeLinkPtr) {
2960                     afs_com_err(whoami, BC_NOMEM, "");
2961                     ERROR(BC_NOMEM);
2962                 }
2963                 memset(volumeLinkPtr, 0, sizeof(*volumeLinkPtr));
2964
2965                 memcpy(&volumeLinkPtr->volumeEntry,
2966                        &vl.budb_volumeList_val[i],
2967                        sizeof(struct budb_volumeEntry));
2968
2969                 /* now insert it onto the right place */
2970                 while ((*link != 0)
2971                        && (volumeLinkPtr->volumeEntry.position >
2972                            (*link)->volumeEntry.position)) {
2973                     link = &((*link)->nextVolume);
2974                 }
2975
2976                 /* now link it in */
2977                 volumeLinkPtr->nextVolume = *link;
2978                 *link = volumeLinkPtr;
2979             }
2980
2981             if (vl.budb_volumeList_val)
2982                 free(vl.budb_volumeList_val);
2983         }                       /*wn */
2984     }                           /*f */
2985
2986     for (tapeLinkPtr = head; tapeLinkPtr; tapeLinkPtr = tapeLinkPtr->nextTape) {
2987         if (detailFlag) {
2988             printf("\nTape\n");
2989             printf("----\n");
2990             printTapeEntry(&tapeLinkPtr->tapeEntry);
2991         } else {
2992             printf("Tape: name %s (%u)\n", tapeLinkPtr->tapeEntry.name,
2993                    tapedumpid);
2994             printf("nVolumes %d, ", tapeLinkPtr->tapeEntry.nVolumes);
2995             compactDateString(&tapeLinkPtr->tapeEntry.written, ds, 50);
2996             printf("created %16s", ds);
2997             if (tapeLinkPtr->tapeEntry.expires != 0) {
2998                 compactDateString(&tapeLinkPtr->tapeEntry.expires, ds, 50);
2999                 printf(", expires %16s", ds);
3000             }
3001             printf("\n\n");
3002         }
3003
3004         /* print out all the volumes */
3005
3006         /* print header for volume listing - db dumps have no volumes */
3007         if ((detailFlag == 0) && !dbDump)
3008             printf("%4s %16s %9s %-s\n", "Pos", "Clone time", "Nbytes",
3009                    "Volume");
3010
3011         for (volumeLinkPtr = tapeLinkPtr->firstVolume; volumeLinkPtr;
3012              volumeLinkPtr = volumeLinkPtr->nextVolume) {
3013             if (detailFlag) {
3014                 printf("\nVolume\n");
3015                 printf("------\n");
3016                 printVolumeEntry(&volumeLinkPtr->volumeEntry);
3017             } else {
3018                 compactDateString(&volumeLinkPtr->volumeEntry.clone, ds, 50),
3019                     printf("%4d %s %10u %16s\n",
3020                            volumeLinkPtr->volumeEntry.position, ds,
3021                            volumeLinkPtr->volumeEntry.nBytes,
3022                            volumeLinkPtr->volumeEntry.name);
3023             }
3024         }
3025     }
3026
3027   error_exit:
3028     if (code)
3029         afs_com_err("dumpInfo", code, "; Can't get dump information");
3030
3031     /* free all allocated structures */
3032     tapeLinkPtr = head;
3033     while (tapeLinkPtr) {
3034         volumeLinkPtr = tapeLinkPtr->firstVolume;
3035         while (volumeLinkPtr) {
3036             lastVolumeLinkPtr = volumeLinkPtr;
3037             volumeLinkPtr = volumeLinkPtr->nextVolume;
3038             free(lastVolumeLinkPtr);
3039         }
3040
3041         lastTapeLinkPtr = tapeLinkPtr;
3042         tapeLinkPtr = tapeLinkPtr->nextTape;
3043         free(lastTapeLinkPtr);
3044     }
3045     return (code);
3046 }
3047
3048 int
3049 compareDump(ptr1, ptr2)
3050      struct budb_dumpEntry *ptr1, *ptr2;
3051 {
3052     if (ptr1->created < ptr2->created)
3053         return (-1);
3054     else if (ptr1->created > ptr2->created)
3055         return (1);
3056     return (0);
3057 }
3058
3059 afs_int32
3060 printRecentDumps(ndumps)
3061      int ndumps;
3062 {
3063     afs_int32 code = 0;
3064     afs_int32 nextindex, index = 0;
3065     afs_int32 dbTime;
3066     budb_dumpList dl;
3067     struct budb_dumpEntry *dumpPtr;
3068     int i;
3069     char ds[50];
3070
3071     extern struct udbHandleS udbHandle;
3072     extern compareDump();
3073
3074     do {                        /* while (nextindex != -1) */
3075         /* initialize the dump list */
3076         dl.budb_dumpList_len = 0;
3077         dl.budb_dumpList_val = 0;
3078
3079         /* outline algorithm */
3080         code = ubik_Call(BUDB_GetDumps, udbHandle.uh_client, 0, BUDB_MAJORVERSION, BUDB_OP_NPREVIOUS, "",       /* no name */
3081                          0,     /* start */
3082                          ndumps,        /* end */
3083                          index, /* index */
3084                          &nextindex, &dbTime, &dl);
3085         if (code) {
3086             if (code == BUDB_ENDOFLIST)
3087                 return 0;
3088             afs_com_err("dumpInfo", code, "; Can't get dump information");
3089             return (code);
3090         }
3091
3092         /* No need to sort, it's already sorted */
3093
3094         if (dl.budb_dumpList_len && (index == 0))
3095             printf("%10s %10s %2s %-16s %2s %5s dump name\n", "dumpid",
3096                    "parentid", "lv", "created", "nt", "nvols");
3097
3098         dumpPtr = dl.budb_dumpList_val;
3099         for (i = 1; i <= dl.budb_dumpList_len; i++) {
3100             compactDateString(&dumpPtr->created, ds, 50),
3101                 printf("%10u %10u %-2d %16s %2d %5d %s", dumpPtr->id,
3102                        dumpPtr->parent, dumpPtr->level, ds,
3103                        dumpPtr->tapes.maxTapes - dumpPtr->tapes.b + 1,
3104                        dumpPtr->nVolumes, dumpPtr->name);
3105             if (dumpPtr->initialDumpID) /* an appended dump */
3106                 printf(" (%u)", dumpPtr->initialDumpID);
3107             else if (dumpPtr->appendedDumpID)   /* has appended dumps */
3108                 printf(" (%u)", dumpPtr->id);
3109             printf("\n");
3110
3111             dumpPtr++;
3112         }
3113
3114         if (dl.budb_dumpList_val)
3115             free(dl.budb_dumpList_val);
3116         index = nextindex;
3117     } while (nextindex != -1);
3118
3119     return (code);
3120 }
3121
3122 /* bc_dumpInfoCmd 
3123  *      list the dumps and contens of the dumps.
3124  * params:
3125  *      as - name of tape
3126  *      arock -
3127  */
3128 int
3129 bc_dumpInfoCmd(struct cmd_syndesc *as, void *arock)
3130 {
3131     afs_int32 dumpid;
3132     afs_int32 detailFlag;
3133     afs_int32 ndumps;
3134     afs_int32 code = 0;
3135
3136     afs_int32 dumpInfo();
3137
3138     if (as->parms[0].items) {
3139         if (as->parms[1].items) {
3140             afs_com_err(whoami, 0,
3141                     "These options are exclusive - select only one");
3142             return (BC_BADARG);
3143         }
3144         ndumps = atoi(as->parms[0].items->data);
3145         if (ndumps <= 0) {
3146             afs_com_err(whoami, 0, "Must provide a positive number");
3147             return -1;
3148         }
3149
3150         code = printRecentDumps(ndumps);
3151     } else if (as->parms[1].items) {
3152         detailFlag = (as->parms[2].items ? 1 : 0);      /* 1 = detailed listing */
3153         dumpid = atoi(as->parms[1].items->data);
3154         code = dumpInfo(dumpid, detailFlag);
3155     } else {
3156         code = printRecentDumps(10);
3157     }
3158
3159     return (code);
3160 }