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