3bf6f2dd41df60f69e1c49e5f7797e6982e25e74
[openafs.git] / src / butc / tcmain.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 #include <afs/procmgmt.h>
14
15 #include <roken.h>
16 #include <afs/opr.h>
17
18 #ifdef IGNORE_SOME_GCC_WARNINGS
19 # pragma GCC diagnostic warning "-Wimplicit-function-declaration"
20 #endif
21
22 #ifdef AFS_NT40_ENV
23 #include <WINNT/afsevent.h>
24 #endif
25
26 #include <ctype.h>
27
28 #include <rx/rx.h>
29 #include <rx/rx_globals.h>
30 #include <rx/rxkad.h>
31 #include <rx/xdr.h>
32
33 #include <afs/afsint.h>
34 #include <afs/prs_fs.h>
35 #include <afs/nfs.h>
36 #include <afs/vlserver.h>
37 #include <lwp.h>
38 #include <lock.h>
39 #include <afs/afsutil.h>
40 #include <afs/cellconfig.h>
41 #include <afs/keys.h>
42 #include <afs/volser.h>
43 #include <ubik.h>
44 #include <afs/com_err.h>
45 #include <afs/cmd.h>
46 #include <afs/tcdata.h>
47 #include <afs/bubasics.h>
48 #include <afs/budb_errs.h>
49 #include <afs/budb_client.h>
50 #include <afs/bucoord_prototypes.h>
51 #include <afs/butx.h>
52 #include <afs/kautils.h>
53 #include <afs/bc.h>
54
55 #include "error_macros.h"
56 #define XBSA_TCMAIN
57 #include "butc_xbsa.h"
58 #include "butc_prototypes.h"
59
60 #define N_SECURITY_OBJECTS 3
61 #define ERRCODE_RANGE 8         /* from error_table.h */
62
63 #define TE_PREFIX  "TE"
64 #define TL_PREFIX  "TL"
65 #define CFG_PREFIX "CFG"
66
67 struct ubik_client *cstruct;
68 FILE *logIO, *ErrorlogIO, *centralLogIO, *lastLogIO;
69 char lFile[AFSDIR_PATH_MAX];
70 char logFile[256];
71 char ErrorlogFile[256];
72 char lastLogFile[256];
73 char eFile[AFSDIR_PATH_MAX];
74 char tapeConfigFile[AFSDIR_PATH_MAX];
75 char pFile[AFSDIR_PATH_MAX];
76 int debugLevel = 0;
77 struct tapeConfig globalTapeConfig;
78 struct deviceSyncNode *deviceLatch;
79 char globalCellName[64];
80 char *whoami = "butc";
81
82 /* GLOBAL CONFIGURATION PARAMETERS */
83 int dump_namecheck;
84 int queryoperator;
85 int autoQuery;
86 int isafile;
87 int tapemounted;
88 char *opencallout;
89 char *closecallout;
90 char *restoretofile;
91 int forcemultiple;
92
93 int maxpass;
94 #define PASSESMIN  1
95 #define PASSESMAX  10
96 #define PASSESDFLT 2
97 afs_int32 groupId;
98 #define MINGROUPID 0x1
99 #define MAXGROUPID 0x7FFFFFFF
100 afs_int32 statusSize;
101 #define MINSTATUS  1
102 #define MAXSTATUS  0x7fffffff
103 afs_int32 BufferSize;           /* Size in B stored for data */
104 char *centralLogFile;
105 afs_int32 lastLog;              /* Log last pass info */
106 int rxBind = 0;
107
108 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
109 afs_uint32 SHostAddrs[ADDRSPERSITE];
110
111 /* dummy routine for the audit work.  It should do nothing since audits */
112 /* occur at the server level and bos is not a server. */
113 int
114 osi_audit(void)
115 {
116     return 0;
117 }
118
119 static afs_int32
120 SafeATOL(char *anum)
121 {
122     afs_int32 total;
123     int tc;
124
125     total = 0;
126     while ((tc = *anum)) {
127         if (tc < '0' || tc > '9')
128             return -1;
129         total *= 10;
130         total += (tc - '0');
131         anum++;
132     }
133     return total;
134 }
135
136 /* atocl
137  *      Convert a string into an afs_int32.
138  *      Returned afs_int32 is in Bytes, Kb, Mb, Gb, or Tb. Based on crunit char.
139  *      This routine only converts unsigned float values.
140  *      The returned value is a whole number.
141  * entry:
142  *      numstring - text string to be converted.
143  *      crunit - value returned in 'B', 'K', 'M', 'G', 'T'.
144  *               ' ' or NULL ==> 'B' (bytes).
145  * exit:
146  *      number - returned value in requested crunit - rounded
147  *               to nearest whole number.
148  * fn return value:
149  *       0 - conversion ok
150  *      -1 - error in conversion
151  * notes:
152  *      should deal with signed numbers. Should signal error if no digits
153  *      seen.
154  */
155 int
156 atocl(char *numstring, char crunit, afs_int32 *number)
157 {
158     float total;
159     afs_int32 runits;
160     char cunit;
161     afs_int32 units;
162     afs_int32 count;
163     char rest[256];
164
165     /* Determine which units to report in */
166     switch (crunit) {
167     case 't':
168     case 'T':
169         runits = 12;
170         break;
171
172     case 'g':
173     case 'G':
174         runits = 9;
175         break;
176
177     case 'm':
178     case 'M':
179         runits = 6;
180         break;
181
182     case 'k':
183     case 'K':
184         runits = 3;
185         break;
186
187     case 'b':
188     case 'B':
189     case ' ':
190     case 0:
191         runits = 0;
192         break;
193
194     default:
195         return (-1);
196     }
197
198     count =
199         sscanf(numstring, "%f%c%s", &total, &cunit, rest);
200     if ((count > 2) || (count <= 0))
201         return -1;
202     if (count == 1)
203         cunit = 'B';            /* bytes */
204
205     switch (cunit) {
206     case 't':
207     case 'T':
208         units = 12;
209         break;
210
211     case 'g':
212     case 'G':
213         units = 9;
214         break;
215
216     case 'm':
217     case 'M':
218         units = 6;
219         break;
220
221     case 'k':
222     case 'K':
223         units = 3;
224         break;
225
226     case 'b':
227     case 'B':
228     case ' ':
229     case 0:
230         units = 0;
231         break;
232
233     default:
234         return (-1);
235     }
236
237     /* Go to correct unit */
238     for (; units < runits; units += 3)
239         total /= 1024.0;
240     for (; units > runits; units -= 3)
241         total *= 1024.0;
242
243     total += 0.5;               /* Round up */
244     if ((total > 0x7fffffff) || (total < 0))    /* Don't go over 2G */
245         total = 0x7fffffff;
246
247     *number = total;
248     return (0);
249 }
250
251 /* replace last two ocurrences of / by _ */
252 #if 0
253 static int
254 stringReplace(char *name)
255 {
256     char *pos;
257     char buffer[256];
258
259     pos = strrchr(name, '/');
260     *pos = '_';
261     strcpy(buffer, pos);
262     pos = strrchr(name, '/');
263     *pos = '\0';
264     strcat(name, buffer);
265     return 0;
266 }
267 #endif
268
269 static int
270 stringNowReplace(char *logFile, char *deviceName)
271 {
272     char *pos = 0;
273     char storeDevice[256];
274     int mvFlag = 0, devPrefLen;
275 #ifdef AFS_NT40_ENV
276     char devPrefix[] = "\\\\.";
277 #else
278     char devPrefix[] = "/dev";
279 #endif
280
281     devPrefLen = strlen(devPrefix);
282     strcpy(storeDevice, deviceName);
283     if (strncmp(deviceName, devPrefix, devPrefLen) == 0) {
284         deviceName += devPrefLen;
285         mvFlag++;
286     }
287     while ((pos = strchr(deviceName, devPrefix[0])))    /* look for / or \ */
288         *pos = '_';
289     strcat(logFile, deviceName);
290     /* now put back deviceName to the way it was */
291     if (mvFlag) {
292         mvFlag = 0;
293         deviceName -= devPrefLen;
294     }
295     strcpy(deviceName, storeDevice);
296
297     return (0);
298 }
299
300
301 /* GetDeviceConfig
302  *      get the configuration information for a particular tape device
303  *      as specified by the portoffset
304  * entry:
305  *      filename - full pathname of file containing the tape device
306  *              configuration information
307  *      config - for return results
308  *      portOffset - for which configuration is required
309  * notes:
310  *      logging not available when this routine is called
311  *      caller return value checks
312  * exit:
313  *      0 => Found entry with same port, return info in config.
314  *     -1 => Error encountered trying to read the file.
315  *      1 => Desired entry does not exist or file does not exist.
316  */
317
318 #define LINESIZE        256
319 static afs_int32
320 GetDeviceConfig(char *filename, struct tapeConfig *config, afs_int32 portOffset)
321 {
322     FILE *devFile = 0;
323     char line[LINESIZE];
324     char devName[LINESIZE], tcapacity[LINESIZE], tfmsize[LINESIZE],
325         trest[LINESIZE];
326     afs_int32 aport;
327     afs_int32 capacity;
328     afs_int32 fmSize;
329     afs_int32 code = 0, count;
330
331     /* Initialize the config struct */
332     config->capacity = 0;
333     config->fileMarkSize = 0;
334     config->portOffset = portOffset;
335     strcpy(config->device, "");
336
337     devFile = fopen(filename, "r");
338     if (!devFile) {
339         if (errno == ENOENT)
340             ERROR_EXIT(1);
341         fprintf(stderr, "Error %d: Can't open %s\n", errno, filename);
342         ERROR_EXIT(-1);
343     }
344
345     while (fgets(line, LINESIZE - 1, devFile)) {
346         count =
347             sscanf(line, "%s %s %s %u%s\n", tcapacity, tfmsize, devName,
348                    &aport, trest);
349
350         if (count == 4 || count == 5) {
351             if (atocl(tcapacity, 'K', &capacity)) {
352                 fprintf(stderr,
353                         "tapeconfig: Tape capacity parse error in: %s\n",
354                         line);
355                 ERROR_EXIT(-1);
356             }
357             if (atocl(tfmsize, 'B', &fmSize)) {
358                 fprintf(stderr,
359                         "tapeconfig: File-mark size parse error in: %s\n",
360                         line);
361                 ERROR_EXIT(-1);
362             }
363         } else {
364             count = sscanf(line, "%s %u%s\n", devName, &aport, trest);
365             if (count == 2 || count == 3) {
366                 capacity = 0x7fffffff;
367                 fmSize = 0;
368             } else {
369                 fprintf(stderr, "tapeconfig: Parse error in: %s\n", line);
370                 ERROR_EXIT(-1);
371             }
372         }
373
374         if ((aport < 0) || (aport > BC_MAXPORTOFFSET)) {
375             fprintf(stderr, "tapeconfig: Port offset parse error in: %s\n",
376                     line);
377             ERROR_EXIT(-1);
378         }
379
380         if (aport != portOffset)
381             continue;
382
383         if (fmSize < 0) {
384             fprintf(stderr, "Invalid file mark size, %d, in: %s\n", fmSize,
385                     line);
386             ERROR_EXIT(-1);
387         }
388
389         config->capacity = capacity;
390         config->fileMarkSize = fmSize;
391         config->portOffset = aport;
392         strncpy(config->device, devName, 100);
393
394         ERROR_EXIT(0);
395     }
396
397     /* fprintf(stderr, "Can't find tapeconfig entry for port offset %d\n", portOffset); */
398     ERROR_EXIT(1);
399
400   error_exit:
401     if (devFile)
402         fclose(devFile);
403     return (code);
404 }
405
406 /* GetConfigParams
407  */
408 static afs_int32
409 GetConfigParams(char *filename, afs_int32 port)
410 {
411     char paramFile[256];
412     FILE *devFile = 0;
413     char line[LINESIZE], cmd[LINESIZE], value[LINESIZE];
414     afs_int32 code = 0;
415     int cnt;
416
417     /* DEFAULT SETTINGS FOR GLOBAL PARAMETERS */
418     dump_namecheck = 1;         /* check tape name on dumps */
419     queryoperator = 1;          /* can question operator */
420     autoQuery = 1;              /* prompt for first tape */
421     isafile = 0;                /* Do not dump to a file */
422     opencallout = NULL;         /* open  callout routine */
423     closecallout = NULL;        /* close callout routine */
424     tapemounted = 0;            /* tape is not mounted */
425 #ifdef xbsa
426     BufferSize = (CONF_XBSA ? XBSADFLTBUFFER : BUTM_BLOCKSIZE);
427     dumpRestAuthnLevel = rpc_c_protect_level_default;
428     xbsaObjectOwner = NULL;     /* bsaObjectOwner */
429     appObjectOwner = NULL;      /* appObjectOwner */
430     adsmServerName = NULL;      /* TSM server name - same as ADSM */
431     xbsaSecToken = NULL;        /* XBSA sercurity token */
432     xbsalGName = NULL;          /* XBSA IGName */
433 #else
434     BufferSize = BUTM_BLOCKSIZE;
435 #endif /*xbsa */
436     centralLogFile = NULL;      /* Log for all butcs */
437     centralLogIO = 0;           /* Log for all butcs */
438     statusSize = 0;             /* size before status message */
439     maxpass = PASSESDFLT;       /* dump passes */
440     lastLog = 0;                /* separate log for last pass */
441     lastLogIO = 0;              /* separate log for last pass */
442     groupId = 0;                /* Group id for multiple dumps */
443
444     /* Try opening the CFG_<port> file */
445     sprintf(paramFile, "%s_%d", filename, port);
446     devFile = fopen(paramFile, "r");
447     if (devFile) {
448         /* Set log names to TL_<port>, TL_<port>.lp and TE_<port> */
449         sprintf(logFile, "%s_%d", lFile, port);
450         sprintf(lastLogFile, "%s_%d.lp", lFile, port);
451         sprintf(ErrorlogFile, "%s_%d", eFile, port);
452     } else if (CONF_XBSA) {
453         /* If configured as XBSA, a configuration file CFG_<port> must exist */
454         printf("Cannot open configuration file %s", paramFile);
455         ERROR_EXIT(1);
456     } else {
457         /* Try the CFG_<device> name as the device file */
458         strcpy(paramFile, filename);
459         stringNowReplace(paramFile, globalTapeConfig.device);
460         /* Set log names to TL_<device>, TL_<device> and TE_<device> */
461         strcpy(logFile, lFile);
462         stringNowReplace(logFile, globalTapeConfig.device);
463         strcpy(lastLogFile, lFile);
464         stringNowReplace(lastLogFile, globalTapeConfig.device);
465         strcat(lastLogFile, ".lp");
466         strcpy(ErrorlogFile, eFile);
467         stringNowReplace(ErrorlogFile, globalTapeConfig.device);
468
469         /* Now open the device file */
470         devFile = fopen(paramFile, "r");
471         if (!devFile)
472             ERROR_EXIT(0);      /* CFG file doesn't exist for non-XBSA and that's ok */
473     }
474
475     /* Read each line of the Configuration file */
476     while (fgets(line, LINESIZE - 1, devFile)) {
477         cnt = sscanf(line, "%s %s", cmd, value);
478         if (cnt != 2) {
479             if (cnt > 0)
480                 printf("Bad line in %s: %s\n", paramFile, line);
481             continue;
482         }
483
484         for (cnt = 0; cnt < strlen(cmd); cnt++)
485             if (islower(cmd[cnt]))
486                 cmd[cnt] = toupper(cmd[cnt]);
487
488         if (!strcmp(cmd, "NAME_CHECK")) {
489             if (CONF_XBSA) {
490                 printf
491                     ("Warning: The %s parameter is ignored with a Backup Service\n",
492                      cmd);
493                 continue;
494             }
495
496             for (cnt = 0; cnt < strlen(value); cnt++)
497                 if (islower(value[cnt]))
498                     value[cnt] = toupper(value[cnt]);
499
500             if (!strcmp(value, "NO")) {
501                 printf("Dump tape name check is disabled\n");
502                 dump_namecheck = 0;
503             } else {
504                 printf("Dump tape name check is enabled\n");
505                 dump_namecheck = 1;
506             }
507         }
508
509         else if (!strcmp(cmd, "MOUNT")) {
510             if (CONF_XBSA) {
511                 printf
512                     ("Warning: The %s parameter is ignored with a Backup Service\n",
513                      cmd);
514                 continue;
515             }
516
517             opencallout = strdup(value);
518             printf("Tape mount callout routine is %s\n", opencallout);
519         }
520
521         else if (!strcmp(cmd, "UNMOUNT")) {
522             if (CONF_XBSA) {
523                 printf
524                     ("Warning: The %s parameter is ignored with a Backup Service\n",
525                      cmd);
526                 continue;
527             }
528
529             closecallout = strdup(value);
530             printf("Tape unmount callout routine is %s\n", closecallout);
531         }
532
533         else if (!strcmp(cmd, "ASK")) {
534             for (cnt = 0; cnt < strlen(value); cnt++)
535                 if (islower(value[cnt]))
536                     value[cnt] = toupper(value[cnt]);
537
538             if (!strcmp(value, "NO")) {
539                 printf("Operator queries are disabled\n");
540                 queryoperator = 0;
541             } else {
542                 printf("Operator queries are enabled\n");
543                 queryoperator = 1;
544             }
545         }
546
547         else if (!strcmp(cmd, "FILE")) {
548             if (CONF_XBSA) {
549                 printf
550                     ("Warning: The %s parameter is ignored with a Backup Service\n",
551                      cmd);
552                 continue;
553             }
554
555             for (cnt = 0; cnt < strlen(value); cnt++)
556                 if (islower(value[cnt]))
557                     value[cnt] = toupper(value[cnt]);
558
559             if (!strcmp(value, "YES")) {
560                 printf("Will dump to a file\n");
561                 isafile = 1;
562             } else {
563                 printf("Will not dump to a file\n");
564                 isafile = 0;
565             }
566         }
567
568         else if (!strcmp(cmd, "AUTOQUERY")) {
569             if (CONF_XBSA) {
570                 printf
571                     ("Warning: The %s parameter is ignored with a Backup Service\n",
572                      cmd);
573                 continue;
574             }
575
576             for (cnt = 0; cnt < strlen(value); cnt++)
577                 if (islower(value[cnt]))
578                     value[cnt] = toupper(value[cnt]);
579
580             if (!strcmp(value, "NO")) {
581                 printf("Auto query is disabled\n");
582                 autoQuery = 0;
583             } else {
584                 printf("Auto query is enabled\n");
585                 autoQuery = 1;
586             }
587         }
588
589         else if (!strcmp(cmd, "BUFFERSIZE")) {
590             afs_int32 size;
591             afs_int32 tapeblocks;
592
593             if (!CONF_XBSA) {
594                 if (atocl(value, 'K', &size)) {
595                     fprintf(stderr, "BUFFERSIZE parse error\n");
596                     size = 0;
597                 }
598
599                 /* A tapeblock is 16KB. Determine # of tapeblocks. Then
600                  * determine BufferSize needed for that many tapeblocks.
601                  */
602                 tapeblocks = size / 16;
603                 if (tapeblocks <= 0)
604                     tapeblocks = 1;
605                 printf("BUFFERSIZE is %u KBytes\n", (tapeblocks * 16));
606                 BufferSize = tapeblocks * BUTM_BLOCKSIZE;
607             } else {
608 #ifdef xbsa
609                 if (atocl(value, 'B', &size)) {
610                     fprintf(stderr, "BUFFERSIZE parse error\n");
611                     size = 0;
612                 }
613                 if (size < XBSAMINBUFFER)
614                     size = XBSAMINBUFFER;
615                 if (size > XBSAMAXBUFFER)
616                     size = XBSAMAXBUFFER;
617                 printf("XBSA buffer size is %u Bytes\n", size);
618                 BufferSize = size;
619 #endif
620             }
621         }
622 #ifndef xbsa
623         /* All the xbsa spacific parameters */
624         else if (!strcmp(cmd, "TYPE") || !strcmp(cmd, "NODE")
625                  || !strcmp(cmd, "SERVER") || !strcmp(cmd, "PASSWORD")
626                  || !strcmp(cmd, "PASSFILE") || !strcmp(cmd, "MGMTCLASS")) {
627             printf("This binary does not have XBSA support\n");
628             return 1;
629         }
630 #else
631         else if (!strcmp(cmd, "TYPE")) {        /* required for XBSA */
632             if (!CONF_XBSA) {
633                 printf
634                     ("Warning: The %s parameter is ignored with a tape drive\n",
635                      cmd);
636                 continue;
637             }
638
639             for (cnt = 0; (size_t) cnt < strlen(value); cnt++)
640                 if (islower(value[cnt]))
641                     value[cnt] = toupper(value[cnt]);
642
643             if (strcmp(value, "TSM") == 0) {
644                 xbsaType = XBSA_SERVER_TYPE_ADSM;       /* Known XBSA server type */
645             } else {
646                 printf("Configuration file error, %s %s is not recognized\n",
647                        cmd, value);
648                 xbsaType = XBSA_SERVER_TYPE_UNKNOWN;
649             }
650             printf("XBSA type is %s\n",
651                    ((xbsaType ==
652                      XBSA_SERVER_TYPE_UNKNOWN) ? "Unknown" : value));
653         }
654
655         else if (!strcmp(cmd, "NODE")) {
656             if (!CONF_XBSA) {
657                 printf
658                     ("Warning: The %s parameter is ignored with a tape drive\n",
659                      cmd);
660                 continue;
661             }
662             xbsaObjectOwner = strdup(value);
663             printf("XBSA node is %s\n", xbsaObjectOwner);
664         }
665
666         else if (!strcmp(cmd, "SERVER")) {      /* required for XBSA */
667             if (!CONF_XBSA) {
668                 printf
669                     ("Warning: The %s parameter is ignored with a tape drive\n",
670                      cmd);
671                 continue;
672             }
673             adsmServerName = strdup(value);
674             printf("XBSA server is %s\n", adsmServerName);
675         }
676
677         else if (!strcmp(cmd, "PASSWORD")) {    /* This or PASSFILE required for XBSA */
678             if (!CONF_XBSA) {
679                 printf
680                     ("Warning: The %s parameter is ignored with a tape drive\n",
681                      cmd);
682                 continue;
683             }
684             if (xbsaSecToken) {
685                 printf
686                     ("Warning: The %s parameter is ignored. Already read password\n",
687                      cmd);
688                 continue;
689             }
690
691             xbsaSecToken = strdup(value);
692             printf("XBSA Password has been read\n");
693         }
694
695         else if (!strcmp(cmd, "PASSFILE")) {    /* This or PASSWORD required for XBSA */
696             FILE *pwdFile;
697             if (!CONF_XBSA) {
698                 printf
699                     ("Warning: The %s parameter is ignored with a tape drive\n",
700                      cmd);
701                 continue;
702             }
703             if (xbsaSecToken) {
704                 printf
705                     ("Warning: The %s parameter is ignored. Already read password\n",
706                      cmd);
707                 continue;
708             }
709
710             pwdFile = fopen(value, "r");
711             if (!pwdFile) {
712                 printf
713                     ("Configuration file error, cannot open password file %s\n",
714                      value);
715                 ERROR_EXIT(1);
716             }
717             xbsaSecToken = malloc(LINESIZE);
718             if (!fscanf(pwdFile, "%s", xbsaSecToken)) {
719                 printf
720                     ("Configuration file error, cannot read password file %s\n",
721                      value);
722                 ERROR_EXIT(1);
723             }
724             printf("XBSA password retrieved from password file\n");
725         }
726
727         else if (!strcmp(cmd, "MGMTCLASS")) {   /* XBSA */
728             if (!CONF_XBSA) {
729                 printf
730                     ("Warning: The %s parameter is ignored with a tape drive\n",
731                      cmd);
732                 continue;
733             }
734             xbsalGName = strdup(value);
735             printf("XBSA management class is %s\n", xbsalGName);
736         }
737 #endif
738
739         else if (!strcmp(cmd, "MAXPASS")) {
740             maxpass = SafeATOL(value);
741             if (maxpass < PASSESMIN)
742                 maxpass = PASSESMIN;
743             if (maxpass > PASSESMAX)
744                 maxpass = PASSESMAX;
745             printf("MAXPASS is %d\n", maxpass);
746         }
747
748         else if (!strcmp(cmd, "GROUPID")) {
749             groupId = SafeATOL(value);
750             if ((groupId < MINGROUPID) || (groupId > MAXGROUPID)) {
751                 printf("Configuration file error, %s %s is invalid\n", cmd,
752                        value);
753                 ERROR_EXIT(1);
754             }
755             printf("Group Id is %d\n", groupId);
756         }
757
758         else if (!strcmp(cmd, "LASTLOG")) {
759             for (cnt = 0; (size_t) cnt < strlen(value); cnt++)
760                 if (islower(value[cnt]))
761                     value[cnt] = toupper(value[cnt]);
762
763             lastLog = (strcmp(value, "YES") == 0);
764             printf("Will %sgenerate a last log\n", (lastLog ? "" : "not "));
765         }
766
767         else if (!strcmp(cmd, "CENTRALLOG")) {
768             centralLogFile = strdup(value);
769             printf("Central log file is %s\n", centralLogFile);
770         }
771
772         else if (!strcmp(cmd, "STATUS")) {
773             if (atocl(value, 'B', &statusSize)) {
774                 fprintf(stderr, "STATUS parse error\n");
775                 statusSize = 0;
776             }
777             if (statusSize < MINSTATUS)
778                 statusSize = MINSTATUS;
779             if (statusSize > MAXSTATUS)
780                 statusSize = MAXSTATUS;
781         }
782
783         else {
784             printf("Warning: Unrecognized configuration parameter: %s", line);
785         }
786     }                           /*fgets */
787
788     if (statusSize) {
789         /* Statussize is in bytes and requires that BufferSize be set first */
790         statusSize *= BufferSize;
791         if (statusSize < 0)
792             statusSize = 0x7fffffff;    /*max size */
793         printf("Status every %ld Bytes\n", afs_printable_int32_ld(statusSize));
794     }
795
796   error_exit:
797     if (devFile)
798         fclose(devFile);
799
800     /* If the butc is configured as XBSA, check for required parameters */
801 #ifdef xbsa
802     if (!code && CONF_XBSA) {
803         if (xbsaType == XBSA_SERVER_TYPE_UNKNOWN) {
804             printf
805                 ("Configuration file error, the TYPE parameter must be specified, or\n");
806             printf("an entry must exist in %s for port %d\n", tapeConfigFile,
807                    port);
808             code = 1;
809         }
810         if (!adsmServerName) {
811             printf
812                 ("Configuration file error, the SERVER parameter must be specified\n");
813             code = 1;
814         }
815         if (!xbsaSecToken) {
816             printf
817                 ("Configuration file error, the PASSWORD or PASSFILE parameter must be specified\n");
818             code = 1;
819         }
820     }
821 #endif /*xbsa */
822     return (code);
823 }
824
825 #ifdef xbsa
826 static void
827 xbsa_shutdown(int x)
828 {
829     xbsa_Finalize(&butxInfo);
830     exit(0);
831 }
832 #endif
833
834 static int
835 WorkerBee(struct cmd_syndesc *as, void *arock)
836 {
837     afs_int32 code;
838     struct rx_securityClass *(securityObjects[3]);
839     struct rx_service *service;
840     time_t tokenExpires;
841     char cellName[64];
842     int localauth;
843     /*process arguments */
844     afs_int32 portOffset = 0;
845 #ifdef AFS_PTHREAD_ENV
846     pthread_t dbWatcherPid;
847     pthread_attr_t tattr;
848     AFS_SIGSET_DECL;
849 #else
850     PROCESS dbWatcherPid;
851 #endif
852     afs_uint32 host = htonl(INADDR_ANY);
853
854     debugLevel = 0;
855
856     /*initialize the error tables */
857     initialize_KA_error_table();
858     initialize_RXK_error_table();
859     initialize_KTC_error_table();
860     initialize_ACFG_error_table();
861     initialize_CMD_error_table();
862     initialize_VL_error_table();
863     initialize_BUTM_error_table();
864     initialize_BUTC_error_table();
865 #ifdef xbsa
866     initialize_BUTX_error_table();
867 #endif /*xbs */
868     initialize_VOLS_error_table();
869     initialize_BUDB_error_table();
870     initialize_BUCD_error_table();
871
872     if (as->parms[0].items) {
873         portOffset = SafeATOL(as->parms[0].items->data);
874         if (portOffset == -1) {
875             fprintf(stderr, "Illegal port offset '%s'\n",
876                     as->parms[0].items->data);
877             exit(1);
878         } else if (portOffset > BC_MAXPORTOFFSET) {
879             fprintf(stderr, "%u exceeds max port offset %u\n", portOffset,
880                     BC_MAXPORTOFFSET);
881             exit(1);
882         }
883     }
884
885     xbsaType = XBSA_SERVER_TYPE_NONE;   /* default */
886     if (as->parms[3].items) {   /* -device */
887         globalTapeConfig.capacity = 0x7fffffff; /* 2T for max tape capacity */
888         globalTapeConfig.fileMarkSize = 0;
889         globalTapeConfig.portOffset = portOffset;
890         strncpy(globalTapeConfig.device, as->parms[3].items->data, 100);
891         xbsaType = XBSA_SERVER_TYPE_NONE;       /* Not XBSA */
892     } else {
893         /* Search for an entry in tapeconfig file */
894         code = GetDeviceConfig(tapeConfigFile, &globalTapeConfig, portOffset);
895         if (code == -1) {
896             fprintf(stderr, "Problem in reading config file %s\n",
897                     tapeConfigFile);
898             exit(1);
899         }
900         /* Set xbsaType. If code == 1, no entry was found in the tapeconfig file so
901          * it's an XBSA server. Don't know if its ADSM or not so its unknown.
902          */
903         xbsaType =
904             ((code == 1) ? XBSA_SERVER_TYPE_UNKNOWN : XBSA_SERVER_TYPE_NONE);
905     }
906
907     if (as->parms[6].items) {   /* -restoretofile */
908         restoretofile = strdup(as->parms[6].items->data);
909         printf("Restore to file '%s'\n", restoretofile);
910     }
911
912     /* Go and read the config file: CFG_<device> or CFG_<port>. We will also set
913      * the exact xbsaType within the call (won't be unknown) - double check.
914      */
915     code = GetConfigParams(pFile, portOffset);
916     if (code)
917         exit(code);
918 #ifdef xbsa
919     if (xbsaType == XBSA_SERVER_TYPE_UNKNOWN) {
920         printf
921             ("\nConfiguration file error, the TYPE parameter must be specified, or\n");
922         printf("an entry must exist in %s for port %d\n", tapeConfigFile,
923                portOffset);
924         exit(1);
925     }
926 #else
927     /* Not compiled for XBSA code so we can't support it */
928     if (CONF_XBSA) {
929         printf("\nNo entry found in %s for port %d\n", tapeConfigFile,
930                portOffset);
931         printf("This binary does not have XBSA support\n");
932         exit(1);
933     }
934 #endif
935
936     /* Open the log files. The pathnames were set in GetConfigParams() */
937     logIO = fopen(logFile, "a");
938     if (!logIO) {
939         fprintf(stderr, "Failed to open %s\n", logFile);
940         exit(1);
941     }
942     ErrorlogIO = fopen(ErrorlogFile, "a");
943     if (!ErrorlogIO) {
944         fprintf(stderr, "Failed to open %s\n", ErrorlogFile);
945         exit(1);
946     }
947     if (lastLog) {
948         lastLogIO = fopen(lastLogFile, "a");
949         if (!lastLogIO) {
950             fprintf(stderr, "Failed to open %s\n", lastLogFile);
951             exit(1);
952         }
953     }
954     if (centralLogFile) {
955         struct stat sbuf;
956         afs_int32 statcode;
957 #ifndef AFS_NT40_ENV
958         char path[AFSDIR_PATH_MAX];
959 #endif
960
961         statcode = stat(centralLogFile, &sbuf);
962         centralLogIO = fopen(centralLogFile, "a");
963         if (!centralLogIO) {
964             fprintf(stderr, "Failed to open %s; error %d\n", centralLogFile,
965                     errno);
966             exit(1);
967         }
968 #ifndef AFS_NT40_ENV
969         /* Make sure it is not in AFS, has to have been created first */
970         if (!realpath(centralLogFile, path)) {
971             fprintf(stderr,
972                     "Warning: can't determine real path of '%s' (%d)\n",
973                     centralLogFile, errno);
974         } else {
975             if (strncmp(path, "/afs/", 5) == 0) {
976                 fprintf(stderr, "The central log '%s' should not be in AFS\n",
977                         centralLogFile);
978                 exit(1);
979             }
980         }
981 #endif
982
983         /* Write header if created it */
984         if (statcode) {
985             char *h1 =
986                 "TASK   START DATE/TIME      END DATE/TIME        ELAPSED   VOLUMESET\n";
987             char *h2 =
988                 "-----  -------------------  -------------------  --------  ---------\n";
989             /* File didn't exist before so write the header lines */
990             fwrite(h1, strlen(h1), 1, centralLogIO);
991             fwrite(h2, strlen(h2), 1, centralLogIO);
992             fflush(centralLogIO);
993         }
994     }
995
996     if (as->parms[1].items) {
997         debugLevel = SafeATOL(as->parms[1].items->data);
998         if (debugLevel == -1) {
999             TLog(0, "Illegal debug level '%s'\n", as->parms[1].items->data);
1000             exit(1);
1001         }
1002     }
1003 #ifdef xbsa
1004     /* Setup XBSA library interface */
1005     if (CONF_XBSA) {
1006         afs_int32 rc;
1007         rc = xbsa_MountLibrary(&butxInfo, xbsaType);
1008         if (rc != XBSA_SUCCESS) {
1009             TapeLog(0, 0, rc, 0, "Unable to mount the XBSA library\n");
1010             return (1);
1011         }
1012
1013         forcemultiple = (as->parms[7].items ? 1 : 0);/*-xbsaforcemultiple */
1014         if (forcemultiple)
1015             printf("Force XBSA multiple server support\n");
1016
1017         rc = InitToServer(0 /*taskid */ , &butxInfo, adsmServerName);
1018         if (rc != XBSA_SUCCESS)
1019             return (1);
1020         (void)signal(SIGINT, xbsa_shutdown);
1021         (void)signal(SIGHUP, xbsa_shutdown);
1022     }
1023 #endif /*xbsa */
1024
1025     /* cell switch */
1026     if (as->parms[2].items)
1027         strncpy(cellName, as->parms[2].items->data, sizeof(cellName));
1028     else
1029         cellName[0] = '\0';
1030
1031     if (as->parms[4].items)
1032         autoQuery = 0;
1033
1034     localauth = (as->parms[5].items ? 1 : 0);
1035     rxBind = (as->parms[8].items ? 1 : 0);
1036
1037     if (rxBind) {
1038         afs_int32 ccode;
1039         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
1040             AFSDIR_SERVER_NETINFO_FILEPATH) {
1041             char reason[1024];
1042             ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
1043                                           ADDRSPERSITE, reason,
1044                                           AFSDIR_SERVER_NETINFO_FILEPATH,
1045                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1046         } else
1047         {
1048             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
1049         }
1050         if (ccode == 1)
1051             host = SHostAddrs[0];
1052     }
1053
1054     code = rx_InitHost(host, htons(BC_TAPEPORT + portOffset));
1055     if (code) {
1056         TapeLog(0, 0, code, 0, "rx init failed on port %u\n",
1057                 BC_TAPEPORT + portOffset);
1058         exit(1);
1059     }
1060     rx_SetRxDeadTime(150);
1061
1062     /* Establish connection with the vldb server */
1063     code = vldbClientInit(0, localauth, cellName, &cstruct, &tokenExpires);
1064     if (code) {
1065         TapeLog(0, 0, code, 0, "Can't access vldb\n");
1066         return code;
1067     }
1068
1069     strcpy(globalCellName, cellName);
1070
1071     /*initialize the dumpNode list */
1072     InitNodeList(portOffset);
1073
1074     deviceLatch = malloc(sizeof(struct deviceSyncNode));
1075     Lock_Init(&(deviceLatch->lock));
1076     deviceLatch->flags = 0;
1077
1078     /* initialize database support, volume support, and logs */
1079
1080     /* Create a single security object, in this case the null security
1081      * object, for unauthenticated connections, which will be used to control
1082      * security on connections made to this server
1083      */
1084
1085     securityObjects[0] = rxnull_NewServerSecurityObject();
1086     securityObjects[1] = (struct rx_securityClass *)0;  /* don't bother with rxvab */
1087     if (!securityObjects[0]) {
1088         TLog(0, "rxnull_NewServerSecurityObject");
1089         exit(1);
1090     }
1091
1092     service =
1093         rx_NewServiceHost(host, 0, 1, "BUTC", securityObjects, 3, TC_ExecuteRequest);
1094     if (!service) {
1095         TLog(0, "rx_NewService");
1096         exit(1);
1097     }
1098     rx_SetMaxProcs(service, 4);
1099
1100     /* Establish connection to the backup database */
1101     code = udbClientInit(0, localauth, cellName);
1102     if (code) {
1103         TapeLog(0, 0, code, 0, "Can't access backup database\n");
1104         exit(1);
1105     }
1106     /* This call is here to verify that we are authentiated.
1107      * The call does nothing and will return BUDB_NOTPERMITTED
1108      * if we don't belong.
1109      */
1110     code = bcdb_deleteDump(0, 0, 0, 0);
1111     if (code == BUDB_NOTPERMITTED) {
1112         TapeLog(0, 0, code, 0, "Can't access backup database\n");
1113         exit(1);
1114     }
1115
1116     initStatus();
1117 #ifdef AFS_PTHREAD_ENV
1118     code = pthread_attr_init(&tattr);
1119     if (code) {
1120         TapeLog(0, 0, code, 0,
1121                 "Can't pthread_attr_init database monitor task");
1122         exit(1);
1123     }
1124     code = pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
1125     if (code) {
1126         TapeLog(0, 0, code, 0,
1127                 "Can't pthread_attr_setdetachstate database monitor task");
1128         exit(1);
1129     }
1130     AFS_SIGSET_CLEAR();
1131     code = pthread_create(&dbWatcherPid, &tattr, dbWatcher, (void *)2);
1132     AFS_SIGSET_RESTORE();
1133 #else
1134     code =
1135         LWP_CreateProcess(dbWatcher, 20480, LWP_NORMAL_PRIORITY, (void *)2,
1136                           "dbWatcher", &dbWatcherPid);
1137 #endif
1138     if (code) {
1139         TapeLog(0, 0, code, 0, "Can't create database monitor task");
1140         exit(1);
1141     }
1142
1143     TLog(0, "Starting Tape Coordinator: Port offset %u   Debug level %u\n",
1144          portOffset, debugLevel);
1145     TLog(0, "Token expires: %s\n", cTIME(&tokenExpires));
1146
1147     rx_StartServer(1);          /* Donate this process to the server process pool */
1148     TLog(0, "Error: StartServer returned");
1149     exit(1);
1150 }
1151
1152 #ifndef AFS_NT40_ENV
1153 #include "AFS_component_version_number.c"
1154 #endif
1155
1156 int
1157 main(int argc, char **argv)
1158 {
1159     struct cmd_syndesc *ts;
1160     struct cmd_item *ti;
1161
1162 #ifdef  AFS_AIX32_ENV
1163     /*
1164      * The following signal action for AIX is necessary so that in case of a
1165      * crash (i.e. core is generated) we can include the user's data section
1166      * in the core dump. Unfortunately, by default, only a partial core is
1167      * generated which, in many cases, isn't too useful.
1168      */
1169     struct sigaction nsa;
1170
1171     sigemptyset(&nsa.sa_mask);
1172     nsa.sa_handler = SIG_DFL;
1173     nsa.sa_flags = SA_FULLDUMP;
1174     sigaction(SIGSEGV, &nsa, NULL);
1175     sigaction(SIGABRT, &nsa, NULL);
1176 #endif
1177
1178     setlinebuf(stdout);
1179
1180     ts = cmd_CreateSyntax(NULL, WorkerBee, NULL, "tape coordinator");
1181     cmd_AddParm(ts, "-port", CMD_SINGLE, CMD_OPTIONAL, "port offset");
1182     cmd_AddParm(ts, "-debuglevel", CMD_SINGLE, CMD_OPTIONAL, "0 | 1 | 2");
1183     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cell name");
1184     cmd_AddParm(ts, "-device", CMD_SINGLE, (CMD_OPTIONAL | CMD_HIDE),
1185                 "tape device path");
1186     cmd_AddParm(ts, "-noautoquery", CMD_FLAG, CMD_OPTIONAL,
1187                 "do not query operator for first tape");
1188     cmd_AddParm(ts, "-localauth", CMD_FLAG, CMD_OPTIONAL,
1189                 "create tickets from KeyFile");
1190     cmd_AddParm(ts, "-restoretofile", CMD_SINGLE, (CMD_OPTIONAL | CMD_HIDE),
1191                 "file to restore to");
1192     cmd_AddParm(ts, "-xbsaforcemultiple", CMD_FLAG, (CMD_OPTIONAL | CMD_HIDE),
1193                 "Force multiple XBSA server support");
1194     cmd_AddParm(ts, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
1195                 "bind Rx socket");
1196
1197     /* Initialize dirpaths */
1198     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
1199 #ifdef AFS_NT40_ENV
1200         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
1201 #endif
1202         fprintf(stderr, "Unable to obtain AFS server directory.\n");
1203         exit(2);
1204     }
1205
1206     /* setup the file paths */
1207     strcompose(eFile, AFSDIR_PATH_MAX, AFSDIR_SERVER_BACKUP_DIRPATH, "/",
1208                TE_PREFIX, (char *)NULL);
1209     strcompose(lFile, AFSDIR_PATH_MAX, AFSDIR_SERVER_BACKUP_DIRPATH, "/",
1210                TL_PREFIX, (char *)NULL);
1211     strcompose(pFile, AFSDIR_PATH_MAX, AFSDIR_SERVER_BACKUP_DIRPATH, "/",
1212                CFG_PREFIX, (char *)NULL);
1213     strcpy(tapeConfigFile, AFSDIR_SERVER_TAPECONFIG_FILEPATH);
1214
1215     /* special case "no args" case since cmd_dispatch gives help message
1216      * instead
1217      */
1218     if (argc == 1) {
1219         ts = calloc(1, sizeof(struct cmd_syndesc));
1220
1221         ti = malloc(sizeof(struct cmd_item));
1222         ti->next = 0;
1223         ti->data = "0";
1224         ts->parms[0].items = ti;
1225         ti = malloc(sizeof(struct cmd_item));
1226         ti->next = 0;
1227         ti->data = "0";
1228         ts->parms[1].items = ti;
1229         ts->parms[2].items = (struct cmd_item *)NULL;
1230         ts->parms[3].items = (struct cmd_item *)NULL;
1231         ts->parms[4].items = (struct cmd_item *)NULL;
1232         ts->parms[5].items = (struct cmd_item *)NULL;
1233         return WorkerBee(ts, NULL);
1234     } else
1235         return cmd_Dispatch(argc, argv);
1236 }