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