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