update to 1.01
[nvi.git] / common / exf.c
blob79fad29ceb74c7fb015644854a6f7fa1ffd10f67
1 /*-
2 * Copyright (c) 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * %sccs.include.redist.c%
6 */
8 #ifndef lint
9 static char sccsid[] = "$Id: exf.c,v 8.65 1994/01/11 22:59:54 bostic Exp $ (Berkeley) $Date: 1994/01/11 22:59:54 $";
10 #endif /* not lint */
12 #include <sys/param.h>
13 #include <sys/stat.h>
16 * We include <sys/file.h>, because the flock(2) #defines were
17 * found there on historical systems. We also include <fcntl.h>
18 * because the open(2) #defines are found there on newer systems.
20 #include <sys/file.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
28 #include "vi.h"
29 #include "excmd.h"
30 #include "pathnames.h"
33 * file_add --
34 * Insert a file name into the FREF list, if it doesn't already
35 * appear in it.
37 * !!!
38 * The "if it doesn't already appear" changes vi's semantics slightly. If
39 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
40 * will reflect the line/column of the previous edit session. Historic nvi
41 * did not do this. The change is a logical extension of the change where
42 * vi now remembers the last location in any file that it has ever edited,
43 * not just the previously edited file.
45 FREF *
46 file_add(sp, frp_append, name, ignore)
47 SCR *sp;
48 FREF *frp_append;
49 CHAR_T *name;
50 int ignore;
52 FREF *frp;
53 char *p;
56 * Return it if it already exists. Note that we test against the
57 * user's current name, whatever that happens to be, including if
58 * it's a temporary file. If the user is trying to set an argument
59 * list, the ignore argument will be on -- if we're ignoring the
60 * file turn off the ignore bit, so it's back in the argument list.
62 if (name != NULL)
63 for (frp = sp->frefq.cqh_first;
64 frp != (FREF *)&sp->frefq; frp = frp->q.cqe_next)
65 if ((p = FILENAME(frp)) != NULL && !strcmp(p, name)) {
66 if (!ignore)
67 F_CLR(frp, FR_IGNORE);
68 return (frp);
71 /* Allocate and initialize the FREF structure. */
72 CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
73 if (frp == NULL)
74 return (NULL);
77 * If no file name specified, or if the file name is a request
78 * for something temporary, file_init() will allocate the file
79 * name. Temporary files are always ignored.
81 #define TEMPORARY_FILE_STRING "/tmp"
82 if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
83 (frp->name = strdup(name)) == NULL) {
84 FREE(frp, sizeof(FREF));
85 msgq(sp, M_SYSERR, NULL);
86 return (NULL);
89 /* Only the initial argument list is "remembered". */
90 if (ignore)
91 F_SET(frp, FR_IGNORE);
93 /* Append into the chain of file names. */
94 if (frp_append != NULL) {
95 CIRCLEQ_INSERT_AFTER(&sp->frefq, frp_append, frp, q);
96 } else
97 CIRCLEQ_INSERT_TAIL(&sp->frefq, frp, q);
99 return (frp);
103 * file_first --
104 * Return the first file name for editing, if any.
106 FREF *
107 file_first(sp)
108 SCR *sp;
110 FREF *frp;
112 /* Return the first file name. */
113 for (frp = sp->frefq.cqh_first;
114 frp != (FREF *)&sp->frefq; frp = frp->q.cqe_next)
115 if (!F_ISSET(frp, FR_IGNORE))
116 return (frp);
117 return (NULL);
121 * file_next --
122 * Return the next file name, if any.
124 FREF *
125 file_next(sp, frp)
126 SCR *sp;
127 FREF *frp;
129 while ((frp = frp->q.cqe_next) != (FREF *)&sp->frefq)
130 if (!F_ISSET(frp, FR_IGNORE))
131 return (frp);
132 return (NULL);
136 * file_prev --
137 * Return the previous file name, if any.
139 FREF *
140 file_prev(sp, frp)
141 SCR *sp;
142 FREF *frp;
144 while ((frp = frp->q.cqe_prev) != (FREF *)&sp->frefq)
145 if (!F_ISSET(frp, FR_IGNORE))
146 return (frp);
147 return (NULL);
151 * file_unedited --
152 * Return if there are files that aren't ignored and are unedited.
154 FREF *
155 file_unedited(sp)
156 SCR *sp;
158 FREF *frp;
160 /* Return the next file name. */
161 for (frp = sp->frefq.cqh_first;
162 frp != (FREF *)&sp->frefq; frp = frp->q.cqe_next)
163 if (!F_ISSET(frp, FR_EDITED | FR_IGNORE))
164 return (frp);
165 return (NULL);
169 * file_init --
170 * Start editing a file, based on the FREF structure. If successsful,
171 * let go of any previous file. Don't release the previous file until
172 * absolutely sure we have the new one.
175 file_init(sp, frp, rcv_name, force)
176 SCR *sp;
177 FREF *frp;
178 char *rcv_name;
179 int force;
181 EXF *ep;
182 RECNOINFO oinfo;
183 struct stat sb;
184 size_t psize;
185 int fd;
186 char *p, *oname, tname[MAXPATHLEN];
189 * Required ep initialization:
190 * Flush the line caches.
191 * Default recover mail file fd to -1.
192 * Set initial EXF flag bits.
194 CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
195 ep->c_lno = ep->c_nlines = OOBLNO;
196 ep->rcv_fd = -1;
197 LIST_INIT(&ep->marks);
198 F_SET(ep, F_FIRSTMODIFY);
201 * If no name or backing file, create a backing temporary file, saving
202 * the temp file name so can later unlink it. Repoint the name to the
203 * temporary name (we display it to the user until they rename it).
204 * There are some games we play with the FR_FREE_TNAME and FR_NONAME
205 * flags (see ex/ex_file.c) to make sure that the temporary memory gets
206 * free'd up.
208 if ((oname = FILENAME(frp)) == NULL || stat(oname, &sb)) {
209 (void)snprintf(tname, sizeof(tname),
210 "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
211 if ((fd = mkstemp(tname)) == -1) {
212 msgq(sp, M_SYSERR, "Temporary file");
213 goto err;
215 (void)close(fd);
216 if ((frp->tname = strdup(tname)) == NULL) {
217 msgq(sp, M_SYSERR, NULL);
218 (void)unlink(tname);
219 goto err;
221 oname = frp->tname;
222 psize = 4 * 1024;
223 F_SET(frp, FR_NEWFILE);
224 } else {
225 /* Try to keep it at 10 pages or less per file. */
226 if (sb.st_size < 40 * 1024)
227 psize = 4 * 1024;
228 else if (sb.st_size < 320 * 1024)
229 psize = 32 * 1024;
230 else
231 psize = 64 * 1024;
233 frp->mtime = sb.st_mtime;
235 if (!S_ISREG(sb.st_mode))
236 msgq(sp, M_ERR,
237 "Warning: %s is not a regular file.", oname);
240 /* Set up recovery. */
241 memset(&oinfo, 0, sizeof(RECNOINFO));
242 oinfo.bval = '\n'; /* Always set. */
243 oinfo.psize = psize;
244 oinfo.flags = F_ISSET(sp->gp, G_SNAPSHOT) ? R_SNAPSHOT : 0;
245 if (rcv_name == NULL) {
246 if (rcv_tmp(sp, ep, FILENAME(frp)))
247 msgq(sp, M_ERR,
248 "Modifications not recoverable if the system crashes.");
249 else
250 oinfo.bfname = ep->rcv_path;
251 } else if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
252 msgq(sp, M_SYSERR, NULL);
253 goto err;
254 } else {
255 oinfo.bfname = ep->rcv_path;
256 F_SET(ep, F_MODIFIED | F_RCV_ON);
259 /* Open a db structure. */
260 if ((ep->db = dbopen(rcv_name == NULL ? oname : NULL,
261 O_NONBLOCK | O_RDONLY, DEFFILEMODE, DB_RECNO, &oinfo)) == NULL) {
262 msgq(sp, M_SYSERR, rcv_name == NULL ? oname : rcv_name);
263 goto err;
266 /* Init file marks. */
267 if (mark_init(sp, ep))
268 goto err;
270 /* Start logging. */
271 if (log_init(sp, ep))
272 goto err;
275 * The -R flag, or doing a "set readonly" during a session causes
276 * all files edited during the session (using an edit command, or
277 * even using tags) to be marked read-only. Changing the file name
278 * (see ex/ex_file.c), clears this flag.
280 * Otherwise, try and figure out if a file is readonly. This is a
281 * dangerous thing to do. The kernel is the only arbiter of whether
282 * or not a file is writeable, and the best that a user program can
283 * do is guess. Obvious loopholes are files that are on a file system
284 * mounted readonly (access catches this one on a few systems), or
285 * alternate protection mechanisms, ACL's for example, that we can't
286 * portably check. Lots of fun, and only here because users whined.
288 * !!!
289 * Historic vi displayed the readonly message if none of the file
290 * write bits were set, or if an an access(2) call on the path
291 * failed. This seems reasonable. If the file is mode 444, root
292 * users may want to know that the owner of the file did not expect
293 * it to be written.
295 * Historic vi set the readonly bit if no write bits were set for
296 * a file, even if the access call would have succeeded. This makes
297 * the superuser force the write even when vi expects that it will
298 * succeed. I'm less supportive of this semantic, but it's historic
299 * practice and the conservative approach to vi'ing files as root.
301 * It would be nice if there was some way to update this when the user
302 * does a "^Z; chmod ...". The problem is that we'd first have to
303 * distinguish between readonly bits set because of file permissions
304 * and those set for other reasons. That's not too hard, but deciding
305 * when to reevaluate the permissions is trickier. An alternative
306 * might be to turn off the readonly bit if the user forces a write
307 * and it succeeds.
309 * XXX
310 * Access(2) doesn't consider the effective uid/gid values. This
311 * probably isn't a problem for vi when it's running standalone.
313 if (O_ISSET(sp, O_READONLY) || !F_ISSET(frp, FR_NEWFILE) &&
314 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
315 access(FILENAME(frp), W_OK)))
316 F_SET(frp, FR_RDONLY);
317 else
318 F_CLR(frp, FR_RDONLY);
321 * Close the previous file; if that fails, close the new one
322 * and run for the border.
324 if (sp->ep != NULL && file_end(sp, sp->ep, force)) {
325 (void)file_end(sp, ep, 1);
326 goto err;
330 * 4.4BSD supports locking in the open call, other systems don't.
331 * Since the user can't interrupt us between the open and here,
332 * it's a don't care.
334 * !!!
335 * We need to distinguish a lock not being available for the file
336 * from the file system not supporting locking. Assume that EAGAIN
337 * or EWOULDBLOCK is the former. There isn't a portable way to do
338 * this.
340 * XXX
341 * The locking is flock(2) style, not fcntl(2). The latter is known
342 * to fail badly on some systems, and its only advantage is that it
343 * occasionally works over NFS.
345 if (flock(ep->db->fd(ep->db), LOCK_EX | LOCK_NB))
346 if (errno == EAGAIN || errno == EWOULDBLOCK) {
347 msgq(sp, M_INFO,
348 "%s already locked, session is read-only", oname);
349 F_SET(frp, FR_RDONLY);
350 } else
351 msgq(sp, M_VINFO, "%s cannot be locked", oname);
354 * Set the previous file pointer and the alternate file name to be
355 * the file we're about to discard.
357 * !!!
358 * If the current file was a temporary file, the call to file_end()
359 * unlinked it and free'd the name. So, there is no previous file,
360 * and there is no alternate file name. This matches historical
361 * practice, although in historical vi it could only happen as the
362 * result of the initial command, i.e. if vi was execute without a
363 * file name.
365 if (sp->frp != NULL) {
366 p = FILENAME(sp->frp);
367 if (p == NULL)
368 sp->p_frp = NULL;
369 else
370 sp->p_frp = sp->frp;
371 set_alt_name(sp, p);
374 /* The new file has now been officially edited. */
375 F_SET(frp, FR_EDITED);
377 /* Switch... */
378 ++ep->refcnt;
379 sp->ep = ep;
380 sp->frp = frp;
381 return (0);
383 err: if (frp->tname != NULL) {
384 (void)unlink(frp->tname);
385 free(frp->tname);
386 frp->tname = NULL;
388 if (ep->rcv_path != NULL) {
389 free(ep->rcv_path);
390 ep->rcv_path = NULL;
392 FREE(ep, sizeof(EXF));
393 return (1);
397 * file_end --
398 * Stop editing a file.
401 file_end(sp, ep, force)
402 SCR *sp;
403 EXF *ep;
404 int force;
406 FREF *frp;
410 * sp->ep MAY NOT BE THE SAME AS THE ARGUMENT ep, SO DON'T USE IT!
412 * Save the cursor location.
414 * XXX
415 * It would be cleaner to do this somewhere else, but by the time
416 * ex or vi knows that we're changing files it's already happened.
418 frp = sp->frp;
419 frp->lno = sp->lno;
420 frp->cno = sp->cno;
421 F_SET(frp, FR_CURSORSET);
423 /* If multiply referenced, just decrement the count and return. */
424 if (--ep->refcnt != 0)
425 return (0);
427 /* Close the db structure. */
428 if (ep->db->close != NULL && ep->db->close(ep->db) && !force) {
429 msgq(sp, M_ERR,
430 "%s: close: %s", FILENAME(frp), strerror(errno));
431 ++ep->refcnt;
432 return (1);
435 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
437 /* Stop logging. */
438 (void)log_end(sp, ep);
440 /* Free up any marks. */
441 mark_end(sp, ep);
444 * Delete the recovery files, close the open descriptor,
445 * free recovery memory.
447 if (!F_ISSET(ep, F_RCV_NORM)) {
448 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
449 msgq(sp, M_ERR,
450 "%s: remove: %s", ep->rcv_path, strerror(errno));
451 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
452 msgq(sp, M_ERR,
453 "%s: remove: %s", ep->rcv_mpath, strerror(errno));
455 if (ep->rcv_fd != -1)
456 (void)close(ep->rcv_fd);
457 if (ep->rcv_path != NULL)
458 free(ep->rcv_path);
459 if (ep->rcv_mpath != NULL)
460 free(ep->rcv_mpath);
463 * Unlink any temporary file, file name. We also turn on the
464 * ignore bit at this point, because it was a "created" file,
465 * not an argument file.
467 if (frp->tname != NULL) {
468 if (unlink(frp->tname))
469 msgq(sp, M_ERR,
470 "%s: remove: %s", frp->tname, strerror(errno));
471 free(frp->tname);
472 frp->tname = NULL;
474 if (frp->name == NULL && frp->cname == NULL)
475 F_SET(frp, FR_IGNORE);
477 /* Free the EXF structure. */
478 FREE(ep, sizeof(EXF));
479 return (0);
483 * file_write --
484 * Write the file to disk. Historic vi had fairly convoluted
485 * semantics for whether or not writes would happen. That's
486 * why all the flags.
489 file_write(sp, ep, fm, tm, name, flags)
490 SCR *sp;
491 EXF *ep;
492 MARK *fm, *tm;
493 char *name;
494 int flags;
496 struct stat sb;
497 FILE *fp;
498 FREF *frp;
499 MARK from, to;
500 u_long nlno, nch;
501 int fd, oflags, rval;
502 char *msg;
505 * Don't permit writing to temporary files. The problem is that
506 * if it's a temp file, and the user does ":wq", we write and quit,
507 * unlinking the temporary file. Not what the user had in mind
508 * at all. This test cannot be forced.
510 frp = sp->frp;
511 if (name == NULL && frp->cname == NULL && frp->name == NULL) {
512 msgq(sp, M_ERR, "No filename to which to write.");
513 return (1);
516 /* Can't write files marked read-only, unless forced. */
517 if (!LF_ISSET(FS_FORCE) &&
518 name == NULL && F_ISSET(frp, FR_RDONLY)) {
519 if (LF_ISSET(FS_POSSIBLE))
520 msgq(sp, M_ERR,
521 "Read-only file, not written; use ! to override.");
522 else
523 msgq(sp, M_ERR,
524 "Read-only file, not written.");
525 return (1);
528 /* If not forced, not appending, and "writeany" not set ... */
529 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
530 /* Don't overwrite anything but the original file. */
531 if (name != NULL) {
532 if (!stat(name, &sb))
533 goto exists;
534 } else if (frp->cname != NULL &&
535 !F_ISSET(frp, FR_CHANGEWRITE) && !stat(frp->cname, &sb)) {
536 name = frp->cname;
537 exists: if (LF_ISSET(FS_POSSIBLE))
538 msgq(sp, M_ERR,
539 "%s exists, not written; use ! to override.", name);
540 else
541 msgq(sp, M_ERR,
542 "%s exists, not written.", name);
543 return (1);
547 * Don't write part of any existing file. Only test for the
548 * original file, the previous test catches anything else.
550 if (!LF_ISSET(FS_ALL) && name == NULL &&
551 frp->cname == NULL && !stat(frp->name, &sb)) {
552 if (LF_ISSET(FS_POSSIBLE))
553 msgq(sp, M_ERR,
554 "Use ! to write a partial file.");
555 else
556 msgq(sp, M_ERR, "Partial file, not written.");
557 return (1);
562 * Figure out if the file already exists -- if it doesn't, we display
563 * the "new file" message. The stat might not be necessary, but we
564 * just repeat it because it's easier than hacking the previous tests.
565 * The information is only used for the user message and modification
566 * time test, so we can ignore the obvious race condition.
568 * If the user is overwriting a file other than the original file, and
569 * O_WRITEANY was what got us here (neither force nor append was set),
570 * display the "existing file" messsage. Since the FR_CHANGEWRITE flag
571 * is set on a successful write, the message only appears once when the
572 * user changes a file name. This is historic practice.
574 * One final test. If we're not forcing or appending, and we have a
575 * saved modification time, stop the user if it's been written since
576 * we last edited or wrote it, and make them force it.
578 if (stat(name == NULL ? FILENAME(frp) : name, &sb))
579 msg = ": new file";
580 else {
581 msg = "";
582 if (!LF_ISSET(FS_FORCE | FS_APPEND)) {
583 if (frp->mtime && sb.st_mtime > frp->mtime) {
584 msgq(sp, M_ERR,
585 "%s: file modified more recently than this copy%s.",
586 name == NULL ? frp->name : name,
587 LF_ISSET(FS_POSSIBLE) ?
588 "; use ! to override" : "");
589 return (1);
591 if (name != NULL ||
592 !F_ISSET(frp, FR_CHANGEWRITE) && frp->cname != NULL)
593 msg = ": existing file";
597 /* We no longer care where the name came from. */
598 if (name == NULL)
599 name = FILENAME(frp);
601 /* Set flags to either append or truncate. */
602 oflags = O_CREAT | O_WRONLY;
603 if (LF_ISSET(FS_APPEND))
604 oflags |= O_APPEND;
605 else
606 oflags |= O_TRUNC;
608 /* Open the file. */
609 if ((fd = open(name, oflags, DEFFILEMODE)) < 0) {
610 msgq(sp, M_SYSERR, name);
611 return (1);
614 /* Use stdio for buffering. */
615 if ((fp = fdopen(fd, "w")) == NULL) {
616 (void)close(fd);
617 msgq(sp, M_SYSERR, name);
618 return (1);
621 /* Build fake addresses, if necessary. */
622 if (fm == NULL) {
623 from.lno = 1;
624 from.cno = 0;
625 fm = &from;
626 if (file_lline(sp, ep, &to.lno))
627 return (1);
628 to.cno = 0;
629 tm = &to;
632 /* Write the file. */
633 rval = ex_writefp(sp, ep, name, fp, fm, tm, &nlno, &nch);
636 * Save the new last modification time -- even if the write fails
637 * we re-init the time if we wrote anything. That way the user can
638 * clean up the disk and rewrite without having to force it.
640 if (nlno || nch)
641 frp->mtime = stat(name, &sb) ? 0 : sb.st_mtime;
643 /* If the write failed, complain loudly. */
644 if (rval) {
645 if (!LF_ISSET(FS_APPEND))
646 msgq(sp, M_ERR, "%s: WARNING: file truncated!", name);
647 return (1);
651 * Once we've actually written the file, it doesn't matter that the
652 * file name was changed -- if it was, we've already whacked it.
654 F_SET(frp, FR_CHANGEWRITE);
656 /* If wrote the entire file, clear the modified bit. */
657 if (LF_ISSET(FS_ALL))
658 F_CLR(ep, F_MODIFIED);
660 msgq(sp, M_INFO, "%s%s: %lu line%s, %lu characters.",
661 name, msg, nlno, nlno == 1 ? "" : "s", nch);
663 return (0);