coverity appeasement - redundant check
[minix.git] / commands / backup / backup.c
blob0e1c2f14d1083c16952e902e539cde4b1423cb2a
1 /* backup - backup a directory Author: Andy Tanenbaum */
3 /* This program recursively backs up a directory. It has two typical uses:
5 * 1. Backing up a directory to 1 or more diskettes
6 * 2. Backing up RAM disk to a shadow directory on hard disk
8 * The backup directory or medium may be empty, in which case, the entire
9 * source directory is copied, or it may contain an old backup, in which
10 * case only those files that are new or out of date are copied. In this
11 * respect, 'backup' resembles 'make', except that no 'makefile' is needed.
12 * The backed up copy may optionally be compressed to save space.
14 * The following flags exist:
16 * -d At the top level, only back up directories (not loose files)
17 * -j Don't copy junk: *.Z, *.bak, *.log, a.out, and core
18 * -m If ENOSPC encountered, ask for another diskette
19 * -n No directories, only loose files are backed up
20 * -o Don't copy *.o files
21 * -r Restore files (ie. uncompress if necessary)
22 * -s Don't copy *.s files
23 * -t Set creation date of target-file equal to cdate of source-file
24 * -v Verbose (announce what is being done)
25 * -z Compress on backup/uncompress on restore
27 * Patches:
28 * 30 Mar 91. Added restore option. cwr.
29 * 9 Sep 91. Changed user interface. cwr.
30 * 21 Jan 93. Revised error messages. cwr.
31 * 29 Mar 95. Added -o, NARROW define. cwr.
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <utime.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <sys/wait.h>
43 #include <stdio.h>
44 #include <dirent.h>
46 #define NAME_SIZE NAME_MAX
48 #undef NARROW /* Width of verbose output */
49 #define COPY_SIZE 4096
50 #define MAX_ENTRIES 512
51 #define MAX_PATH 256
52 #define NONFATAL 0
53 #define FATAL 1
54 #define NO_SAVINGS 512 /* compress can return code 2 */
55 #define OUT_OF_SPACE 2
57 struct dirent dir_ent[MAX_ENTRIES];
58 int entries = 0;
60 struct sorted {
61 int mode; /* file mode */
62 char *namep; /* pointer to name in dir_buf */
63 long acctime; /* time of last access */
64 long modtime; /* time of last modification */
65 } sorted[MAX_ENTRIES];
67 char copybuf[COPY_SIZE];
68 char *pname;
69 int dflag, jflag, mflag, nflag, oflag, rflag, sflag, tflag, vflag, zflag;
71 extern int errno;
72 extern char **environ;
74 int main(int argc, char **argv);
75 void maketarget(char *dir2);
76 int make_dir(char *dir);
77 int stat_all(char *dir1, int n);
78 void sort_dir(int m);
79 void process(int m, char *dir1, char *dir2);
80 void swap(struct sorted *sp1, struct sorted *sp2);
81 int copy(char *dir1, struct sorted *sp, char *cbuf2);
82 int zcopy(char *src, char *targ);
83 void copydir(char *dir1, char *dir2, char *namep);
84 void newdisk(char *dir);
85 void usage(void);
86 void error(int type, char *s1, char *s2, char *s3);
88 int main(argc, argv)
89 int argc;
90 char *argv[];
92 int n, m;
93 char *dir1, *dir2, *cp, c;
94 struct stat s;
95 struct dirent *e;
96 DIR *DIR1;
98 (void) sync();
100 /* Get the flags */
101 if ((pname = strrchr(argv[0], '/')) == (char *)NULL)
102 pname = argv[0];
103 else
104 pname++;
105 if (argc < 3 || argc > 4) usage();
106 if (argc == 4) {
107 cp = argv[1];
108 if (*cp++ != '-') usage();
109 while ((c = *cp++) != '\0') {
110 switch (c) {
111 case 'd': dflag++; break;
112 case 'j': jflag++; break;
113 case 'm': mflag++; break;
114 case 'n': nflag++; break;
115 case 'o': oflag++; break;
116 case 's': sflag++; break;
117 case 'r': rflag++; break;
118 case 't': tflag++; break;
119 case 'v': vflag++; break;
120 case 'z': zflag++; break;
121 default: usage();
124 dir1 = argv[2];
125 dir2 = argv[3];
126 } else {
127 dir1 = argv[1];
128 dir2 = argv[2];
130 if (!strcmp(pname, "restore") && !rflag) rflag++;
132 /* Check for a valid source */
133 if (stat(dir1, &s) < 0) error(FATAL, "cannot stat ", dir1, "");
134 if ((s.st_mode & S_IFMT) != S_IFDIR) error(FATAL, "non-directory ", dir1, "");
136 /* Read in the source directory */
137 if(!(DIR1 = opendir(dir1))) {
138 perror(dir1);
139 return 1;
141 while(entries < MAX_ENTRIES && (e=readdir(DIR1)))
142 memcpy(&dir_ent[entries++], e, sizeof(*e));
143 closedir(DIR1);
144 if (entries == MAX_ENTRIES)
145 error(FATAL, "directory ", dir1, " is too large");
147 /* Create the target directory. */
148 maketarget(dir2);
150 /* Stat all the entries. */
151 n = entries;
152 m = stat_all(dir1, n);
154 /* Remove non-entries and sort what's left. */
155 sort_dir(m);
157 /* Process each of the m entries one at a time. */
158 process(m, dir1, dir2);
159 return(0);
163 void maketarget(dir2)
164 char *dir2;
166 /* The target directory is created if it does not already exist. */
168 char *p, c, dbuf[MAX_PATH];
170 if (access(dir2, 6) == 0)
171 return; /* if target exists, we're done */
172 if (make_dir(dir2) == 0) return; /* we just made it */
174 /* We have to try creating all the higher level directories. */
175 strcpy(dbuf, dir2);
176 p = dbuf + 1;
177 while (1) {
178 while (*p != '/' && *p != '\0') p++;
179 c = *p; /* either / or \0 */
180 *p = 0;
181 make_dir(dbuf);
182 if (c == '\0') return;
183 *p = c;
184 p++;
188 int make_dir(dir)
189 char *dir;
191 /* Create a directory. */
192 int pid, status;
194 if ((pid = fork()) < 0)
195 error(FATAL, "cannot fork off mkdir to create ", dir, "");
196 if (pid > 0) {
197 /* Parent process waits for child (mkdir). */
198 wait(&status);
199 return(status);
200 } else {
201 /* Child process executes mkdir */
202 close(2); /* don't want mkdir's error messages */
203 execle("/bin/mkdir", "mkdir", dir, (char *) 0, environ);
204 execle("/usr/bin/mkdir", "mkdir", dir, (char *) 0, environ);
205 error(FATAL, "cannot execute mkdir", "", "");
207 return(0);
211 int stat_all(dir1, n)
212 char *dir1;
213 int n;
215 /* Stat all the directory entries. By doing this all at once, the disk
216 * head can stay in the inode area.
219 int i, j;
220 char cbuf[MAX_PATH];
221 struct stat s;
223 for (i = 0; i < n; i++) {
224 /* Mark "." and ".." as null entries, as well as unstatable ones. */
225 if (strcmp(dir_ent[i].d_name, ".") == 0) dir_ent[i].d_ino = 0;
226 if (strcmp(dir_ent[i].d_name, "..") == 0) dir_ent[i].d_ino = 0;
227 if (dir_ent[i].d_ino == 0) continue;
229 /* Stat the file. */
230 snprintf(cbuf, sizeof(cbuf), "%s/%s", dir1, dir_ent[i].d_name);
231 if (stat(cbuf, &s) < 0) {
232 error(NONFATAL, "cannot stat ", cbuf, "");
233 dir_ent[i].d_ino = 0; /* mark as unusable */
234 continue;
236 sorted[i].mode = s.st_mode;
237 sorted[i].acctime = s.st_atime;
238 sorted[i].modtime = s.st_mtime;
239 sorted[i].namep = dir_ent[i].d_name;
240 sorted[i].namep[NAME_SIZE-1] = '\0';
243 /* Squeeze out all the entries whose ino field is 0. */
244 j = 0;
245 for (i = 0; i < n; i++) {
246 if (dir_ent[i].d_ino != 0) {
247 sorted[j] = sorted[i];
248 j++;
251 return(j);
255 void sort_dir(m)
256 int m;
258 /* Sort the directory using bubble sort. */
260 struct sorted *sp1, *sp2;
262 for (sp1 = &sorted[0]; sp1 < &sorted[m - 1]; sp1++) {
263 for (sp2 = sp1 + 1; sp2 < &sorted[m]; sp2++) {
264 if (strcmp(sp1->namep, sp2->namep) > 0)
265 swap(sp1, sp2);
271 void process(m, dir1, dir2)
272 int m;
273 char *dir1, *dir2;
275 /* Process each entry in sorted[]. If it is a regular file, stat the target
276 * file. The the source is newer, copy it. If the entry is a directory,
277 * recursively call the entire program to process the directory.
280 int er, fmode, res;
281 struct sorted *sp;
282 struct stat s;
283 char cbuf[MAX_PATH];
285 for (sp = &sorted[0]; sp < &sorted[m]; sp++) {
286 int namlen;
287 fmode = sp->mode & S_IFMT;
288 if (fmode == S_IFREG) {
289 /* Regular file. Construct target name and stat it. */
290 snprintf(cbuf, sizeof(cbuf), "%s/%s", dir2, sp->namep);
291 namlen = strlen(sp->namep);
292 /* Switch between compressed and uncompressed file names */
293 if (zflag && !rflag && strncmp((sp->namep + namlen - 2), ".Z", (size_t)2)
294 && (namlen <= (NAME_SIZE - 2)))
295 strncat(cbuf, ".Z", (size_t)2);
296 if (zflag && rflag && !strncmp((sp->namep + namlen - 2), ".Z", (size_t)2))
297 cbuf[strlen(cbuf) - 2] = '\0';
298 er = stat(cbuf, &s);
299 if (er < 0 || sp->modtime > s.st_mtime) {
300 res = copy(dir1, sp, cbuf);
301 } else {
302 res = NONFATAL;
305 /* Check status of the copy. */
306 if (res == OUT_OF_SPACE) {
307 printf("Out of space while copying to %s\n", cbuf);
308 /* We ran out of space copying a regular file. */
309 if (mflag == 0)
310 error(FATAL, "Quitting, disk full", "", "");
312 /* If -m, ask for new diskette and continue. */
313 newdisk(dir2);
314 sp--;
315 continue;
317 } else if (fmode == S_IFDIR) {
318 /* Directory. Execute this program recursively. */
319 copydir(dir1, dir2, sp->namep);
320 } else if (fmode == S_IFBLK || fmode == S_IFCHR) {
321 /* Special file. */
322 strncpy(cbuf, sp->namep, sizeof(cbuf));
323 printf("%s is special file. Not backed up.\n", cbuf);
331 void swap(sp1, sp2)
332 struct sorted *sp1, *sp2;
334 /* Swap two directory entries. */
336 struct sorted d;
338 d = *sp1;
339 *sp1 = *sp2;
340 *sp2 = d;
344 int copy(dir1, sp, cbuf2)
345 struct sorted *sp;
346 char *dir1, *cbuf2;
348 /* Copy a regular file. */
350 int fd1, fd2, nr, nw, res, n;
351 char cbuf1[MAX_PATH], *p;
352 #ifdef NARROW
353 char *msg = (rflag || strcmp(pname, "backup")) ? "Restored" : "Backing up";
354 #endif
356 /* If the -j or -o or -s flags were given, suppress certain files. */
357 p = sp->namep;
358 n = strlen(p);
359 if (n > NAME_SIZE) n = NAME_SIZE;
360 if (jflag) {
361 if (strcmp(p, "a.out") == 0) return(0);
362 if (strcmp(p, "core") == 0) return (0);
363 if (strcmp(p + n - 2, ".Z") == 0) return (0);
364 if (strcmp(p + n - 4, ".bak") == 0) return (0);
365 if (strcmp(p + n - 4, ".log") == 0) return (0);
367 if (oflag) {
368 if (strcmp(p + n - 2, ".o") == 0) return(0);
370 if (sflag) {
371 if (strcmp(p + n - 2, ".s") == 0) return(0);
373 res = 0;
374 if (dflag) return(0); /* backup -d means only directories */
375 strcpy(cbuf1, dir1);
376 strncat(cbuf1, "/", (size_t)1);
377 strncat(cbuf1, sp->namep, (size_t)NAME_SIZE); /* cbuf1 = source file name */
379 /* At this point, cbuf1 contains the source file name, cbuf2 the target. */
380 fd1 = open(cbuf1, O_RDONLY);
381 if (fd1 < 0) {
382 error(NONFATAL, "cannot open ", cbuf1, "");
383 return(res);
385 fd2 = creat(cbuf2, (sp->mode | S_IWUSR) & 07777);
386 if (fd2 < 0) {
387 if (errno == ENFILE) {
388 close(fd1);
389 return(OUT_OF_SPACE);
391 error(NONFATAL, "cannot create ", cbuf2, "");
392 close(fd1);
393 return(res);
396 /* Both files are now open. Do the copying. */
397 if (!rflag && strncmp((sp->namep + n - 2), ".Z", (size_t)2) ||
398 rflag && !strncmp((sp->namep + n - 2), ".Z", (size_t)2)) {
399 if (zflag && (rflag || (n <= (NAME_SIZE - 2)))) {
400 close(fd1);
401 close(fd2);
402 res = zcopy(cbuf1, cbuf2);
403 if (tflag) utime(cbuf2, (struct utimbuf *) & (sp->acctime));
404 if (res != 0) unlink(cbuf2); /* if error, get rid of the corpse */
405 #ifdef NARROW
406 if (vflag && res == 0) printf("%s %s\n", msg, cbuf1);
407 #else
408 if (vflag && res == 0) {
409 printf("%-37.37s -> %-37.37s\n", cbuf1, cbuf2);
410 if (strlen(cbuf1) > 37 || strlen(cbuf2) > 37)
411 printf("%37.37s %37.37s\n",
412 (strlen(cbuf1) > 37) ? (cbuf1 + 37) : "",
413 (strlen(cbuf2) > 37) ? (cbuf2 + 37) : "");
415 #endif
416 return(res);
419 while (1) {
420 nr = read(fd1, copybuf, COPY_SIZE);
421 if (nr == 0) break;
422 if (nr < 0) {
423 error(NONFATAL, "read error on ", cbuf1, "");
424 res = EIO;
425 break;
427 nw = write(fd2, copybuf, nr);
428 if (nw < 0) {
429 if (errno == ENOSPC) {
430 /* Device is full. */
431 res = OUT_OF_SPACE;
432 break;
435 /* True write error. */
436 error(NONFATAL, "write error on ", cbuf2, "");
437 res = EIO;
438 break;
441 if (res == 0) {
442 #ifdef NARROW
443 if (vflag) printf("%s %s\n", msg, cbuf1);
444 #else
445 if (vflag) {
446 printf("%-37.37s -> %-37.37s\n", cbuf1, cbuf2);
447 if (strlen(cbuf1) > 37 || strlen(cbuf2) > 37)
448 printf("%37.37s %37.37s\n",
449 (strlen(cbuf1) > 37) ? (cbuf1 + 37) : "",
450 (strlen(cbuf2) > 37) ? (cbuf2 + 37) : "");
452 #endif
453 } else {
454 unlink(cbuf2);
456 close(fd1);
457 close(fd2);
458 if (tflag) utime(cbuf2, (struct utimbuf *) & (sp->acctime));
459 return(res);
463 int zcopy(src, targ)
464 char *src, *targ;
467 int pid, status, res, s;
468 char fbuf[20];
470 /* These flags go for compress and gzip. */
471 strcpy(fbuf, "-c");
472 if (rflag)
473 strcat(fbuf, "d");
474 else
475 strcat(fbuf, "f");
477 if ((pid = fork()) < 0) error(FATAL, "cannot fork", "", "");
478 if (pid > 0) {
479 wait(&status);
481 /* Error codes 0 and 2 are ok, assume others mean disk is full. */
482 res = (status == 0 || status == NO_SAVINGS ? 0 : OUT_OF_SPACE);
483 return(res);
484 } else {
485 /* Child must execute compress. */
486 close(1);
487 s = open(targ, O_RDWR);
488 if (s < 0) error(FATAL, "cannot write on ", "targ", "");
489 execle("/usr/bin/gzip", "gzip", fbuf, src, (char *)0, environ);
490 execle("/usr/local/bin/gzip", "gzip", fbuf, src, (char *)0, environ);
491 execle("/bin/compress", "compress", fbuf, src, (char *)0, environ);
492 execle("/usr/bin/compress", "compress", fbuf, src, (char *)0, environ);
493 error(FATAL, "cannot exec gzip or compress", "", "");
495 return(0);
499 void copydir(dir1, dir2, namep)
500 char *dir1, *dir2, *namep;
502 /* Copy a directory. */
504 int pid, status;
505 char fbuf[20], d1buf[MAX_PATH], d2buf[MAX_PATH];
507 if (nflag) return; /* backup -n means no directories */
509 fbuf[0] = '\0';
511 /* Handle directory copy by forking off 'backup' ! */
512 if (jflag || mflag || oflag || rflag || sflag || tflag || vflag || zflag)
513 strcpy(fbuf, "-");
514 if (jflag) strcat(fbuf, "j");
515 if (mflag) strcat(fbuf, "m");
516 if (oflag) strcat(fbuf, "o");
517 if (rflag) strcat(fbuf, "r");
518 if (sflag) strcat(fbuf, "s");
519 if (tflag) strcat(fbuf, "t");
520 if (vflag) strcat(fbuf, "v");
521 if (zflag) strcat(fbuf, "z");
522 snprintf(d1buf, sizeof(d1buf), "%s/%s", dir1, namep);
523 snprintf(d2buf, sizeof(d2buf), "%s/%s", dir2, namep);
525 if ((pid = fork()) < 0) error(FATAL, "cannot fork", "", "");
526 if (pid > 0) {
527 /* Parent waits for child, then returns. */
528 wait(&status);
529 return;
532 if (fbuf[0] == '-') {
533 execle(pname, pname, fbuf, d1buf, d2buf, (char *) 0, environ);
534 execle("/bin/backup", "backup", fbuf, d1buf, d2buf, (char *)0,environ);
535 execle("/usr/bin/backup","backup",fbuf,d1buf,d2buf,(char *)0,environ);
536 error(FATAL, "cannot recursively exec backup", "", "");
537 } else {
538 execle(pname, pname, d1buf, d2buf, (char *) 0, environ);
539 execle("/bin/backup", "backup", d1buf, d2buf, (char *)0,environ);
540 execle("/usr/bin/backup","backup", d1buf, d2buf, (char *)0,environ);
541 error(FATAL, "cannot recursively exec backup", "", "");
545 void newdisk(dir)
546 char *dir;
548 /* Ask for a new diskette. A big problem is that this program does not
549 * know which device is being used and where it is mounted on. As an
550 * emergency solution, fork off a shell and ask the user to do the work.
553 int pid, status;
555 printf("\nDiskette full. Please do the following:\n");
556 printf(" 1. Unmount the diskette using /etc/umount\n");
557 printf(" 2. Physically replace the diskette by the next one.\n");
558 printf(" 3. Mount the new diskette using /etc/mount\n");
559 printf(" 4. Type CTRL-D to return to the backup/restore program\n");
561 if ((pid = fork()) < 0) error(FATAL, "cannot fork", "", "");
562 if (pid > 0) {
563 wait(&status);
564 maketarget(dir); /* make the directory */
565 } else {
566 execle("/bin/sh", "sh", "-i", (char *) 0, environ);
567 execle("/usr/bin/sh", "sh", "-i", (char *) 0, environ);
568 error(FATAL, "cannot execute shell to ask for new diskette", "", "");
572 void usage()
574 fprintf(stderr, "Usage: %s [-djmnorstvz] dir1 dir2\n", pname);
575 exit(2);
579 void error(type, s1, s2, s3)
580 int type;
581 char *s1, *s2, *s3;
583 fprintf(stderr, "%s: %s%s%s\n", pname, s1, s2, s3);
585 if (type == NONFATAL)
586 return;
587 else
588 exit(type);