butc-prototyping-20060701
[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 RCSID
14     ("$Header$");
15
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #ifdef AFS_NT40_ENV
19 #include <winsock2.h>
20 #include <WINNT/afsevent.h>
21 #else
22 #include <netinet/in.h>
23 #include <sys/time.h>
24 #endif
25 #include <afs/procmgmt.h>
26 #include <rx/xdr.h>
27 #include <afs/afsint.h>
28 #include <stdio.h>
29 #ifdef AFS_PTHREAD_ENV
30 #include <assert.h>
31 #else
32 #include <afs/assert.h>
33 #endif
34 #include <afs/prs_fs.h>
35 #include <afs/nfs.h>
36 #include <string.h>
37 #include <afs/vlserver.h>
38 #include <lwp.h>
39 #include <lock.h>
40 #include <afs/afsutil.h>
41 #include <rx/rx.h>
42 #include <rx/rx_globals.h>
43 #include <afs/auth.h>
44 #include <rx/rxkad.h>
45 #include <afs/cellconfig.h>
46 #include <afs/keys.h>
47 #include <afs/volser.h>
48 #include <ubik.h>
49 #include <afs/com_err.h>
50 #include <errno.h>
51 #include <afs/cmd.h>
52 #include <afs/tcdata.h>
53 #include <afs/bubasics.h>
54 #include <ctype.h>
55 #include "error_macros.h"
56 #include <afs/budb_errs.h>
57 #include "afs/butx.h"
58 #define XBSA_TCMAIN
59 #include "butc_xbsa.h"
60
61 #define N_SECURITY_OBJECTS 3
62 #define ERRCODE_RANGE 8         /* from error_table.h */
63
64 #define TE_PREFIX  "TE"
65 #define TL_PREFIX  "TL"
66 #define CFG_PREFIX "CFG"
67
68 struct ubik_client *cstruct;
69 extern void TC_ExecuteRequest();
70 extern int dbWatcher();
71 FILE *logIO, *ErrorlogIO, *centralLogIO, *lastLogIO;
72 char lFile[AFSDIR_PATH_MAX];
73 char logFile[256];
74 char ErrorlogFile[256];
75 char lastLogFile[256];
76 char eFile[AFSDIR_PATH_MAX];
77 char tapeConfigFile[AFSDIR_PATH_MAX];
78 char pFile[AFSDIR_PATH_MAX];
79 int debugLevel = 0;
80 struct tapeConfig globalTapeConfig;
81 struct deviceSyncNode *deviceLatch;
82 char globalCellName[64];
83 char *whoami = "butc";
84
85 /* GLOBAL CONFIGURATION PARAMETERS */
86 int dump_namecheck;
87 int queryoperator;
88 int autoQuery;
89 int isafile;
90 int tapemounted;
91 char *opencallout;
92 char *closecallout;
93 char *restoretofile;
94 int forcemultiple;
95
96 int maxpass;
97 #define PASSESMIN  1
98 #define PASSESMAX  10
99 #define PASSESDFLT 2
100 afs_int32 groupId;
101 #define MINGROUPID 0x1
102 #define MAXGROUPID 0x7FFFFFFF
103 afs_int32 statusSize;
104 #define MINSTATUS  1
105 #define MAXSTATUS  0x7fffffff
106 afs_int32 BufferSize;           /* Size in B stored for data */
107 char *centralLogFile;
108 afs_int32 lastLog;              /* Log last pass info */
109 int rxBind = 0;
110
111 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
112 afs_uint32 SHostAddrs[ADDRSPERSITE];
113
114 /* dummy routine for the audit work.  It should do nothing since audits */
115 /* occur at the server level and bos is not a server. */
116 osi_audit()
117 {
118     return 0;
119 }
120
121 static afs_int32
122 SafeATOL(register char *anum)
123 {
124     register afs_int32 total;
125     register int tc;
126
127     total = 0;
128     while (tc = *anum) {
129         if (tc < '0' || tc > '9')
130             return -1;
131         total *= 10;
132         total += (tc - '0');
133         anum++;
134     }
135     return total;
136 }
137
138 /* atocl
139  *      Convert a string into an afs_int32.
140  *      Returned afs_int32 is in Bytes, Kb, Mb, Gb, or Tb. Based on crunit char.
141  *      This routine only converts unsigned float values.
142  *      The returned value is a whole number.
143  * entry:
144  *      numstring - text string to be converted.
145  *      crunit - value returned in 'B', 'K', 'M', 'G', 'T'.
146  *               ' ' or NULL ==> 'B' (bytes).
147  * exit:
148  *      number - returned value in requested crunit - rounded
149  *               to nearest whole number.
150  * fn return value:
151  *       0 - conversion ok
152  *      -1 - error in conversion
153  * notes:
154  *      should deal with signed numbers. Should signal error if no digits
155  *      seen.
156  */
157 int
158 atocl(char *numstring, char crunit, afs_int32 *number)
159 {
160     float total;
161     afs_int32 runits;
162     char cunit;
163     afs_int32 units;
164     afs_int32 count;
165     char rest[256];
166
167     /* Determine which units to report in */
168     switch (crunit) {
169     case 't':
170     case 'T':
171         runits = 12;
172         break;
173
174     case 'g':
175     case 'G':
176         runits = 9;
177         break;
178
179     case 'm':
180     case 'M':
181         runits = 6;
182         break;
183
184     case 'k':
185     case 'K':
186         runits = 3;
187         break;
188
189     case 'b':
190     case 'B':
191     case ' ':
192     case 0:
193         runits = 0;
194         break;
195
196     default:
197         return (-1);
198     }
199
200     count =
201         sscanf(numstring, "%f%c%s", &total, &cunit, rest);
202     if ((count > 2) || (count <= 0))
203         return -1;
204     if (count == 1)
205         cunit = 'B';            /* bytes */
206
207     switch (cunit) {
208     case 't':
209     case 'T':
210         units = 12;
211         break;
212
213     case 'g':
214     case 'G':
215         units = 9;
216         break;
217
218     case 'm':
219     case 'M':
220         units = 6;
221         break;
222
223     case 'k':
224     case 'K':
225         units = 3;
226         break;
227
228     case 'b':
229     case 'B':
230     case ' ':
231     case 0:
232         units = 0;
233         break;
234
235     default:
236         return (-1);
237     }
238
239     /* Go to correct unit */
240     for (; units < runits; units += 3)
241         total /= 1024.0;
242     for (; units > runits; units -= 3)
243         total *= 1024.0;
244
245     total += 0.5;               /* Round up */
246     if ((total > 0x7fffffff) || (total < 0))    /* Don't go over 2G */
247         total = 0x7fffffff;
248
249     *number = total;
250     return (0);
251 }
252
253 /* replace last two ocurrences of / by _ */
254 static
255 stringReplace(char *name)
256 {
257     char *pos;
258     char buffer[256];
259
260     pos = strrchr(name, '/');
261     *pos = '_';
262     strcpy(buffer, pos);
263     pos = strrchr(name, '/');
264     *pos = '\0';
265     strcat(name, buffer);
266     return 0;
267 }
268
269 static
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_uint32 capacity;
328     afs_uint32 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 = (char *)malloc(strlen(value) + 1);
518             strcpy(opencallout, value);
519             printf("Tape mount callout routine is %s\n", opencallout);
520         }
521
522         else if (!strcmp(cmd, "UNMOUNT")) {
523             if (CONF_XBSA) {
524                 printf
525                     ("Warning: The %s parameter is ignored with a Backup Service\n",
526                      cmd);
527                 continue;
528             }
529
530             closecallout = (char *)malloc(strlen(value) + 1);
531             strcpy(closecallout, value);
532             printf("Tape unmount callout routine is %s\n", closecallout);
533         }
534
535         else if (!strcmp(cmd, "ASK")) {
536             for (cnt = 0; cnt < strlen(value); cnt++)
537                 if (islower(value[cnt]))
538                     value[cnt] = toupper(value[cnt]);
539
540             if (!strcmp(value, "NO")) {
541                 printf("Operator queries are disabled\n");
542                 queryoperator = 0;
543             } else {
544                 printf("Operator queries are enabled\n");
545                 queryoperator = 1;
546             }
547         }
548
549         else if (!strcmp(cmd, "FILE")) {
550             if (CONF_XBSA) {
551                 printf
552                     ("Warning: The %s parameter is ignored with a Backup Service\n",
553                      cmd);
554                 continue;
555             }
556
557             for (cnt = 0; cnt < strlen(value); cnt++)
558                 if (islower(value[cnt]))
559                     value[cnt] = toupper(value[cnt]);
560
561             if (!strcmp(value, "YES")) {
562                 printf("Will dump to a file\n");
563                 isafile = 1;
564             } else {
565                 printf("Will not dump to a file\n");
566                 isafile = 0;
567             }
568         }
569
570         else if (!strcmp(cmd, "AUTOQUERY")) {
571             if (CONF_XBSA) {
572                 printf
573                     ("Warning: The %s parameter is ignored with a Backup Service\n",
574                      cmd);
575                 continue;
576             }
577
578             for (cnt = 0; cnt < strlen(value); cnt++)
579                 if (islower(value[cnt]))
580                     value[cnt] = toupper(value[cnt]);
581
582             if (!strcmp(value, "NO")) {
583                 printf("Auto query is disabled\n");
584                 autoQuery = 0;
585             } else {
586                 printf("Auto query is enabled\n");
587                 autoQuery = 1;
588             }
589         }
590
591         else if (!strcmp(cmd, "BUFFERSIZE")) {
592             afs_int32 size;
593             afs_int32 tapeblocks;
594
595             if (!CONF_XBSA) {
596                 if (atocl(value, 'K', &size)) {
597                     fprintf(stderr, "BUFFERSIZE parse error\n");
598                     size = 0;
599                 }
600
601                 /* A tapeblock is 16KB. Determine # of tapeblocks. Then
602                  * determine BufferSize needed for that many tapeblocks.
603                  */
604                 tapeblocks = size / 16;
605                 if (tapeblocks <= 0)
606                     tapeblocks = 1;
607                 printf("BUFFERSIZE is %u KBytes\n", (tapeblocks * 16));
608                 BufferSize = tapeblocks * BUTM_BLOCKSIZE;
609             } else {
610 #ifdef xbsa
611                 if (atocl(value, 'B', &size)) {
612                     fprintf(stderr, "BUFFERSIZE parse error\n");
613                     size = 0;
614                 }
615                 if (size < XBSAMINBUFFER)
616                     size = XBSAMINBUFFER;
617                 if (size > XBSAMAXBUFFER)
618                     size = XBSAMAXBUFFER;
619                 printf("XBSA buffer size is %u Bytes\n", size);
620                 BufferSize = size;
621 #endif
622             }
623         }
624 #ifndef xbsa
625         /* All the xbsa spacific parameters */
626         else if (!strcmp(cmd, "TYPE") || !strcmp(cmd, "NODE")
627                  || !strcmp(cmd, "SERVER") || !strcmp(cmd, "PASSWORD")
628                  || !strcmp(cmd, "PASSFILE") || !strcmp(cmd, "MGMTCLASS")) {
629             printf("This binary does not have XBSA support\n");
630             return 1;
631         }
632 #else
633         else if (!strcmp(cmd, "TYPE")) {        /* required for XBSA */
634             if (!CONF_XBSA) {
635                 printf
636                     ("Warning: The %s parameter is ignored with a tape drive\n",
637                      cmd);
638                 continue;
639             }
640
641             for (cnt = 0; (size_t) cnt < strlen(value); cnt++)
642                 if (islower(value[cnt]))
643                     value[cnt] = toupper(value[cnt]);
644
645             if (strcmp(value, "TSM") == 0) {
646                 xbsaType = XBSA_SERVER_TYPE_ADSM;       /* Known XBSA server type */
647             } else {
648                 printf("Configuration file error, %s %s is not recognized\n",
649                        cmd, value);
650                 xbsaType = XBSA_SERVER_TYPE_UNKNOWN;
651             }
652             printf("XBSA type is %s\n",
653                    ((xbsaType ==
654                      XBSA_SERVER_TYPE_UNKNOWN) ? "Unknown" : value));
655         }
656
657         else if (!strcmp(cmd, "NODE")) {
658             if (!CONF_XBSA) {
659                 printf
660                     ("Warning: The %s parameter is ignored with a tape drive\n",
661                      cmd);
662                 continue;
663             }
664             xbsaObjectOwner = malloc(strlen(value) + 1);
665             strcpy(xbsaObjectOwner, value);
666             printf("XBSA node is %s\n", xbsaObjectOwner);
667         }
668
669         else if (!strcmp(cmd, "SERVER")) {      /* required for XBSA */
670             if (!CONF_XBSA) {
671                 printf
672                     ("Warning: The %s parameter is ignored with a tape drive\n",
673                      cmd);
674                 continue;
675             }
676             adsmServerName = malloc(strlen(value) + 1);
677             strcpy(adsmServerName, value);
678             printf("XBSA server is %s\n", adsmServerName);
679         }
680
681         else if (!strcmp(cmd, "PASSWORD")) {    /* This or PASSFILE required for XBSA */
682             if (!CONF_XBSA) {
683                 printf
684                     ("Warning: The %s parameter is ignored with a tape drive\n",
685                      cmd);
686                 continue;
687             }
688             if (xbsaSecToken) {
689                 printf
690                     ("Warning: The %s parameter is ignored. Already read password\n",
691                      cmd);
692                 continue;
693             }
694
695             xbsaSecToken = malloc(strlen(value) + 1);
696             strcpy(xbsaSecToken, value);
697             printf("XBSA Password has been read\n");
698         }
699
700         else if (!strcmp(cmd, "PASSFILE")) {    /* This or PASSWORD required for XBSA */
701             FILE *pwdFile;
702             if (!CONF_XBSA) {
703                 printf
704                     ("Warning: The %s parameter is ignored with a tape drive\n",
705                      cmd);
706                 continue;
707             }
708             if (xbsaSecToken) {
709                 printf
710                     ("Warning: The %s parameter is ignored. Already read password\n",
711                      cmd);
712                 continue;
713             }
714
715             pwdFile = fopen(value, "r");
716             if (!pwdFile) {
717                 printf
718                     ("Configuration file error, cannot open password file %s\n",
719                      value);
720                 ERROR_EXIT(1);
721             }
722             xbsaSecToken = malloc(LINESIZE);
723             if (!fscanf(pwdFile, "%s", xbsaSecToken)) {
724                 printf
725                     ("Configuration file error, cannot read password file %s\n",
726                      value);
727                 ERROR_EXIT(1);
728             }
729             printf("XBSA password retrieved from password file\n");
730         }
731
732         else if (!strcmp(cmd, "MGMTCLASS")) {   /* XBSA */
733             if (!CONF_XBSA) {
734                 printf
735                     ("Warning: The %s parameter is ignored with a tape drive\n",
736                      cmd);
737                 continue;
738             }
739             xbsalGName = malloc(strlen(value) + 1);
740             strcpy(xbsalGName, value);
741             printf("XBSA management class is %s\n", xbsalGName);
742         }
743 #endif
744
745         else if (!strcmp(cmd, "MAXPASS")) {
746             maxpass = SafeATOL(value);
747             if (maxpass < PASSESMIN)
748                 maxpass = PASSESMIN;
749             if (maxpass > PASSESMAX)
750                 maxpass = PASSESMAX;
751             printf("MAXPASS is %d\n", maxpass);
752         }
753
754         else if (!strcmp(cmd, "GROUPID")) {
755             groupId = SafeATOL(value);
756             if ((groupId < MINGROUPID) || (groupId > MAXGROUPID)) {
757                 printf("Configuration file error, %s %s is invalid\n", cmd,
758                        value);
759                 ERROR_EXIT(1);
760             }
761             printf("Group Id is %d\n", groupId);
762         }
763
764         else if (!strcmp(cmd, "LASTLOG")) {
765             for (cnt = 0; (size_t) cnt < strlen(value); cnt++)
766                 if (islower(value[cnt]))
767                     value[cnt] = toupper(value[cnt]);
768
769             lastLog = (strcmp(value, "YES") == 0);
770             printf("Will %sgenerate a last log\n", (lastLog ? "" : "not "));
771         }
772
773         else if (!strcmp(cmd, "CENTRALLOG")) {
774             centralLogFile = malloc(strlen(value) + 1);
775             strcpy(centralLogFile, value);
776             printf("Central log file is %s\n", centralLogFile);
777         }
778
779         else if (!strcmp(cmd, "STATUS")) {
780             if (atocl(value, 'B', &statusSize)) {
781                 fprintf(stderr, "STATUS parse error\n");
782                 statusSize = 0;
783             }
784             if (statusSize < MINSTATUS)
785                 statusSize = MINSTATUS;
786             if (statusSize > MAXSTATUS)
787                 statusSize = MAXSTATUS;
788         }
789
790         else {
791             printf("Warning: Unrecognized configuration parameter: %s", line);
792         }
793     }                           /*fgets */
794
795     if (statusSize) {
796         /* Statussize is in bytes and requires that BufferSize be set first */
797         statusSize *= BufferSize;
798         if (statusSize < 0)
799             statusSize = 0x7fffffff;    /*max size */
800         printf("Status every %ld Bytes\n", statusSize);
801     }
802
803   error_exit:
804     if (devFile)
805         fclose(devFile);
806
807     /* If the butc is configured as XBSA, check for required parameters */
808 #ifdef xbsa
809     if (!code && CONF_XBSA) {
810         if (xbsaType == XBSA_SERVER_TYPE_UNKNOWN) {
811             printf
812                 ("Configuration file error, the TYPE parameter must be specified, or\n");
813             printf("an entry must exist in %s for port %d\n", tapeConfigFile,
814                    port);
815             code = 1;
816         }
817         if (!adsmServerName) {
818             printf
819                 ("Configuration file error, the SERVER parameter must be specified\n");
820             code = 1;
821         }
822         if (!xbsaSecToken) {
823             printf
824                 ("Configuration file error, the PASSWORD or PASSFILE parameter must be specified\n");
825             code = 1;
826         }
827     }
828 #endif /*xbsa */
829     return (code);
830 }
831
832 static int
833 WorkerBee(struct cmd_syndesc *as, char *arock)
834 {
835     register afs_int32 code;
836     struct rx_securityClass *(securityObjects[3]);
837     struct rx_service *service;
838     struct ktc_token ttoken;
839     char cellName[64];
840     int localauth;
841     /*process arguments */
842     afs_int32 portOffset = 0;
843 #ifdef AFS_PTHREAD_ENV
844     pthread_t dbWatcherPid;
845     pthread_attr_t tattr;
846     AFS_SIGSET_DECL;
847 #else
848     PROCESS dbWatcherPid;
849 #endif
850     time_t t;
851     afs_uint32 host = htonl(INADDR_ANY);
852
853     debugLevel = 0;
854
855     /*initialize the error tables */
856     initialize_KA_error_table();
857     initialize_RXK_error_table();
858     initialize_KTC_error_table();
859     initialize_ACFG_error_table();
860     initialize_CMD_error_table();
861     initialize_VL_error_table();
862     initialize_BUTM_error_table();
863     initialize_BUTC_error_table();
864 #ifdef xbsa
865     initialize_BUTX_error_table();
866 #endif /*xbs */
867     initialize_VOLS_error_table();
868     initialize_BUDB_error_table();
869     initialize_BUCD_error_table();
870
871     if (as->parms[0].items) {
872         portOffset = SafeATOL(as->parms[0].items->data);
873         if (portOffset == -1) {
874             fprintf(stderr, "Illegal port offset '%s'\n",
875                     as->parms[0].items->data);
876             exit(1);
877         } else if (portOffset > BC_MAXPORTOFFSET) {
878             fprintf(stderr, "%u exceeds max port offset %u\n", portOffset,
879                     BC_MAXPORTOFFSET);
880             exit(1);
881         }
882     }
883
884     xbsaType = XBSA_SERVER_TYPE_NONE;   /* default */
885     if (as->parms[3].items) {   /* -device */
886         globalTapeConfig.capacity = 0x7fffffff; /* 2T for max tape capacity */
887         globalTapeConfig.fileMarkSize = 0;
888         globalTapeConfig.portOffset = portOffset;
889         strncpy(globalTapeConfig.device, as->parms[3].items->data, 100);
890         xbsaType = XBSA_SERVER_TYPE_NONE;       /* Not XBSA */
891     } else {
892         /* Search for an entry in tapeconfig file */
893         code = GetDeviceConfig(tapeConfigFile, &globalTapeConfig, portOffset);
894         if (code == -1) {
895             fprintf(stderr, "Problem in reading config file %s\n",
896                     tapeConfigFile);
897             exit(1);
898         }
899         /* Set xbsaType. If code == 1, no entry was found in the tapeconfig file so
900          * it's an XBSA server. Don't know if its ADSM or not so its unknown.
901          */
902         xbsaType =
903             ((code == 1) ? XBSA_SERVER_TYPE_UNKNOWN : XBSA_SERVER_TYPE_NONE);
904     }
905
906     if (as->parms[6].items) {   /* -restoretofile */
907         int s = strlen(as->parms[6].items->data);
908         restoretofile = malloc(s + 1);
909         strncpy(restoretofile, as->parms[6].items->data, s + 1);
910         printf("Restore to file '%s'\n", restoretofile);
911     }
912
913     /* Go and read the config file: CFG_<device> or CFG_<port>. We will also set
914      * the exact xbsaType within the call (won't be unknown) - double check.
915      */
916     code = GetConfigParams(pFile, portOffset);
917     if (code)
918         exit(code);
919 #ifdef xbsa
920     if (xbsaType == XBSA_SERVER_TYPE_UNKNOWN) {
921         printf
922             ("\nConfiguration file error, the TYPE parameter must be specified, or\n");
923         printf("an entry must exist in %s for port %d\n", tapeConfigFile,
924                portOffset);
925         exit(1);
926     }
927 #else
928     /* Not compiled for XBSA code so we can't support it */
929     if (CONF_XBSA) {
930         printf("\nNo entry found in %s for port %d\n", tapeConfigFile,
931                portOffset);
932         printf("This binary does not have XBSA support\n");
933         exit(1);
934     }
935 #endif
936
937     /* Open the log files. The pathnames were set in GetConfigParams() */
938     logIO = fopen(logFile, "a");
939     if (!logIO) {
940         fprintf(stderr, "Failed to open %s\n", logFile);
941         exit(1);
942     }
943     ErrorlogIO = fopen(ErrorlogFile, "a");
944     if (!ErrorlogIO) {
945         fprintf(stderr, "Failed to open %s\n", ErrorlogFile);
946         exit(1);
947     }
948     if (lastLog) {
949         lastLogIO = fopen(lastLogFile, "a");
950         if (!lastLogIO) {
951             fprintf(stderr, "Failed to open %s\n", lastLogFile);
952             exit(1);
953         }
954     }
955     if (centralLogFile) {
956         struct stat sbuf;
957         afs_int32 statcode;
958 #ifndef AFS_NT40_ENV
959         char path[AFSDIR_PATH_MAX];
960 #endif
961
962         statcode = stat(centralLogFile, &sbuf);
963         centralLogIO = fopen(centralLogFile, "a");
964         if (!centralLogIO) {
965             fprintf(stderr, "Failed to open %s; error %d\n", centralLogFile,
966                     errno);
967             exit(1);
968         }
969 #ifndef AFS_NT40_ENV
970         /* Make sure it is not in AFS, has to have been created first */
971         if (!realpath(centralLogFile, path)) {
972             fprintf(stderr,
973                     "Warning: can't determine real path of '%s' (%d)\n",
974                     centralLogFile, errno);
975         } else {
976             if (strncmp(path, "/afs/", 5) == 0) {
977                 fprintf(stderr, "The central log '%s' should not be in AFS\n",
978                         centralLogFile);
979                 exit(1);
980             }
981         }
982 #endif
983
984         /* Write header if created it */
985         if (statcode) {
986             char *h1 =
987                 "TASK   START DATE/TIME      END DATE/TIME        ELAPSED   VOLUMESET\n";
988             char *h2 =
989                 "-----  -------------------  -------------------  --------  ---------\n";
990             /* File didn't exist before so write the header lines */
991             fwrite(h1, strlen(h1), 1, centralLogIO);
992             fwrite(h2, strlen(h2), 1, centralLogIO);
993             fflush(centralLogIO);
994         }
995     }
996
997     if (as->parms[1].items) {
998         debugLevel = SafeATOL(as->parms[1].items->data);
999         if (debugLevel == -1) {
1000             TLog(0, "Illegal debug level '%s'\n", as->parms[1].items->data);
1001             exit(1);
1002         }
1003     }
1004 #ifdef xbsa
1005     /* Setup XBSA library interface */
1006     if (CONF_XBSA) {
1007         afs_int32 rc;
1008         rc = xbsa_MountLibrary(&butxInfo, xbsaType);
1009         if (rc != XBSA_SUCCESS) {
1010             TapeLog(0, 0, rc, 0, "Unable to mount the XBSA library\n");
1011             return (1);
1012         }
1013
1014         forcemultiple = (as->parms[7].items ? 1 : 0);/*-xbsaforcemultiple */
1015         if (forcemultiple)
1016             printf("Force XBSA multiple server support\n");
1017
1018         rc = InitToServer(0 /*taskid */ , &butxInfo, adsmServerName);
1019         if (rc != XBSA_SUCCESS)
1020             return (1);
1021     }
1022 #endif /*xbsa */
1023
1024     /* cell switch */
1025     if (as->parms[2].items)
1026         strncpy(cellName, as->parms[2].items->data, sizeof(cellName));
1027     else
1028         cellName[0] = '\0';
1029
1030     if (as->parms[4].items)
1031         autoQuery = 0;
1032
1033     localauth = (as->parms[5].items ? 1 : 0);
1034     rxBind = (as->parms[8].items ? 1 : 0);
1035
1036     if (rxBind) {
1037         afs_int32 ccode;
1038 #ifndef AFS_NT40_ENV
1039         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
1040             AFSDIR_SERVER_NETINFO_FILEPATH) {
1041             char reason[1024];
1042             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
1043                                            ADDRSPERSITE, reason,
1044                                            AFSDIR_SERVER_NETINFO_FILEPATH,
1045                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1046         } else 
1047 #endif  
1048         {
1049             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
1050         }
1051         if (ccode == 1) 
1052             host = SHostAddrs[0];
1053     }
1054
1055     code = rx_InitHost(host, htons(BC_TAPEPORT + portOffset));
1056     if (code) {
1057         TapeLog(0, 0, code, 0, "rx init failed on port %u\n",
1058                 BC_TAPEPORT + portOffset);
1059         exit(1);
1060     }
1061     rx_SetRxDeadTime(150);
1062
1063     /* Establish connection with the vldb server */
1064     code = vldbClientInit(0, localauth, cellName, &cstruct, &ttoken);
1065     if (code) {
1066         TapeLog(0, 0, code, 0, "Can't access vldb\n");
1067         return code;
1068     }
1069
1070     strcpy(globalCellName, cellName);
1071
1072     /*initialize the dumpNode list */
1073     InitNodeList(portOffset);
1074
1075     deviceLatch =
1076         (struct deviceSyncNode *)(malloc(sizeof(struct deviceSyncNode)));
1077     Lock_Init(&(deviceLatch->lock));
1078     deviceLatch->flags = 0;
1079
1080     /* initialize database support, volume support, and logs */
1081
1082     /* Create a single security object, in this case the null security
1083      * object, for unauthenticated connections, which will be used to control
1084      * security on connections made to this server 
1085      */
1086
1087     securityObjects[0] = rxnull_NewServerSecurityObject();
1088     securityObjects[1] = (struct rx_securityClass *)0;  /* don't bother with rxvab */
1089     if (!securityObjects[0]) {
1090         TLog(0, "rxnull_NewServerSecurityObject");
1091         exit(1);
1092     }
1093
1094     service =
1095         rx_NewServiceHost(host, 0, 1, "BUTC", securityObjects, 3, TC_ExecuteRequest);
1096     if (!service) {
1097         TLog(0, "rx_NewService");
1098         exit(1);
1099     }
1100     rx_SetMaxProcs(service, 4);
1101
1102     /* Establish connection to the backup database */
1103     code = udbClientInit(0, localauth, cellName);
1104     if (code) {
1105         TapeLog(0, 0, code, 0, "Can't access backup database\n");
1106         exit(1);
1107     }
1108     /* This call is here to verify that we are authentiated.
1109      * The call does nothing and will return BUDB_NOTPERMITTED 
1110      * if we don't belong.
1111      */
1112     code = bcdb_deleteDump(0, 0, 0, 0);
1113     if (code == BUDB_NOTPERMITTED) {
1114         TapeLog(0, 0, code, 0, "Can't access backup database\n");
1115         exit(1);
1116     }
1117
1118     initStatus();
1119 #ifdef AFS_PTHREAD_ENV
1120     code = pthread_attr_init(&tattr);
1121     if (code) {
1122         TapeLog(0, 0, code, 0,
1123                 "Can't pthread_attr_init database monitor task");
1124         exit(1);
1125     }
1126     code = pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
1127     if (code) {
1128         TapeLog(0, 0, code, 0,
1129                 "Can't pthread_attr_setdetachstate database monitor task");
1130         exit(1);
1131     }
1132     AFS_SIGSET_CLEAR();
1133     code = pthread_create(&dbWatcherPid, &tattr, dbWatcher, (void *)2);
1134     AFS_SIGSET_RESTORE();
1135 #else
1136     code =
1137         LWP_CreateProcess(dbWatcher, 20480, LWP_NORMAL_PRIORITY, (void *)2,
1138                           "dbWatcher", &dbWatcherPid);
1139 #endif
1140     if (code) {
1141         TapeLog(0, 0, code, 0, "Can't create database monitor task");
1142         exit(1);
1143     }
1144
1145     TLog(0, "Starting Tape Coordinator: Port offset %u   Debug level %u\n",
1146          portOffset, debugLevel);
1147     t = ttoken.endTime;
1148     TLog(0, "Token expires: %s\n", cTIME(&t));
1149
1150     rx_StartServer(1);          /* Donate this process to the server process pool */
1151     TLog(0, "Error: StartServer returned");
1152     exit(1);
1153 }
1154
1155 #ifndef AFS_NT40_ENV
1156 #include "AFS_component_version_number.c"
1157 #endif
1158
1159 int
1160 main(int argc, char **argv)
1161 {
1162     register struct cmd_syndesc *ts;
1163     register struct cmd_item *ti;
1164
1165 #ifdef  AFS_AIX32_ENV
1166     /*
1167      * The following signal action for AIX is necessary so that in case of a 
1168      * crash (i.e. core is generated) we can include the user's data section 
1169      * in the core dump. Unfortunately, by default, only a partial core is
1170      * generated which, in many cases, isn't too useful.
1171      */
1172     struct sigaction nsa;
1173
1174     sigemptyset(&nsa.sa_mask);
1175     nsa.sa_handler = SIG_DFL;
1176     nsa.sa_flags = SA_FULLDUMP;
1177     sigaction(SIGSEGV, &nsa, NULL);
1178     sigaction(SIGABRT, &nsa, NULL);
1179 #endif
1180
1181     setlinebuf(stdout);
1182
1183     ts = cmd_CreateSyntax(NULL, WorkerBee, NULL, "tape coordinator");
1184     cmd_AddParm(ts, "-port", CMD_SINGLE, CMD_OPTIONAL, "port offset");
1185     cmd_AddParm(ts, "-debuglevel", CMD_SINGLE, CMD_OPTIONAL, "0 | 1 | 2");
1186     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cell name");
1187     cmd_AddParm(ts, "-device", CMD_SINGLE, (CMD_OPTIONAL | CMD_HIDE),
1188                 "tape device path");
1189     cmd_AddParm(ts, "-noautoquery", CMD_FLAG, CMD_OPTIONAL,
1190                 "do not query operator for first tape");
1191     cmd_AddParm(ts, "-localauth", CMD_FLAG, CMD_OPTIONAL,
1192                 "create tickets from KeyFile");
1193     cmd_AddParm(ts, "-restoretofile", CMD_SINGLE, (CMD_OPTIONAL | CMD_HIDE),
1194                 "file to restore to");
1195     cmd_AddParm(ts, "-xbsaforcemultiple", CMD_FLAG, (CMD_OPTIONAL | CMD_HIDE),
1196                 "Force multiple XBSA server support");
1197     cmd_AddParm(ts, "-rxbind", CMD_FLAG, CMD_OPTIONAL,
1198                 "bind Rx socket");
1199
1200     /* Initialize dirpaths */
1201     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
1202 #ifdef AFS_NT40_ENV
1203         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
1204 #endif
1205         fprintf(stderr, "Unable to obtain AFS server directory.\n");
1206         exit(2);
1207     }
1208
1209     /* setup the file paths */
1210     strcompose(eFile, AFSDIR_PATH_MAX, AFSDIR_SERVER_BACKUP_DIRPATH, "/",
1211                TE_PREFIX, NULL);
1212     strcompose(lFile, AFSDIR_PATH_MAX, AFSDIR_SERVER_BACKUP_DIRPATH, "/",
1213                TL_PREFIX, NULL);
1214     strcompose(pFile, AFSDIR_PATH_MAX, AFSDIR_SERVER_BACKUP_DIRPATH, "/",
1215                CFG_PREFIX, NULL);
1216     strcpy(tapeConfigFile, AFSDIR_SERVER_TAPECONFIG_FILEPATH);
1217
1218     /* special case "no args" case since cmd_dispatch gives help message
1219      * instead
1220      */
1221     if (argc == 1) {
1222         ts = (struct cmd_syndesc *)malloc(sizeof(struct cmd_syndesc));
1223         memset(ts, 0, sizeof(*ts));
1224
1225         ti = (struct cmd_item *)malloc(sizeof(struct cmd_item));
1226         ti->next = 0;
1227         ti->data = "0";
1228         ts->parms[0].items = ti;
1229         ti = (struct cmd_item *)malloc(sizeof(struct cmd_item));
1230         ti->next = 0;
1231         ti->data = "0";
1232         ts->parms[1].items = ti;
1233         ts->parms[2].items = (struct cmd_item *)NULL;
1234         ts->parms[3].items = (struct cmd_item *)NULL;
1235         ts->parms[4].items = (struct cmd_item *)NULL;
1236         ts->parms[5].items = (struct cmd_item *)NULL;
1237         return WorkerBee(ts, NULL);
1238     } else
1239         return cmd_Dispatch(argc, argv);
1240 }