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