rxbind-for-servers-20060612
[openafs.git] / src / update / server.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 <afs/stds.h>
17 #ifdef  AFS_AIX32_ENV
18 #include <signal.h>
19 #endif
20 #include <sys/types.h>
21 #ifdef AFS_NT40_ENV
22 #include <winsock2.h>
23 #include <WINNT/afsevent.h>
24 #include <fcntl.h>
25 #include <io.h>
26 #include <afs/dirent.h>
27 #include <afs/procmgmt.h>
28 #else
29 #include <netdb.h>
30 #include <netinet/in.h>
31 #include <sys/file.h>
32 #include <dirent.h>
33 #endif
34 #ifdef HAVE_STRING_H
35 #include <string.h>
36 #else
37 #ifdef HAVE_STRINGS_H
38 #include <strings.h>
39 #endif
40 #endif
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #include <sys/stat.h>
45 #include <errno.h>
46 #include <stdio.h>
47 #include <rx/xdr.h>
48 #include <rx/rx.h>
49 #include <rx/rxkad.h>
50 #include <afs/cellconfig.h>
51 #include <afs/afsutil.h>
52 #include <afs/fileutil.h>
53 #ifdef  AFS_AIX_ENV
54 #include <sys/statfs.h>
55 #endif
56 #include "update.h"
57 #include "global.h"
58
59 extern int UPDATE_ExecuteRequest();
60
61 static int AddObject(char **expPath, char *dir);
62 static int PathInDirectory(char *dir, char *path);
63
64 struct afsconf_dir *cdir;
65 int nDirs;
66 char *dirName[MAXENTRIES];
67 int dirLevel[MAXENTRIES];
68 char *whoami;
69
70 static int Quit();
71
72 int rxBind = 0;
73
74 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
75 afs_uint32 SHostAddrs[ADDRSPERSITE];
76
77 /* check whether caller is authorized to manage RX statistics */
78 int
79 update_rxstat_userok(struct rx_call *call)
80 {
81     return afsconf_SuperUser(cdir, call, NULL);
82 }
83
84 /*
85  * PathInDirectory() -- determine if path is in directory (or is directory)
86  */
87 static int
88 PathInDirectory(char *dir, char *path)
89 {
90     int inDir = 0;
91     size_t dirLen;
92     char dirNorm[AFSDIR_PATH_MAX], pathNorm[AFSDIR_PATH_MAX];
93
94 #ifdef AFS_NT40_ENV
95     /* case-insensitive comparison of normalized, same-flavor (short) paths */
96     DWORD status;
97
98     status = GetShortPathName(dir, dirNorm, AFSDIR_PATH_MAX);
99     if (status == 0 || status > AFSDIR_PATH_MAX) {
100         /* can't convert path to short version; just use long version */
101         strcpy(dirNorm, dir);
102     }
103     FilepathNormalize(dirNorm);
104
105     status = GetShortPathName(path, pathNorm, AFSDIR_PATH_MAX);
106     if (status == 0 || status > AFSDIR_PATH_MAX) {
107         /* can't convert path to short version; just use long version */
108         strcpy(pathNorm, path);
109     }
110     FilepathNormalize(pathNorm);
111
112     dirLen = strlen(dirNorm);
113
114     if (_strnicmp(dirNorm, pathNorm, dirLen) == 0) {
115         /* substrings match; path must match dir or be subdirectory */
116         if (pathNorm[dirLen] == '\0' || pathNorm[dirLen] == '/') {
117             inDir = 1;
118         }
119     }
120 #else
121     /* case-sensitive comparison of normalized paths */
122     strcpy(dirNorm, dir);
123     FilepathNormalize(dirNorm);
124
125     strcpy(pathNorm, path);
126     FilepathNormalize(pathNorm);
127
128     dirLen = strlen(dirNorm);
129
130     if (strncmp(dirNorm, pathNorm, dirLen) == 0) {
131         /* substrings match; path must match dir or be subdirectory */
132         if (pathNorm[dirLen] == '\0' || pathNorm[dirLen] == '/') {
133             inDir = 1;
134         }
135     }
136 #endif /* AFS_NT40_ENV */
137     return inDir;
138 }
139
140 int
141 AuthOkay(struct rx_call *call, char *name)
142 {
143     int i;
144     rxkad_level level;
145     afs_int32 code;
146     int matches;
147
148     /* Must be in 'UserList' to use */
149     if (!afsconf_SuperUser(cdir, call, NULL))
150         return 0;
151
152     if (rx_SecurityClassOf(rx_ConnectionOf(call)) == 2) {
153         code = rxkad_GetServerInfo(call->conn, &level, 0, 0, 0, 0, 0);
154         if (code)
155             return 0;
156     } else
157         level = 0;
158
159     matches = 0;
160     for (i = 0; i < nDirs; i++) {
161         if (PathInDirectory(dirName[i], name)) {
162             if (dirLevel[i] > level)
163                 return 0;
164             matches++;
165             /* keep searching in case there's a more restrictive subtree
166              * specified later. */
167         }
168     }
169     if (nDirs && !matches)
170         return 0;               /* if dirs spec., name must match */
171     return 1;                   /* okay or no dirs */
172 }
173
174 int
175 osi_audit()
176 {
177 /* this sucks but it works for now.
178 */
179     return 0;
180 }
181
182 #ifndef AFS_NT40_ENV
183 #include "AFS_component_version_number.c"
184 #endif
185
186 int
187 main(int argc, char *argv[])
188 {
189     struct rx_securityClass *securityObjects[3];
190     struct rx_service *service;
191     afs_uint32 host = htonl(INADDR_ANY);
192
193     int a = 0;
194     rxkad_level level;
195     rxkad_level newLevel;
196
197 #ifdef  AFS_AIX32_ENV
198     /*
199      * The following signal action for AIX is necessary so that in case of a 
200      * crash (i.e. core is generated) we can include the user's data section 
201      * in the core dump. Unfortunately, by default, only a partial core is
202      * generated which, in many cases, isn't too useful.
203      */
204     struct sigaction nsa;
205
206     sigemptyset(&nsa.sa_mask);
207     nsa.sa_handler = SIG_DFL;
208     nsa.sa_flags = SA_FULLDUMP;
209     sigaction(SIGABRT, &nsa, NULL);
210     sigaction(SIGSEGV, &nsa, NULL);
211 #endif
212
213     whoami = argv[0];
214
215 #ifdef AFS_NT40_ENV
216     /* dummy signal call to force afsprocmgmt.dll to load on NT */
217     signal(SIGUSR1, SIG_DFL);
218 #endif
219
220     /* Initialize dirpaths */
221     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
222 #ifdef AFS_NT40_ENV
223         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
224 #endif
225         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
226                 argv[0]);
227         exit(2);
228     }
229     nDirs = 0;
230     level = rxkad_clear;
231
232     if (argc == 1)              /* no arguments */
233         goto usage;
234
235     /* support help flag */
236     if (strcmp("-help", argv[1]) == 0)
237         goto usage;
238     if (strcmp("help", argv[1]) == 0)
239         goto usage;
240
241     for (a = 1; a < argc; a++) {
242         if (argv[a][0] == '-') {        /* parse options */
243             if (strcmp(argv[a], "-rxbind") == 0) {
244                 rxBind = 1;
245                 continue;
246             } else {
247                 char arg[256];
248                 lcstring(arg, argv[a], sizeof(arg));
249                 newLevel = rxkad_StringToLevel(&argv[a][1]);
250                 if (newLevel != -1) {
251                     level = newLevel;   /* set new level */
252                     continue;
253                 }
254             }
255           usage:
256             Quit("Usage: upserver [<directory>+] [-crypt <directory>+] [-clear <directory>+] [-auth <directory>+] [-rxbind] [-help]\n");
257         } else {
258             int dirlen;
259             if (nDirs >= sizeof(dirName) / sizeof(dirName[0]))
260                 Quit("Too many dirs");
261             dirlen = strlen(argv[a]);
262             if (AddObject(&dirName[nDirs], argv[a])) {
263                 printf("%s: Unable to export dir %s. Skipping\n", whoami,
264                        argv[a]);
265                 continue;
266             }
267             dirLevel[nDirs] = level;    /* remember current level */
268             nDirs++;
269         }
270     }
271
272     if (nDirs == 0) {           /* Didn't find any directories to export */
273         printf("%s: No directories to export. Quitting\n", whoami);
274         exit(1);
275     }
276
277     cdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
278     if (cdir == 0) {
279         fprintf(stderr, "Can't get server configuration info (%s)\n",
280                 AFSDIR_SERVER_ETC_DIRPATH);
281         exit(1);
282     }
283
284     if (rxBind) {
285         afs_int32 ccode;
286         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
287             AFSDIR_SERVER_NETINFO_FILEPATH) {
288             char reason[1024];
289             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
290                                            ADDRSPERSITE, reason,
291                                            AFSDIR_SERVER_NETINFO_FILEPATH,
292                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
293         } else {
294             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
295         }
296         if (ccode == 1) 
297             host = SHostAddrs[0];
298     }
299
300     /* Initialize Rx, telling it port number this server will use for its
301      * single service */
302     if (rx_InitHost(host, htons(AFSCONF_UPDATEPORT)) < 0)
303         Quit("rx_init");
304
305     /* Create a single security object, in this case the null security object,
306      * for unauthenticated connections, which will be used to control security
307      * on connections made to this server. */
308
309     /* WHAT A JOKE!  Let's use rxkad at least so we know who we're talking to,
310      * then sometimes require full encryption. */
311
312     /* rxnull and rxvab are no longer supported */
313     securityObjects[0] = rxnull_NewServerSecurityObject();
314
315     securityObjects[1] = (struct rx_securityClass *)0;
316
317     securityObjects[2] =
318         rxkad_NewServerSecurityObject(rxkad_clear, cdir, afsconf_GetKey, 0);
319     if (securityObjects[2] == (struct rx_securityClass *)0)
320         Quit("rxkad_NewServerSecurityObject");
321
322     /* Instantiate a single UPDATE service.  The rxgen-generated procedure
323      * which is called to decode requests is passed in here
324      * (UPDATE_ExecuteRequest). */
325     service =
326         rx_NewServiceHost(host, 0, UPDATE_SERVICEID, "UPDATE", securityObjects,
327                           3, UPDATE_ExecuteRequest);
328     if (service == (struct rx_service *)0)
329         Quit("rx_NewService");
330     rx_SetMaxProcs(service, 2);
331
332     /* allow super users to manage RX statistics */
333     rx_SetRxStatUserOk(update_rxstat_userok);
334
335     rx_StartServer(1);          /* Donate this process to the server process pool */
336     Quit("StartServer returned?");
337     return 0;
338 }
339
340 /* fetch the file name and send it to the remote requester specified by call */
341
342 int
343 UPDATE_FetchFile(struct rx_call *call, char *name)
344 {
345     int fd = -1;
346     int error = 0;
347     struct stat status;
348     char *reqObject;
349
350     /* construct a local path from a canonical (wire-format) path */
351     if ((error = ConstructLocalPath(name, "/", &reqObject))) {
352         com_err(whoami, error, "Unable to construct local path");
353         return UPDATE_ERROR;
354     }
355
356     if (!AuthOkay(call, reqObject)) {
357         error = UPDATE_ERROR;
358     } else {
359         fd = open(reqObject, O_RDONLY, 0);
360         if (fd < 0 || fstat(fd, &status) < 0) {
361             printf("Failed to open %s\n", reqObject);
362             error = UPDATE_ERROR;
363         }
364         if (!error)
365             error = update_SendFile(fd, call, &status);
366         if (fd >= 0)
367             close(fd);
368     }
369     free(reqObject);
370     return error;
371 }
372
373 /* fetch dir info about directory name and send it to remote host associated
374   with call. */
375 int
376 UPDATE_FetchInfo(struct rx_call *call, char *name)
377 {
378     int error = 0;
379     struct stat status;
380     char *reqObject;
381
382     /* construct a local path from a canonical (wire-format) path */
383     if ((error = ConstructLocalPath(name, "/", &reqObject))) {
384         com_err(whoami, error, "Unable to construct local path");
385         return UPDATE_ERROR;
386     }
387
388     if (!AuthOkay(call, reqObject)) {
389         error = UPDATE_ERROR;
390     } else {
391         /* we only need to stat the obj, not open it. */
392         if (stat(reqObject, &status) < 0) {
393             printf("Failed to open %s\n", reqObject);
394             error = UPDATE_ERROR;
395         }
396         if ((status.st_mode & S_IFMT) != S_IFDIR) {
397             printf(" file %s is not a directory \n", reqObject);
398             error = -1;
399         }
400
401         if (!error)
402             error = update_SendDirInfo(reqObject, call, &status, name);
403     }
404     free(reqObject);
405     return error;
406 }
407
408 static int
409 Quit(msg, a, b)
410      char *msg;
411 {
412     fprintf(stderr, msg, a, b);
413     exit(1);
414 }
415
416 int
417 update_SendFile(register int fd, register struct rx_call *call, register struct stat *status)
418 {
419     char *buffer = (char *)0;
420     int blockSize;
421     afs_int32 length, tlen;
422 #ifdef  AFS_AIX_ENV
423     struct statfs tstatfs;
424 #endif
425
426     afs_int32 error = 0;
427 #ifdef  AFS_AIX_ENV
428     /* Unfortunately in AIX valuable fields such as st_blksize are gone from the stat structure!! */
429     fstatfs(fd, &tstatfs);
430     blockSize = tstatfs.f_bsize;
431 #elif AFS_NT40_ENV
432     blockSize = 4096;
433 #else
434     blockSize = status->st_blksize;
435 #endif
436     length = status->st_size;
437     buffer = (char *)malloc(blockSize);
438     if (!buffer) {
439         printf("malloc failed\n");
440         return UPDATE_ERROR;
441     }
442     tlen = htonl(length);
443     rx_Write(call, &tlen, sizeof(afs_int32));   /* send length on fetch */
444     while (!error && length) {
445         register int nbytes = (length > blockSize ? blockSize : length);
446         nbytes = read(fd, buffer, nbytes);
447         if (nbytes <= 0) {
448             fprintf(stderr, "File system read failed\n");
449             break;
450         }
451         if (rx_Write(call, buffer, nbytes) != nbytes)
452             break;
453         length -= nbytes;
454     }
455     if (buffer)
456         free(buffer);
457     if (length)
458         error = UPDATE_ERROR;
459     return error;
460 }
461
462 /* Enumerate dir (name) and write dir entry info into temp file. 
463  */
464 int
465 update_SendDirInfo(char *name,          /* Name of dir to enumerate */
466      register struct rx_call *call,     /* rx call */
467      register struct stat *status,      /* stat struct for dir */
468      char *origDir)             /* orig name of dir before being localized */
469 {
470     DIR *dirp;
471     struct dirent *dp;
472     FILE *stream;
473     struct stat tstatus;
474     char filename[MAXSIZE], dirInfoFile[MAXSIZE];
475     int fd, tfd, errcode, error, err;
476
477     error = 0;
478     dirp = opendir(name);
479     sprintf(dirInfoFile, "%s/upserver.tmp", gettmpdir());
480     stream = fopen(dirInfoFile, "w");
481     if (!stream) {
482         error = EIO;
483     } else {
484         while ((dp = readdir(dirp))) {
485             strcpy(filename, name);
486             strcat(filename, "/");
487             strcat(filename, dp->d_name);
488
489             tfd = open(filename, O_RDONLY, 0);
490             if (tfd < 0 || fstat(tfd, &tstatus) < 0) {
491                 printf("Failed to open %s\n", name);
492                 error = UPDATE_ERROR;
493                 goto fail;
494             }
495             if ((tstatus.st_mode & S_IFMT) != S_IFDIR) {        /* not a directory */
496                 char dirEntry[MAXSIZE];
497
498                 strcpy(dirEntry, origDir);
499                 strcat(dirEntry, "/");
500                 strcat(dirEntry, dp->d_name);
501                 err =
502                     fprintf(stream, "\"%s\" %u %u %u %u %u %u\n", dirEntry,
503                             (unsigned int)tstatus.st_mtime,
504                             (unsigned int)tstatus.st_size, tstatus.st_mode,
505                             tstatus.st_uid, tstatus.st_gid,
506                             (unsigned int)tstatus.st_atime);
507                 if (err < 0)
508                     error = EIO;
509             }
510             err = close(tfd);
511             if (err) {
512                 printf("could not close file %s \n", filename);
513                 error = UPDATE_ERROR;
514                 goto fail;
515             }
516         }
517     }
518   fail:
519     if (dirp)
520         closedir(dirp);
521     if (stream) {
522         if (ferror(stream))
523             if (!error)
524                 error = UPDATE_ERROR;
525         fclose(stream);
526     }
527     if (error == 0) {
528         fd = open(dirInfoFile, O_RDONLY, 0);
529         if (fd >= 0) {
530             fstat(fd, &tstatus);
531             errcode = update_SendFile(fd, call, &tstatus);
532             if (errcode)
533                 if (!error)
534                     error = UPDATE_ERROR;
535             close(fd);
536         }
537     }
538     unlink(dirInfoFile);
539     return error;
540 }
541
542
543 /* AddObject() - Adds the object to the list of exported objects after
544  *     converting to a local path.
545  *
546  * expPath : points to allocated storage in which the exportable path is 
547  *           passed back.
548  * dir     : dir name passed in for export 
549  *
550  */
551 static int
552 AddObject(char **expPath, char *dir)
553 {
554     int error;
555     struct stat statbuf;
556
557     /* construct a local path from a canonical (wire-format) path */
558     if ((error = ConstructLocalPath(dir, "/", expPath))) {
559         com_err(whoami, error, "Unable to construct local path");
560         return error;
561     }
562
563     /* stat the object */
564     error = stat(*expPath, &statbuf);
565     if (error) {
566         com_err(whoami, error, ";Can't stat object.");
567         return error;
568     }
569     /* now check if the object has an exportable (file/dir)  type */
570     if (!(statbuf.st_mode & S_IFDIR)) {
571         fprintf(stderr, "%s: Unacceptable object type for %s\n", whoami,
572                 *expPath);
573         return -1;
574     }
575
576     return 0;
577 }