pthreaded-ubik-20080402
[openafs.git] / src / ptserver / ptserver.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 /*
11  *                      A general description of the supergroup changes
12  *                      to ptserver:
13  *
14  *                      In AFS users can be members of groups. When you add
15  *                      a user, u1, to a group, g1, you add the user id for u1
16  *                      to an entries list in g1. This is a list of all the
17  *                      members of g1.
18  *                      You also add the id for g1 to an entries list in u1.
19  *                      This is a list of all the groups this user is a
20  *                      member of.
21  *                      The list has room for 10 entries. If more are required,
22  *                      a continuation record is created.
23  *
24  *                      With UMICH mods, u1 can be a group. When u1 is a group
25  *                      a new field is required to list the groups this group
26  *                      is a member of (since the entries field is used to
27  *                      list it's members). This new field is supergroups and
28  *                      has two entries. If more are required, a continuation
29  *                      record is formed. 
30  *                      There are two additional fields required, nextsg is
31  *                      an address of the next continuation record for this
32  *                      group, and countsg is the count for the number of 
33  *                      groups this group is a member of.
34  *                   
35  *
36  *
37  *      09/18/95 jjm    Add mdw's changes to afs-3.3a Changes:
38  *                      (1) Add the parameter -groupdepth or -depth to
39  *                          define the maximum search depth for supergroups.
40  *                          Define the variable depthsg to be the value of
41  *                          the parameter. The default value is set to 5.
42  *
43  *                      (3) Make sure the sizes of the struct prentry and
44  *                          struct prentryg are equal. If they aren't equal
45  *                          the pt database will be corrupted.
46  *                          The error is reported with an fprintf statement,
47  *                          but this doesn't print when ptserver is started by
48  *                          bos, so all you see is an error message in the
49  *                          /usr/afs/logs/BosLog file. If you start the
50  *                          ptserver without bos the fprintf will print
51  *                          on stdout.
52  *                          The program will terminate with a PT_EXIT(1).
53  *
54  *
55  *                      Transarc does not currently use opcodes past 520, but
56  *                      they *could* decide at any time to use more opcodes.
57  *                      If they did, then one part of our local mods,
58  *                      ListSupergroups, would break.  I've therefore
59  *                      renumbered it to 530, and put logic in to enable the
60  *                      old opcode to work (for now).
61  *
62  *      2/1/98 jjm      Add mdw's changes for bit mapping for supergroups
63  *                      Overview:
64  *                      Before fetching a supergroup, this version of ptserver
65  *                      checks to see if it was marked "found" and "not a
66  *                      member".  If and only if so, it doesn't fetch the group.
67  *                      Since this should be the case with most groups, this
68  *                      should save a significant amount of CPU in redundant
69  *                      fetches of the same group.  After fetching the group,
70  *                      it sets "found", and either sets or clears "not a
71  *                      member", depending on if the group was a member of
72  *                      other groups.  When it writes group entries to the
73  *                      database, it clears the "found" flag.
74  */
75
76 #if defined(SUPERGROUPS)
77 /*
78  *  A general description of the supergroup changes
79  *  to ptserver:
80  *
81  *  In AFS users can be members of groups. When you add a user, u1,
82  *  to a group, g1, you add the user id for u1 to an entries list
83  *  in g1. This is a list of all the members of g1.  You also add
84  *  the id for g1 to an entries list in u1.  This is a list of all
85  *  the groups this user is a member of.  The list has room for 10
86  *  entries. If more are required, a continuation record is created.
87  *
88  *  With UMICH mods, u1 can be a group. When u1 is a group a new
89  *  field is required to list the groups this group is a member of
90  *  (since the entries field is used to list it's members). This
91  *  new field is supergroups and has two entries. If more are
92  *  required, a continuation record is formed.
93  *
94  *  There are two additional fields required, nextsg is an address
95  *  of the next continuation record for this group, and countsg is
96  *  the count for the number of groups this group is a member of.
97  *
98  *  Bit mapping support for supergroups:
99  *
100  *  Before fetching a supergroup, this version of ptserver checks to
101  *  see if it was marked "found" and "not a member".  If and only if
102  *  so, it doesn't fetch the group.  Since this should be the case
103  *  with most groups, this should save a significant amount of CPU in
104  *  redundant fetches of the same group.  After fetching the group, it
105  *  sets "found", and either sets or clears "not a member", depending
106  *  on if the group was a member of other groups.  When it writes
107  *  group entries to the database, it clears the "found" flag.
108  */
109 #endif
110
111 #include <afsconfig.h>
112 #include <afs/param.h>
113
114 RCSID
115     ("$Header$");
116
117 #include <afs/stds.h>
118 #ifdef  AFS_AIX32_ENV
119 #include <signal.h>
120 #endif
121 #include <sys/types.h>
122 #include <stdio.h>
123 #include <fcntl.h>
124 #include <sys/stat.h>
125 #ifdef AFS_NT40_ENV
126 #include <winsock2.h>
127 #include <WINNT/afsevent.h>
128 #else
129 #include <netdb.h>
130 #include <netinet/in.h>
131 #endif
132 #include <string.h>
133 #include <rx/xdr.h>
134 #include <rx/rx.h>
135 #include <rx/rx_globals.h>
136 #include <lock.h>
137 #include <ubik.h>
138 #include <afs/cellconfig.h>
139 #include <afs/auth.h>
140 #include <afs/keys.h>
141 #include "ptserver.h"
142 #include "error_macros.h"
143 #include "afs/audit.h"
144 #include <afs/afsutil.h>
145 #include <afs/com_err.h>
146
147
148 /* make all of these into a structure if you want */
149 struct prheader cheader;
150 struct ubik_dbase *dbase;
151 struct afsconf_dir *prdir;
152
153 #if defined(SUPERGROUPS)
154 extern afs_int32 depthsg;
155 #endif
156
157 extern int afsconf_ServerAuth();
158 extern int afsconf_CheckAuth();
159
160 int pr_realmNameLen;
161 char *pr_realmName;
162
163 int restricted = 0;
164 int rxMaxMTU = -1;
165 int rxBind = 0;
166 int rxkadDisableDotCheck = 0;
167
168 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
169 afs_uint32 SHostAddrs[ADDRSPERSITE];
170
171 static struct afsconf_cell info;
172
173 extern int prp_group_default;
174 extern int prp_user_default;
175
176 #include "AFS_component_version_number.c"
177
178 int
179 prp_access_mask(s)
180     char *s;
181 {
182     int r;
183     if (*s >= '0' && *s <= '9') {
184         return strtol(s, NULL, 0);
185     }
186     r = 0;
187     while (*s) switch(*s++)
188     {
189     case 'S':   r |= PRP_STATUS_ANY; break;
190     case 's':   r |= PRP_STATUS_MEM; break;
191     case 'O':   r |= PRP_OWNED_ANY; break;
192     case 'M':   r |= PRP_MEMBER_ANY; break;
193     case 'm':   r |= PRP_MEMBER_MEM; break;
194     case 'A':   r |= PRP_ADD_ANY; break;
195     case 'a':   r |= PRP_ADD_MEM; break;
196     case 'r':   r |= PRP_REMOVE_MEM; break;
197     }
198     return r;
199 }
200
201 /* check whether caller is authorized to manage RX statistics */
202 int
203 pr_rxstat_userok(struct rx_call *call)
204 {
205     return afsconf_SuperUser(prdir, call, NULL);
206 }
207
208 int
209 main(int argc, char **argv)
210 {
211     register afs_int32 code;
212     afs_int32 myHost;
213     register struct hostent *th;
214     char hostname[64];
215     struct rx_service *tservice;
216     struct rx_securityClass *sc[3];
217     extern int RXSTATS_ExecuteRequest();
218     extern int PR_ExecuteRequest();
219 #if 0
220     struct ktc_encryptionKey tkey;
221 #endif
222     int kerberosKeys;           /* set if found some keys */
223     int lwps = 3;
224     char clones[MAXHOSTSPERCELL];
225     afs_uint32 host = htonl(INADDR_ANY);
226
227     const char *pr_dbaseName;
228     char *whoami = "ptserver";
229
230     int a;
231     char arg[100];
232
233 #ifdef  AFS_AIX32_ENV
234     /*
235      * The following signal action for AIX is necessary so that in case of a 
236      * crash (i.e. core is generated) we can include the user's data section 
237      * in the core dump. Unfortunately, by default, only a partial core is
238      * generated which, in many cases, isn't too useful.
239      */
240     struct sigaction nsa;
241
242     sigemptyset(&nsa.sa_mask);
243     nsa.sa_handler = SIG_DFL;
244     nsa.sa_flags = SA_FULLDUMP;
245     sigaction(SIGABRT, &nsa, NULL);
246     sigaction(SIGSEGV, &nsa, NULL);
247 #endif
248     osi_audit_init();
249     osi_audit(PTS_StartEvent, 0, AUD_END);
250
251     /* Initialize dirpaths */
252     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
253 #ifdef AFS_NT40_ENV
254         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
255 #endif
256         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
257                 argv[0]);
258         exit(2);
259     }
260
261     pr_dbaseName = AFSDIR_SERVER_PRDB_FILEPATH;
262
263 #if defined(SUPERGROUPS)
264     /* make sure the structures for database records are the same size */
265     if ((sizeof(struct prentry) != ENTRYSIZE)
266         || (sizeof(struct prentryg) != ENTRYSIZE)) {
267         fprintf(stderr,
268                 "The structures for the database records are different"
269                 " sizes\n" "struct prentry = %d\n" "struct prentryg = %d\n"
270                 "ENTRYSIZE = %d\n", sizeof(struct prentry),
271                 sizeof(struct prentryg), ENTRYSIZE);
272         PT_EXIT(1);
273     }
274 #endif
275
276     for (a = 1; a < argc; a++) {
277         int alen;
278         lcstring(arg, argv[a], sizeof(arg));
279         alen = strlen(arg);
280         if ((strncmp(arg, "-database", alen) == 0)
281             || (strncmp(arg, "-db", alen) == 0)) {
282             pr_dbaseName = argv[++a];   /* specify a database */
283         } else if (strncmp(arg, "-p", alen) == 0) {
284             lwps = atoi(argv[++a]);
285             if (lwps > 16) {    /* maximum of 16 */
286                 printf("Warning: '-p %d' is too big; using %d instead\n",
287                        lwps, 16);
288                 lwps = 16;
289             } else if (lwps < 3) {      /* minimum of 3 */
290                 printf("Warning: '-p %d' is too small; using %d instead\n",
291                        lwps, 3);
292                 lwps = 3;
293             }
294         } else if (strncmp(arg, "-rebuild", alen) == 0) /* rebuildDB++ */
295             ;
296 #if defined(SUPERGROUPS)
297         else if ((strncmp(arg, "-groupdepth", alen) == 0)
298                  || (strncmp(arg, "-depth", alen) == 0)) {
299             depthsg = atoi(argv[++a]);  /* Max search depth for supergroups */
300         }
301 #endif
302         else if (strncmp(arg, "-default_access", alen) == 0) {
303             prp_user_default = prp_access_mask(argv[++a]);
304             prp_group_default = prp_access_mask(argv[++a]);
305         }
306         else if (strncmp(arg, "-restricted", alen) == 0) {
307             restricted = 1;
308         }
309         else if (strncmp(arg, "-rxbind", alen) == 0) {
310             rxBind = 1;
311         }
312         else if (strncmp(arg, "-allow-dotted-principals", alen) == 0) {
313             rxkadDisableDotCheck = 1;
314         }
315         else if (strncmp(arg, "-enable_peer_stats", alen) == 0) {
316             rx_enablePeerRPCStats();
317         } else if (strncmp(arg, "-enable_process_stats", alen) == 0) {
318             rx_enableProcessRPCStats();
319         }
320 #ifndef AFS_NT40_ENV
321         else if (strncmp(arg, "-syslog", alen) == 0) {
322             /* set syslog logging flag */
323             serverLogSyslog = 1;
324         } else if (strncmp(arg, "-syslog=", MIN(8, alen)) == 0) {
325             serverLogSyslog = 1;
326             serverLogSyslogFacility = atoi(arg + 8);
327         }
328 #endif
329         else if (strncmp(arg, "-auditlog", alen) == 0) {
330             int tempfd, flags;
331             FILE *auditout;
332             char oldName[MAXPATHLEN];
333             char *fileName = argv[++a];
334
335 #ifndef AFS_NT40_ENV
336             struct stat statbuf;
337
338             if ((lstat(fileName, &statbuf) == 0) 
339                 && (S_ISFIFO(statbuf.st_mode))) {
340                 flags = O_WRONLY | O_NONBLOCK;
341             } else 
342 #endif
343             {
344                 strcpy(oldName, fileName);
345                 strcat(oldName, ".old");
346                 renamefile(fileName, oldName);
347                 flags = O_WRONLY | O_TRUNC | O_CREAT;
348             }
349             tempfd = open(fileName, flags, 0666);
350             if (tempfd > -1) {
351                 auditout = fdopen(tempfd, "a");
352                 if (auditout) {
353                     osi_audit_file(auditout);
354                     osi_audit(PTS_StartEvent, 0, AUD_END);
355                 } else
356                     printf("Warning: auditlog %s not writable, ignored.\n", fileName);
357             } else
358                 printf("Warning: auditlog %s not writable, ignored.\n", fileName);
359         }
360         else if (!strncmp(arg, "-rxmaxmtu", alen)) {
361             if ((a + 1) >= argc) {
362                 fprintf(stderr, "missing argument for -rxmaxmtu\n");
363                 PT_EXIT(1);
364             }
365             rxMaxMTU = atoi(argv[++a]);
366             if ((rxMaxMTU < RX_MIN_PACKET_SIZE) ||
367                  (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
368                 printf("rxMaxMTU %d invalid; must be between %d-%d\n",
369                         rxMaxMTU, RX_MIN_PACKET_SIZE,
370                         RX_MAX_PACKET_DATA_SIZE);
371                 PT_EXIT(1);
372             }
373         } 
374         else if (*arg == '-') {
375             /* hack in help flag support */
376
377 #if defined(SUPERGROUPS)
378 #ifndef AFS_NT40_ENV
379             printf("Usage: ptserver [-database <db path>] "
380                    "[-auditlog <log path>] "
381                    "[-syslog[=FACILITY]] "
382                    "[-p <number of processes>] [-rebuild] "
383                    "[-groupdepth <depth>] "
384                    "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
385                    "[-allow-dotted-principals] "
386                    "[-enable_peer_stats] [-enable_process_stats] "
387                    "[-default_access default_user_access default_group_access] "
388                    "[-help]\n");
389 #else /* AFS_NT40_ENV */
390             printf("Usage: ptserver [-database <db path>] "
391                    "[-auditlog <log path>] "
392                    "[-p <number of processes>] [-rebuild] [-rxbind] "
393                    "[-allow-dotted-principals] "
394                    "[-default_access default_user_access default_group_access] "
395                    "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
396                    "[-groupdepth <depth>] " "[-help]\n");
397 #endif
398 #else
399 #ifndef AFS_NT40_ENV
400             printf("Usage: ptserver [-database <db path>] "
401                    "[-auditlog <log path>] "
402                    "[-syslog[=FACILITY]] "
403                    "[-p <number of processes>] [-rebuild] "
404                    "[-enable_peer_stats] [-enable_process_stats] "
405                    "[-default_access default_user_access default_group_access] "
406                    "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
407                    "[-allow-dotted-principals] "
408                    "[-help]\n");
409 #else /* AFS_NT40_ENV */
410             printf("Usage: ptserver [-database <db path>] "
411                    "[-auditlog <log path>] "
412                    "[-default_access default_user_access default_group_access] "
413                    "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
414                    "[-allow-dotted-principals] "
415                    "[-p <number of processes>] [-rebuild] " "[-help]\n");
416 #endif
417 #endif
418             fflush(stdout);
419
420             PT_EXIT(1);
421         }
422 #if defined(SUPERGROUPS)
423         else {
424             fprintf(stderr, "Unrecognized arg: '%s' ignored!\n", arg);
425         }
426 #endif
427     }
428
429 #ifndef AFS_NT40_ENV
430     serverLogSyslogTag = "ptserver";
431 #endif
432     OpenLog(AFSDIR_SERVER_PTLOG_FILEPATH);      /* set up logging */
433     SetupLogSignals();
434
435     prdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
436     if (!prdir) {
437         fprintf(stderr, "ptserver: can't open configuration directory.\n");
438         PT_EXIT(1);
439     }
440     if (afsconf_GetNoAuthFlag(prdir))
441         printf("ptserver: running unauthenticated\n");
442
443 #ifdef AFS_NT40_ENV
444     /* initialize winsock */
445     if (afs_winsockInit() < 0) {
446         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
447
448         fprintf(stderr, "ptserver: couldn't initialize winsock. \n");
449         PT_EXIT(1);
450     }
451 #endif
452     /* get this host */
453     gethostname(hostname, sizeof(hostname));
454     th = gethostbyname(hostname);
455     if (!th) {
456         fprintf(stderr, "ptserver: couldn't get address of this host.\n");
457         PT_EXIT(1);
458     }
459     memcpy(&myHost, th->h_addr, sizeof(afs_int32));
460
461     /* get list of servers */
462     code =
463         afsconf_GetExtendedCellInfo(prdir, NULL, "afsprot", &info, &clones);
464     if (code) {
465         afs_com_err(whoami, code, "Couldn't get server list");
466         PT_EXIT(2);
467     }
468     pr_realmName = info.name;
469     pr_realmNameLen = strlen(pr_realmName);
470
471 #if 0
472     /* get keys */
473     code = afsconf_GetKey(prdir, 999, &tkey);
474     if (code) {
475         afs_com_err(whoami, code,
476                 "couldn't get bcrypt keys from key file, ignoring.");
477     }
478 #endif
479     {
480         afs_int32 kvno;         /* see if there is a KeyFile here */
481         struct ktc_encryptionKey key;
482         code = afsconf_GetLatestKey(prdir, &kvno, &key);
483         kerberosKeys = (code == 0);
484         if (!kerberosKeys)
485             printf
486                 ("ptserver: can't find any Kerberos keys, code = %d, ignoring\n",
487                  code);
488     }
489     if (kerberosKeys) {
490         /* initialize ubik */
491         ubik_CRXSecurityProc = afsconf_ClientAuth;
492         ubik_CRXSecurityRock = (char *)prdir;
493         ubik_SRXSecurityProc = afsconf_ServerAuth;
494         ubik_SRXSecurityRock = (char *)prdir;
495         ubik_CheckRXSecurityProc = afsconf_CheckAuth;
496         ubik_CheckRXSecurityRock = (char *)prdir;
497     }
498     /* The max needed is when deleting an entry.  A full CoEntry deletion
499      * required removal from 39 entries.  Each of which may refers to the entry
500      * being deleted in one of its CoEntries.  If a CoEntry is freed its
501      * predecessor CoEntry will be modified as well.  Any freed blocks also
502      * modifies the database header.  Counting the entry being deleted and its
503      * CoEntry this adds up to as much as 1+1+39*3 = 119.  If all these entries
504      * and the header are in separate Ubik buffers then 120 buffers may be
505      * required. */
506     ubik_nBuffers = 120 + /*fudge */ 40;
507
508     if (rxBind) {
509         afs_int32 ccode;
510 #ifndef AFS_NT40_ENV
511         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
512             AFSDIR_SERVER_NETINFO_FILEPATH) {
513             char reason[1024];
514             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
515                                            ADDRSPERSITE, reason,
516                                            AFSDIR_SERVER_NETINFO_FILEPATH,
517                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
518         } else 
519 #endif
520         {
521             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
522         }
523         if (ccode == 1) {
524             host = SHostAddrs[0];
525             /* the following call is idempotent so if/when it gets called
526              * again by the ubik init stuff, it doesn't really matter
527              * -- klm
528              */
529             rx_InitHost(host, htons(AFSCONF_PROTPORT));
530         }
531     }
532
533     code =
534         ubik_ServerInitByInfo(myHost, htons(AFSCONF_PROTPORT), &info, &clones,
535                               pr_dbaseName, &dbase);
536     if (code) {
537         afs_com_err(whoami, code, "Ubik init failed");
538         PT_EXIT(2);
539     }
540 #if defined(SUPERGROUPS)
541     pt_hook_write();
542 #endif
543
544     sc[0] = rxnull_NewServerSecurityObject();
545     sc[1] = 0;
546     if (kerberosKeys) {
547         sc[2] = rxkad_NewServerSecurityObject(0, prdir, afsconf_GetKey, NULL);
548     } else
549         sc[2] = sc[0];
550
551     /* Disable jumbograms */
552     rx_SetNoJumbo();
553
554     if (rxMaxMTU != -1) {
555         rx_SetMaxMTU(rxMaxMTU);
556     }
557
558     tservice =
559         rx_NewServiceHost(host, 0, PRSRV, "Protection Server", sc, 3,
560                       PR_ExecuteRequest);
561     if (tservice == (struct rx_service *)0) {
562         fprintf(stderr, "ptserver: Could not create new rx service.\n");
563         PT_EXIT(3);
564     }
565     rx_SetMinProcs(tservice, 2);
566     rx_SetMaxProcs(tservice, lwps);
567     if (rxkadDisableDotCheck) {
568         rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
569                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK,
570                                     NULL);
571     }
572
573     tservice =
574         rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats", sc, 3,
575                       RXSTATS_ExecuteRequest);
576     if (tservice == (struct rx_service *)0) {
577         fprintf(stderr, "ptserver: Could not create new rx service.\n");
578         PT_EXIT(3);
579     }
580     rx_SetMinProcs(tservice, 2);
581     rx_SetMaxProcs(tservice, 4);
582
583     /* allow super users to manage RX statistics */
584     rx_SetRxStatUserOk(pr_rxstat_userok);
585
586     rx_StartServer(1);
587     osi_audit(PTS_FinishEvent, -1, AUD_END);
588     exit(0);
589 }