8eb9758e2abe5018f1e5afb32c11607336880319
[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(void *unused)
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     return NULL;
169 }
170
171 /* Background daemon for sleeping so the volserver does not become I/O bound */
172 afs_int32 TTsleep, TTrun;
173 static void *
174 BKGSleep(void *unused)
175 {
176     struct volser_trans *tt;
177
178     if (TTsleep) {
179         while (1) {
180 #ifdef AFS_PTHREAD_ENV
181             sleep(TTrun);
182 #else /* AFS_PTHREAD_ENV */
183             IOMGR_Sleep(TTrun);
184 #endif
185             VTRANS_LOCK;
186             for (tt = TransList(); tt; tt = tt->next) {
187                 if ((strcmp(tt->lastProcName, "DeleteVolume") == 0)
188                     || (strcmp(tt->lastProcName, "Clone") == 0)
189                     || (strcmp(tt->lastProcName, "ReClone") == 0)
190                     || (strcmp(tt->lastProcName, "Forward") == 0)
191                     || (strcmp(tt->lastProcName, "Restore") == 0)
192                     || (strcmp(tt->lastProcName, "ForwardMulti") == 0))
193                     break;
194             }
195             if (tt) {
196                 VTRANS_UNLOCK;
197                 sleep(TTsleep);
198             } else
199                 VTRANS_UNLOCK;
200         }
201     }
202     return NULL;
203 }
204
205 #ifndef AFS_NT40_ENV
206 int
207 volser_syscall(afs_uint32 a3, afs_uint32 a4, void *a5)
208 {
209     afs_uint32 rcode;
210     void (*old) ();
211
212 #ifndef AFS_LINUX20_ENV
213     old = signal(SIGSYS, SIG_IGN);
214 #endif
215     rcode =
216         syscall(AFS_SYSCALL /* AFS_SYSCALL */ , 28 /* AFSCALL_CALL */ , a3,
217                 a4, a5);
218 #ifndef AFS_LINUX20_ENV
219     signal(SIGSYS, old);
220 #endif
221
222     return rcode;
223 }
224 #endif
225
226
227 /* check whether caller is authorized to manage RX statistics */
228 int
229 vol_rxstat_userok(struct rx_call *call)
230 {
231     return afsconf_SuperUser(tdir, call, NULL);
232 }
233
234 #include "AFS_component_version_number.c"
235 int 
236 main(int argc, char **argv)
237 {
238     register afs_int32 code;
239     struct rx_securityClass *(securityObjects[3]);
240     struct rx_service *service;
241     struct ktc_encryptionKey tkey;
242     int rxpackets = 100;
243     char commandLine[150];
244     int i;
245     int rxJumbograms = 1;       /* default is to send and receive jumbograms. */
246     int rxMaxMTU = -1;
247     int bufSize = 0;            /* temp variable to read in udp socket buf size */
248     afs_uint32 host = ntohl(INADDR_ANY);
249
250 #ifdef  AFS_AIX32_ENV
251     /*
252      * The following signal action for AIX is necessary so that in case of a 
253      * crash (i.e. core is generated) we can include the user's data section 
254      * in the core dump. Unfortunately, by default, only a partial core is
255      * generated which, in many cases, isn't too useful.
256      */
257     struct sigaction nsa;
258
259     sigemptyset(&nsa.sa_mask);
260     nsa.sa_handler = SIG_DFL;
261     nsa.sa_flags = SA_FULLDUMP;
262     sigaction(SIGABRT, &nsa, NULL);
263     sigaction(SIGSEGV, &nsa, NULL);
264 #endif
265     osi_audit_init();
266     osi_audit(VS_StartEvent, 0, AUD_END);
267
268     /* Initialize dirpaths */
269     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
270 #ifdef AFS_NT40_ENV
271         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
272 #endif
273         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
274                 argv[0]);
275         exit(2);
276     }
277
278     for (commandLine[0] = '\0', i = 0; i < argc; i++) {
279         if (i > 0)
280             strcat(commandLine, " ");
281         strcat(commandLine, argv[i]);
282     }
283
284     TTsleep = TTrun = 0;
285
286     /* parse cmd line */
287     for (code = 1; code < argc; code++) {
288         if (strcmp(argv[code], "-log") == 0) {
289             /* set extra logging flag */
290             DoLogging = 1;
291         } else if (strcmp(argv[code], "-help") == 0) {
292             goto usage;
293         } else if (strcmp(argv[code], "-rxbind") == 0) {
294             rxBind = 1;
295         } else if (strcmp(argv[code], "-allow-dotted-principals") == 0) {
296             rxkadDisableDotCheck = 1;
297         } else if (strcmp(argv[code], "-p") == 0) {
298             lwps = atoi(argv[++code]);
299             if (lwps > MAXLWP) {
300                 printf("Warning: '-p %d' is too big; using %d instead\n",
301                        lwps, MAXLWP);
302                 lwps = MAXLWP;
303             }
304         } else if (strcmp(argv[code], "-auditlog") == 0) {
305             int tempfd, flags;
306             FILE *auditout;
307             char oldName[MAXPATHLEN];
308             char *fileName = argv[++code];
309
310 #ifndef AFS_NT40_ENV
311             struct stat statbuf;
312             
313             if ((lstat(fileName, &statbuf) == 0) 
314                 && (S_ISFIFO(statbuf.st_mode))) {
315                 flags = O_WRONLY | O_NONBLOCK;
316             } else 
317 #endif
318             {
319                 strcpy(oldName, fileName);
320                 strcat(oldName, ".old");
321                 renamefile(fileName, oldName);
322                 flags = O_WRONLY | O_TRUNC | O_CREAT;
323             }
324             tempfd = open(fileName, flags, 0666);
325             if (tempfd > -1) {
326                 auditout = fdopen(tempfd, "a");
327                 if (auditout) {
328                     osi_audit_file(auditout);
329                     osi_audit(VS_StartEvent, 0, AUD_END);
330                 } else
331                     printf("Warning: auditlog %s not writable, ignored.\n", fileName);
332             } else
333                 printf("Warning: auditlog %s not writable, ignored.\n", fileName);
334         } else if (strcmp(argv[code], "-nojumbo") == 0) {
335             rxJumbograms = 0;
336         } else if (!strcmp(argv[code], "-rxmaxmtu")) {
337             if ((code + 1) >= argc) {
338                 fprintf(stderr, "missing argument for -rxmaxmtu\n"); 
339                 exit(1); 
340             }
341             rxMaxMTU = atoi(argv[++code]);
342             if ((rxMaxMTU < RX_MIN_PACKET_SIZE) || 
343                 (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
344                 printf("rxMaxMTU %d% invalid; must be between %d-%d\n",
345                        rxMaxMTU, RX_MIN_PACKET_SIZE, 
346                        RX_MAX_PACKET_DATA_SIZE);
347                 exit(1);
348             }
349         } else if (strcmp(argv[code], "-sleep") == 0) {
350             sscanf(argv[++code], "%d/%d", &TTsleep, &TTrun);
351             if ((TTsleep < 0) || (TTrun <= 0)) {
352                 printf("Warning: '-sleep %d/%d' is incorrect; ignoring\n",
353                        TTsleep, TTrun);
354                 TTsleep = TTrun = 0;
355             }
356         } else if (strcmp(argv[code], "-udpsize") == 0) {
357             if ((code + 1) >= argc) {
358                 printf("You have to specify -udpsize <integer value>\n");
359                 exit(1);
360             }
361             sscanf(argv[++code], "%d", &bufSize);
362             if (bufSize < rx_GetMinUdpBufSize())
363                 printf
364                     ("Warning:udpsize %d is less than minimum %d; ignoring\n",
365                      bufSize, rx_GetMinUdpBufSize());
366             else
367                 udpBufSize = bufSize;
368         } else if (strcmp(argv[code], "-enable_peer_stats") == 0) {
369             rx_enablePeerRPCStats();
370         } else if (strcmp(argv[code], "-enable_process_stats") == 0) {
371             rx_enableProcessRPCStats();
372         }
373 #ifndef AFS_NT40_ENV
374         else if (strcmp(argv[code], "-syslog") == 0) {
375             /* set syslog logging flag */
376             serverLogSyslog = 1;
377         } else if (strncmp(argv[code], "-syslog=", 8) == 0) {
378             serverLogSyslog = 1;
379             serverLogSyslogFacility = atoi(argv[code] + 8);
380         }
381 #endif
382         else {
383             printf("volserver: unrecognized flag '%s'\n", argv[code]);
384           usage:
385 #ifndef AFS_NT40_ENV
386             printf("Usage: volserver [-log] [-p <number of processes>] "
387                    "[-auditlog <log path>] "
388                    "[-nojumbo] [-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals] "
389                    "[-udpsize <size of socket buffer in bytes>] "
390                    "[-syslog[=FACILITY]] "
391                    "[-enable_peer_stats] [-enable_process_stats] "
392                    "[-help]\n");
393 #else
394             printf("Usage: volserver [-log] [-p <number of processes>] "
395                    "[-auditlog <log path>] "
396                    "[-nojumbo] [-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals] "
397                    "[-udpsize <size of socket buffer in bytes>] "
398                    "[-enable_peer_stats] [-enable_process_stats] "
399                    "[-help]\n");
400 #endif
401             VS_EXIT(1);
402         }
403     }
404 #ifdef AFS_SGI_VNODE_GLUE
405     if (afs_init_kernel_config(-1) < 0) {
406         printf
407             ("Can't determine NUMA configuration, not starting volserver.\n");
408         exit(1);
409     }
410 #endif
411     InitErrTabs();
412
413 #ifdef AFS_PTHREAD_ENV
414     SetLogThreadNumProgram( threadNum );
415 #endif
416
417 #ifdef AFS_NT40_ENV
418     if (afs_winsockInit() < 0) {
419         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
420         printf("Volume server unable to start winsock, exiting.\n");
421         exit(1);
422     }
423 #endif
424     /* Open VolserLog and map stdout, stderr into it; VInitVolumePackage can
425        log, so we need to do this here */
426     OpenLog(AFSDIR_SERVER_VOLSERLOG_FILEPATH);
427
428     VInitVolumePackage(volumeUtility, 0, 0, CONNECT_FS, 0);
429     /* For nuke() */
430     Lock_Init(&localLock);
431     DInit(40);
432 #ifndef AFS_PTHREAD_ENV
433     vol_PollProc = IOMGR_Poll;  /* tell vol pkg to poll io system periodically */
434 #endif
435 #ifndef AFS_NT40_ENV
436     rxi_syscallp = volser_syscall;
437 #endif
438     rx_nPackets = rxpackets;    /* set the max number of packets */
439     if (udpBufSize)
440         rx_SetUdpBufSize(udpBufSize);   /* set the UDP buffer size for receive */
441     if (rxBind) {
442         afs_int32 ccode;
443 #ifndef AFS_NT40_ENV
444         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
445             AFSDIR_SERVER_NETINFO_FILEPATH) {
446             char reason[1024];
447             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
448                                            ADDRSPERSITE, reason,
449                                            AFSDIR_SERVER_NETINFO_FILEPATH,
450                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
451         } else 
452 #endif  
453         {
454             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
455         }
456         if (ccode == 1) 
457             host = SHostAddrs[0];
458     }
459
460     code = rx_InitHost(host, (int)htons(AFSCONF_VOLUMEPORT));
461     if (code) {
462         fprintf(stderr, "rx init failed on socket AFSCONF_VOLUMEPORT %u\n",
463                 AFSCONF_VOLUMEPORT);
464         VS_EXIT(1);
465     }
466     if (!rxJumbograms) {
467         /* Don't allow 3.4 vos clients to send jumbograms and we don't send. */
468         rx_SetNoJumbo();
469     }
470     if (rxMaxMTU != -1) {
471         rx_SetMaxMTU(rxMaxMTU);
472     }
473     rx_GetIFInfo();
474     rx_SetRxDeadTime(420);
475     memset(busyFlags, 0, sizeof(busyFlags));
476
477     SetupLogSignals();
478
479     {
480 #ifdef AFS_PTHREAD_ENV
481         pthread_t tid;
482         pthread_attr_t tattr;
483         assert(pthread_attr_init(&tattr) == 0);
484         assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
485
486         assert(pthread_create(&tid, &tattr, (void *)BKGLoop, NULL) == 0);
487 #else
488         PROCESS pid;
489         LWP_CreateProcess(BKGLoop, 16*1024, 3, 0, "vol bkg daemon", &pid);
490         LWP_CreateProcess(BKGSleep,16*1024, 3, 0, "vol slp daemon", &pid);
491 #endif
492     }
493
494     /* 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 */
495
496     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
497     if (!tdir) {
498         Abort("volser: could not open conf files in %s\n",
499               AFSDIR_SERVER_ETC_DIRPATH);
500         VS_EXIT(1);
501     }
502     afsconf_GetKey(tdir, 999, &tkey);
503     securityObjects[0] = rxnull_NewServerSecurityObject();
504     securityObjects[1] = (struct rx_securityClass *)0;  /* don't bother with rxvab */
505     securityObjects[2] =
506         rxkad_NewServerSecurityObject(0, tdir, afsconf_GetKey, NULL);
507     if (securityObjects[0] == (struct rx_securityClass *)0)
508         Abort("rxnull_NewServerSecurityObject");
509     service =
510         rx_NewServiceHost(host, 0, VOLSERVICE_ID, "VOLSER", securityObjects, 3,
511                       AFSVolExecuteRequest);
512     if (service == (struct rx_service *)0)
513         Abort("rx_NewService");
514     rx_SetBeforeProc(service, MyBeforeProc);
515     rx_SetAfterProc(service, MyAfterProc);
516     rx_SetIdleDeadTime(service, 0);     /* never timeout */
517     if (lwps < 4)
518         lwps = 4;
519     rx_SetMaxProcs(service, lwps);
520 #if defined(AFS_XBSD_ENV)
521     rx_SetStackSize(service, (128 * 1024));
522 #elif defined(AFS_SGI_ENV)
523     rx_SetStackSize(service, (48 * 1024));
524 #else
525     rx_SetStackSize(service, (32 * 1024));
526 #endif
527
528     if (rxkadDisableDotCheck) {
529         rx_SetSecurityConfiguration(service, RXS_CONFIG_FLAGS,
530                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK,
531                                     NULL);
532     }
533
534     service =
535         rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityObjects, 3,
536                       RXSTATS_ExecuteRequest);
537     if (service == (struct rx_service *)0)
538         Abort("rx_NewService");
539     rx_SetMinProcs(service, 2);
540     rx_SetMaxProcs(service, 4);
541
542     Log("Starting AFS Volserver %s (%s)\n", VolserVersion, commandLine);
543     if (TTsleep) {
544         Log("Will sleep %d second%s every %d second%s\n", TTsleep,
545             (TTsleep > 1) ? "s" : "", TTrun + TTsleep,
546             (TTrun + TTsleep > 1) ? "s" : "");
547     }
548
549     /* allow super users to manage RX statistics */
550     rx_SetRxStatUserOk(vol_rxstat_userok);
551
552     rx_StartServer(1);          /* Donate this process to the server process pool */
553
554     osi_audit(VS_FinishEvent, (-1), AUD_END);
555     Abort("StartServer returned?");
556     return 0; /* not reached */
557 }