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