rxkad-v5-dot-check-20080122
[openafs.git] / src / volser / volmain.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 <string.h>
18 #ifdef AFS_NT40_ENV
19 #include <time.h>
20 #include <fcntl.h>
21 #include <windows.h>
22 #include <WINNT/afsevent.h>
23 #else
24 #include <sys/time.h>
25 #include <sys/file.h>
26 #include <netinet/in.h>
27 #endif
28 #include <rx/xdr.h>
29 #include <afs/afsint.h>
30 #include <stdio.h>
31 #include <signal.h>
32 #ifdef AFS_PTHREAD_ENV
33 #include <assert.h>
34 #else /* AFS_PTHREAD_ENV */
35 #include <afs/assert.h>
36 #endif /* AFS_PTHREAD_ENV */
37 #include <afs/prs_fs.h>
38 #include <afs/nfs.h>
39 #include <lwp.h>
40 #include <lock.h>
41 #include <afs/afssyscalls.h>
42 #include <afs/ihandle.h>
43 #ifdef AFS_NT40_ENV
44 #include <afs/ntops.h>
45 #endif
46 #include <afs/vnode.h>
47 #include <afs/volume.h>
48 #include <afs/partition.h>
49 #include <rx/rx.h>
50 #include <rx/rx_globals.h>
51 #include <afs/auth.h>
52 #include <afs/cellconfig.h>
53 #include <afs/keys.h>
54 #include <ubik.h>
55 #include <fcntl.h>
56 #include <sys/stat.h>
57
58 #include "volser.h"
59 #include <errno.h>
60 #include <afs/audit.h>
61 #include <afs/afsutil.h>
62
63 /*@printflike@*/ extern void Log(const char *format, ...);
64 /*@printflike@*/ extern void Abort(const char *format, ...);
65
66 #define VolserVersion "2.0"
67 #define N_SECURITY_OBJECTS 3
68
69 extern struct Lock localLock;
70 extern struct volser_trans *TransList();
71 #ifndef AFS_PTHREAD_ENV
72 extern int (*vol_PollProc) ();
73 extern int IOMGR_Poll();
74 #endif
75 char *GlobalNameHack = NULL;
76 int hackIsIn = 0;
77 afs_int32 GlobalVolCloneId, GlobalVolParentId;
78 int GlobalVolType;
79 int VolumeChanged;              /* XXXX */
80 static char busyFlags[MAXHELPERS];
81 struct volser_trans *QI_GlobalWriteTrans = 0;
82 extern void AFSVolExecuteRequest();
83 extern void RXSTATS_ExecuteRequest();
84 struct afsconf_dir *tdir;
85 static afs_int32 runningCalls = 0;
86 int DoLogging = 0;
87 #define MAXLWP 16
88 int lwps = 9;
89 int udpBufSize = 0;             /* UDP buffer size for receive */
90
91 int rxBind = 0;
92 int rxkadDisableDotCheck = 0;
93
94 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
95 afs_uint32 SHostAddrs[ADDRSPERSITE];
96
97 #define VS_EXIT(code)  {                                          \
98                           osi_audit(VS_ExitEvent, code, AUD_END); \
99                           exit(code);                             \
100                        }
101
102 #if defined(AFS_PTHREAD_ENV)
103 char *
104 threadNum(void)
105 {
106     return pthread_getspecific(rx_thread_id_key);
107 }
108 #endif
109
110 static afs_int32
111 MyBeforeProc(struct rx_call *acall)
112 {
113     VTRANS_LOCK;
114     runningCalls++;
115     VTRANS_UNLOCK;
116     return 0;
117 }
118
119 static afs_int32
120 MyAfterProc(struct rx_call *acall, afs_int32 code)
121 {
122     VTRANS_LOCK;
123     runningCalls--;
124     VTRANS_UNLOCK;
125     return 0;
126 }
127
128 /* Called every GCWAKEUP seconds to try to unlock all our partitions,
129  * if we're idle and there are no active transactions 
130  */
131 static void
132 TryUnlock()
133 {
134     /* if there are no running calls, and there are no active transactions, then
135      * it should be safe to release any partition locks we've accumulated */
136     VTRANS_LOCK;
137     if (runningCalls == 0 && TransList() == (struct volser_trans *)0) {
138         VTRANS_UNLOCK;
139         VPFullUnlock();         /* in volprocs.c */
140     } else
141         VTRANS_UNLOCK;
142 }
143
144 /* background daemon for timing out transactions */
145 static void
146 BKGLoop()
147 {
148     struct timeval tv;
149     int loop = 0;
150
151     while (1) {
152         tv.tv_sec = GCWAKEUP;
153         tv.tv_usec = 0;
154 #ifdef AFS_PTHREAD_ENV
155         select(0, 0, 0, 0, &tv);
156 #else
157         (void)IOMGR_Select(0, 0, 0, 0, &tv);
158 #endif
159         GCTrans();
160         TryUnlock();
161         loop++;
162         if (loop == 10) {       /* reopen log every 5 minutes */
163             loop = 0;
164             ReOpenLog(AFSDIR_SERVER_VOLSERLOG_FILEPATH);
165         }
166     }
167 }
168
169 /* Background daemon for sleeping so the volserver does not become I/O bound */
170 afs_int32 TTsleep, TTrun;
171 static void
172 BKGSleep()
173 {
174     struct volser_trans *tt;
175
176     if (TTsleep) {
177         while (1) {
178 #ifdef AFS_PTHREAD_ENV
179             sleep(TTrun);
180 #else /* AFS_PTHREAD_ENV */
181             IOMGR_Sleep(TTrun);
182 #endif
183             VTRANS_LOCK;
184             for (tt = TransList(); tt; tt = tt->next) {
185                 if ((strcmp(tt->lastProcName, "DeleteVolume") == 0)
186                     || (strcmp(tt->lastProcName, "Clone") == 0)
187                     || (strcmp(tt->lastProcName, "ReClone") == 0)
188                     || (strcmp(tt->lastProcName, "Forward") == 0)
189                     || (strcmp(tt->lastProcName, "Restore") == 0)
190                     || (strcmp(tt->lastProcName, "ForwardMulti") == 0))
191                     break;
192             }
193             if (tt) {
194                 VTRANS_UNLOCK;
195                 sleep(TTsleep);
196             } else
197                 VTRANS_UNLOCK;
198         }
199     }
200 }
201
202 #ifndef AFS_NT40_ENV
203 int
204 volser_syscall(afs_uint32 a3, afs_uint32 a4, void *a5)
205 {
206     afs_uint32 rcode;
207     void (*old) ();
208
209 #ifndef AFS_LINUX20_ENV
210     old = signal(SIGSYS, SIG_IGN);
211 #endif
212     rcode =
213         syscall(AFS_SYSCALL /* AFS_SYSCALL */ , 28 /* AFSCALL_CALL */ , a3,
214                 a4, a5);
215 #ifndef AFS_LINUX20_ENV
216     signal(SIGSYS, old);
217 #endif
218
219     return rcode;
220 }
221 #endif
222
223
224 /* check whether caller is authorized to manage RX statistics */
225 int
226 vol_rxstat_userok(struct rx_call *call)
227 {
228     return afsconf_SuperUser(tdir, call, NULL);
229 }
230
231 #include "AFS_component_version_number.c"
232 int 
233 main(int argc, char **argv)
234 {
235     register afs_int32 code;
236     struct rx_securityClass *(securityObjects[3]);
237     struct rx_service *service;
238     struct ktc_encryptionKey tkey;
239     int rxpackets = 100;
240     char commandLine[150];
241     int i;
242     int rxJumbograms = 1;       /* default is to send and receive jumbograms. */
243     int rxMaxMTU = -1;
244     int bufSize = 0;            /* temp variable to read in udp socket buf size */
245     afs_uint32 host = ntohl(INADDR_ANY);
246
247 #ifdef  AFS_AIX32_ENV
248     /*
249      * The following signal action for AIX is necessary so that in case of a 
250      * crash (i.e. core is generated) we can include the user's data section 
251      * in the core dump. Unfortunately, by default, only a partial core is
252      * generated which, in many cases, isn't too useful.
253      */
254     struct sigaction nsa;
255
256     sigemptyset(&nsa.sa_mask);
257     nsa.sa_handler = SIG_DFL;
258     nsa.sa_flags = SA_FULLDUMP;
259     sigaction(SIGABRT, &nsa, NULL);
260     sigaction(SIGSEGV, &nsa, NULL);
261 #endif
262     osi_audit_init();
263     osi_audit(VS_StartEvent, 0, AUD_END);
264
265     /* Initialize dirpaths */
266     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
267 #ifdef AFS_NT40_ENV
268         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
269 #endif
270         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
271                 argv[0]);
272         exit(2);
273     }
274
275     for (commandLine[0] = '\0', i = 0; i < argc; i++) {
276         if (i > 0)
277             strcat(commandLine, " ");
278         strcat(commandLine, argv[i]);
279     }
280
281     TTsleep = TTrun = 0;
282
283     /* parse cmd line */
284     for (code = 1; code < argc; code++) {
285         if (strcmp(argv[code], "-log") == 0) {
286             /* set extra logging flag */
287             DoLogging = 1;
288         } else if (strcmp(argv[code], "-help") == 0) {
289             goto usage;
290         } else if (strcmp(argv[code], "-rxbind") == 0) {
291             rxBind = 1;
292         } else if (strcmp(argv[code], "-allow-dotted-principals") == 0) {
293             rxkadDisableDotCheck = 1;
294         } else if (strcmp(argv[code], "-p") == 0) {
295             lwps = atoi(argv[++code]);
296             if (lwps > MAXLWP) {
297                 printf("Warning: '-p %d' is too big; using %d instead\n",
298                        lwps, MAXLWP);
299                 lwps = MAXLWP;
300             }
301         } else if (strcmp(argv[code], "-auditlog") == 0) {
302             int tempfd, flags;
303             FILE *auditout;
304             char oldName[MAXPATHLEN];
305             char *fileName = argv[++code];
306
307 #ifndef AFS_NT40_ENV
308             struct stat statbuf;
309             
310             if ((lstat(fileName, &statbuf) == 0) 
311                 && (S_ISFIFO(statbuf.st_mode))) {
312                 flags = O_WRONLY | O_NONBLOCK;
313             } else 
314 #endif
315             {
316                 strcpy(oldName, fileName);
317                 strcat(oldName, ".old");
318                 renamefile(fileName, oldName);
319                 flags = O_WRONLY | O_TRUNC | O_CREAT;
320             }
321             tempfd = open(fileName, flags, 0666);
322             if (tempfd > -1) {
323                 auditout = fdopen(tempfd, "a");
324                 if (auditout) {
325                     osi_audit_file(auditout);
326                     osi_audit(VS_StartEvent, 0, AUD_END);
327                 } else
328                     printf("Warning: auditlog %s not writable, ignored.\n", fileName);
329             } else
330                 printf("Warning: auditlog %s not writable, ignored.\n", fileName);
331         } else if (strcmp(argv[code], "-nojumbo") == 0) {
332             rxJumbograms = 0;
333         } else if (!strcmp(argv[code], "-rxmaxmtu")) {
334             if ((code + 1) >= argc) {
335                 fprintf(stderr, "missing argument for -rxmaxmtu\n"); 
336                 exit(1); 
337             }
338             rxMaxMTU = atoi(argv[++code]);
339             if ((rxMaxMTU < RX_MIN_PACKET_SIZE) || 
340                 (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
341                 printf("rxMaxMTU %d% invalid; must be between %d-%d\n",
342                        rxMaxMTU, RX_MIN_PACKET_SIZE, 
343                        RX_MAX_PACKET_DATA_SIZE);
344                 exit(1);
345             }
346         } else if (strcmp(argv[code], "-sleep") == 0) {
347             sscanf(argv[++code], "%d/%d", &TTsleep, &TTrun);
348             if ((TTsleep < 0) || (TTrun <= 0)) {
349                 printf("Warning: '-sleep %d/%d' is incorrect; ignoring\n",
350                        TTsleep, TTrun);
351                 TTsleep = TTrun = 0;
352             }
353         } else if (strcmp(argv[code], "-udpsize") == 0) {
354             if ((code + 1) >= argc) {
355                 printf("You have to specify -udpsize <integer value>\n");
356                 exit(1);
357             }
358             sscanf(argv[++code], "%d", &bufSize);
359             if (bufSize < rx_GetMinUdpBufSize())
360                 printf
361                     ("Warning:udpsize %d is less than minimum %d; ignoring\n",
362                      bufSize, rx_GetMinUdpBufSize());
363             else
364                 udpBufSize = bufSize;
365         } else if (strcmp(argv[code], "-enable_peer_stats") == 0) {
366             rx_enablePeerRPCStats();
367         } else if (strcmp(argv[code], "-enable_process_stats") == 0) {
368             rx_enableProcessRPCStats();
369         }
370 #ifndef AFS_NT40_ENV
371         else if (strcmp(argv[code], "-syslog") == 0) {
372             /* set syslog logging flag */
373             serverLogSyslog = 1;
374         } else if (strncmp(argv[code], "-syslog=", 8) == 0) {
375             serverLogSyslog = 1;
376             serverLogSyslogFacility = atoi(argv[code] + 8);
377         }
378 #endif
379         else {
380             printf("volserver: unrecognized flag '%s'\n", argv[code]);
381           usage:
382 #ifndef AFS_NT40_ENV
383             printf("Usage: volserver [-log] [-p <number of processes>] "
384                    "[-auditlog <log path>] "
385                    "[-nojumbo] [-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals] "
386                    "[-udpsize <size of socket buffer in bytes>] "
387                    "[-syslog[=FACILITY]] "
388                    "[-enable_peer_stats] [-enable_process_stats] "
389                    "[-help]\n");
390 #else
391             printf("Usage: volserver [-log] [-p <number of processes>] "
392                    "[-auditlog <log path>] "
393                    "[-nojumbo] [-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals] "
394                    "[-udpsize <size of socket buffer in bytes>] "
395                    "[-enable_peer_stats] [-enable_process_stats] "
396                    "[-help]\n");
397 #endif
398             VS_EXIT(1);
399         }
400     }
401 #ifdef AFS_SGI_VNODE_GLUE
402     if (afs_init_kernel_config(-1) < 0) {
403         printf
404             ("Can't determine NUMA configuration, not starting volserver.\n");
405         exit(1);
406     }
407 #endif
408     InitErrTabs();
409
410 #ifdef AFS_PTHREAD_ENV
411     SetLogThreadNumProgram( threadNum );
412 #endif
413
414 #ifdef AFS_NT40_ENV
415     if (afs_winsockInit() < 0) {
416         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
417         printf("Volume server unable to start winsock, exiting.\n");
418         exit(1);
419     }
420 #endif
421     /* Open VolserLog and map stdout, stderr into it; VInitVolumePackage can
422        log, so we need to do this here */
423     OpenLog(AFSDIR_SERVER_VOLSERLOG_FILEPATH);
424
425     VInitVolumePackage(volumeUtility, 0, 0, CONNECT_FS, 0);
426     /* For nuke() */
427     Lock_Init(&localLock);
428     DInit(40);
429 #ifndef AFS_PTHREAD_ENV
430     vol_PollProc = IOMGR_Poll;  /* tell vol pkg to poll io system periodically */
431 #endif
432 #ifndef AFS_NT40_ENV
433     rxi_syscallp = volser_syscall;
434 #endif
435     rx_nPackets = rxpackets;    /* set the max number of packets */
436     if (udpBufSize)
437         rx_SetUdpBufSize(udpBufSize);   /* set the UDP buffer size for receive */
438     if (rxBind) {
439         afs_int32 ccode;
440 #ifndef AFS_NT40_ENV
441         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
442             AFSDIR_SERVER_NETINFO_FILEPATH) {
443             char reason[1024];
444             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
445                                            ADDRSPERSITE, reason,
446                                            AFSDIR_SERVER_NETINFO_FILEPATH,
447                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
448         } else 
449 #endif  
450         {
451             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
452         }
453         if (ccode == 1) 
454             host = SHostAddrs[0];
455     }
456
457     code = rx_InitHost(host, (int)htons(AFSCONF_VOLUMEPORT));
458     if (code) {
459         fprintf(stderr, "rx init failed on socket AFSCONF_VOLUMEPORT %u\n",
460                 AFSCONF_VOLUMEPORT);
461         VS_EXIT(1);
462     }
463     if (!rxJumbograms) {
464         /* Don't allow 3.4 vos clients to send jumbograms and we don't send. */
465         rx_SetNoJumbo();
466     }
467     if (rxMaxMTU != -1) {
468         rx_SetMaxMTU(rxMaxMTU);
469     }
470     rx_GetIFInfo();
471     rx_SetRxDeadTime(420);
472     memset(busyFlags, 0, sizeof(busyFlags));
473
474     SetupLogSignals();
475
476     {
477 #ifdef AFS_PTHREAD_ENV
478         pthread_t tid;
479         pthread_attr_t tattr;
480         assert(pthread_attr_init(&tattr) == 0);
481         assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
482
483         assert(pthread_create(&tid, &tattr, (void *)BKGLoop, NULL) == 0);
484 #else
485         PROCESS pid;
486         LWP_CreateProcess(BKGLoop, 16*1024, 3, 0, "vol bkg daemon", &pid);
487         LWP_CreateProcess(BKGSleep,16*1024, 3, 0, "vol slp daemon", &pid);
488 #endif
489     }
490
491     /* Create a single security object, in this case the null security object, for unauthenticated connections, which will be used to control security on connections made to this server */
492
493     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
494     if (!tdir) {
495         Abort("volser: could not open conf files in %s\n",
496               AFSDIR_SERVER_ETC_DIRPATH);
497         VS_EXIT(1);
498     }
499     afsconf_GetKey(tdir, 999, &tkey);
500     securityObjects[0] = rxnull_NewServerSecurityObject();
501     securityObjects[1] = (struct rx_securityClass *)0;  /* don't bother with rxvab */
502     securityObjects[2] =
503         rxkad_NewServerSecurityObject(0, tdir, afsconf_GetKey, NULL);
504     if (securityObjects[0] == (struct rx_securityClass *)0)
505         Abort("rxnull_NewServerSecurityObject");
506     service =
507         rx_NewServiceHost(host, 0, VOLSERVICE_ID, "VOLSER", securityObjects, 3,
508                       AFSVolExecuteRequest);
509     if (service == (struct rx_service *)0)
510         Abort("rx_NewService");
511     rx_SetBeforeProc(service, MyBeforeProc);
512     rx_SetAfterProc(service, MyAfterProc);
513     rx_SetIdleDeadTime(service, 0);     /* never timeout */
514     if (lwps < 4)
515         lwps = 4;
516     rx_SetMaxProcs(service, lwps);
517 #if defined(AFS_XBSD_ENV)
518     rx_SetStackSize(service, (128 * 1024));
519 #elif defined(AFS_SGI_ENV)
520     rx_SetStackSize(service, (48 * 1024));
521 #else
522     rx_SetStackSize(service, (32 * 1024));
523 #endif
524
525     if (rxkadDisableDotCheck) {
526         rx_SetSecurityConfiguration(service, RXS_CONFIG_FLAGS,
527                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK,
528                                     NULL);
529     }
530
531     service =
532         rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityObjects, 3,
533                       RXSTATS_ExecuteRequest);
534     if (service == (struct rx_service *)0)
535         Abort("rx_NewService");
536     rx_SetMinProcs(service, 2);
537     rx_SetMaxProcs(service, 4);
538
539     Log("Starting AFS Volserver %s (%s)\n", VolserVersion, commandLine);
540     if (TTsleep) {
541         Log("Will sleep %d second%s every %d second%s\n", TTsleep,
542             (TTsleep > 1) ? "s" : "", TTrun + TTsleep,
543             (TTrun + TTsleep > 1) ? "s" : "");
544     }
545
546     /* allow super users to manage RX statistics */
547     rx_SetRxStatUserOk(vol_rxstat_userok);
548
549     rx_StartServer(1);          /* Donate this process to the server process pool */
550
551     osi_audit(VS_FinishEvent, (-1), AUD_END);
552     Abort("StartServer returned?");
553     return 0; /* not reached */
554 }