pull-prototypes-to-head-20020821
[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_STRING_H
39 #include <string.h>
40 #else
41 #ifdef HAVE_STRINGS_H
42 #include <strings.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     memcpy(&addr, th->h_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 = NULL;
164     ModFiles =  NULL;
165     okhostfiles = NULL;
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                       fclose(stream);
319                       unlink(dirbuf);
320                       return -1;
321                     }
322                 }
323
324             }
325             fclose(stream);
326             unlink(dirbuf);
327
328             {/*delete all the redundant files on the client */
329                 DIR *dirp;
330                 struct dirent *dp;
331                 char filename[MAXSIZE];
332
333                 dirp = opendir(curDir);
334                 if (dirp == 0) {
335                     com_err (whoami, errno,
336                              "Can't open local dir %s", curDir);
337                     goto fail;
338                 }
339
340                 while((dp = readdir(dirp))) {
341                     /* for all the files in the directory df->name do*/
342                     strcpy(filename, curDir);
343                     strcat(filename,"/");
344                     strcat(filename,dp->d_name);
345                     /* if the file filename is redundant, delete it */
346                     errcode = NotOnHost(filename, okhostfiles);
347                     if (errcode == -1)
348                       return -1;
349                     if ( errcode == 1) {
350                         if (verbose >= 2) printf ("  flushing %s\n", filename);
351                         errcode = unlink(filename);
352                         if(errcode) {
353                             printf("could not delete file %s \n",filename);
354                             com_err (whoami, errno,"could not delete file %s",filename);
355                         }
356                     }
357                 }
358                 closedir(dirp);
359             }
360             /* Now, rename the .NEW files created by FetchFile */
361             if (RenameNewFiles(ModFiles))
362               return -1;
363             
364             free(curDir);
365         } /* end for each dir loop */
366         /*delete the file with info on files in directory df->name */
367         IOMGR_Sleep(interval);
368         continue;
369
370 fail_dirbuf:
371         fclose(stream);
372         unlink(dirbuf);
373 fail:
374         IOMGR_Sleep(retrytime);
375         if (cnt > 10) {
376             rx_DestroyConnection(conn);
377             goto again;
378         }
379         /* start the cycle again */
380
381     }
382 }
383
384 /* returns 1 if the file is upto date else returns 0*/
385 int IsCompatible(filename, time, length)/*check the dir case more carefully*/
386 char *filename;
387 afs_int32 time, length;
388 {
389     struct stat status;
390     afs_int32 error;
391     char *localname;
392
393     /* construct a local path from canonical (wire-format) path */
394     if ((error = ConstructLocalPath(filename, "/", &localname))) {
395         com_err(whoami, error, "Unable to construct local path");
396         return error;
397     }
398
399     error = stat(localname, &status);
400
401     free(localname);
402
403     if(error == -1) return 0;/*a non-existent file, has to be fetched fresh*/
404     if( (status.st_mode & S_IFMT) == S_IFDIR || ((status.st_mtime == time) && (status.st_size == length)))
405         return(1);
406     else
407         return 0;
408 }
409
410 int
411 FetchFile(call, remoteFile, localFile, dirFlag)
412   struct rx_call *call;
413   char *localFile, *remoteFile;
414   int dirFlag;
415 {
416       int fd = -1, error = 0;
417       struct stat status;
418      
419     if(dirFlag){
420         if (StartUPDATE_FetchInfo(call,remoteFile)) return UPDATE_ERROR;
421     }
422     else{
423         if (StartUPDATE_FetchFile(call,remoteFile)) return UPDATE_ERROR;
424     }
425     fd = open(localFile, O_CREAT|O_TRUNC|O_WRONLY, 0666);
426     if (fd < 0) {
427         printf("Could not create %s\n", localFile);
428         com_err (whoami, errno, "Could not create %s", localFile);
429         error = UPDATE_ERROR;
430         return error;
431     }
432     if (fstat(fd, &status) < 0) {
433         com_err (whoami, errno, "Could not stat %s", localFile);
434         close(fd);
435         printf("could not stast %s\n", localFile);
436         return UPDATE_ERROR;
437     }
438     if (update_ReceiveFile(fd, call, &status)) error = UPDATE_ERROR;
439     
440     close(fd);
441     
442     return error;
443 }
444                     
445
446             
447 int update_ReceiveFile(fd, call, status)
448     register int fd;
449     register struct rx_call *call;
450     register struct stat *status;
451 {
452     register char *buffer = (char*) 0;
453     afs_int32 length;
454 #ifdef notdef
455     XDR xdr;
456 #endif
457     register int blockSize;
458     afs_int32 error = 0, len;
459 #ifdef  AFS_AIX_ENV
460 #include <sys/statfs.h>
461     struct statfs tstatfs;
462 #endif
463
464 #ifdef  notdef
465     xdrrx_create(&xdr, call, XDR_DECODE);
466     if (!xdr_afs_int32(&xdr, &length)) return UPDATE_ERROR;
467 #else
468     len = rx_Read(call, &length, sizeof(afs_int32));
469     length = ntohl(length);
470     if (len != sizeof(afs_int32)) return UPDATE_ERROR;
471 #endif
472 #ifdef  AFS_AIX_ENV
473     /* Unfortunately in AIX valuable fields such as st_blksize are gone from the stat structure!! */
474     fstatfs(fd, &tstatfs);
475     blockSize = tstatfs.f_bsize;
476 #elif AFS_NT40_ENV
477     blockSize = 4096;
478 #else
479     blockSize = status->st_blksize;
480 #endif
481     buffer = (char *)malloc(blockSize);
482     if (!buffer) {
483         printf("malloc failed\n");
484         return UPDATE_ERROR;
485     }
486     while (!error && length) {
487         register int nbytes = (length>blockSize?blockSize:length);
488         nbytes = rx_Read(call, buffer, nbytes);
489         if (!nbytes) error = UPDATE_ERROR;
490         if (write(fd, buffer, nbytes) != nbytes) {
491             com_err (whoami, errno, "File system write failed!");
492             printf("File system write failed!\n");
493             error = UPDATE_ERROR;
494         }
495         length -= nbytes;
496     }
497     if (buffer) free(buffer);
498     if (!error) fstat(fd, status);
499     return error;
500 }
501
502
503 /*
504  * PathsAreEquivalent() -- determine if paths are equivalent
505  */
506 static int
507 PathsAreEquivalent(char *path1, char *path2)
508 {
509     int areEq = 0;
510     char pathNorm1[AFSDIR_PATH_MAX], pathNorm2[AFSDIR_PATH_MAX];
511
512 #ifdef AFS_NT40_ENV
513     /* case-insensitive comparison of normalized, same-flavor (short) paths */
514     DWORD status;
515
516     status = GetShortPathName(path1, pathNorm1, AFSDIR_PATH_MAX);
517     if (status == 0 || status > AFSDIR_PATH_MAX) {
518         /* can't convert path to short version; just use long version */
519         strcpy(pathNorm1, path1);
520     }
521     FilepathNormalize(pathNorm1);
522
523     status = GetShortPathName(path2, pathNorm2, AFSDIR_PATH_MAX);
524     if (status == 0 || status > AFSDIR_PATH_MAX) {
525         /* can't convert path to short version; just use long version */
526         strcpy(pathNorm2, path2);
527     }
528     FilepathNormalize(pathNorm2);
529
530     if (_stricmp(pathNorm1, pathNorm2) == 0) {
531         areEq = 1;
532     }
533 #else
534     /* case-sensitive comparison of normalized paths */
535     strcpy(pathNorm1, path1);
536     FilepathNormalize(pathNorm1);
537
538     strcpy(pathNorm2, path2);
539     FilepathNormalize(pathNorm2);
540
541     if (strcmp(pathNorm1, pathNorm2) == 0) {
542         areEq = 1;
543     }
544 #endif /* AFS_NT40_ENV */
545     return areEq;
546 }
547
548
549
550 /* returns 1 if filename does not exist on the host site (=> it should be
551  * deleted on client site) else it returns 0 */
552
553 int NotOnHost(filename, okhostfiles)
554   char *filename;
555   struct filestr *okhostfiles;
556 {
557     int i, rc;
558     struct stat status;
559     struct filestr *tf;
560     char *hostfile;
561
562     stat(filename,&status);
563
564     if((status.st_mode & S_IFMT) == S_IFDIR)
565         return 0;
566     i = strlen(filename);
567     if(!strcmp(&filename[i-4],".NEW"))
568         return 0;
569     
570     for(tf=okhostfiles; tf; tf=tf->next) {
571         /* construct local path from canonical (wire-format) path */
572         if ((rc = ConstructLocalPath(tf->name, "/", &hostfile))) {
573             com_err(whoami, rc, "Unable to construct local path");
574             return -1;
575         }
576         if (PathsAreEquivalent(hostfile, filename)) {
577             free(hostfile);
578             return 0;
579         }
580         free(hostfile);
581     }
582     return 1;
583 }
584
585
586 /* RenameNewFiles() - renames all the newly copied files from the
587  * server. Looks for files with .NEW extension and renames them
588  */
589 static int RenameNewFiles(struct filestr *modFiles)
590 {  
591   char newname[MAXSIZE];
592   char *fname;
593   int errcode = 0;
594   struct filestr *tf;
595
596   for(tf = modFiles; tf; tf=tf->next) {
597       /* construct local path from canonical (wire-format) path */
598       if ((errcode = ConstructLocalPath(tf->name, "/", &fname))) {
599           com_err(whoami, errcode, "Unable to construct local path");
600           return errcode;
601       }
602       strcpy(newname, fname); strcat(newname, ".NEW");
603       if (verbose >= 2) printf ("  renaming %s\n", newname);
604       errcode = renamefile(newname, fname);
605       if (errcode) {
606           printf("could not rename %s to %s\n", newname, fname);
607           com_err (whoami, errno, "could not rename %s to %s", newname, 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
628 int 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) /* access/modification times */
633                         
634 {
635   struct rx_call *call;
636   afs_int32  errcode;
637   char *lfile;
638 #ifdef AFS_NT40_ENV
639   struct _utimbuf utbuf;
640 #else
641   struct timeval tvp[2];
642 #endif
643   char newfile[MAXSIZE];
644
645   /* construct local path from canonical (wire-format) path */
646   errcode = ConstructLocalPath(filename, "/", &lfile);
647   if (errcode) {
648       com_err(whoami, errcode, "Unable to construct local path");
649       return -1; 
650   }
651   strcpy(newfile, lfile);
652   free(lfile);
653
654   strcat(newfile, ".NEW");
655   
656   /* fetch filename into newfile from the host, since the current file
657    * is outdated. the new versions of changed files is stored as
658    * oldname.new */
659   call = rx_NewCall(conn);
660   errcode = FetchFile(call, filename, newfile, 0);
661   errcode = rx_EndCall(call, errcode);
662   
663   if(errcode) {
664     printf("failed to fetch file %s \n",filename);
665     com_err (whoami, errcode, "fetching file");
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     com_err (whoami, errno,
675              "could not change protection on %s to %u",
676              newfile, mode);
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",newfile, gid, uid);
687     com_err (whoami, errno,
688              "warning: could not change uid and gid on %s to %u and %u",newfile, gid, uid);
689   }
690   tvp[0].tv_sec = atime;
691   tvp[0].tv_usec = 0;
692   tvp[1].tv_sec = mtime;
693   tvp[1].tv_usec = 0;
694   errcode = utimes(newfile, tvp);
695 #endif /* NT40 */
696   if (errcode) {
697     printf("could not change access and modify times on %s to %u %u\n",newfile, (unsigned int) atime, (unsigned int) mtime);
698     com_err (whoami, errno,
699              "could not change access and modify times on %s to %u %u",newfile, atime, mtime);
700     return 1;
701   }
702   
703   return 0;
704 }