5bf827bdc3d8509d2af1b0401a5bbdc6d6263357
[openafs.git] / src / update / client.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 #include <afs/stds.h>
13
14 #include <afs/procmgmt.h>
15 #include <roken.h>
16 #include <afs/opr.h>
17
18 #ifdef AFS_NT40_ENV
19 #include <WINNT/afsevent.h>
20 #include <sys/utime.h>
21 #include <direct.h>
22 #endif
23
24 #ifdef  AFS_AIX_ENV
25 #include <sys/statfs.h>
26 #endif
27
28 #include <rx/xdr.h>
29 #include <rx/rx.h>
30 #include <rx/rxkad.h>
31 #include <afs/com_err.h>
32 #include <afs/cellconfig.h>
33 #include <afs/afsutil.h>
34 #include <afs/fileutil.h>
35
36 #include "update.h"
37 #include "global.h"
38 #include "update_internal.h"
39
40 char *whoami;
41 static int verbose;
42
43 /* prototypes */
44 static int GetFileFromUpServer(struct rx_connection *conn, char *filename,
45                                short uid, short gid, afs_uint32 mode,
46                                afs_int32 atime, afs_int32 mtime);
47 static int RenameNewFiles(struct filestr *modFiles);
48 static int PathsAreEquivalent(char *path1, char *path2);
49 int FetchFile(struct rx_call *, char *, char *, int);
50 int IsCompatible(char *, afs_int32, afs_int32);
51 int NotOnHost(char *, struct filestr *);
52 int update_ReceiveFile(int, struct rx_call *, struct stat *);
53
54 afs_int32
55 GetServer(char *aname)
56 {
57     struct hostent *th;
58     afs_int32 addr;
59
60     th = gethostbyname(aname);
61     if (!th) {
62         printf("host %s not found \n", aname);
63         exit(1);
64     }
65     memcpy(&addr, th->h_addr, sizeof(addr));
66     return addr;
67 }
68
69
70 int
71 osi_audit(void)
72 {
73 /* this sucks but it works for now.
74 */
75     return 0;
76 }
77
78 #ifndef AFS_NT40_ENV
79 #include "AFS_component_version_number.c"
80 #endif
81
82 int
83 main(int argc, char **argv)
84 {
85     struct rx_connection *conn;
86     struct rx_call *call;
87     struct afsconf_dir *cdir;
88     afs_int32 scIndex;
89     struct rx_securityClass *sc;
90
91     short uid, gid;
92     afs_uint32 u_uid, u_gid;    /*Unsigned long versions of the above */
93     struct stat tstat;
94
95     afs_uint32 mode;
96     int error;
97     char hostname[MAXFNSIZE];
98     FILE *stream;
99     afs_int32 time, length, atime;
100     struct filestr *df;
101     afs_int32 errcode;
102     int retrytime;
103     unsigned int interval;
104     afs_int32 host;
105     int a, cnt;
106     rxkad_level level;
107
108     char dirbuf[MAXFNSIZE], filename[MAXFNSIZE];
109     struct filestr *dirname, *ModFiles, *okhostfiles;
110 #ifdef  AFS_AIX32_ENV
111     /*
112      * The following signal action for AIX is necessary so that in case of a
113      * crash (i.e. core is generated) we can include the user's data section
114      * in the core dump. Unfortunately, by default, only a partial core is
115      * generated which, in many cases, isn't too useful.
116      */
117     struct sigaction nsa;
118
119     sigemptyset(&nsa.sa_mask);
120     nsa.sa_handler = SIG_DFL;
121     nsa.sa_flags = SA_FULLDUMP;
122     sigaction(SIGABRT, &nsa, NULL);
123     sigaction(SIGSEGV, &nsa, NULL);
124 #endif
125     whoami = argv[0];
126 #ifdef AFS_NT40_ENV
127     /* dummy signal call to force afsprocmgmt.dll to load on NT */
128     signal(SIGUSR1, SIG_DFL);
129
130     /* initialize winsock */
131     if (afs_winsockInit() < 0) {
132         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
133         fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
134         exit(1);
135     }
136 #endif
137
138     /* Initialize dirpaths */
139     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
140 #ifdef AFS_NT40_ENV
141         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
142 #endif
143         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
144                 argv[0]);
145         exit(2);
146     }
147     retrytime = 60;
148     dirname = NULL;
149     ModFiles = NULL;
150     okhostfiles = NULL;
151
152     verbose = 0;
153     interval = TIMEOUT;
154     level = rxkad_crypt;        /* safest default */
155     strcpy(hostname, "");
156
157     /* Note that IsArg only checks as many bytes as specified in the command line arg,
158      * so that, for instance, -t still matches -time.
159      */
160     for (a = 1; a < argc; a++) {
161         if (argv[a][0] == '-') {        /* parse options */
162             int arglen = strlen(argv[a]);
163             char arg[256];
164             lcstring(arg, argv[a], sizeof(arg));
165 #define IsArg(a) (strncmp (arg,a, arglen) == 0)
166             if (IsArg("-time"))
167                 interval = atol(argv[++a]);
168             else if (IsArg("-crypt"))
169                 level = rxkad_crypt;
170             else if (IsArg("-clear"))
171                 level = rxkad_clear;
172             else if (IsArg("-verbose"))
173                 verbose++;
174             else {
175               usage:
176                 printf
177                     ("Usage: upclient <hostname> [-crypt] [-clear] [-t <retry time>] [-verbose]* <dir>+ [-help]\n");
178                 exit(1);
179             }
180         } else if (strlen(hostname) == 0)
181             strcpy(hostname, argv[a]);
182         else {
183             strcpy(filename, argv[a]);
184             FilepathNormalize(filename);
185             AddToList(&dirname, filename);
186         }
187     }
188     if (level == -1)
189         goto usage;
190     if (strlen(hostname) == 0)
191         goto usage;
192     host = GetServer(hostname);
193     if (interval < retrytime)
194         retrytime = interval;
195     if (dirname == 0)
196         goto usage;
197
198     errcode = rx_Init(0);
199     if (errcode) {
200         printf("Rx initialize failed \n");
201         afs_com_err(whoami, errcode, "calling Rx init");
202         exit(1);
203     }
204
205     cdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
206     if (cdir == 0) {
207         fprintf(stderr, "Can't get server configuration info (%s)\n",
208                 AFSDIR_SERVER_ETC_DIRPATH);
209         exit(1);
210     }
211
212     if (level == rxkad_crypt)
213         errcode = afsconf_ClientAuthSecure(cdir, &sc, &scIndex);
214     else if (level == rxkad_clear)
215         errcode = afsconf_ClientAuth(cdir, &sc, &scIndex);
216     else {
217         printf("Unsupported security level %d\n", level);
218         exit(1);
219     }
220     if (errcode) {
221         afs_com_err(whoami, errcode, "Couldn't get security obect for localAuth");
222         exit(1);
223     }
224
225   again:
226     conn =
227         rx_NewConnection(host, htons(AFSCONF_UPDATEPORT), UPDATE_SERVICEID,
228                          sc, scIndex);
229     cnt = 0;
230     while (1) {                 /*keep doing it */
231         char c, c1;
232         for (df = dirname; df; df = df->next) { /*for each directory do */
233             char *curDir;
234
235             if (verbose)
236                 printf("Checking dir %s\n", df->name);
237             /* initialize lists */
238             ZapList(&ModFiles);
239             ZapList(&okhostfiles);
240
241             /* construct local path from canonical (wire-format) path */
242             if ((errcode = ConstructLocalPath(df->name, "/", &curDir))) {
243                 afs_com_err(whoami, errcode, "Unable to construct local path");
244                 return errcode;
245             }
246
247             if (stat(curDir, &tstat) < 0) {
248                 /* try to make the dir */
249 #ifdef AFS_NT40_ENV
250                 if (mkdir(curDir) < 0) {
251 #else
252                 if (mkdir(curDir, 0700) < 0) {
253 #endif
254                     afs_com_err(whoami, errno, "can't create dir");
255                     printf("upclient: Can't update dir %s\n", curDir);
256                     return -1;
257                 }
258             } else {
259                 if ((tstat.st_mode & S_IFMT) != S_IFDIR) {
260                     printf(" file %s is not a directory; aborting\n", curDir);
261                     return -1;
262                 }
263             }
264             call = rx_NewCall(conn);
265
266             /* scratch pad file */
267             sprintf(dirbuf, "%s/upclient.%d", gettmpdir(), getpid());
268
269             errcode = FetchFile(call, df->name, dirbuf, 1);     /* get the names and relevant info about all the files in the directory df->name into file dirbuf */
270             error = rx_EndCall(call, 0);
271             if (error && !errcode) {
272                 printf("could not end rx call \n");
273                 afs_com_err(whoami, error, "calling EndCall");
274                 goto fail;
275             }
276             if (errcode) {
277                 printf
278                     ("warning: could not fetch the contents of directory %s \n",
279                      df->name);
280                 afs_com_err(whoami, errcode, "calling FetchFile");
281                 cnt++;
282                 goto fail;
283             }
284
285             stream = fopen(dirbuf, "r");
286             if (stream == NULL) {
287                 printf("fopen failed on %s \n", dirbuf);
288                 afs_com_err(whoami, errno, "fopen");
289                 goto fail;
290             }
291             umask(00);
292
293             /* while there is more info about files in file dirbuf */
294             while (fscanf
295                    (stream, "%c%[^\"]%c %u %u %u %u %u %u\n", &c, filename,
296                     &c1, &time, &length, &mode, &u_uid, &u_gid,
297                     &atime) != EOF) {
298                 uid = (short)u_uid;
299                 gid = (short)u_gid;
300                 AddToList(&okhostfiles, filename);
301                 /*record all the file names which exist on the remote
302                  * sync site, to enable purging of redundant files */
303                 if (verbose >= 3)
304                     printf("    checking %s\n", filename);
305                 if (!IsCompatible(filename, time, length)) {
306                     /* if the file info has changed , record all the
307                      *changed files in the ModFiles array*/
308                     if (verbose >= 2)
309                         printf("  getting %s\n", filename);
310                     AddToList(&ModFiles, filename);
311
312                     /* now get the file from the server. The received
313                      * file is created under the name filename.NEW */
314                     errcode =
315                         GetFileFromUpServer(conn, filename, uid, gid, mode,
316                                             atime, time);
317                     if (errcode == 1)   /* this file failed, but keep trying */
318                         goto fail_dirbuf;
319                     if (errcode == -1) {        /* time to quit */
320                         fclose(stream);
321                         unlink(dirbuf);
322                         return -1;
323                     }
324                 }
325
326             }
327             fclose(stream);
328             unlink(dirbuf);
329
330             {                   /*delete all the redundant files on the client */
331                 DIR *dirp;
332                 struct dirent *dp;
333                 char filename[MAXFNSIZE];
334
335                 dirp = opendir(curDir);
336                 if (dirp == 0) {
337                     afs_com_err(whoami, errno, "Can't open local dir %s", curDir);
338                     goto fail;
339                 }
340
341                 while ((dp = readdir(dirp))) {
342                     /* for all the files in the directory df->name do */
343                     strcpy(filename, curDir);
344                     strcat(filename, "/");
345                     strcat(filename, dp->d_name);
346                     /* if the file filename is redundant, delete it */
347                     errcode = NotOnHost(filename, okhostfiles);
348                     if (errcode == -1)
349                         return -1;
350                     if (errcode == 1) {
351                         if (verbose >= 2)
352                             printf("  flushing %s\n", filename);
353                         errcode = unlink(filename);
354                         if (errcode) {
355                             printf("could not delete file %s \n", filename);
356                             afs_com_err(whoami, errno, "could not delete file %s",
357                                     filename);
358                         }
359                     }
360                 }
361                 closedir(dirp);
362             }
363             /* Now, rename the .NEW files created by FetchFile */
364             if (RenameNewFiles(ModFiles))
365                 return -1;
366
367             free(curDir);
368         }                       /* end for each dir loop */
369         /*delete the file with info on files in directory df->name */
370         IOMGR_Sleep(interval);
371         continue;
372
373       fail_dirbuf:
374         fclose(stream);
375         unlink(dirbuf);
376       fail:
377         IOMGR_Sleep(retrytime);
378         if (cnt > 10) {
379             rx_DestroyConnection(conn);
380             goto again;
381         }
382         /* start the cycle again */
383
384     }
385 }
386
387 /* returns 1 if the file is upto date else returns 0*/
388 /*check the dir case more carefully */
389 int
390 IsCompatible(char *filename, afs_int32 time, afs_int32 length)
391 {
392     struct stat status;
393     afs_int32 error;
394     char *localname;
395
396     /* construct a local path from canonical (wire-format) path */
397     if ((error = ConstructLocalPath(filename, "/", &localname))) {
398         afs_com_err(whoami, error, "Unable to construct local path");
399         return error;
400     }
401
402     error = stat(localname, &status);
403
404     free(localname);
405
406     if (error == -1)
407         return 0;       /*a non-existent file, has to be fetched fresh */
408     if ((status.st_mode & S_IFMT) == S_IFDIR
409         || ((status.st_mtime == time) && (status.st_size == length)))
410         return (1);
411     else
412         return 0;
413 }
414
415 int
416 FetchFile(struct rx_call *call, char *remoteFile, char *localFile, int dirFlag)
417 {
418     int fd = -1, error = 0;
419     struct stat status;
420
421     if (dirFlag) {
422         if (StartUPDATE_FetchInfo(call, remoteFile))
423             return UPDATE_ERROR;
424     } else {
425         if (StartUPDATE_FetchFile(call, remoteFile))
426             return UPDATE_ERROR;
427     }
428     fd = open(localFile, O_CREAT | O_TRUNC | O_WRONLY, 0666);
429     if (fd < 0) {
430         printf("Could not create %s\n", localFile);
431         afs_com_err(whoami, errno, "Could not create %s", localFile);
432         error = UPDATE_ERROR;
433         return error;
434     }
435     if (fstat(fd, &status) < 0) {
436         afs_com_err(whoami, errno, "Could not stat %s", localFile);
437         close(fd);
438         printf("could not stat %s\n", localFile);
439         return UPDATE_ERROR;
440     }
441     if (update_ReceiveFile(fd, call, &status))
442         error = UPDATE_ERROR;
443
444     close(fd);
445
446     return error;
447 }
448
449
450
451 int
452 update_ReceiveFile(int fd, struct rx_call *call, struct stat *status)
453 {
454     char *buffer = (char *)0;
455     afs_int32 length;
456     int blockSize;
457     afs_int32 error = 0, len;
458 #ifdef  AFS_AIX_ENV
459     struct statfs tstatfs;
460 #endif
461
462     len = rx_Read(call, (char *)&length, sizeof(afs_int32));
463     length = ntohl(length);
464     if (len != sizeof(afs_int32))
465         return UPDATE_ERROR;
466 #ifdef  AFS_AIX_ENV
467     /* Unfortunately in AIX valuable fields such as st_blksize are gone from the stat structure!! */
468     fstatfs(fd, &tstatfs);
469     blockSize = tstatfs.f_bsize;
470 #elif AFS_NT40_ENV
471     blockSize = 4096;
472 #else
473     blockSize = status->st_blksize;
474 #endif
475     buffer = malloc(blockSize);
476     if (!buffer) {
477         printf("malloc failed\n");
478         return UPDATE_ERROR;
479     }
480     while (!error && length) {
481         int nbytes = (length > blockSize ? blockSize : length);
482         nbytes = rx_Read(call, buffer, nbytes);
483         if (!nbytes)
484             error = UPDATE_ERROR;
485         if (write(fd, buffer, nbytes) != nbytes) {
486             afs_com_err(whoami, errno, "File system write failed!");
487             printf("File system write failed!\n");
488             error = UPDATE_ERROR;
489         }
490         length -= nbytes;
491     }
492     if (buffer)
493         free(buffer);
494     if (!error)
495         fstat(fd, status);
496     return error;
497 }
498
499
500 /*
501  * PathsAreEquivalent() -- determine if paths are equivalent
502  */
503 static int
504 PathsAreEquivalent(char *path1, char *path2)
505 {
506     int areEq = 0;
507     char pathNorm1[AFSDIR_PATH_MAX], pathNorm2[AFSDIR_PATH_MAX];
508
509 #ifdef AFS_NT40_ENV
510     /* case-insensitive comparison of normalized, same-flavor (short) paths */
511     DWORD status;
512
513     status = GetShortPathName(path1, pathNorm1, AFSDIR_PATH_MAX);
514     if (status == 0 || status > AFSDIR_PATH_MAX) {
515         /* can't convert path to short version; just use long version */
516         strcpy(pathNorm1, path1);
517     }
518     FilepathNormalize(pathNorm1);
519
520     status = GetShortPathName(path2, pathNorm2, AFSDIR_PATH_MAX);
521     if (status == 0 || status > AFSDIR_PATH_MAX) {
522         /* can't convert path to short version; just use long version */
523         strcpy(pathNorm2, path2);
524     }
525     FilepathNormalize(pathNorm2);
526
527     if (_stricmp(pathNorm1, pathNorm2) == 0) {
528         areEq = 1;
529     }
530 #else
531     /* case-sensitive comparison of normalized paths */
532     strcpy(pathNorm1, path1);
533     FilepathNormalize(pathNorm1);
534
535     strcpy(pathNorm2, path2);
536     FilepathNormalize(pathNorm2);
537
538     if (strcmp(pathNorm1, pathNorm2) == 0) {
539         areEq = 1;
540     }
541 #endif /* AFS_NT40_ENV */
542     return areEq;
543 }
544
545
546
547 /* returns 1 if filename does not exist on the host site (=> it should be
548  * deleted on client site) else it returns 0 */
549
550 int
551 NotOnHost(char *filename, struct filestr *okhostfiles)
552 {
553     int i, rc;
554     struct stat status;
555     struct filestr *tf;
556     char *hostfile;
557
558     stat(filename, &status);
559
560     if ((status.st_mode & S_IFMT) == S_IFDIR)
561         return 0;
562     i = strlen(filename);
563     if (!strcmp(&filename[i - 4], ".NEW"))
564         return 0;
565
566     for (tf = okhostfiles; tf; tf = tf->next) {
567         /* construct local path from canonical (wire-format) path */
568         if ((rc = ConstructLocalPath(tf->name, "/", &hostfile))) {
569             afs_com_err(whoami, rc, "Unable to construct local path");
570             return -1;
571         }
572         if (PathsAreEquivalent(hostfile, filename)) {
573             free(hostfile);
574             return 0;
575         }
576         free(hostfile);
577     }
578     return 1;
579 }
580
581
582 /* RenameNewFiles() - renames all the newly copied files from the
583  * server. Looks for files with .NEW extension and renames them
584  */
585 static int
586 RenameNewFiles(struct filestr *modFiles)
587 {
588     char newname[MAXFNSIZE];
589     char *fname;
590     int errcode = 0;
591     struct filestr *tf;
592
593     for (tf = modFiles; tf; tf = tf->next) {
594         /* construct local path from canonical (wire-format) path */
595         if ((errcode = ConstructLocalPath(tf->name, "/", &fname))) {
596             afs_com_err(whoami, errcode, "Unable to construct local path");
597             return errcode;
598         }
599         strcpy(newname, fname);
600         strcat(newname, ".NEW");
601         if (verbose >= 2)
602             printf("  renaming %s\n", newname);
603         errcode = renamefile(newname, fname);
604         if (errcode) {
605             printf("could not rename %s to %s\n", newname, fname);
606             afs_com_err(whoami, errno, "could not rename %s to %s", newname,
607                     fname);
608         }
609         free(fname);
610     }
611     return errcode;
612 }
613
614
615
616 /* GetFileFromUpServer() - Makes the FetchFile() call and gets the
617  * file from the upserver.
618  * Return Values:
619  *   0 -  Alls well
620  *   -1 - Serious error. Quit right away.
621  *   1  - Error, but keep trying for the other files
622  *
623  * The file obtained is written to the localized version of the filename.NEW
624  * and the uid, gid, file mode, access and modification times will be set to
625  * the passed in values.
626  */
627 static int
628 GetFileFromUpServer(struct rx_connection *conn, /* handle for upserver */
629                     char *filename,     /* name of file to be fetched */
630                     short uid, short gid,       /* uid/gid for fetched file */
631                     afs_uint32 mode,    /* file mode */
632                     afs_int32 atime, afs_int32 mtime)
633 {                               /* access/modification times */
634     struct rx_call *call;
635     afs_int32 errcode;
636     char *lfile;
637 #ifdef AFS_NT40_ENV
638     struct _utimbuf utbuf;
639 #else
640     struct timeval tvp[2];
641 #endif
642     char newfile[MAXFNSIZE];
643
644     /* construct local path from canonical (wire-format) path */
645     errcode = ConstructLocalPath(filename, "/", &lfile);
646     if (errcode) {
647         afs_com_err(whoami, errcode, "Unable to construct local path");
648         return -1;
649     }
650     strcpy(newfile, lfile);
651     free(lfile);
652
653     strcat(newfile, ".NEW");
654
655     /* fetch filename into newfile from the host, since the current file
656      * is outdated. the new versions of changed files is stored as
657      * oldname.new */
658     call = rx_NewCall(conn);
659     errcode = FetchFile(call, filename, newfile, 0);
660     errcode = rx_EndCall(call, errcode);
661
662     if (errcode) {
663         printf("failed to fetch file %s \n", filename);
664         afs_com_err(whoami, errcode, "fetching file");
665         unlink(newfile);
666         return 1;
667     }
668
669     /* now set the rest of the file status */
670     errcode = chmod(newfile, mode);
671     if (errcode) {
672         printf("could not change protection on %s to %u\n", newfile,
673                (unsigned int)mode);
674         afs_com_err(whoami, errno, "could not change protection on %s to %u",
675                 newfile, mode);
676         unlink(newfile);
677         return 1;
678     }
679 #ifdef AFS_NT40_ENV
680     utbuf.actime = atime;
681     utbuf.modtime = mtime;
682     errcode = _utime(newfile, &utbuf);
683 #else
684     errcode = chown(newfile, uid, gid);
685     if (errcode) {
686         printf("warning: could not change uid and gid on %s to %u and %u \n",
687                newfile, gid, uid);
688         afs_com_err(whoami, errno,
689                 "warning: could not change uid and gid on %s to %u and %u",
690                 newfile, gid, uid);
691     }
692     tvp[0].tv_sec = atime;
693     tvp[0].tv_usec = 0;
694     tvp[1].tv_sec = mtime;
695     tvp[1].tv_usec = 0;
696     errcode = utimes(newfile, tvp);
697 #endif /* NT40 */
698     if (errcode) {
699         printf("could not change access and modify times on %s to %u %u\n",
700                newfile, (unsigned int)atime, (unsigned int)mtime);
701         afs_com_err(whoami, errno,
702                 "could not change access and modify times on %s to %u %u",
703                 newfile, atime, mtime);
704         unlink(newfile);
705         return 1;
706     }
707
708     return 0;
709 }