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