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