Debian Codegraph @

io.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 #include "jove.h"
9 #include "list.h"
10 #include "fp.h"
11 #include "jctype.h"
12 #include "disp.h"
13 #include "ask.h"
14 #include "fmt.h"
15 #include "insert.h"
16 #include "marks.h"
17 #include "proc.h"
18 #include "wind.h" /* only used by JReadFile for fixup */
19 #include "rec.h"
20
21 #ifdef MAC
22 # include "mac.h"
23 #else
24 # include <sys/stat.h>
25 #endif
26
27 #ifdef MSFILESYSTEM
28 # include <direct.h>
29 # include <dos.h>
30 # ifndef _MAX_DIR
31 # define _MAX_DIR FILESIZE
32 # endif
33 # ifndef _MAX_FNAME
34 # define _MAX_FNAME 9
35 # endif
36 # ifndef _MAX_EXT
37 # define _MAX_EXT 4
38 # endif
39 #endif /* MSFILESYSTEM */
40
41 private void
42 filemunge(char *newname),
43 chk_divergence(Buffer *thisbuf, const char *fname, const char *how);
44
45 private struct block *lookup_block(daddr);
46
47 private char *getblock(daddr, jbool);
48
49 private jbool f_getputl(LinePtr line, File *fp);
50
51 #ifdef BACKUPFILES
52 private void
53 file_backup(char *fname);
54 #endif
55
56 long io_chars; /* number of chars in this open_file */
57 long io_lines; /* number of lines in this open_file */
58
59 #ifdef BACKUPFILES
60 jbool BkupOnWrite = NO; /* VAR: make backup files when writing */
61 #endif
62
63 #ifndef MSFILESYSTEM
64
65 #define Dchdir(to) chdir(to)
66
67 #else /* MSFILESYSTEM */
68
69 # ifdef WIN32
70 # define _dos_getdrive(dd) (*(dd)=_getdrive())
71 # define _dos_setdrive(d, n) ((*(n)=_getdrive()), _chdrive((d)))
72 # endif
73
74 # ifdef ZTCDOS
75
76 # define _dos_getdrive(dd) dos_getdrive(dd)
77 # define _dos_setdrive(d, n) dos_setdrive((d), (n))
78
79 private void
80 _splitpath(const char *path, char *drv, char *dir, char *fn, char *ext)
81 {
82 const char *p;
83 size_t l;
84
85 if (path[0]!='\0' && path[1]==':') {
86 *drv++ = *path++;
87 *drv++ = *path++;
88 }
89 *drv = '\0';
90
91 p = strrchr(path, '/');
92 if (p != NULL) {
93 /* ??? should we have / at the end of the directory? */
94 p++;
95 memcpy(dir, path, (size_t) (p-path));
96 dir += p-path;
97 path = p;
98 }
99 *dir = '\0';
100
101 p = strchr(path, '.');
102 if (p == NULL)
103 p = path+strlen(path);
104 l = p-path;
105 if (l > 8)
106 l = 8;
107 null_ncpy(fn, path, l);
108
109 l = strlen(p);
110 if (l > 4)
111 l = 4;
112 null_ncpy(ext, p, l);
113 }
114
115 private void
116 _makepath(char *path, const char *drv, const char *dir, const char *fn, const char *ext)
117 {
118 if (drv[0] != '\0') {
119 *path++ = drv[0];
120 *path++ = ':';
121 *path = '\0';
122 }
123 if (dir[0] != '\0') {
124 strcpy(path, dir);
125 path += strlen(path);
126 if (path[-1] != '/' && path[-1] != '\\') {
127 *path++ = '/';
128 *path = '\0';
129 }
130 }
131 strcpy(path, fn);
132 path += strlen(path);
133 switch (ext[0]) {
134 case '\0':
135 break;
136 default:
137 *path++ = '.';
138 /*FALLTHROUGH*/
139 case '.':
140 strcpy(path, ext);
141 break;
142 }
143 }
144 # endif /* ZTCDOS */
145
146 /* Change drive and directory
147 * This is not quite like a UNIX chdir because each drive has a
148 * separate current directory. If the path is not absolute, it
149 * will be relative to the current directory of the drive.
150 * On the other hand, this is not the DOS chdir because it does
151 * change the current drive if one is specified.
152 */
153 private int
154 Dchdir(to)
155 char *to;
156 {
157 unsigned d, dd;
158
159 if (to[1] == ':') {
160 d = CharUpcase(to[0]) - ('A' - 1);
161 if (d < 'A'-('A'-1) || 'Z'-('A'-1) < d) {
162 complain("invalid drive");
163 /* NOTREACHED */
164 }
165 _dos_getdrive(&dd);
166 if (dd != d)
167 _dos_setdrive(d, &dd); /* ??? no failure report? */
168 to += 2; /* skip drive spec */
169 }
170 return *to == '\0'? 0 : chdir(to);
171 }
172
173 private char *
174 fixpath(path)
175 char *path;
176 {
177 char *p;
178
179 for (p = path; *p != '\0'; p++)
180 if (*p == '\\')
181 *p = '/';
182 # ifdef MSDOS
183 return strlwr(path);
184 # else
185 return path; /* Win32 is case-preserving. */
186 # endif
187 }
188
189 private void
190 abspath(so, dest)
191 char *so, *dest;
192 {
193 char cwd[FILESIZE],
194 cwdD[3], cwdDIR[_MAX_DIR], cwdF[_MAX_FNAME], cwdEXT[_MAX_EXT],
195 soD[3], soDIR[_MAX_DIR], soF[_MAX_FNAME], soEXT[_MAX_EXT];
196
197 _splitpath(fixpath(so), soD, soDIR, soF, soEXT);
198 getcwd(cwd, FILESIZE);
199 if (*soD != '\0') {
200 /* Find current working directory on specified drive
201 * There is a DOS system call to do this (service 0x47),
202 * but the C library doesn't have a glue routine for it.
203 * We get the same effect with this kludgy code.
204 */
205 Dchdir(soD); /* note: without a path, current directory is unchanged */
206 getcwd(cwdDIR, FILESIZE);
207 cwd[2] = '\0'; /* toss away path, leaving only drive spec */
208 Dchdir(cwd);
209 strcpy(cwd, cwdDIR);
210 }
211 (void) fixpath(cwd);
212 if (cwd[strlen(cwd)-1] != '/')
213 strcat(cwd, "/x.x"); /* need dummy filename */
214
215 _splitpath(fixpath(cwd), cwdD, cwdDIR, cwdF, cwdEXT);
216 /* Reconstruct the path as follows:
217 * - If it is NOT a UNC (network) name, and doesn't have a drive letter,
218 * add one.
219 * - If it is a relative path, add the current drive/directory
220 * to convert it to an absolute path.
221 */
222 _makepath(dest,
223 *soD == '\0' && (soDIR[0]!='/'||soDIR[1]!='/') ? cwdD : soD,
224 *soDIR != '/'? strcat(cwdDIR, soDIR) : soDIR, soF, soEXT);
225 fixpath(dest); /* can't do it often enough */
226 }
227
228 #endif /* MSFILESYSTEM */
229
230
231 int
232 MakeTemp(char *buf, const char *complaint)
233 {
234 const char *errfmt = "cannot create \"%s\" for %s: %s (%d)";
235 #ifdef NO_MKSTEMP
236 # ifdef NO_MKTEMP
237 /* Some systems don't provide mkstemp or mktemp (nor should
238 * they -- ANSI defines tmpnam). Unfortunately tmpnam doesn't
239 * do what we want either, so we roll one by hand.
240 */
241 char *seq;
242 char *p;
243
244 for (seq = buf + strlen(buf); seq>buf && seq[-1]=='X'; seq--)
245 ;
246 for (p = seq; *p != '\0'; p++)
247 *p = '0';
248 for (;;) {
249 struct stat sb;
250
251 jdbg("stat temp \"%s\"\n", buf);
252 if (stat(buf, &sb) < 0
253 # ifdef ZTCDOS
254 /* Zortech yields ENOTDIR when path isn't found,
255 * even if the prefix does exist. Pretty silly!
256 */
257 && errno == ENOTDIR
258 # else
259 && errno == ENOENT
260 # endif
261 ) {
262 # ifdef O_EXCL
263 int fd = open(buf, O_CREAT | O_EXCL | O_RDWR | O_BINARY,
264 S_IWRITE | S_IREAD);
265 # else /* !O_EXCL */
266 int fd = creat(buf, 0600);
267 # endif /* !O_EXCL */
268 jdbg("opened temp \"%s\" %d %d\n", buf, fd, errno);
269
270 if (fd != -1)
271 return fd;
272 }
273 for (p = seq; ; ) {
274 if (*p == '\0') {
275 /* we ran out of possible names! */
276 complain(errfmt, buf, complaint, "ran out of names", 0);
277 /*NOTREACHED*/
278 } else if (*p == '9') {
279 *p++ = '0';
280 } else {
281 *p += 1;
282 break;
283 }
284 }
285 }
286 # else /* !NO_MKTEMP */
287 int fd;
288
289 jdbg("mktemp \"%s\"\n", buf);
290 if (mktemp(buf) == NULL
291 || -1 == (fd =
292 # ifdef O_EXCL
293 open(buf, O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IWRITE | S_IREAD)
294 # else /* !O_EXCL */
295 creat(buf, 0600)
296 # endif /* !O_EXCL */
297 ))
298 {
299 complain(errfmt, buf, complaint, strerror(errno), errno);
300 /* NOTREACHED */
301 }
302 return fd;
303 # endif /* !NO_MKTEMP */
304 #else /* !NO_MKSTEMP */
305 /* Ordinary mkstemp, except that we juggle umask to ensure
306 * that the file is only readable by the owner.
307 * Modern mkstemp implementations don't need this,
308 * because they create the tempfile with 0600,
309 * but old ones use 0666. Making the umask 0077 should
310 * solve this.
311 */
312 jmode_t saved_umask
313 #ifdef S_IRWXG
314 = umask(S_IRWXG | S_IRWXO);
315 #else
316 = umask(077);
317 #endif
318 int fd = mkstemp(buf);
319 int saved_errno = errno;
320
321 jdbg("mkstemp \"%s\" %d %d\n", buf, fd, saved_errno);
322 (void) umask(saved_umask);
323 errno = saved_errno;
324 if (fd == -1) {
325 complain(errfmt, buf, complaint, strerror(errno), errno);
326 /*NOTREACHED*/
327 }
328 return fd;
329 #endif /* !NO_MKSTEMP */
330 }
331
332 void
333 close_file(File *fp)
334 {
335 if (fp != NULL) {
336 if (fp->f_flags & F_TELLALL)
337 add_mess(" %D lines, %D characters.",
338 io_lines, io_chars);
339 f_close(fp);
340 }
341 }
342
343 /* Write the region from line1/char1 to line2/char2 to FP. This
344 * never CLOSES the file since we don't know if we want to.
345 */
346 jbool EndWNewline = 1; /* VAR: end files with a blank line */
347
348 void
349 putreg(File *fp,
350 LinePtr line1, int char1,
351 LinePtr line2, int char2,
352 jbool makesure)
353 {
354 if (makesure)
355 (void) fixorder(&line1, &char1, &line2, &char2);
356 while (line1 != line2->l_next) {
357 char *lp = lcontents(line1) + char1;
358
359 if (line1 == line2) {
360 fputnchar(lp, (char2 - char1), fp);
361 io_chars += (char2 - char1);
362 } else {
363 char c;
364
365 while ((c = *lp++) != '\0') {
366 f_putc(c, fp);
367 io_chars += 1;
368 }
369 }
370 if (line1 != line2) {
371 io_lines += 1;
372 io_chars += 1;
373 #ifdef USE_CRLF
374 f_putc('\r', fp);
375 #endif /* USE_CRLF */
376 f_putc(EOL, fp);
377 }
378 line1 = line1->l_next;
379 char1 = 0;
380 }
381 flushout(fp);
382 }
383
384 private void
385 dofread(File *fp)
386 {
387 char end[LBSIZE];
388 jbool xeof;
389 LinePtr savel = curline;
390 int savec = curchar;
391
392 strcpy(end, linebuf + curchar);
393 xeof = f_gets(fp, linebuf + curchar, (size_t) (LBSIZE - curchar));
394 SavLine(curline, linebuf);
395 while(!xeof) {
396 curline = listput(curbuf, curline);
397 xeof = f_getputl(curline, fp);
398 }
399 getDOT();
400 linecopy(linebuf, (curchar = strlen(linebuf)), end);
401 SavLine(curline, linebuf);
402 IFixMarks(savel, savec, curline, curchar);
403 }
404
405 void
406 read_file(char *file, jbool is_insert)
407 {
408 Bufpos save;
409 File *fp;
410 jbool err;
411 int save_type;
412 char *save_fname;
413
414 if (!is_insert)
415 curbuf->b_ntbf = NO;
416 fp = open_file(file, iobuff, F_READ | F_TELLALL, NO);
417 if (fp == NULL) {
418 if (!is_insert && errno == ENOENT)
419 s_mess("(new file)");
420 else
421 s_mess(IOerr("open", file));
422 return;
423 }
424 if (!is_insert) {
425 (void) do_stat(curbuf->b_fname, curbuf, DS_SET);
426 set_arg_value((fp->f_flags & F_READONLY)? 1 : 0);
427 TogMinor(BReadOnly);
428 }
429
430 DOTsave(&save);
431
432 /*
433 * if read fails, e.g. too long line, it would be
434 * dangerous to save the buffer back to the real
435 * filename, so we mark the buffer as scratch (unless
436 * we are inserting, in which case the buffer might
437 * have other valuable info worth saving, even with
438 * the truncated line, sigh!), and give it a temporary
439 * fname, which we restore after the read succeeds.
440 */
441 save_type = curbuf->b_type;
442 save_fname = curbuf->b_fname;
443 if (save_fname) {
444 char *tmpfname = (char *)emalloc(FILESIZE);
445 backup_name(save_fname, "+", tmpfname, FILESIZE);
446 jdbg("temporary name \"%s\"\n", tmpfname);
447 curbuf->b_fname = tmpfname;
448 }
449 if (!is_insert)
450 curbuf->b_type = B_SCRATCH;
451
452 dofread(fp);
453
454 if (is_insert && io_chars > 0) {
455 modify();
456 set_mark();
457 }
458 SetDot(&save);
459 getDOT();
460 err = (fp->f_flags & (F_ERR | F_LINETOOLONG)) != 0;
461 close_file(fp);
462 if (err) {
463 if (save_fname)
464 free(save_fname);
465 complain("[Error reading file%s]", is_insert ? ", buffer has tmp name now" : ", buffer marked as scratch with tmp name");
466 /* NOTREACHED */
467 }
468 curbuf->b_type = save_type;
469 if (save_fname) {
470 char *tmpfname = curbuf->b_fname;
471 jdbg("restoring original name \"%s\"\n", save_fname);
472 curbuf->b_fname = save_fname;
473 free(tmpfname);
474 }
475 }
476
477 void
478 SaveFile(void)
479 {
480 if (!IsModified(curbuf) && !curbuf->b_diverged) {
481 if (curbuf->b_fname != NULL)
482 (void) do_stat(curbuf->b_fname, curbuf, DS_NONE);
483 if (!curbuf->b_diverged) {
484 message("No changes need to be written.");
485 return;
486 }
487 }
488 if (curbuf->b_fname == NULL) {
489 /* We change LastCmd because otherwise the prompt for
490 * the filename will be ": visit-file". With this
491 * fudge, it will be ": write-file".
492 */
493 const data_obj *saved_lc = LastCmd;
494 static const data_obj dummy = { 0, "write-file" };
495
496 LastCmd = &dummy;
497 JWriteFile();
498 LastCmd = saved_lc;
499 } else {
500 filemunge(curbuf->b_fname);
501 chk_divergence(curbuf, curbuf->b_fname, "save");
502 file_write(curbuf->b_fname, NO);
503 }
504 }
505
506 const char *HomeDir; /* home directory */
507 size_t HomeLen; /* length of home directory string */
508
509 private List *DirStack = NULL;
510 #define dir_name(dp) ((char *) list_data((dp)))
511 #define PWD_PTR (list_data(DirStack))
512 #define PWD ((char *) PWD_PTR)
513
514 char *
515 pwd(void)
516 {
517 return PWD;
518 }
519
520 /* Format a file name without redundant prefix.
521 * The result will be in a static buffer.
522 * Note: by always using the static buffer, we allow ask_ford,
523 * as it is currently coded, to accept aliased arguments.
524 * The result will always fit in a FILESIZE buffer.
525 */
526 char *
527 pr_name(const char *fname, jbool okay_home)
528 {
529 if (fname == NULL) {
530 return NULL;
531 } else {
532 static char name_buf[FILESIZE];
533 size_t PWDlen = strlen(PWD);
534 size_t improvement = 0;
535
536 if (strlen(fname) >= (size_t)FILESIZE) {
537 complain("filename longer than %d", FILESIZE-1);
538 /* NOTREACHED */
539 }
540 strcpy(name_buf, fname); /* default: unchanged */
541 if (strncmp(fname, PWD, PWDlen) == 0 && fname[PWDlen] == '/') {
542 /* Below current directory: strip prefix and /.
543 * Assumption: fname[PWDlen+1] is not / or \0.
544 */
545 strcpy(name_buf, fname + PWDlen + 1);
546 improvement = PWDlen + 1;
547 }
548 if (okay_home && HomeLen > improvement + 1
549 && strncmp(fname, HomeDir, HomeLen) == 0 && fname[HomeLen] == '/')
550 {
551 /* Below home directory: replace prefix with ~. */
552 name_buf[0] = '~';
553 strcpy(name_buf + 1, fname + HomeLen);
554 /* improvement = HomeLen - 1; */
555 }
556 return name_buf;
557 }
558 }
559
560 void
561 Chdir(void)
562 {
563 char dirbuf[FILESIZE];
564
565 (void) ask_dir((char *)NULL, PWD, dirbuf);
566 if (Dchdir(dirbuf) == -1)
567 {
568 s_mess("cd: cannot change into %s.", dirbuf);
569 return;
570 }
571 UpdModLine = YES;
572 setCWD(dirbuf);
573 prCWD();
574 #ifdef MAC
575 Bufchange = YES;
576 #endif
577 }
578
579 /* Check if dn is the name of the current working directory
580 * and that it is in cannonical form
581 */
582
583 jbool
584 chkCWD(char *dn)
585 {
586 #ifdef USE_INO
587 char filebuf[FILESIZE];
588 struct stat dnstat,
589 dotstat;
590
591 if (dn[0] != '/')
592 return NO; /* need absolute pathname */
593
594 PathParse(dn, filebuf);
595 return stat(filebuf, &dnstat) == 0
596 && stat(".", &dotstat) == 0
597 && dnstat.st_dev == dotstat.st_dev
598 && dnstat.st_ino == dotstat.st_ino;
599 #else /* !USE_INO */
600 return NO; /* no way of telling */
601 #endif /* !USE_INO */
602 }
603
604 void
605 setCWD(char *d)
606 {
607 if (DirStack == NULL)
608 list_push(&DirStack, NULL);
609 PWD_PTR = freealloc(PWD, strlen(d) + 1);
610 strcpy(PWD, d);
611 }
612
613 void
614 getCWD(void)
615 {
616 char *cwd;
617 char pathname[FILESIZE];
618
619 #ifndef MAC /* no environment in MacOS */
620 cwd = getenv("CWD");
621 if (cwd == NULL || !chkCWD(cwd)) {
622 cwd = getenv("PWD");
623 if (cwd == NULL || !chkCWD(cwd)) {
624 #endif
625 cwd = getcwd(pathname, sizeof(pathname));
626 if (cwd == NULL) {
627 error("Cannot get current directory");
628 /* NOTREACHED */
629 }
630 #ifndef MAC /* no environment in MacOS */
631 }
632 }
633 #endif
634 #ifdef MSFILESYSTEM
635 cwd = fixpath(cwd);
636 #endif /* MSFILESYSTEM */
637 setCWD(cwd);
638 }
639
640 void
641 prDIRS(void)
642 {
643 List *lp;
644
645 s_mess(ProcFmt);
646 for (lp = DirStack; lp != NULL; lp = list_next(lp))
647 add_mess("%s ", pr_name(dir_name(lp), YES));
648 }
649
650 void
651 prCWD(void)
652 {
653 f_mess(": %f => \"%s\"", PWD);
654 stickymsg = YES;
655 }
656
657 private void
658 doPushd(char *newdir)
659 {
660 UpdModLine = YES;
661 if (*newdir == '\0') { /* Wants to swap top two entries */
662 if (list_next(DirStack) == NULL) {
663 complain("pushd: no other directory.");
664 /* NOTREACHED */
665 }
666 newdir = dir_name(list_next(DirStack));
667 if (Dchdir(newdir) == -1)
668 {
669 s_mess("pushd: cannot change back into %s.", newdir);
670 return;
671 }
672 list_data(list_next(DirStack)) = list_data(DirStack);
673 list_data(DirStack) = newdir;
674 } else {
675 if (Dchdir(newdir) == -1)
676 {
677 s_mess("pushd: cannot change into %s.", newdir);
678 return;
679 }
680 (void) list_push(&DirStack, NULL);
681 setCWD(newdir);
682 }
683 prDIRS();
684 }
685
686 void
687 Pushd(void)
688 {
689 char dirbuf[FILESIZE];
690
691 (void) ask_dir((char *)NULL, NullStr, dirbuf);
692 doPushd(dirbuf);
693 }
694
695 void
696 Pushlibd(void)
697 {
698 char dirbuf[FILESIZE];
699
700 /* Do we even need to make a copy of ShareDir? -- MM */
701 jamstrsub(dirbuf, ShareDir, sizeof dirbuf);
702 doPushd(dirbuf);
703 }
704
705 void
706 Popd(void)
707 {
708 char *newdir;
709
710 if (list_next(DirStack) == NULL) {
711 complain("popd: directory stack is empty.");
712 /* NOTREACHED */
713 }
714 newdir = dir_name(list_next(DirStack));
715 if (Dchdir(newdir) == -1) {
716 s_mess("popd: cannot change back into %s.", newdir);
717 return;
718 }
719 UpdModLine = YES;
720 free(list_pop(&DirStack));
721 prDIRS();
722 }
723
724 #ifdef UNIX
725
726 # ifdef USE_GETPWNAM
727
728 #include <pwd.h>
729
730 private void
731 get_hdir(char *user, char *buf)
732 {
733 struct passwd *p;
734
735 p = getpwnam(user);
736 endpwent();
737 if (p == NULL) {
738 add_mess(" [unknown user: %s]", user);
739 SitFor(7);
740 complain((char *)NULL);
741 /* NOTREACHED */
742 }
743 jamstrsub(buf, p->pw_dir, (size_t)FILESIZE);
744 }
745
746 # else /* ! USE_GETPWNAM */
747
748 # include "re.h"
749
750 private void
751 get_hdir(char *user, char *buf)
752 {
753 char fbuf[LBSIZE],
754 pattern[100];
755 int u_len;
756 File *fp;
757
758 u_len = strlen(user);
759 fp = open_file("/etc/passwd", fbuf, F_READ, YES);
760 swritef(pattern, sizeof(pattern),
761 "%s:[^:]*:[^:]*:[^:]*:[^:]*:\\([^:]*\\):", user);
762 while (!f_gets(fp, genbuf, LBSIZE))
763 if ((strncmp(genbuf, user, u_len) == 0)
764 && LookingAt(pattern, genbuf, 0)) {
765 putmatch(1, buf, FILESIZE);
766 close_file(fp);
767 return;
768 }
769 close_file(fp);
770 add_mess(" [unknown user: %s]", user);
771 SitFor(7);
772 complain((char *)NULL);
773 /* NOTREACHED */
774 }
775
776 # endif /* USE_GETPWNAM */
777 #endif /* UNIX */
778
779 /* Concatenate two parts of a pathname.
780 * They should end up separated by a '/' (or optionally '\\', if MSFILESYSTEM)
781 * but we are careful not to add one if the prefix already ends in one.
782 * Arbitrarily, if pre is empty, the result is the same as if it were root (/).
783 */
784 void
785 PathCat(char *buf, size_t buflen, const char *pre, const char *post)
786 {
787 size_t prelen = strlen(pre);
788
789 swritef(buf, buflen,
790 prelen > 0
791 && (pre[prelen-1] == '/'
792 #ifdef MSFILESYSTEM
793 || pre[prelen-1] == '\\'
794 #endif
795 )? "%s%s" : "%s/%s",
796 pre, post);
797 }
798
799 /* Convert path in name into a more-canonical one in intobuf.
800 * - makes path absolute
801 * - handles ~ (and \~, if not MSFILESYSTEM)
802 * - if MSFILESYSTEM, turns \ into /
803 * - on MSDOS, lower cases everything
804 * Note: name and intobuf must not be aliases.
805 * Note: because \~ is turned into ~, this routine is not idempotent.
806 * ??? I suspect that there are places where in the code that presume
807 * it is idempotent! -- DHR
808 * It seems that all callers of PathParse (or their callers) provide
809 * an intobuf of size FILESIZE, which is important, and it seems
810 * that the operations in PathParse or callees are careful to
811 * not go outside FILESIZE bounds, but I really wish I could feel
812 * more confident of that. -- MM
813 *
814 * *intobuf MUST BE at least FILESIZE
815 */
816
817 void
818 PathParse(const char *name, char *intobuf)
819 {
820 char localbuf[FILESIZE];
821
822 intobuf[0] = localbuf[0] = '\0';
823 if (*name == '\0')
824 return;
825
826 /* Place pathname in localbuf, with any specified home directory */
827
828 if (*name == '~') {
829 if (name[1] == '/' || name[1] == '\0') {
830 jamstrsub(localbuf, HomeDir, sizeof(localbuf));
831 name += 1;
832 }
833 #ifdef UNIX /* may add for mac in future */
834 else {
835 const char *uendp = strchr(name, '/');
836 char unamebuf[30];
837
838 if (uendp == NULL)
839 uendp = name + strlen(name);
840 name += 1;
841 if ((size_t) (uendp - name) >= sizeof(unamebuf)) {
842 len_error(JMP_COMPLAIN);
843 /* NOTREACHED */
844 }
845 null_ncpy(unamebuf, name, (size_t) (uendp - name));
846 get_hdir(unamebuf, localbuf);
847 name = uendp;
848 }
849 #endif
850 #ifndef MSFILESYSTEM
851 } else if (name[0] == '\\' && name[1] == '~') {
852 /* allow quoting of ~ (but \ is a path separator in MSDOS) */
853 name += 1;
854 #endif /* MSFILESYSTEM */
855 }
856 jamstrcat(localbuf, name, sizeof(localbuf));
857
858 /* Make path absolute, and prepare for processing each component
859 * of the path by placing prefix in intobuf.
860 */
861 #ifndef MSFILESYSTEM
862 jamstrsub(intobuf, localbuf[0] == '/'? "/" : PWD, FILESIZE);
863 #else /* MSFILESYSTEM */
864 /* Convert to an absolute path, and then fudge thing so that the
865 * generic code does not have to deal with drive specifications.
866 * If the path starts with '//' it is a UNC name. Otherwise,
867 * our absolute path starts with a d: drive specification and
868 * uses forward slashes as the path separator (including one
869 * right after the drive specification).
870 */
871 abspath(localbuf, intobuf);
872 if (localbuf[0] == '/' && localbuf[1] == '/') {
873 strcpy(localbuf, intobuf+1);
874 intobuf += 1;
875 intobuf[1] = '\0';
876 } else {
877 strcpy(localbuf, intobuf+3); /* copy back all but d:/ */
878 intobuf += 2; /* "forget" drive spec: point to / */
879 intobuf[1] = '\0'; /* truncate after d:/ */
880 }
881 #endif /* MSFILESYSTEM */
882
883 /* Process each path component, attempting to make the path canonical. */
884 {
885 char
886 *fp = localbuf, /* start of current component */
887 *dp = intobuf; /* current end of resulting path (but lazy) */
888 #ifdef HAS_SYMLINKS
889 int linkcnt = 0; /* to detect symlink loops */
890 #endif
891
892 while (*fp != '\0') {
893 /* for each path component: */
894 char *sp = strchr(fp, '/'); /* end of current component */
895
896 if (sp != NULL)
897 *sp = '\0';
898 dp += strlen(dp); /* move to end of resulting path */
899 if (*fp == '\0' || strcmp(fp, ".") == 0) {
900 /* ignore this component */
901 } else if (strcmp(fp, "..") == 0) {
902 /* Strip one directory name from "intobuf".
903 * Assume that intobuf[0] == '/'.
904 * Symlinks are the only hard part.
905 * ??? is this correct for the Mac? CP/M?
906 */
907 #ifdef HAS_SYMLINKS
908 char linkbuf[FILESIZE];
909 JSSIZE_T linklen;
910 #endif
911
912 do {} while (dp > intobuf+1 && *--dp != '/');
913 #ifdef HAS_SYMLINKS
914 /* If we find that the path up to the .. is a symlink,
915 * and we don't appear to be in a symlink loop
916 * and we have room to handle it,
917 * we jam the symlink's target on the front of fp
918 * and try again.
919 * Note: this code will only work for UNIX-like pathnames.
920 */
921 if (sp != NULL)
922 *sp = '/';
923 linklen = readlink(intobuf, linkbuf, sizeof(linkbuf)-1);
924 if (linklen >= 0 && ++linkcnt < 100
925 && strlen(fp) + linklen + (linkbuf[0]=='/'? 0 : dp - intobuf) + 2 <= sizeof(linkbuf))
926 {
927 if (linklen <= 1 || linkbuf[linklen-1] != '/')
928 linkbuf[linklen++] = '/';
929 strcpy(&linkbuf[linklen], fp);
930 strcpy(localbuf, linkbuf);
931 fp = localbuf;
932 if (linkbuf[0] == '/') {
933 fp += 1;
934 dp = &intobuf[0];
935 *dp++ = '/';
936 }
937 *dp = '\0';
938 continue;
939 }
940 #endif
941 *dp = '\0';
942 } else {
943 if (dp!=intobuf && dp[-1]!='/')
944 *dp++ = '/';
945 strcpy(dp, fp);
946 }
947 if (sp == NULL)
948 break;
949
950 fp = sp + 1;
951 }
952 }
953 }
954
955 int CreatMode = DFLT_MODE; /* VAR: default mode for creat'ing files */
956
957 private void
958 DoWriteReg(jbool app)
959 {
960 char fnamebuf[FILESIZE];
961 Mark *mp = CurMark();
962 File *fp;
963
964 /* Won't get here if there isn't a Mark */
965 (void) ask_file((char *)NULL, (char *)NULL, fnamebuf);
966
967 if (!app) {
968 filemunge(fnamebuf);
969 chk_divergence((Buffer *)NULL, fnamebuf, "write-region");
970 #ifdef BACKUPFILES
971 if (BkupOnWrite)
972 file_backup(fnamebuf);
973 #endif
974 }
975
976 fp = open_file(fnamebuf, iobuff, app ? F_APPEND|F_TELLALL : F_WRITE|F_TELLALL, YES);
977 putreg(fp, mp->m_line, mp->m_char, curline, curchar, YES);
978 close_file(fp);
979 }
980
981 void
982 WrtReg(void)
983 {
984 DoWriteReg(NO);
985 }
986
987 void
988 AppReg(void)
989 {
990 DoWriteReg(YES);
991 }
992
993 jbool OkayBadChars = NO; /* VAR: allow bad characters in filenames created by JOVE */
994
995 void
996 JWriteFile(void)
997 {
998 char
999 fnamebuf[FILESIZE];
1000
1001 #ifdef MAC
1002 if (Macmode) {
1003 if (pfile(fnamebuf) == NULL)
1004 return;
1005 } else
1006 #endif /* MAC */
1007 (void) ask_file((char *)NULL, curbuf->b_fname, fnamebuf);
1008 /* Don't allow bad characters when creating new files. */
1009 if (!OkayBadChars
1010 && (curbuf->b_fname==NULL || strcmp(curbuf->b_fname, fnamebuf) != 0))
1011 {
1012 static const char badchars[] =
1013 #ifdef UNIX
1014 "!$^&*()~`{}\"'\\|<>? ";
1015 #elif MSDOS
1016 "*|<>? ";
1017 #elif WIN32
1018 "*|<>?\"";
1019 #elif MAC
1020 ":";
1021 #else
1022 #error "unsupported file system architecture"
1023 #endif
1024 char *cp = fnamebuf;
1025 char c;
1026
1027 while ((c = *cp++) != '\0') {
1028 if (!jisprint(c) || strchr(badchars, c)!=NULL) {
1029 complain("'%p': bad character in filename.", c);
1030 /* NOTREACHED */
1031 }
1032 }
1033 }
1034
1035 filemunge(fnamebuf);
1036 chk_divergence(curbuf, fnamebuf, "write");
1037 curbuf->b_type = B_FILE; /* in case it wasn't before */
1038 setfname(curbuf, fnamebuf);
1039 file_write(fnamebuf, NO);
1040 }
1041
1042 void
1043 WtModBuf(void)
1044 {
1045 if (!ModBufs(NO))
1046 message("[No buffers need saving]");
1047 else
1048 put_bufs(is_an_arg());
1049 }
1050
1051 void
1052 put_bufs(jbool askp)
1053 {
1054 Buffer *oldb = curbuf,
1055 *b;
1056
1057 for (b = world; b != NULL; b = b->b_next) {
1058 if (!IsModified(b) || b->b_type != B_FILE)
1059 continue;
1060 SetBuf(b); /* Make this current Buffer */
1061 if (curbuf->b_fname == NULL) {
1062 const char *newname;
1063
1064 newname = ask(NullStr, "Buffer \"%s\" needs a file name; type Return to skip: ", b->b_name);
1065 if (*newname == '\0')
1066 continue;
1067
1068 setfname(b, newname);
1069 }
1070 if (askp && !yes_or_no_p("Write %s? ", curbuf->b_fname))
1071 continue;
1072
1073 SaveFile();
1074 }
1075 SetBuf(oldb);
1076 }
1077
1078 /* Open file FNAME supplying the buffer IO routine with buffer BUF.
1079 * HOW is F_READ, F_WRITE or F_APPEND. HOW can have the F_TELLALL
1080 * flag to request the displaying of I/O status. Only if COMPLAINIFBAD
1081 * will a complain diagnostic be produced for a failed open.
1082 *
1083 * NOTE: This opens the pr_name(fname, NO) of fname. That is, FNAME
1084 * is usually an entire pathname, which can be slow when the
1085 * pathname is long and there are lots of symbolic links along
1086 * the way (which has become very common in my experience). So,
1087 * this speeds up opens file names in the local directory. It
1088 * will not speed up things like "../scm/foo.scm" simply because
1089 * by the time we get here that's already been expanded to an
1090 * absolute pathname. But this is a start.
1091 */
1092 File *
1093 open_file(char *fname, char *buf, int how, jbool complainifbad)
1094 {
1095 File *fp;
1096
1097 io_chars = 0;
1098 io_lines = 0;
1099
1100 fp = f_open(pr_name(fname, NO), how, buf, LBSIZE);
1101 if (fp == NULL) {
1102 if (complainifbad) {
1103 message(IOerr((F_MODE(how) == F_READ) ? "open" : "create",
1104 fname));
1105 complain((char *)NULL);
1106 /* NOTREACHED */
1107 }
1108 } else {
1109 const char *rd_only = NullStr;
1110
1111 #ifndef MAC
1112 if (access(pr_name(fname, NO), W_OK) == -1 && errno != ENOENT) {
1113 rd_only = " [Read only]";
1114 fp->f_flags |= F_READONLY;
1115 }
1116 #endif
1117 if (how & F_TELLALL)
1118 f_mess("\"%s\"%s", pr_name(fname, YES), rd_only);
1119 }
1120 return fp;
1121 }
1122
1123 /* We're about to write to a file (save-file, write-region, append-region,
1124 * or write-file): query user when it is an existing but different file.
1125 * Note: even if we are doing an append-region or write-region,
1126 * we assume that the current buffer's file is fair game.
1127 */
1128 private void
1129 filemunge(char *newname)
1130 {
1131 if (do_stat(newname, curbuf, DS_NONE) != curbuf && was_file) {
1132 rbell();
1133 confirm("\"%s\" already exists; overwrite it? ", newname);
1134 /* in case user has fiddled some more, refresh stat cache */
1135 (void) do_stat(newname, (Buffer *)NULL, DS_NONE);
1136 }
1137 }
1138
1139 /* Check to see if the file has been modified since it was
1140 * last visited or saved. If so, make sure they know what
1141 * they're doing. Buffer "thisbuf" is tested for divergence;
1142 * if thisbuf is NULL, the first buffer with the file is tested.
1143 *
1144 * To avoid excessive stats, we presume that the stat cache is
1145 * already primed. We refresh it if we get a confirmation because
1146 * it left the user a window of opportunity for fiddling.
1147 */
1148
1149 private void
1150 chk_divergence(Buffer *thisbuf, const char *fname, const char *how)
1151 {
1152 static const char mesg[] = "Shall I go ahead and %s anyway? ";
1153 Buffer *buf = do_stat(fname, thisbuf, DS_REUSE);
1154
1155 if (buf != NULL && buf->b_diverged) {
1156 rbell();
1157 redisplay(); /* Ring that bell! */
1158 TOstart("Warning");
1159 Typeout("\"%s\" now saved on disk is not what you last", pr_name(fname, YES));
1160 Typeout("visited or saved. Probably someone else is editing");
1161 Typeout("your file at the same time.");
1162 Typeout(NullStr);
1163 Typeout("Type \"y\" if I should %s, anyway.", how);
1164 f_mess(mesg, how);
1165 TOstop();
1166 confirm(mesg, how);
1167 /* in case user has fiddled some more, refresh stat cache */
1168 (void) do_stat(fname, (Buffer *)NULL, DS_NONE);
1169 }
1170 }
1171
1172 void
1173 file_write(char *fname, jbool app)
1174 {
1175 File *fp;
1176
1177 #ifdef BACKUPFILES
1178 if (!app && BkupOnWrite)
1179 file_backup(fname);
1180 #endif
1181
1182 fp = open_file(fname, iobuff, app ? F_APPEND|F_TELLALL : F_WRITE|F_TELLALL, YES);
1183
1184 if (EndWNewline) { /* Make sure file ends with a newLine */
1185 Bufpos save;
1186
1187 DOTsave(&save);
1188 ToLast();
1189 if (length(curline)) /* Not a blank Line */
1190 LineInsert(1);
1191 SetDot(&save);
1192 }
1193 putreg(fp, curbuf->b_first, 0, curbuf->b_last, length(curbuf->b_last), NO);
1194 close_file(fp);
1195 (void) do_stat(curbuf->b_fname, curbuf, DS_SET);
1196 unmodify();
1197 }
1198
1199 void
1200 JReadFile(void)
1201 {
1202 char
1203 fnamebuf[FILESIZE];
1204 jbool
1205 reloading;
1206 Window
1207 *wp;
1208 long
1209 curlineno;
1210
1211 #ifdef MAC
1212 if (Macmode) {
1213 if (gfile(fnamebuf) == NULL)
1214 return;
1215 } else
1216 #endif /* MAC */
1217 (void) ask_file((char *)NULL, curbuf->b_fname, fnamebuf);
1218
1219 if (IsModified(curbuf)
1220 && yes_or_no_p("Shall I make your changes to \"%s\" permanent? ", curbuf->b_name))
1221 SaveFile();
1222
1223 (void) do_stat(fnamebuf, (Buffer *)NULL, DS_NONE); /* prime stat cache */
1224 chk_divergence(curbuf, fnamebuf, "read");
1225
1226 reloading = do_stat(fnamebuf, curbuf, DS_REUSE) == curbuf;
1227
1228 /* preserve w_line in each window into curbuf */
1229 wp = fwind;
1230 do {
1231 if (wp->w_bufp == curbuf) {
1232 /* hijack w_topnum -- nobody was using it anyway */
1233 wp->w_topnum = reloading? LinesTo(curbuf->b_first, wp->w_line) : 0;
1234 wp->w_top = wp->w_line = NULL;
1235 wp->w_flags |= W_TOPGONE;
1236 }
1237 } while ((wp = wp->w_next) != fwind);
1238
1239 curlineno = reloading? LinesTo(curbuf->b_first, curline) : 0;
1240
1241 buf_clear(curbuf);
1242 setfname(curbuf, fnamebuf);
1243 read_file(fnamebuf, NO);
1244
1245 /* recover dot in each window into curbuf */
1246 wp = fwind;
1247 do {
1248 if (wp->w_bufp == curbuf) {
1249 wp->w_top = curbuf->b_first;
1250 wp->w_line = next_line(curbuf->b_first, wp->w_topnum);
1251 }
1252 } while ((wp = wp->w_next) != fwind);
1253
1254 SetLine(next_line(curbuf->b_first, curlineno));
1255 }
1256
1257 void
1258 InsFile(void)
1259 {
1260 char
1261 fnamebuf[FILESIZE];
1262 #ifdef MAC
1263 if (Macmode) {
1264 if (gfile(fnamebuf) == NULL)
1265 return;
1266 } else
1267 #endif /* MAC */
1268 (void) ask_file((char *)NULL, curbuf->b_fname, fnamebuf);
1269 read_file(fnamebuf, YES);
1270 }
1271
1272 #include "temp.h"
1273
1274 jbool DOLsave = NO; /* Do Lsave flag. If lines aren't being saved
1275 * when you think they should have been, this
1276 * flag is probably not being set, or is being
1277 * cleared before lsave() was called.
1278 */
1279
1280 private int nleft, /* number of good characters left in current block */
1281 tmpfd = -1;
1282 daddr DFree = 1; /* pointer to end of tmp file */
1283 private char *tfname; /* pathname of tempfile where buffer lines go */
1284
1285 private void
1286 tmpinit(void)
1287 {
1288 char buf[FILESIZE];
1289
1290 PathCat(buf, sizeof(buf), TmpDir,
1291 #ifdef MAC
1292 ".joveXXX" /* must match string in mac.c:Ffilter() */
1293 #else
1294 "jvXXXXXX"
1295 #endif
1296 );
1297 tfname = copystr(buf);
1298 tmpfd = MakeTemp(tfname, "editing");
1299 #ifdef RECOVER
1300 rectmpname(strrchr(tfname, '/') + 1);
1301 #endif
1302 }
1303
1304 /* Close tempfile before execing a child process.
1305 * Since we might be vforking, we must not change any variables
1306 * (in particular tmpfd).
1307 */
1308 void
1309 tmpclose(void)
1310 {
1311 if (tmpfd != -1)
1312 (void) close(tmpfd);
1313 }
1314
1315 /* Close and remove tempfile before exiting. */
1316
1317 void
1318 tmpremove(void)
1319 {
1320 if (tmpfd != -1) {
1321 tmpclose();
1322 (void) unlink(tfname);
1323 }
1324 }
1325
1326 /* get a line at `tl' in the tmp file into `buf' which should be LBSIZE
1327 * long
1328 */
1329
1330 int Jr_Len; /* length of Just Read Line */
1331
1332 void
1333 jgetline(daddr addr, register char *buf)
1334 {
1335 register char *bp,
1336 *lp;
1337
1338 lp = buf;
1339 bp = getblock(addr, NO);
1340 do {} while ((*lp++ = *bp++) != '\0');
1341 Jr_Len = (lp - buf) - 1;
1342 }
1343
1344 /* Put `buf' and return the disk address */
1345
1346 daddr
1347 jputline(char *buf)
1348 {
1349 register char *bp,
1350 *lp;
1351 register int nl;
1352 daddr line_daddr;
1353
1354 lp = buf;
1355 bp = getblock(DFree, YES);
1356 nl = nleft;
1357 while ((*bp = *lp++) != '\0') {
1358 if (*bp++ == '\n') {
1359 *--bp = '\0';
1360 break;
1361 }
1362 if (--nl == 0) {
1363 DFree = blk_chop(DFree) + BLK_CHNKS;
1364 bp = getblock(DFree, YES);
1365 lp = buf; /* start over ... */
1366 nl = nleft;
1367 }
1368 }
1369 line_daddr = DFree;
1370 DFree += REQ_CHNKS(lp - buf); /* (lp - buf) includes the null */
1371 return line_daddr;
1372 }
1373
1374 /* The theory is that the critical section of code inside this procedure
1375 * will never cause a problem to occur. Basically, we need to ensure
1376 * that two blocks are in memory at the same time, but I think that
1377 * this can never screw up.
1378 */
1379 #define lockblock(addr)
1380 #define unlockblock(addr)
1381
1382 private jbool
1383 f_getputl(LinePtr line, File *fp)
1384 {
1385 char *bp;
1386 ZXchar c;
1387 int nl,
1388 room = LBSIZE-1;
1389 char *base;
1390
1391 base = bp = getblock(DFree, YES);
1392 nl = nleft;
1393 for (;;) {
1394 c = f_getc(fp);
1395 if (c == EOF)
1396 break;
1397
1398 /* We can't store NUL in our buffer, so ignore it.
1399 * Similarly, we can only store characters less than NCHARS.
1400 * Of course, with a little ingenuity we could store NUL:
1401 * NUL could be represented by \n.
1402 */
1403 if (c == '\0'
1404 #if NCHARS != UCHAR_ROOF
1405 || c >= NCHARS
1406 #endif
1407 )
1408 continue;
1409
1410 if (c == EOL) {
1411 #ifdef USE_CRLF
1412 /* a CR followed by an EOL is treated as a NL.
1413 * Bug: the line-buffer is effectively shortened by one character.
1414 */
1415 if (bp != base && bp[-1] == '\r') {
1416 bp -= 1;
1417 room += 1;
1418 }
1419 #endif /* USE_CRLF */
1420 break;
1421 }
1422 if (--room < 0)
1423 break; /* no room for this character */
1424
1425 if (--nl == 0) {
1426 char *newbp;
1427 size_t nbytes;
1428 daddr old_free_block = blk_chop(DFree);
1429
1430 lockblock(old_free_block);
1431 DFree = old_free_block + BLK_CHNKS;
1432 nbytes = bp - base;
1433 newbp = getblock(DFree, YES);
1434 nl = nleft;
1435 byte_copy(base, newbp, nbytes);
1436 bp = newbp + nbytes;
1437 base = newbp;
1438 unlockblock(old_free_block);
1439 }
1440 *bp++ = c;
1441 }
1442 *bp++ = '\0';
1443 line->l_dline = DFree;
1444 DFree += REQ_CHNKS(bp - base);
1445 if (room < 0) {
1446 fp->f_flags |= F_LINETOOLONG;
1447 add_mess(" [Line too long]");
1448 rbell();
1449 return YES;
1450 }
1451 if (c == EOF) {
1452 if (--bp != base)
1453 add_mess(" [Incomplete last line]");
1454 return YES;
1455 }
1456 io_lines += 1;
1457 return NO;
1458 }
1459
1460 typedef struct block {
1461 char b_dirty; /* (jbool) */
1462 daddr b_bno;
1463 char b_buf[JBUFSIZ];
1464 struct block
1465 *b_LRUnext,
1466 *b_LRUprev,
1467 *b_HASHnext;
1468 } Block;
1469
1470 #define HASHSIZE 7 /* Primes work best (so I'm told) */
1471 #define B_HASH(bno) ((bno) % HASHSIZE)
1472
1473 #ifdef MALLOC_CACHE
1474 private Block *b_cache = NULL;
1475 #else
1476 private Block b_cache[NBUF];
1477 #endif
1478
1479 private Block
1480 *bht[HASHSIZE], /* Block hash table. Must be zero initially */
1481 *f_block = NULL,
1482 *l_block = NULL;
1483
1484 private daddr next_bno = 0;
1485
1486 /* Needed to comfort MS Visual C */
1487 private void blkio(Block *, JSSIZE_T (*)(int, void *, JRWSIZE_T));
1488
1489 private void
1490 blkio(Block *b, JSSIZE_T (*iofcn)(int, void *, JRWSIZE_T))
1491 {
1492 off_t boff = bno_to_seek_off(b->b_bno);
1493 JSSIZE_T nb;
1494 static jbool first_time = YES;
1495
1496 if (first_time) {
1497 tmpinit();
1498 first_time = NO;
1499 }
1500 if (lseek(tmpfd, boff, 0) < 0) {
1501 error("[Tmp file seek error to %D: %d %s; to continue editing would be dangerous]",
1502 (long)boff, errno, strerror(errno));
1503 /* NOTREACHED */
1504 }
1505 else if ((nb = (*iofcn)(tmpfd, b->b_buf, (JRWSIZE_T)JBUFSIZ)) != JBUFSIZ) {
1506 error("[Tmp file %s error got %D: %d %s: to continue editing would be dangerous]",
1507 (iofcn == (JSSIZE_T (*)(int, void *, JRWSIZE_T))read) ? "READ" : "WRITE", (long)nb,
1508 nb < 0 ? errno : 0, nb < 0 ? strerror(errno): "");
1509 /* NOTREACHED */
1510 }
1511 }
1512
1513 void
1514 d_cache_init(void)
1515 {
1516 Block *bp, /* Block pointer */
1517 **hp; /* Hash pointer */
1518 daddr bno;
1519
1520 jdbg("MAX_BLOCKS=%D\n", (long)MAX_BLOCKS);
1521 jdbg("CHNK_CHARS=%D\n", (long)CHNK_CHARS);
1522 jdbg("BLK_CHNKS=%D\n", (long)BLK_CHNKS);
1523 #ifdef MALLOC_CACHE
1524 if (b_cache == NULL) {
1525 b_cache = (Block *) calloc((size_t)NBUF,sizeof(Block));
1526 if (b_cache == NULL) {
1527 error("cannot allocate buffer cache");
1528 /* NOTREACHED */
1529 }
1530 }
1531 #endif /* MALLOC_CACHE */
1532
1533 for (bp = b_cache, bno = NBUF; bno-- > 0; bp++) {
1534 bp->b_dirty = NO;
1535 bp->b_bno = bno;
1536 if (l_block == NULL)
1537 l_block = bp;
1538 bp->b_LRUprev = NULL;
1539 bp->b_LRUnext = f_block;
1540 if (f_block != NULL)
1541 f_block->b_LRUprev = bp;
1542 f_block = bp;
1543
1544 bp->b_HASHnext = *(hp = &bht[B_HASH(bno)]);
1545 *hp = bp;
1546 }
1547 }
1548
1549 void
1550 SyncTmp(void)
1551 {
1552 Block *b;
1553 #ifdef MSDOS
1554 daddr bno = 0;
1555
1556 /* sync the blocks in order, for file systems that don't allow
1557 * holes (MSDOS). Perhaps this benefits floppy-based file systems.
1558 */
1559 for (bno = 0; bno < next_bno; bno++) {
1560 if ((b = lookup_block(bno)) != NULL && b->b_dirty) {
1561 blkio(b, (JSSIZE_T (*)(int, void *, JRWSIZE_T))write);
1562 b->b_dirty = NO;
1563 }
1564 }
1565 #else /* !MSDOS */
1566 for (b = f_block; b != NULL; b = b->b_LRUnext)
1567 if (b->b_dirty) {
1568 blkio(b, (JSSIZE_T (*)(int, void *, JRWSIZE_T))write);
1569 b->b_dirty = NO;
1570 }
1571 #endif /* !MSDOS */
1572 }
1573
1574 private Block *
1575 lookup_block(daddr bno)
1576 {
1577 Block *bp;
1578
1579 for (bp = bht[B_HASH(bno)]; bp != NULL; bp = bp->b_HASHnext)
1580 if (bp->b_bno == bno)
1581 break;
1582 return bp;
1583 }
1584
1585 private void
1586 LRUunlink(Block *b)
1587 {
1588 if (b->b_LRUprev == NULL)
1589 f_block = b->b_LRUnext;
1590 else
1591 b->b_LRUprev->b_LRUnext = b->b_LRUnext;
1592 if (b->b_LRUnext == NULL)
1593 l_block = b->b_LRUprev;
1594 else
1595 b->b_LRUnext->b_LRUprev = b->b_LRUprev;
1596 }
1597
1598 private Block *
1599 b_unlink(Block *bp)
1600 {
1601 Block *hp,
1602 *prev = NULL;
1603
1604 LRUunlink(bp);
1605 /* Now that we have the block, we remove it from its position
1606 * in the hash table, so we can THEN put it somewhere else with
1607 * it's new block assignment.
1608 */
1609 for (hp = bht[B_HASH(bp->b_bno)]; hp != NULL; prev = hp, hp = hp->b_HASHnext)
1610 if (hp == bp)
1611 break;
1612 if (hp == NULL) {
1613 writef("\rBlock %ld missing!", (long)bp->b_bno);
1614 finish(0);
1615 }
1616 if (prev)
1617 prev->b_HASHnext = hp->b_HASHnext;
1618 else
1619 bht[B_HASH(bp->b_bno)] = hp->b_HASHnext;
1620
1621 if (bp->b_dirty) { /* do, now, the delayed write */
1622 blkio(bp, (JSSIZE_T (*)(int, void *, JRWSIZE_T))write);
1623 bp->b_dirty = NO;
1624 }
1625
1626 return bp;
1627 }
1628
1629 /* Get a block which contains at least part of the line with the address
1630 * atl. Returns a pointer to the block and sets the global variable
1631 * nleft (number of good characters left in the buffer).
1632 */
1633
1634 private char *
1635 getblock(daddr atl, jbool IsWrite)
1636 {
1637 daddr bno,
1638 off;
1639 Block *bp;
1640 static Block *lastb = NULL;
1641
1642 bno = da_to_bno(atl);
1643 off = da_to_off(atl);
1644 /* We don't allow block number MAX_BLOCKS-1 to be used because
1645 * NOWHERE_DADDR and NOTYET_DADDR must not be valid disk references,
1646 * and we want to prevent space overflow from being undetected
1647 * through arithmetic overflow.
1648 */
1649 if (bno >= MAX_BLOCKS-1) {
1650 error("Tmp file too large for line %D bno %D, max is %D. Get help!", (long)atl, (long)bno, (long)(MAX_BLOCKS-1));
1651 /* NOTREACHED */
1652 }
1653 nleft = JBUFSIZ - off;
1654 if (lastb != NULL && lastb->b_bno == bno) {
1655 bp = lastb; /* same as last time */
1656 } else if ((bp = lookup_block(bno)) != NULL) {
1657 /* The requested block already lives in memory, so we move
1658 * it to the end of the LRU list (making it Most Recently Used)
1659 * and then return a pointer to it.
1660 */
1661 if (bp != l_block) {
1662 LRUunlink(bp);
1663 if (l_block == NULL)
1664 f_block = bp;
1665 else
1666 l_block->b_LRUnext = bp;
1667 bp->b_LRUprev = l_block;
1668 l_block = bp;
1669 bp->b_LRUnext = NULL;
1670 }
1671 if (bno >= next_bno)
1672 next_bno = bno + 1;
1673 } else {
1674 /* The block we want doesn't reside in memory so we take the
1675 * least recently used clean block (if there is one) and use
1676 * it.
1677 */
1678 bp = f_block;
1679 if (bp->b_dirty) /* The best block is dirty ... */
1680 SyncTmp();
1681
1682 bp = b_unlink(bp);
1683 if (l_block == NULL)
1684 f_block = bp;
1685 else
1686 l_block->b_LRUnext = bp; /* Place it at the end ... */
1687 bp->b_LRUprev = l_block;
1688 l_block = bp;
1689 bp->b_LRUnext = NULL; /* so it's Most Recently Used */
1690
1691 bp->b_dirty = NO;
1692 bp->b_bno = bno;
1693 bp->b_HASHnext = bht[B_HASH(bno)];
1694 bht[B_HASH(bno)] = bp;
1695
1696 /* Get the current contents of the block UNLESS this is a new
1697 * block that's never been looked at before, i.e., it's past
1698 * the end of the tmp file.
1699 */
1700
1701 if (bno < next_bno)
1702 blkio(bp, read);
1703 else
1704 next_bno = bno + 1;
1705 }
1706 lastb = bp;
1707 bp->b_dirty |= IsWrite;
1708 return bp->b_buf + off;
1709 }
1710
1711 char *
1712 lbptr(LinePtr line)
1713 {
1714 return getblock(line->l_dline, NO);
1715 }
1716
1717 /* save the current contents of linebuf, if it has changed */
1718
1719 void
1720 lsave(void)
1721 {
1722 if (curbuf == NULL || !DOLsave) /* Nothing modified recently */
1723 return;
1724
1725 if (strcmp(lbptr(curline), linebuf) != 0)
1726 SavLine(curline, linebuf); /* Put linebuf on the disk. */
1727 DOLsave = NO;
1728 }
1729
1730 /* build backup file name, also used by SetBuf */
1731 void
1732 backup_name(const char *fname, const char *btype,
1733 char *bfname, size_t bfnamesize)
1734 {
1735 const char *s = strrchr(fname, '/');
1736 size_t dirlen = (s == NULL)? 0 : s + 1 - fname;
1737
1738 jamstrsub(bfname, fname, bfnamesize);
1739 swritef(bfname+dirlen, (size_t) (bfnamesize - dirlen), "#%s%s~",
1740 fname+dirlen, btype);
1741 }
1742
1743 #ifdef BACKUPFILES
1744 private void
1745 file_backup(char *fname)
1746 {
1747 # ifndef MSFILESYSTEM
1748 JSSIZE_T rr;
1749 int
1750 ffd,
1751 bffd = 0; /* avoid uninitialized complaint from gcc -W */
1752 char
1753 buf[JBUFSIZ],
1754 bfname[FILESIZE];
1755
1756 backup_name(fname, "", bfname, sizeof(bfname));
1757
1758 if ((ffd = open(fname, O_RDONLY | O_BINARY | O_CLOEXEC)) < 0)
1759 return; /* cannot open original file: nothing to backup, we assume */
1760
1761 /* create backup file with same mode as input file */
1762 {
1763 # ifdef MAC
1764 jmode_t mode = CreatMode; /* dummy */
1765 # else
1766 struct stat statbuf;
1767 jmode_t mode = fstat(ffd, &statbuf) != 0?
1768 (jmode_t)CreatMode : statbuf.st_mode;
1769 # endif
1770
1771 /* Unlink the pathname before creating. It may have been
1772 * created by someone else, or worse it may be linked or
1773 * symlinked somewhere else, none of which we want to
1774 * overwrite. There is still a possible race-condition,
1775 * so we need to use O_EXCL if we can.
1776 */
1777 if ((unlink(bfname) < 0 && errno != ENOENT)
1778 # ifdef O_EXCL
1779 || (bffd = open(bfname, O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC, mode)) < 0
1780 # else
1781 || (bffd = creat(bfname, mode)) < 0
1782 # endif
1783 ) {
1784 int e = errno;
1785
1786 (void) close(ffd);
1787 complain("[cannot create backup \"%s\": %d %s]",
1788 bfname, e, strerror(e));
1789 /* NOTREACHED */
1790 }
1791 }
1792
1793 /* copy the contents */
1794 while ((rr = read(ffd, buf, sizeof(buf))) > 0) {
1795 char *p = buf;
1796
1797 while (rr > 0) {
1798 JSSIZE_T wr = write(bffd, p, (size_t) rr);
1799
1800 if (wr < 0) {
1801 int e = errno;
1802
1803 close(bffd);
1804 close(ffd);
1805 complain("[error writing backup: %d %s]", e, strerror(e));
1806 /* NOTREACHED */
1807 }
1808 p += wr;
1809 rr -= wr;
1810 }
1811 }
1812
1813 if (rr < 0 || close(ffd) != 0) {
1814 complain("[error reading \"%s\": %d %s]", fname, errno, strerror(errno));
1815 /* NOTREACHED */
1816 }
1817 # ifdef USE_FSYNC
1818 if (fsync(bffd) != 0) {
1819 int e = errno;
1820
1821 (void) close(bffd);
1822 complain("[error fsyncing backup: %d %s]", e, strerror(e));
1823 /* NOTREACHED */
1824 }
1825 # endif /* USE_FSYNC */
1826 if (close(bffd) != 0) {
1827 complain("[error closing backup: %d %s]", errno, strerror(errno));
1828 /* NOTREACHED */
1829 }
1830 # else /* MSFILESYSTEM */
1831 /* This code is designed to fit withing the 8.3 limitation of
1832 * MSDOS ("FAT" -- huh!) file systems. Even though newer versions
1833 * of these APIs (Win32) may support longer file names, we may still
1834 * be dealing with a FAT file system.
1835 */
1836 char *dot,
1837 *slash,
1838 tmp[FILESIZE];
1839
1840 if (access(fname, 0) < 0)
1841 return; /* cannot open original file: nothing to backup, we assume */
1842
1843 strcpy(tmp, fname);
1844 slash = (char *)jbasename(tmp);
1845 if ((dot = strrchr(slash, '.')) != NULL) {
1846 if (stricmp(dot,".bak") == 0)
1847 return; /* don't rename .bak to .bak */
1848 *dot = '\0';
1849 }
1850 strcat(tmp, ".bak");
1851 unlink(tmp);
1852 if (rename(fname, tmp) != 0) {
1853 complain("[cannot rename to \"%s\": %s]", tmp, strerror(errno));
1854 /* NOTREACHED */
1855 }
1856 # endif /* MSFILESYSTEM */
1857 }
1858 #endif /* BACKUPFILES */