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