7d4afea3a1ab777fe175649c2e9d3c863ab5756d
[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_STRINGS_H
34 #include <strings.h>
35 #else
36 #ifdef HAVE_STRING_H
37 #include <string.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, (char *)0);
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, (char *)0)) 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     extern struct rx_securityClass *rxnull_NewServerSecurityObject();
179
180     int a = 0;
181     rxkad_level level;
182     rxkad_level newLevel;
183
184 #ifdef  AFS_AIX32_ENV
185     /*
186      * The following signal action for AIX is necessary so that in case of a 
187      * crash (i.e. core is generated) we can include the user's data section 
188      * in the core dump. Unfortunately, by default, only a partial core is
189      * generated which, in many cases, isn't too useful.
190      */
191     struct sigaction nsa;
192     
193     sigemptyset(&nsa.sa_mask);
194     nsa.sa_handler = SIG_DFL;
195     nsa.sa_flags = SA_FULLDUMP;
196     sigaction(SIGABRT, &nsa, NULL);
197     sigaction(SIGSEGV, &nsa, NULL);
198 #endif
199
200     whoami = argv[0];
201
202 #ifdef AFS_NT40_ENV
203       /* dummy signal call to force afsprocmgmt.dll to load on NT */
204       signal(SIGUSR1, SIG_DFL);
205 #endif
206
207     /* Initialize dirpaths */
208     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
209 #ifdef AFS_NT40_ENV
210         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0],0);
211 #endif
212         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n", argv[0]);
213         exit(2);
214     }
215     nDirs = 0;
216     level = rxkad_clear;
217
218     if (argc == 1) /* no arguments */
219       goto usage;
220
221     /* support help flag */
222     if(strcmp("-help",argv[1])==0)
223       goto usage;
224     if(strcmp("help",argv[1])==0)
225       goto usage;
226
227     for (a=1; a<argc; a++) {
228         if (argv[a][0] == '-') { /* parse options */
229             char arg[256];
230             lcstring (arg, argv[a], sizeof(arg));
231             newLevel = StringToLevel (&argv[a][1]);
232             if (newLevel != -1) {
233                 level = newLevel;       /* set new level */
234                 continue;
235             }
236   usage:
237             Quit ("Usage: upserver [<directory>+] [-crypt <directory>+] [-clear <directory>+] [-auth <directory>+] [-help]\n");
238         } else {
239             int dirlen;
240             if (nDirs >= sizeof(dirName)/sizeof(dirName[0]))
241                 Quit("Too many dirs");
242             dirlen = strlen (argv[a]);
243             if (AddObject(&dirName[nDirs], argv[a])) {
244               printf("%s: Unable to export dir %s. Skipping\n", whoami, argv[a]);
245               continue;
246             }
247             dirLevel[nDirs] = level; /* remember current level */
248             nDirs++;
249         }
250     }
251
252     if (nDirs == 0) { /* Didn't find any directories to export */
253       printf("%s: No directories to export. Quitting\n", whoami);
254       exit(1);
255     }
256
257     cdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
258     if (cdir == 0) {
259         fprintf (stderr, "Can't get server configuration info (%s)\n",
260                  AFSDIR_SERVER_ETC_DIRPATH);
261         exit (1);
262     }
263
264     /* Initialize Rx, telling it port number this server will use for its
265      * single service */
266     if (rx_Init(htons(AFSCONF_UPDATEPORT)) < 0) Quit("rx_init");
267
268     /* Create a single security object, in this case the null security object,
269      * for unauthenticated connections, which will be used to control security
270      * on connections made to this server. */
271
272     /* WHAT A JOKE!  Let's use rxkad at least so we know who we're talking to,
273      * then sometimes require full encryption. */
274
275     /* rxnull and rxvab are no longer supported */
276     securityObjects[0] = rxnull_NewServerSecurityObject();
277
278     securityObjects[1] = (struct rx_securityClass *) 0;
279
280     securityObjects[2] = rxkad_NewServerSecurityObject
281         (rxkad_clear, cdir, afsconf_GetKey, 0);
282     if (securityObjects[2] == (struct rx_securityClass *) 0)
283         Quit("rxkad_NewServerSecurityObject");
284
285     /* Instantiate a single UPDATE service.  The rxgen-generated procedure
286      * which is called to decode requests is passed in here
287      * (UPDATE_ExecuteRequest). */
288     service = rx_NewService (0, UPDATE_SERVICEID, "UPDATE",
289                              securityObjects, 3, UPDATE_ExecuteRequest);
290     if (service == (struct rx_service *) 0) Quit("rx_NewService");
291     rx_SetMaxProcs(service, 2);
292
293     /* allow super users to manage RX statistics */
294     rx_SetRxStatUserOk(update_rxstat_userok);
295
296     rx_StartServer(1); /* Donate this process to the server process pool */
297     Quit("StartServer returned?");
298     return 0;
299 }
300
301 /* fetch the file name and send it to the remote requester specified by call */
302
303 int UPDATE_FetchFile(call, name)
304     struct rx_call *call;
305     char *name;
306 {
307     int fd = -1;
308     int error = 0;
309     struct stat status;
310     char *reqObject;
311
312     /* construct a local path from a canonical (wire-format) path */
313     if ((error = ConstructLocalPath(name, "/", &reqObject))) {
314         com_err(whoami, error, "Unable to construct local path");
315         return UPDATE_ERROR;
316     }
317
318     if (!AuthOkay (call, reqObject)) {
319         error = UPDATE_ERROR;
320     } else {
321         fd = open(reqObject, O_RDONLY, 0);
322         if (fd < 0 || fstat(fd, &status) < 0) {
323             printf("Failed to open %s\n", reqObject);
324             error = UPDATE_ERROR;
325         }
326         if (!error) error = update_SendFile(fd, call, &status);
327         if (fd >= 0) close(fd);
328     }
329     free(reqObject);
330     return error;
331 }
332
333 /* fetch dir info about directory name and send it to remote host associated
334   with call. */
335 int UPDATE_FetchInfo(call, name)
336    struct rx_call *call;
337    char *name;
338 {
339     int fd = -1;
340     int error = 0;
341     struct stat status;
342     char *reqObject;
343
344     /* construct a local path from a canonical (wire-format) path */
345     if ((error = ConstructLocalPath(name, "/", &reqObject))) {
346         com_err(whoami, error, "Unable to construct local path");
347         return UPDATE_ERROR;
348     }
349
350     if (!AuthOkay (call, reqObject)) {
351         error = UPDATE_ERROR;
352     } else {
353         /* we only need to stat the obj, not open it. */
354         if (stat(reqObject, &status) < 0) {
355             printf("Failed to open %s\n", reqObject);
356             error = UPDATE_ERROR;
357         }
358         if((status.st_mode & S_IFMT) != S_IFDIR){
359             printf(" file %s is not a directory \n", reqObject);
360             if (fd >= 0) close(fd);
361             error = -1;
362         }
363
364         if (fd >= 0) close(fd);
365         if (!error) error = update_SendDirInfo(reqObject, call, &status, name);
366     }
367     free(reqObject);
368     return error;
369
370
371 static int Quit(msg, a, b)
372     char *msg;
373 {
374     fprintf(stderr, msg, a, b);
375     exit(1);
376 }
377
378 int update_SendFile(fd, call, status)
379 register int fd;
380 register struct rx_call *call;
381 register struct stat *status;
382 {
383     char *buffer = (char*) 0;
384     int blockSize;
385     afs_int32 length, tlen;
386 #ifdef notdef
387     XDR xdr;
388 #endif
389 #ifdef  AFS_AIX_ENV
390 #include <sys/statfs.h>
391     struct statfs tstatfs;
392 #endif
393
394     afs_int32 error = 0;
395 #ifdef  AFS_AIX_ENV
396     /* Unfortunately in AIX valuable fields such as st_blksize are gone from the stat structure!! */
397     fstatfs(fd, &tstatfs);
398     blockSize = tstatfs.f_bsize;
399 #elif AFS_NT40_ENV
400     blockSize = 4096;
401 #else
402     blockSize = status->st_blksize;
403 #endif
404     length = status->st_size;
405     buffer = (char *)malloc(blockSize);
406     if (!buffer) {
407         printf("malloc failed\n");
408         return UPDATE_ERROR;
409     }
410 #ifdef  notdef
411     xdrrx_create(&xdr, call, XDR_ENCODE);
412     if (!xdr_afs_int32(&xdr, &length)) error = UPDATE_ERROR;
413 #else
414     tlen = htonl(length);
415     rx_Write(call, &tlen, sizeof(afs_int32));   /* send length on fetch */
416 #endif
417     while (!error && length) {
418         register int nbytes = (length>blockSize?blockSize:length);
419         nbytes = read(fd, buffer, nbytes);
420         if (nbytes <= 0) {
421             fprintf(stderr, "File system read failed\n");
422             break;
423         }
424         if (rx_Write(call, buffer, nbytes) != nbytes)
425             break;
426         length -= nbytes;
427     }
428     if (buffer) free(buffer);
429     if (length) error = UPDATE_ERROR;
430     return error;
431 }
432
433 /* Enumerate dir (name) and write dir entry info into temp file. 
434  */
435 int update_SendDirInfo(name, call, status, origDir)
436 char *name;                      /* Name of dir to enumerate */
437 register struct rx_call *call;   /* rx call */
438 register struct stat *status;    /* stat struct for dir */
439 char *origDir;                   /* orig name of dir before being localized */
440 {
441     DIR *dirp;
442     struct dirent *dp;
443     FILE *stream;
444     struct stat tstatus;
445     char filename[MAXSIZE], dirInfoFile[MAXSIZE];
446     int fd, tfd, errcode, error, err;
447
448     error = 0;
449     dirp = opendir(name);
450     sprintf(dirInfoFile, "%s/upserver.tmp", gettmpdir());
451     stream = fopen(dirInfoFile, "w");
452     if (!stream) {
453         error = EIO;
454     } else {
455         while((dp = readdir(dirp))){
456             strcpy(filename, name);
457             strcat(filename,"/");
458             strcat(filename,dp->d_name);
459         
460             tfd = open(filename, O_RDONLY, 0);
461             if (tfd < 0 || fstat(tfd, &tstatus) < 0) {
462                 printf("Failed to open %s\n", name);
463                 error = UPDATE_ERROR;
464                 goto fail;
465             }
466             if((tstatus.st_mode & S_IFMT) != S_IFDIR){/* not a directory */
467                 char dirEntry[MAXSIZE];
468                 
469                 strcpy(dirEntry, origDir); strcat(dirEntry, "/");
470                 strcat(dirEntry, dp->d_name);
471                 err = fprintf(stream, "\"%s\" %u %u %u %u %u %u\n", dirEntry, 
472                         (unsigned int) tstatus.st_mtime,
473                         (unsigned int) tstatus.st_size,
474                         tstatus.st_mode,
475                         tstatus.st_uid,
476                         tstatus.st_gid, 
477                         (unsigned int) tstatus.st_atime);
478                 if (err < 0) error = EIO;
479             }   
480             err = close(tfd);
481             if(err) {
482                 printf("could not close file %s \n",filename);
483                 error = UPDATE_ERROR;
484                 goto fail;
485             }
486         }
487     }
488 fail:
489     if (dirp) closedir(dirp);
490     if (stream) {
491         if (ferror(stream))
492             if (!error) error = UPDATE_ERROR;
493         fclose(stream);
494     }
495     if (error == 0) {
496         fd = open(dirInfoFile, O_RDONLY, 0);
497         if (fd) {
498             fstat(fd, &tstatus);
499             errcode = update_SendFile(fd, call, &tstatus); 
500             if(errcode) if(!error) error = UPDATE_ERROR;
501             close(fd);
502         }
503     }
504     unlink(dirInfoFile);
505     return error;
506 }
507
508
509 /* AddObject() - Adds the object to the list of exported objects after
510  *     converting to a local path.
511  *
512  * expPath : points to allocated storage in which the exportable path is 
513  *           passed back.
514  * dir     : dir name passed in for export 
515  *
516  */  
517 static int AddObject(char **expPath, char *dir)
518 {
519   int error;
520   struct stat statbuf;
521
522   /* construct a local path from a canonical (wire-format) path */
523   if ((error = ConstructLocalPath(dir, "/", expPath))) {
524       com_err(whoami, error, "Unable to construct local path");
525       return error;
526   }
527
528   /* stat the object */
529   error = stat(*expPath, &statbuf);
530   if (error) {
531     com_err(whoami, error, ";Can't stat object.");
532     return error;
533   }
534   /* now check if the object has an exportable (file/dir)  type */
535   if ( ! (statbuf.st_mode & S_IFDIR) ) {
536     fprintf(stderr, "%s: Unacceptable object type for %s\n", whoami, *expPath);
537     return -1;
538   }
539
540   return 0;
541 }