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