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