Debian Codegraph @

recover.c

raw
1 /**************************************************************************
2 * This program is Copyright (C) 1986-2002 by Jonathan Payne. JOVE is *
3 * provided by Jonathan and Jovehacks without charge and without *
4 * warranty. You may copy, modify, and/or distribute JOVE, provided that *
5 * this notice is included in all the source files and documentation. *
6 **************************************************************************/
7
8 /* Recovers JOVE files after a system/editor crash.
9 * Usage: recover [-d directory] [-syscrash] [-uid UID][-v] [-D]
10 * The -syscrash option is specified in /etc/rc. It directs recover to
11 * move all the jove tmp files from tmp_dir (/tmp) to RECDIR (/usr/preserve).
12 * recover -syscrash must be invoked in /etc/rc BEFORE /tmp gets cleared out.
13 * (about the same place as expreserve gets invoked to save ed/vi/ex files.
14 *
15 * The -d option lets you specify the directory to search for tmp files when
16 * the default isn't the right one.
17 *
18 * The -uid option lets you specify the user id if you wish to recover
19 * files for another user (presumably as root, since otherwise you should
20 * not be able to read the recovery/tmp files)
21 *
22 * The -v option turns on some verbose chatter to the screen, and -D
23 * turns on even more verbose debugging to a file.
24 *
25 * Change JRECDIR and JTMPDIR in Makefile to change the default directories.
26 */
27
28 #include "jove.h"
29
30 #define SMALLSTRSIZE 30 /* used for small buffers */
31 #define MAXRECDIRSIZE 64 /* enough for RECDIR */
32 #define MAXFILENAMESIZE 16 /* /jvNNNNNN and trailing NUL */
33 #define PATHBUFSIZE (MAXRECDIRSIZE+MAXFILENAMESIZE)
34
35 #define BUFCHUNK 100 /* number of recs to allocate at once */
36
37 #ifndef RECOVER
38
39 int
40 main(argc, argv)
41 int argc;
42 char *argv[];
43 {
44 printf("%s: recovery not implemented in this JOVE configuration.\n",
45 argv[0]);
46 return 1;
47 }
48
49 #else /* RECOVER */ /* the body is the rest of this file */
50
51 #include "rec.h"
52 #include "paths.h"
53 #include "recover.h"
54
55 #ifndef UNIX
56 # define signal(x, y) -1
57 # define kill(x, y) -1
58 # ifdef WIN32
59 # define uid_t int
60 # endif
61 #else /*UNIX */
62 # include <signal.h>
63 # include <pwd.h>
64 # include <time.h>
65
66 # ifdef USE_UNAME
67 # include <sys/utsname.h>
68 # endif
69
70 #endif /* UNIX */
71
72 #ifndef L_SET
73 # define L_SET 0
74 # define L_INCR 1
75 #endif
76
77 private const char *progname;
78 private char blk_buf[JBUFSIZ];
79 private long nleft;
80 private long nshort;
81 private FILE *ptrs_fp;
82 private int data_fd = -1;
83 private struct rec_head Header;
84 private long Nchars,
85 Nlines;
86 private char tty[] = "/dev/tty";
87 private const char *tmp_dir = TMPDIR;
88 private uid_t UserID;
89 private jbool Verbose = NO;
90 private jbool Debug = NO;
91 private FILE *dfp;
92 private const char *RecDir = RECDIR;
93
94 private struct file_pair {
95 char *file_data,
96 *file_rec;
97 #define INSPECTED 01
98 int file_flags;
99 struct file_pair *file_next;
100 } *First = NULL;
101
102 private long maxbufs;
103 private struct rec_entry **buflist; /* system initializes to 0 */
104
105 #ifndef F_COMPLETION
106 # define F_COMPLETION /* since scandir.c is surrounded by an ifdef */
107 #endif
108
109 /* non-reentrant version of one in util.c since we do not have sprint */
110 #ifdef NO_STRERROR
111 extern int sys_nerr;
112 extern char *sys_errlist[];
113
114 /*
115 * Unix version of strerror - map error number to descriptive string.
116 * ANSI systems have this.
117 */
118 char *
119 strerror(errnum)
120 int errnum;
121 {
122 static char ebuf[SMALLSTRSIZE]; /* large enough for Error number NNNNN */
123 if (0 < errnum && errnum < sys_nerr) return sys_errlist[errnum];
124 (void) sprintf(ebuf, "Error number %d", (errnum % 10000)); /* errno is never larger, but avoid string overflow -- rarely reaches here */
125 return ebuf;
126 }
127 #endif /* NO_STRERROR */
128
129 /* simpler version of one in util.c, needed by scandir.c */
130 void *
131 emalloc(size_t size)
132 {
133 void *ptr;
134
135 if ((ptr = malloc(size)) == NULL) {
136 fprintf(stderr, "couldn't malloc(%ld)\n", (long)size);
137 exit(1);
138 }
139 return ptr;
140 }
141
142 /* simpler version of one in util.c, needed by scandir.c */
143 void *
144 erealloc(void *ptr, size_t size)
145 {
146 if (ptr == NULL)
147 return emalloc(size); /* some realloc do not like ptr == NULL */
148 if ((ptr = realloc(ptr, size)) == NULL) {
149 fprintf(stderr, "couldn't realloc(%ld)\n", (long)size);
150 exit(1);
151 }
152 return ptr;
153 }
154
155 /* copy a string into buffer; truncate silently if too large; NUL-pad.
156 * Note: buffer must be 1 larger than n to fit NUL!
157 * Duplicated from util.c: needed by scandir.c
158 */
159 void
160 null_ncpy(char *to, const char *from, size_t n)
161 {
162 (void) strncpy(to, from, n);
163 to[n] = '\0';
164 }
165
166 /* duplicate s, and if t is not-NULL, concatenate space and t */
167 char *
168 copystrs(const char *s, const char *t)
169 {
170 char *str, *sp;
171 size_t ns = strlen(s) + 1, nt = 0;
172
173 if (t)
174 nt = strlen(t) + 1;
175
176 sp = str = emalloc(ns + nt);
177 memcpy(sp, s, ns);
178 if (t) {
179 sp += ns;
180 sp[-1] = ' ';
181 memcpy(sp, t, nt);
182 }
183 return str;
184 }
185
186 /* needed by scandir.c */
187 #define copystr(s) copystrs(s, NULL)
188
189 #include "scandir.c" /* to get dirent simulation and jscandir */
190
191 /* Get a line at `tl' in the tmp file into `buf' which should be LBSIZE
192 * long.
193 */
194
195 private char *getblock(daddr atl);
196
197 void
198 jgetline(daddr tl, char *buf)
199 {
200 char *bp = getblock(tl),
201 *lp = buf;
202 long nl = nleft;
203
204 while ((*lp++ = *bp++) != '\0') {
205 if (--nl == 0) {
206 /* oops: line didn't end within block: fake it */
207 if (Verbose)
208 fprintf(dfp, "warning: truncated line %lu\n", (unsigned long)tl);
209 *lp++ = '\0';
210 break;
211 }
212 }
213 }
214
215 private jmp_buf int_env;
216
217 private char *
218 getblock(daddr atl)
219 {
220 daddr bno,
221 off;
222 static daddr curblock = MAX_BLOCKS;
223
224 bno = da_to_bno(atl);
225 off = da_to_off(atl);
226 nleft = JBUFSIZ - off;
227 if (Debug)
228 fprintf(dfp, "getblock atl %ld bno %ld off %ld nleft %ld\n",
229 (long)atl, (long)bno, (long)off, (long)nleft);
230
231 if (bno != curblock) {
232 JSSIZE_T nb;
233 const char *what;
234 off_t r,
235 boff = bno_to_seek_off(bno);
236
237 if (Debug)
238 fprintf(dfp, "lseek %d to bno %lu 0x%lx boff %ld 0x%lx\n", data_fd, (unsigned long)bno, (unsigned long) bno, (long)boff, (long)boff);
239 what = "lseek";
240 r = lseek(data_fd, boff, L_SET);
241 if (r >= 0) {
242 what = "read";
243 nb = read(data_fd, blk_buf, (size_t)JBUFSIZ);
244 if (nb >= 0 && nb != JBUFSIZ) {
245 if (nshort == 0)
246 fprintf(stderr, "short read from JOVE tempfile %ld\n", (long)nb);
247 nshort++;
248 bno = MAX_BLOCKS;
249 if (nb > off) {
250 nleft = nb - off;
251 } else {
252 blk_buf[off] = '\0';
253 nleft = 1;
254 }
255 } else if (nb < 0) {
256 r = -1;
257 }
258 }
259 if (r < 0) {
260 fprintf(stderr, "%s of JOVE tempfile failed bno %ld: %s\n", what, (long)bno, strerror(errno));
261 longjmp(int_env, 1);
262 /* NOTREACHED */
263 }
264 curblock = bno;
265 }
266 return blk_buf + off;
267 }
268
269 private const char *CurDir;
270
271 /* Scan the DIRNAME directory for jove tmp files, and make a linked list
272 * out of them.
273 */
274
275 private jbool add_name(const char *);
276
277 private void
278 free_files(void) {
279 while (First != NULL) {
280 struct file_pair *p = First;
281
282 First = p->file_next;
283 free(p->file_data);
284 free(p->file_rec);
285 free(p);
286 }
287 }
288
289 private void
290 get_files(const char *dirname)
291 {
292 char **nmptr;
293 int nentries;
294
295 /* first, free any previous entries */
296 free_files();
297
298 CurDir = dirname;
299 nentries = jscandir(dirname, &nmptr, add_name,
300 (int (*)(const void *, const void *))NULL);
301 if (nentries != -1)
302 freedir(&nmptr, nentries);
303 }
304
305 private jbool
306 add_name(const char *fname)
307 {
308 char dfile[FILESIZE*2+2], /* CurDir/filename */
309 rfile[FILESIZE*2+2];
310 struct file_pair *fp;
311 struct rec_head header;
312 int fd;
313 /* jrecstr must match the start of the string in recinit */
314 #ifdef MAC
315 static const char jrecstr[] = ".jrec";
316 #else
317 static const char jrecstr[] = "jr";
318 #endif
319 struct stat stbuf;
320
321 if (strncmp(fname, jrecstr, sizeof(jrecstr)-1) != 0) {
322 if (Debug)
323 fprintf(dfp, "skipping %s\n", fname);
324 return NO;
325 }
326
327 /* If we get here, we found a "recover" tmp file, so now
328 * we look for the corresponding "data" tmp file. First,
329 * though, we check to see whether there is anything in
330 * the "recover" file. If it's 0 length, there's no point
331 * in saving its name.
332 */
333 (void) sprintf(rfile, "%s/%s", CurDir, fname);
334 if (stat(rfile, &stbuf) != 0 || (stbuf.st_mode & S_IFMT) != S_IFREG) {
335 if (Verbose)
336 fprintf(dfp, "skipping non-regular file %s\n", rfile);
337 return NO;
338 }
339 if (Debug)
340 fprintf(dfp, "checking %s\n", rfile);
341 if ((fd = open(rfile, O_RDONLY | O_BINARY | O_CLOEXEC)) != -1) {
342 if (read(fd, &header, sizeof header) != sizeof header) {
343 close(fd);
344 fprintf(stderr, "%s: could not read complete header from %s, skipping\n",
345 progname, rfile);
346 return NO;
347 }
348 if (header.RecMagic != RECMAGIC) {
349 close(fd);
350 fprintf(stderr, "%s: skipping incompatible %s magic 0x%lx != our 0x%lx\n",
351 progname, rfile, header.RecMagic, (unsigned long)RECMAGIC);
352 return NO;
353 }
354 close(fd);
355 }
356 (void) sprintf(dfile, "%s/%s", CurDir, header.TmpFileName);
357 if (access(dfile, F_OK) != 0) {
358 fprintf(stderr, "%s: can't find the data file `%s' for %s\n",
359 progname, header.TmpFileName, rfile);
360 #ifdef NEVER
361 /*
362 * MM: I don't think it's a good idea to delete the files
363 * because access() failed. We should probably ask the user
364 * if it is ok to delete the file!
365 */
366 fprintf(stderr, "so deleting...\n");
367 (void) unlink(rfile);
368 #endif
369 return NO;
370 }
371 /* If we get here, we've found both files, so we put them
372 * in the list.
373 */
374 fp = (struct file_pair *) emalloc(sizeof *fp);
375 fp->file_data = copystr(dfile);
376 fp->file_rec = copystr(rfile);
377 fp->file_flags = 0;
378 fp->file_next = First;
379 First = fp;
380
381 return YES;
382 }
383
384 private void
385 options(void)
386 {
387 printf("Options are:\n");
388 printf(" ? list options.\n");
389 printf(" get get a buffer to a file.\n");
390 printf(" list list known buffers.\n");
391 printf(" print print a buffer to terminal.\n");
392 printf(" quit quit and delete jove tmp files.\n");
393 printf(" restore restore all buffers.\n");
394 }
395
396 /* Returns a legitimate buffer # */
397
398 private void tellme(const char *, char *, size_t),
399 list(void);
400
401 private long
402 getsrc(void)
403 {
404 char name[FILESIZE];
405 long number;
406
407 for (;;) {
408 tellme("Which buffer ('?' for list)? ", name, sizeof(name));
409 if (name[0] == '?')
410 list();
411 else if (name[0] == '\0')
412 return -1;
413 else if ((number = atoi(name)) > 0 && number <= Header.Nbuffers)
414 return number;
415 else {
416 long i;
417
418 for (i = 1; i <= Header.Nbuffers; i++)
419 if (strcmp(buflist[i]->r_bname, name) == 0)
420 return i;
421 printf("%s: unknown buffer.\n", name);
422 }
423 }
424 }
425
426 /* Get a destination file name. */
427
428 private char *
429 getdest(void)
430 {
431 static char filebuf[FILESIZE];
432
433 tellme("Output file: ", filebuf, sizeof(filebuf));
434 if (filebuf[0] == '\0')
435 return NULL;
436 return filebuf;
437 }
438
439 #include "jctype.h"
440
441 private char *
442 readword(char *buf, size_t buflen)
443 {
444 int c;
445 char *bp = buf,
446 *ep = buf + buflen - 1;
447
448 do {} while (strchr(" \t\n", c = getchar()) != NULL);
449
450 for (;;) {
451 if (c == EOF)
452 exit(0);
453 if (strchr(" \t\n", c) != NULL)
454 break;
455
456 if (bp == ep) {
457 *bp = '\0';
458 fprintf(stderr, "%lu byte buffer too small for word `%s'",
459 (unsigned long) buflen, buf);
460 exit(0);
461 }
462 *bp++ = c;
463 c = getchar();
464 }
465 *bp = '\0';
466
467 return buf;
468 }
469
470 private void
471 tellme(const char *quest, char *answer, size_t anslen)
472 {
473 printf("%s", quest);
474 fflush(stdout);
475 readword(answer, anslen);
476 }
477
478 #ifdef UNIX
479 private SIGRESTYPE
480 catch(int UNUSED(junk))
481 {
482 longjmp(int_env, 1);
483 /*NOTREACHED*/
484 }
485 #endif /* UNIX */
486
487 private void get(long src, char *dest);
488
489 private void
490 restore(void)
491 {
492 long i;
493 char tofile[FILESIZE+1], /* leading # */
494 answer[SMALLSTRSIZE];
495 int nrecovered = 0;
496
497 for (i = 1; i <= Header.Nbuffers; i++) {
498 (void) sprintf(tofile, "#%s", buflist[i]->r_bname);
499 tryagain:
500 printf("Restoring %s to %s, okay?", buflist[i]->r_bname,
501 tofile);
502 tellme(" ", answer, sizeof(answer));
503 switch (answer[0]) {
504 case 'y':
505 break;
506
507 case 'n':
508 continue;
509
510 default:
511 tellme("What file should I use instead? ", tofile,
512 sizeof(tofile));
513 goto tryagain;
514 }
515 if (Debug)
516 fprintf(dfp, "getting %ld %s to %s\n", i,
517 buflist[i]->r_bname, tofile);
518 get(i, tofile);
519 nrecovered += 1;
520 }
521 printf("Recovered %d buffers.\n", nrecovered);
522 }
523
524 private void dump_file(long which, FILE *out);
525
526 private void
527 get(long src, char *dest)
528 {
529 FILE *volatile outfile; /* "volatile" to preserve outfile across setjmp */
530
531 if (src < 0 || src > Header.Nbuffers || src >= maxbufs || dest == NULL) {
532 const char *pdest = dest ? dest : "(NULL)";
533 fprintf(stderr, "internal error: get: src %ld nbuf %ld maxbuf %ld dest %s\n",
534 src, Header.Nbuffers, maxbufs, pdest);
535 return;
536 }
537
538 if (dest == tty) {
539 outfile = stdout;
540 } else {
541 if ((outfile = fopen(dest, "wb")) == NULL) {
542 fprintf(stderr, "%s: cannot create %s: %s\n", progname, dest, strerror(errno));
543 (void) signal(SIGINT, SIG_DFL);
544 return;
545 }
546 printf("\"%s\"", dest);
547 }
548 if (setjmp(int_env) == 0) {
549 (void) signal(SIGINT, catch);
550 dump_file(src, outfile);
551 } else {
552 printf("\nAborted!\n");
553 }
554 (void) signal(SIGINT, SIG_DFL);
555 if (dest != tty) {
556 if (fflush(outfile) == EOF || ferror(outfile) ||
557 #ifdef USE_FSYNC
558 fsync(fileno(outfile)) < 0 ||
559 #endif
560 fclose(outfile) == EOF) {
561 fprintf(stderr, "Error flushing/closing %s: %s\n", dest, strerror(errno));
562 }
563 printf(" %ld lines, %ld characters.\n", Nlines, Nchars);
564 }
565 fflush(stdout);
566 if (nshort) {
567 fprintf(stderr, "%ld missing lines (short reads of data file)\n", nshort);
568 nshort = 0;
569 }
570 }
571
572 private jbool
573 isopt(char **args, char *str, jbool needval)
574 {
575 char *cp = *args;
576 if (Debug)
577 fprintf(dfp, "isopt \"%s\" \"%s\" %d\n", *args, str, needval);
578 if (*cp++ != '-') return NO;
579 if (*cp == '-') cp++; /* accept either single or double dash */
580 if (strcmp(cp, str) == 0) {
581 if (Debug)
582 fprintf(dfp, "found option \"%s\" needval %d args[1] \"%s\"\n",
583 str, needval,
584 args[1] ? args[1] : "!NULL!");
585 /* XXX for error checking, we sacrifice ability to provide option values
586 starting with - since those are very unlikely */
587 if (needval && (args[1] == NULL || args[1][0] == '-')) {
588 fprintf(stderr, "need value after option %s\n", str);
589 exit(1);
590 }
591 return YES;
592 }
593 return NO;
594 }
595
596
597 private void
598 read_rec(struct rec_entry *recptr)
599 {
600 if (fread(recptr, sizeof *recptr, (size_t)1, ptrs_fp) != 1)
601 fprintf(stderr, "%s: cannot read record. %s\n", progname, strerror(errno));
602 }
603
604 private void
605 seekto(long which)
606 {
607 long offset,
608 i;
609
610 offset = sizeof (Header) + (Header.Nbuffers * sizeof (struct rec_entry));
611 for (i = 1; i < which; i++)
612 offset += buflist[i]->r_nlines * sizeof (daddr);
613 fseek(ptrs_fp, offset, L_SET);
614 }
615
616 private void
617 freeblist(void)
618 {
619 long i;
620 for (i = 0; i < maxbufs; i++) {
621 if (buflist[i]) {
622 free(buflist[i]);
623 buflist[i] = NULL;
624 }
625 }
626 free(buflist);
627 buflist = NULL;
628 maxbufs = 0;
629 }
630
631 private void
632 makblist(void)
633 {
634 long i, nmax;
635
636 fseek(ptrs_fp, (long) sizeof (Header), L_SET);
637 /* resize buflist up to multiple of BUFCHUNK */
638 nmax = ( (Header.Nbuffers+1)/BUFCHUNK + 1 ) * BUFCHUNK;
639 if (Debug)
640 fprintf(dfp, "maxbufs %ld nmax %ld\n", maxbufs, nmax);
641 if (maxbufs < nmax) {
642 buflist = (struct rec_entry **) erealloc(buflist, nmax*sizeof(struct rec_entry *));
643 for (i = maxbufs; i < nmax; i++)
644 buflist[i] = NULL;
645 maxbufs = nmax;
646 }
647 for (i = 1; i <= Header.Nbuffers; i++) {
648 if (Debug) {
649 /* XXX may end up truncating addr if unsigned long smaller than DADDR */
650 printf("i %ld 0x%lx\n",i, (unsigned long)((DADDR)buflist[i]));
651 }
652 if (buflist[i] == NULL)
653 buflist[i] = (struct rec_entry *) emalloc (sizeof (struct rec_entry));
654 read_rec(buflist[i]);
655 }
656 /*
657 * just for safety, unset any remaining buflist
658 * entries. since we should always be using
659 * Header.Nbuffers as a limit, we should never touch these.
660 */
661 while (i < maxbufs) {
662 if (buflist[i]) {
663 buflist[i]->r_bname[0] = buflist[i]->r_fname[0] = '\0';
664 buflist[i]->r_nlines = buflist[i]->r_dotline =
665 buflist[i]->r_dotchar = 0;
666 }
667 i++;
668 }
669 }
670
671 private daddr
672 getaddr(FILE *fp)
673 {
674 int nchars = sizeof (daddr);
675 daddr addr;
676 char *cp = (char *) &addr;
677
678 while (--nchars >= 0)
679 *cp++ = getc(fp);
680
681 return addr & ~DDIRTY;
682 }
683
684 private void
685 dump_file(long which, FILE *out)
686 {
687 long nlines; /* XXX lnum_t */
688 daddr addr;
689 char buf[JBUFSIZ];
690
691 seekto(which);
692 nlines = buflist[which]->r_nlines;
693 Nchars = Nlines = 0L;
694 while (--nlines >= 0) {
695 addr = getaddr(ptrs_fp);
696 if (Debug) {
697 /* XXX may end up truncating addr if unsigned long smaller than DADDR */
698 fprintf(dfp, "line %ld addr %lu\n", nlines, (unsigned long)((DADDR)addr));
699 }
700 jgetline(addr, buf);
701 Nlines += 1;
702 Nchars += 1 + strlen(buf);
703 fputs(buf, out);
704 if (nlines > 0) {
705 #ifdef USE_CRLF
706 fputc('\r', out);
707 #endif
708 fputc(EOL, out);
709 }
710 }
711 }
712
713 /* List all the buffers. */
714
715 private void
716 list(void)
717 {
718 long i;
719
720 for (i = 1; i <= Header.Nbuffers; i++)
721 printf("%ld) buffer %s \"%s\" (%ld lines)\n", i,
722 buflist[i]->r_bname,
723 buflist[i]->r_fname,
724 buflist[i]->r_nlines);
725 }
726
727 private void ask_del(const char *prompt, struct file_pair *fp);
728
729 private int
730 doit(struct file_pair *fp)
731 {
732 char answer[SMALLSTRSIZE];
733 char *datafile = fp->file_data,
734 *pntrfile = fp->file_rec;
735 time_t tupd;
736
737 ptrs_fp = fopen(pntrfile, "rb");
738 if (ptrs_fp == NULL) {
739 fprintf(stderr, "%s: cannot read rec file (%s).\n", progname, pntrfile);
740 return 0;
741 }
742 if (Debug)
743 fprintf(dfp, "opened %s\n", pntrfile);
744 if (fread(&Header, sizeof Header, (size_t)1, ptrs_fp) != 1) {
745 fprintf(stderr, "%s: cannot read header from rec file (%s).\n", progname, pntrfile);
746 return 0;
747 }
748 if (Debug)
749 fprintf(dfp, "read header from %s, uid %ld, pid %ld, %ld bufs, %s\n",
750 pntrfile, Header.Uid, Header.Pid, Header.Nbuffers, Header.TmpFileName);
751
752 if (Header.Uid != (long)UserID) {
753 if (Debug)
754 fprintf(dfp, "different user %ld != %ld\n",
755 (long)Header.Uid, (long)UserID);
756 return 0;
757 }
758
759 /* Ask about JOVE's that are still running ... */
760 if (kill((pid_t)Header.Pid, 0) == 0) {
761 if (Debug)
762 fprintf(dfp, "still running pid %ld\n", Header.Pid);
763 return 0;
764 }
765
766 if (Header.Nbuffers == 0) {
767 printf("There are no modified buffers in %s; should I delete the tmp file?", pntrfile);
768 ask_del(" ", fp);
769 return 1;
770 }
771
772 if (Header.Nbuffers < 0) {
773 fprintf(stderr, "%s: %s doesn't look like a jove recovery file.\n", progname, pntrfile);
774 ask_del("Should I delete it? ", fp);
775 return 1; /* We'll, we sort of found something. */
776 }
777 tupd = (time_t)Header.UpdTime;
778 printf("Found %ld buffer%s last updated: %s",
779 Header.Nbuffers, Header.Nbuffers != 1 ? "s" : "", ctime(&tupd));
780 data_fd = open(datafile, O_RDONLY | O_BINARY | O_CLOEXEC);
781 if (data_fd == -1) {
782 fprintf(stderr, "%s: but I can't read the data file (%s).\n", progname, datafile);
783 ask_del("Should I delete the tmp files? ", fp);
784 return 1;
785 }
786 if (Debug)
787 fprintf(dfp, "opened fd %d data file %s\n", data_fd, datafile);
788 makblist();
789 list();
790
791 for (;;) {
792 long src;
793
794 tellme("(Type '?' for options): ", answer, sizeof(answer));
795 switch (answer[0]) {
796 case '\0':
797 continue;
798
799 case '?':
800 options();
801 break;
802
803 case 'l':
804 list();
805 break;
806
807 case 'p':
808 if ((src = getsrc()) < 0)
809 break;
810 if (Debug)
811 fprintf(dfp, "getting %ld %s to %s\n",
812 src, buflist[src]->r_bname, tty);
813 get(src, tty);
814 break;
815
816 case 'q':
817 ask_del("Shall I delete the tmp files? ", fp);
818 return 1;
819
820 case 'g':
821 {
822 /* So it asks for src first. */
823 char *dest;
824 if ((src = getsrc()) < 0)
825 break;
826
827 dest = getdest();
828 if (Debug)
829 fprintf(dfp, "getting %ld %s to %s\n",
830 src, buflist[src]->r_bname, dest);
831 get(src, dest);
832 break;
833 }
834
835 case 'r':
836 restore();
837 break;
838
839 default:
840 printf("I don't know how to \"%s\"!\n", answer);
841 break;
842 }
843 }
844 }
845
846 private void del_files(struct file_pair *fp);
847
848 private void
849 ask_del(const char *prompt, struct file_pair *fp)
850 {
851 char yorn[SMALLSTRSIZE];
852
853 tellme(prompt, yorn, sizeof(yorn));
854 if (yorn[0] == 'y')
855 del_files(fp);
856 }
857
858 private void
859 del_files(struct file_pair *fp)
860 {
861 (void) unlink(fp->file_data);
862 (void) unlink(fp->file_rec);
863 }
864
865
866 #ifdef UNIX
867 private const char *
868 hname(void)
869 {
870 const char *p = "unknown";
871 #ifdef USE_UNAME
872 static struct utsname mach;
873
874 if (uname(&mach) >= 0)
875 p = mach.nodename;
876 #endif
877 #ifdef USE_GETHOSTNAME
878 static char mach[BUFSIZ];
879
880 if (gethostname(mach, sizeof(mach)) >= 0)
881 p = mach;
882 #endif
883 return p;
884 }
885
886 private void
887 MailUser(struct rec_head *rec)
888 {
889 char *last_update, *mail_cmd;
890 const char *buf_string, *mail_prog;
891 FILE *mail_pipe;
892 struct passwd *pw;
893 int r;
894 time_t tupd;
895
896 if ((pw = getpwuid((uid_t)rec->Uid))== NULL)
897 return;
898
899 tupd = (time_t)(rec->UpdTime);
900 last_update = ctime(&tupd);
901 /* Start up mail */
902 if ((mail_prog = getenv("JOVEMAILER")) == NULL)
903 mail_prog = "/bin/mail";
904 mail_cmd = copystrs(mail_prog, pw->pw_name);
905 if ((r = setuid(getuid())) < 0) {
906 fprintf(stderr, "WARNING: %s: setuid(getuid()) failed: %s\n",
907 progname, strerror(errno));
908 /*
909 * used to continue without checking return value,
910 * so let that behaviour continue, I guess?
911 */
912 }
913 if ((mail_pipe = popen(mail_cmd, "w")) == NULL) {
914 fprintf(stderr, "%s: failed to popen mail command \"%s\": %s\n",
915 progname, mail_cmd, strerror(errno));
916 free(mail_cmd);
917 return;
918 }
919 /* Let's be grammatically correct! */
920 buf_string = rec->Nbuffers == 1? "buffer" : "buffers";
921 fprintf(mail_pipe, "Subject: Jove saved %ld %s after \"%s\" crashed\n",
922 rec->Nbuffers, buf_string, hname());
923 fprintf(mail_pipe, " \n");
924 fprintf(mail_pipe, "Jove saved %ld %s when the system \"%s\"\n",
925 rec->Nbuffers, buf_string, hname());
926 fprintf(mail_pipe, "crashed on %s\n\n", last_update);
927 fprintf(mail_pipe, "You can retrieve the %s using Jove's -r\n",
928 buf_string);
929 fprintf(mail_pipe, "(recover option) i.e. give the command.\n");
930 fprintf(mail_pipe, "\tjove -r\n");
931 fprintf(mail_pipe, "See the Jove manual for more details\n");
932 pclose(mail_pipe);
933 free(mail_cmd);
934 }
935
936
937 private void
938 savetmps(void)
939 {
940 struct file_pair *fp;
941 wait_status_t status;
942 pid_t pid;
943 int fd, rc;
944 struct rec_head header;
945 char buf[PATHBUFSIZE];
946 char *fname;
947 struct stat stbuf;
948
949 if (strcmp(tmp_dir, RecDir) == 0)
950 return; /* Files are moved to the same place. */
951
952 /* sanity check on RecDir */
953 if (strlen(RecDir) > MAXRECDIRSIZE) {
954 fprintf(stderr, "%s: recovery directory len is %u, must be smaller than %u\n",
955 progname, (unsigned)strlen(RecDir), MAXRECDIRSIZE);
956 exit(2);
957 }
958 sprintf(buf, "%s/jv%06u", RecDir, (unsigned)getpid()); /* dummy name */
959 stbuf.st_mode = stbuf.st_uid = 0;
960 if ((rc = stat(RecDir, &stbuf)) < 0)
961 if ((rc = mkdir(RecDir, 0755)) == 0)
962 rc = stat(RecDir, &stbuf);
963 if (rc < 0 || (stbuf.st_mode & S_IFMT) != S_IFDIR || stbuf.st_uid != getuid() /*||
964 access(buf, W_OK) != 0*/) {
965 fprintf(stderr, "%s: need writable directory \"%s\" owned by %u: got mode 0%o uid %u rc %d: %s\n",
966 progname, RecDir, getuid(), (unsigned)stbuf.st_mode,
967 (unsigned)stbuf.st_uid, rc, rc < 0 ? strerror(errno) : "");
968 exit(2);
969 }
970
971 printf("Recovering jove files ... ");
972 get_files(tmp_dir);
973 for (fp = First; fp != NULL; fp = fp->file_next) {
974 if (Debug)
975 fprintf(dfp, "Recovering: %s, %s\n", fp->file_data,
976 fp->file_rec);
977 if (stat(fp->file_data, &stbuf) < 0) {
978 fprintf(stderr, "%s: stat data %s failed, rec %s: %s\n",
979 progname, fp->file_data, fp->file_rec, strerror(errno));
980 continue;
981 }
982 switch (pid = fork()) {
983 case -1:
984 fprintf(stderr, "%s: can't fork. %s\n!", progname, strerror(errno));
985 exit(-1);
986 /*NOTREACHED*/
987
988 case 0:
989 if ((fd = open(fp->file_rec, O_RDONLY | O_BINARY | O_CLOEXEC)) != -1) {
990 if ((read(fd, &header, sizeof header) != sizeof header)) {
991 close(fd);
992 return;
993 } else
994 close(fd);
995 }
996 MailUser(&header);
997 execl("/bin/mv", "mv", fp->file_data, fp->file_rec,
998 RecDir, (char *)NULL);
999 fprintf(stderr, "%s: cannot execl /bin/mv. %s\n", progname, strerror(errno));
1000 exit(-1);
1001 /*NOTREACHED*/
1002
1003 default:
1004 do {} while (wait(&status) != pid);
1005 if (WIFSIGNALED(status))
1006 fprintf(stderr, "%s: copy terminated by signal %d\n.\n", progname, WTERMSIG(status));
1007 if (WIFEXITED(status))
1008 fprintf(stderr, "%s: copy exited with %d.\n", progname, WEXITSTATUS(status));
1009 fname = fp->file_data + strlen(tmp_dir);
1010 if (strlen(fname)+1 > MAXFILENAMESIZE) {
1011 fprintf(stderr, "%s: filename \"%s\" len %u, must be smaller than %u\n",
1012 progname, fname, (unsigned)strlen(fname), MAXFILENAMESIZE-1);
1013 exit(2);
1014 }
1015 strcpy(buf, RecDir);
1016 strcat(buf, fname);
1017 if (chown(buf, stbuf.st_uid, stbuf.st_gid) != 0) {
1018 fprintf(stderr, "%s: chown data %s to %u.%u failed: %s",
1019 progname, buf, (unsigned)stbuf.st_uid, (unsigned)stbuf.st_gid,
1020 strerror(errno));
1021 }
1022 fname = fp->file_rec + strlen(tmp_dir);
1023 if (strlen(fname)+1 > MAXFILENAMESIZE) {
1024 fprintf(stderr, "%s: filename \"%s\" len %u, must be smaller than %u\n",
1025 progname, fname, (unsigned)strlen(fname), MAXFILENAMESIZE-1);
1026 exit(2);
1027 }
1028 strcpy(buf, RecDir);
1029 strcat(buf, fname);
1030 if (chown(buf, stbuf.st_uid, stbuf.st_gid) != 0) {
1031 fprintf(stderr, "%s: chown rec %s to %u.%u failed: %s",
1032 progname, buf, (unsigned)stbuf.st_uid, (unsigned)stbuf.st_gid,
1033 strerror(errno));
1034 }
1035 fputc('.', stdout);
1036 }
1037 }
1038 free_files();
1039 printf("Done.\n");
1040 }
1041 #endif /* UNIX */
1042
1043 private int
1044 lookup(const char *dir)
1045 {
1046 struct file_pair *fp;
1047 int nfound = 0;
1048
1049 printf("Checking %s ...\n", dir);
1050 get_files(dir);
1051 for (fp = First; fp != NULL; fp = fp->file_next) {
1052 nfound += doit(fp);
1053 if (ptrs_fp) {
1054 (void) fclose(ptrs_fp);
1055 ptrs_fp = NULL;
1056 }
1057 if (data_fd > 0) {
1058 (void) close(data_fd);
1059 data_fd = -1;
1060 }
1061 }
1062 free_files();
1063 return nfound;
1064 }
1065
1066 int
1067 main(int UNUSED(argc), char *argv[])
1068 {
1069 int nfound;
1070 char **argvp;
1071
1072 progname = argv[0];
1073 UserID = getuid();
1074 setbuf(stdout, NULL);
1075 dfp = stdout;
1076
1077 /* override tmp_dir with $TMPDIR, RecDir with $JOVERECDIR if any */
1078 {
1079 char *cp = getenv("TMPDIR");
1080
1081 if (cp != NULL)
1082 tmp_dir = cp;
1083 cp = getenv("JOVERECDIR");
1084 if (cp != NULL)
1085 RecDir = cp;
1086 }
1087 for (argvp = argv + 1; *argvp; argvp++) {
1088 if (isopt(argvp, "v", NO)) {
1089 Verbose = YES;
1090 continue;
1091 }
1092 if (isopt(argvp, "D", YES)) {
1093 time_t t;
1094 Debug = YES;
1095 dfp = fopen(*++argvp, "wc");
1096 (void) time(&t);
1097 fprintf(dfp, "debugfile \"%s\" %s", *argvp, ctime(&t));
1098 continue;
1099 }
1100 if (isopt(argvp, "d", YES)) {
1101 tmp_dir = *++argvp;
1102 continue;
1103 }
1104 if (isopt(argvp, "r", YES)) {
1105 RecDir = *++argvp;
1106 continue;
1107 }
1108 if (isopt(argvp, "uid", YES)) {
1109 UserID = atoi(*++argvp);
1110 continue;
1111 }
1112 #ifdef UNIX
1113 if (isopt(argvp, "syscrash", NO)) {
1114 savetmps();
1115 exit(0);
1116 }
1117 #endif
1118 fprintf(stderr, "Usage: %s [-v] [-d TMPDIR] [-D DEBUGFILE] [-r RecDir] [-uid UID] [-syscrash]\n\n", progname);
1119 fprintf(stderr, "Use \"jove -r\" to interactively recover saved state\n");
1120 fprintf(stderr, "\tafter JOVE has died for some unknown reason.\n\n");
1121 fprintf(stderr, "Use \"%s/recover -syscrash\"\n", LIBDIR);
1122 fprintf(stderr, "\tin reboot scripts to copy JOVE saved state to\n");
1123 fprintf(stderr, "\t%s before temporary files in %s are cleared.\n\n", RecDir, tmp_dir);
1124 fprintf(stderr, "Use \"recover -d TMPDIR\"\n");
1125 fprintf(stderr, "\twhen the tmp files are stored in directory TMPDIR\n");
1126 fprintf(stderr, "\tinstead of in the default one (%s).\n\n", tmp_dir);
1127 exit(1);
1128 }
1129 /* Check default directory */
1130 nfound = lookup(tmp_dir);
1131 /* Check whether anything was saved when system died? */
1132 if (strcmp(tmp_dir, RecDir) != 0)
1133 nfound += lookup(RecDir);
1134 if (nfound == 0)
1135 printf("There's nothing to recover.\n");
1136 freeblist();
1137 return 0;
1138 }
1139
1140 #endif /* RECOVER */