2 * Copyright (c) 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1992, 1993, 1994, 1995, 1996
5 * Keith Bostic. All rights reserved.
7 * See the LICENSE file for redistribution information.
13 static const char sccsid
[] = "$Id: exf.c,v 10.56 2000/07/14 14:29:15 skimo Exp $ (Berkeley) $Date: 2000/07/14 14:29:15 $";
16 #include <sys/param.h>
17 #include <sys/types.h> /* XXX: param.h may not have included types.h */
18 #include <sys/queue.h>
22 * We include <sys/file.h>, because the flock(2) and open(2) #defines
23 * were found there on historical systems. We also include <fcntl.h>
24 * because the open(2) #defines are found there on newer systems.
28 #include <bitstring.h>
41 static int file_backup
__P((SCR
*, char *, char *));
42 static void file_cinit
__P((SCR
*));
43 static void file_comment
__P((SCR
*));
44 static int file_spath
__P((SCR
*, FREF
*, struct stat
*, int *));
48 * Insert a file name into the FREF list, if it doesn't already
52 * The "if it doesn't already appear" changes vi's semantics slightly. If
53 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
54 * will reflect the line/column of the previous edit session. Historic nvi
55 * did not do this. The change is a logical extension of the change where
56 * vi now remembers the last location in any file that it has ever edited,
57 * not just the previously edited file.
59 * PUBLIC: FREF *file_add __P((SCR *, char *));
70 * Return it if it already exists. Note that we test against the
71 * user's name, whatever that happens to be, including if it's a
74 * If the user added a file but was unable to initialize it, there
75 * can be file list entries where the name field is NULL. Discard
76 * them the next time we see them.
80 for (frp
= gp
->frefq
.cqh_first
;
81 frp
!= (FREF
*)&gp
->frefq
; frp
= frp
->q
.cqe_next
) {
82 if (frp
->name
== NULL
) {
83 tfrp
= frp
->q
.cqe_next
;
84 CIRCLEQ_REMOVE(&gp
->frefq
, frp
, q
);
85 if (frp
->name
!= NULL
)
91 if (!strcmp(frp
->name
, name
))
95 /* Allocate and initialize the FREF structure. */
96 CALLOC(sp
, frp
, FREF
*, 1, sizeof(FREF
));
101 * If no file name specified, or if the file name is a request
102 * for something temporary, file_init() will allocate the file
103 * name. Temporary files are always ignored.
105 if (name
!= NULL
&& strcmp(name
, TEMPORARY_FILE_STRING
) &&
106 (frp
->name
= strdup(name
)) == NULL
) {
108 msgq(sp
, M_SYSERR
, NULL
);
112 /* Append into the chain of file names. */
113 CIRCLEQ_INSERT_TAIL(&gp
->frefq
, frp
, q
);
120 * Start editing a file, based on the FREF structure. If successsful,
121 * let go of any previous file. Don't release the previous file until
122 * absolutely sure we have the new one.
124 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
127 file_init(sp
, frp
, rcv_name
, flags
)
136 int fd
, exists
, open_err
, readonly
;
137 char *oname
, tname
[MAXPATHLEN
];
139 open_err
= readonly
= 0;
142 * If the file is a recovery file, let the recovery code handle it.
143 * Clear the FR_RECOVER flag first -- the recovery code does set up,
144 * and then calls us! If the recovery call fails, it's probably
145 * because the named file doesn't exist. So, move boldly forward,
146 * presuming that there's an error message the user will get to see.
148 if (F_ISSET(frp
, FR_RECOVER
)) {
149 F_CLR(frp
, FR_RECOVER
);
150 return (rcv_read(sp
, frp
));
154 * Required FRP initialization; the only flag we keep is the
155 * cursor information.
157 F_CLR(frp
, ~FR_CURSORSET
);
160 * Scan the user's path to find the file that we're going to
163 if (file_spath(sp
, frp
, &sb
, &exists
))
167 * Check whether we already have this file opened in some
172 for (exfp
= sp
->gp
->exfq
.cqh_first
;
173 exfp
!= (EXF
*)&sp
->gp
->exfq
; exfp
= exfp
->q
.cqe_next
) {
174 if (exfp
->mdev
== sb
.st_dev
&&
175 exfp
->minode
== sb
.st_ino
&&
176 (exfp
!= sp
->ep
|| exfp
->refcnt
> 1)) {
184 * Required EXF initialization:
185 * Flush the line caches.
186 * Default recover mail file fd to -1.
187 * Set initial EXF flag bits.
189 CALLOC_RET(sp
, ep
, EXF
*, 1, sizeof(EXF
));
190 ep
->c_lno
= ep
->c_nlines
= OOBLNO
;
191 ep
->rcv_fd
= ep
->fcntl_fd
= -1;
192 F_SET(ep
, F_FIRSTMODIFY
);
195 * If no name or backing file, for whatever reason, create a backing
196 * temporary file, saving the temp file name so we can later unlink
197 * it. If the user never named this file, copy the temporary file name
198 * to the real name (we display that until the user renames it).
201 if (LF_ISSET(FS_OPENERR
) || oname
== NULL
|| !exists
) {
202 if (opts_empty(sp
, O_DIRECTORY
, 0))
204 (void)snprintf(tname
, sizeof(tname
),
205 "%s/vi.XXXXXX", O_STR(sp
, O_DIRECTORY
));
206 if ((fd
= mkstemp(tname
)) == -1) {
208 "237|Unable to create temporary file");
213 if (frp
->name
== NULL
)
214 F_SET(frp
, FR_TMPFILE
);
215 if ((frp
->tname
= strdup(tname
)) == NULL
||
216 (frp
->name
== NULL
&&
217 (frp
->name
= strdup(tname
)) == NULL
)) {
218 if (frp
->tname
!= NULL
) {
221 msgq(sp
, M_SYSERR
, NULL
);
227 if (!LF_ISSET(FS_OPENERR
))
228 F_SET(frp
, FR_NEWFILE
);
234 * A seat of the pants calculation: try to keep the file in
235 * 15 pages or less. Don't use a page size larger than 10K
236 * (vi should have good locality) or smaller than 1K.
238 psize
= ((sb
.st_size
/ 15) + 1023) / 1024;
246 ep
->mdev
= sb
.st_dev
;
247 ep
->minode
= sb
.st_ino
;
249 ep
->mtime
= sb
.st_mtime
;
251 if (!S_ISREG(sb
.st_mode
))
252 msgq_str(sp
, M_ERR
, oname
,
253 "238|Warning: %s is not a regular file");
256 /* Set up recovery. */
257 if (rcv_name
== NULL
) {
258 /* ep->rcv_path NULL if rcv_tmp fails */
259 rcv_tmp(sp
, ep
, frp
->name
);
261 if ((ep
->rcv_path
= strdup(rcv_name
)) == NULL
) {
262 msgq(sp
, M_SYSERR
, NULL
);
265 F_SET(ep
, F_MODIFIED
);
268 /* Open a db structure. */
269 if ((sp
->db_error
= db_create(&ep
->db
, sp
->gp
->env
, 0)) != 0) {
271 fprintf(stderr
, "db_create %d\n", sp
->db_error
);
275 ep
->db
->set_re_delim(ep
->db
, '\n'); /* Always set. */
276 ep
->db
->set_pagesize(ep
->db
, psize
);
277 ep
->db
->set_flags(ep
->db
, DB_RENUMBER
|
278 (F_ISSET(sp
->gp
, G_SNAPSHOT
) ? DB_SNAPSHOT
: 0));
279 if (rcv_name
== NULL
)
280 ep
->db
->set_re_source(ep
->db
, oname
);
282 if ((sp
->db_error
= ep
->db
->open(ep
->db
, ep
->rcv_path
, NULL
,
283 DB_RECNO
, ((rcv_name
== 0) ? DB_TRUNCATE
: 0),
284 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
)) != 0) {
286 M_DBERR
, rcv_name
== NULL
? oname
: rcv_name
, "%s");
289 * Historically, vi permitted users to edit files that couldn't
290 * be read. This isn't useful for single files from a command
291 * line, but it's quite useful for "vi *.c", since you can skip
292 * past files that you can't read.
295 ep
->db
= NULL
; /* Don't close it */
300 * Do the remaining things that can cause failure of the new file,
301 * mark and logging initialization.
303 if (mark_init(sp
, ep
) || log_init(sp
, ep
))
308 * Set the alternate file name to be the file we're discarding.
311 * Temporary files can't become alternate files, so there's no file
312 * name. This matches historical practice, although it could only
313 * happen in historical vi as the result of the initial command, i.e.
314 * if vi was executed without a file name.
316 if (LF_ISSET(FS_SETALT
))
317 set_alt_name(sp
, sp
->frp
== NULL
||
318 F_ISSET(sp
->frp
, FR_TMPFILE
) ? NULL
: sp
->frp
->name
);
321 * Close the previous file; if that fails, close the new one and run
325 * There's a nasty special case. If the user edits a temporary file,
326 * and then does an ":e! %", we need to re-initialize the backing
327 * file, but we can't change the name. (It's worse -- we're dealing
328 * with *names* here, we can't even detect that it happened.) Set a
329 * flag so that the file_end routine ignores the backing information
330 * of the old file if it happens to be the same as the new one.
333 * Side-effect: after the call to file_end(), sp->frp may be NULL.
335 if (sp
->ep
!= NULL
) {
336 F_SET(frp
, FR_DONTDELETE
);
337 if (file_end(sp
, NULL
, LF_ISSET(FS_FORCE
))) {
338 (void)file_end(sp
, ep
, 1);
341 F_CLR(frp
, FR_DONTDELETE
);
345 * Lock the file; if it's a recovery file, it should already be
346 * locked. Note, we acquire the lock after the previous file
347 * has been ended, so that we don't get an "already locked" error
351 * While the user can't interrupt us between the open and here,
352 * there's a race between the dbopen() and the lock. Not much
353 * we can do about it.
356 * We don't make a big deal of not being able to lock the file. As
357 * locking rarely works over NFS, and often fails if the file was
358 * mmap(2)'d, it's far too common to do anything like print an error
359 * message, let alone make the file readonly. At some future time,
360 * when locking is a little more reliable, this should change to be
363 if (rcv_name
== NULL
&& ep
->refcnt
== 0) {
364 if ((ep
->fd
= open(oname
, O_RDONLY
)) == -1)
367 /* DB 3 appears to not return the fd of re_source
368 if (ep->db->fd(ep->db, &fd) != 0)
372 switch (file_lock(sp
, oname
, &ep
->fcntl_fd
, ep
->fd
, 0)) {
375 F_SET(frp
, FR_UNLOCKED
);
379 msgq_str(sp
, M_INFO
, oname
,
380 "239|%s already locked, session is read-only");
388 * Historically, the readonly edit option was set per edit buffer in
389 * vi, unless the -R command-line option was specified or the program
390 * was executed as "view". (Well, to be truthful, if the letter 'w'
391 * occurred anywhere in the program name, but let's not get into that.)
392 * So, the persistant readonly state has to be stored in the screen
393 * structure, and the edit option value toggles with the contents of
394 * the edit buffer. If the persistant readonly flag is set, set the
395 * readonly edit option.
397 * Otherwise, try and figure out if a file is readonly. This is a
398 * dangerous thing to do. The kernel is the only arbiter of whether
399 * or not a file is writeable, and the best that a user program can
400 * do is guess. Obvious loopholes are files that are on a file system
401 * mounted readonly (access catches this one on a few systems), or
402 * alternate protection mechanisms, ACL's for example, that we can't
403 * portably check. Lots of fun, and only here because users whined.
406 * Historic vi displayed the readonly message if none of the file
407 * write bits were set, or if an an access(2) call on the path
408 * failed. This seems reasonable. If the file is mode 444, root
409 * users may want to know that the owner of the file did not expect
412 * Historic vi set the readonly bit if no write bits were set for
413 * a file, even if the access call would have succeeded. This makes
414 * the superuser force the write even when vi expects that it will
415 * succeed. I'm less supportive of this semantic, but it's historic
416 * practice and the conservative approach to vi'ing files as root.
418 * It would be nice if there was some way to update this when the user
419 * does a "^Z; chmod ...". The problem is that we'd first have to
420 * distinguish between readonly bits set because of file permissions
421 * and those set for other reasons. That's not too hard, but deciding
422 * when to reevaluate the permissions is trickier. An alternative
423 * might be to turn off the readonly bit if the user forces a write
427 * Access(2) doesn't consider the effective uid/gid values. This
428 * probably isn't a problem for vi when it's running standalone.
430 if (readonly
|| F_ISSET(sp
, SC_READONLY
) ||
431 (!F_ISSET(frp
, FR_NEWFILE
) &&
432 (!(sb
.st_mode
& (S_IWUSR
| S_IWGRP
| S_IWOTH
)) ||
433 access(frp
->name
, W_OK
))))
434 O_SET(sp
, O_READONLY
);
436 O_CLR(sp
, O_READONLY
);
443 /* Set the initial cursor position, queue initial command. */
446 /* Redraw the screen from scratch, schedule a welcome message. */
447 F_SET(sp
, SC_SCR_REFORMAT
| SC_SCR_TOP
| SC_STATUS
);
449 /* Append into the chain of file structures. */
451 CIRCLEQ_INSERT_TAIL(&sp
->gp
->exfq
, ep
, q
);
455 err
: if (frp
->name
!= NULL
) {
459 if (frp
->tname
!= NULL
) {
460 (void)unlink(frp
->tname
);
465 oerr
: if (F_ISSET(ep
, F_RCV_ON
))
466 (void)unlink(ep
->rcv_path
);
467 if (ep
->rcv_path
!= NULL
) {
472 (void)ep
->db
->close(ep
->db
, DB_NOSYNC
);
475 return (open_err
&& !LF_ISSET(FS_OPENERR
) ?
476 file_init(sp
, frp
, rcv_name
, flags
| FS_OPENERR
) : 1);
481 * Scan the user's path to find the file that we're going to
485 file_spath(sp
, frp
, sbp
, existsp
)
494 char *name
, *p
, *t
, path
[MAXPATHLEN
];
497 * If the name is NULL or an explicit reference (i.e., the first
498 * component is . or ..) ignore the O_PATH option.
505 if (name
[0] == '/' || (name
[0] == '.' &&
506 (name
[1] == '/' || (name
[1] == '.' && name
[2] == '/')))) {
507 *existsp
= !stat(name
, sbp
);
512 if (!stat(name
, sbp
)) {
517 /* Try the O_PATH option values. */
518 for (found
= 0, p
= t
= O_STR(sp
, O_PATH
);; ++p
)
519 if (*p
== ':' || *p
== '\0') {
524 sizeof(path
), "%s/%s", t
, name
);
526 if (!stat(path
, sbp
)) {
536 /* If we found it, build a new pathname and discard the old one. */
538 MALLOC_RET(sp
, p
, char *, len
+ 1);
539 memcpy(p
, path
, len
+ 1);
549 * Set up the initial cursor position.
562 /* Set some basic defaults. */
567 * Historically, initial commands (the -c option) weren't executed
568 * until a file was loaded, e.g. "vi +10 nofile", followed by an
569 * :edit or :tag command, would execute the +10 on the file loaded
570 * by the subsequent command, (assuming that it existed). This
571 * applied as well to files loaded using the tag commands, and we
572 * follow that historic practice. Also, all initial commands were
573 * ex commands and were always executed on the last line of the file.
575 * Otherwise, if no initial command for this file:
576 * If in ex mode, move to the last line, first nonblank character.
577 * If the file has previously been edited, move to the last known
578 * position, and check it for validity.
579 * Otherwise, move to the first line, first nonblank.
581 * This gets called by the file init code, because we may be in a
582 * file of ex commands and we want to execute them from the right
583 * location in the file.
587 if (gp
->c_option
!= NULL
&& !F_ISSET(sp
->frp
, FR_NEWFILE
)) {
588 if (db_last(sp
, &sp
->lno
))
594 CHAR2INT(sp
, gp
->c_option
, strlen(gp
->c_option
) + 1,
596 if (ex_run_str(sp
, "-c option", wp
, wlen
- 1, 1, 1))
599 } else if (F_ISSET(sp
, SC_EX
)) {
600 if (db_last(sp
, &sp
->lno
))
609 if (F_ISSET(sp
->frp
, FR_CURSORSET
)) {
610 sp
->lno
= sp
->frp
->lno
;
611 sp
->cno
= sp
->frp
->cno
;
613 /* If returning to a file in vi, center the line. */
614 F_SET(sp
, SC_SCR_CENTER
);
616 if (O_ISSET(sp
, O_COMMENT
))
622 if (db_get(sp
, sp
->lno
, 0, NULL
, &len
)) {
627 if (!nb
&& sp
->cno
> len
)
632 (void)nonblank(sp
, sp
->lno
, &sp
->cno
);
637 * The initial column is also the most attractive column.
643 * Historically, vi initialized the absolute mark, but ex did not.
644 * Which meant, that if the first command in ex mode was "visual",
645 * or if an ex command was executed first (e.g. vi +10 file) vi was
646 * entered without the mark being initialized. For consistency, if
647 * the file isn't empty, we initialize it for everyone, believing
648 * that it can't hurt, and is generally useful. Not initializing it
649 * if the file is empty is historic practice, although it has always
650 * been possible to set (and use) marks in empty vi files.
654 (void)mark_set(sp
, ABSMARK1
, &m
, 0);
659 * Stop editing a file.
661 * PUBLIC: int file_end __P((SCR *, EXF *, int));
664 file_end(sp
, ep
, force
)
673 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
674 * (If argument ep is NULL, use sp->ep.)
676 * If multiply referenced, just decrement the count and return.
680 if (--ep
->refcnt
!= 0)
685 * Clean up the FREF structure.
687 * Save the cursor location.
690 * It would be cleaner to do this somewhere else, but by the time
691 * ex or vi knows that we're changing files it's already happened.
696 F_SET(frp
, FR_CURSORSET
);
699 * We may no longer need the temporary backing file, so clean it
700 * up. We don't need the FREF structure either, if the file was
701 * never named, so lose it.
704 * Re: FR_DONTDELETE, see the comment above in file_init().
706 if (!F_ISSET(frp
, FR_DONTDELETE
) && frp
->tname
!= NULL
) {
707 if (unlink(frp
->tname
))
708 msgq_str(sp
, M_SYSERR
, frp
->tname
, "240|%s: remove");
711 if (F_ISSET(frp
, FR_TMPFILE
)) {
712 CIRCLEQ_REMOVE(&sp
->gp
->frefq
, frp
, q
);
713 if (frp
->name
!= NULL
)
721 * Clean up the EXF structure.
723 * Close the db structure.
725 if (ep
->db
->close
!= NULL
&&
726 (sp
->db_error
= ep
->db
->close(ep
->db
, DB_NOSYNC
)) != 0 &&
728 msgq_str(sp
, M_DBERR
, frp
->name
, "241|%s: close");
733 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
736 (void)log_end(sp
, ep
);
738 /* Free up any marks. */
739 (void)mark_end(sp
, ep
);
742 * Delete recovery files, close the open descriptor, free recovery
743 * memory. See recover.c for a description of the protocol.
746 * Unlink backup file first, we can detect that the recovery file
747 * doesn't reference anything when the user tries to recover it.
748 * There's a race, here, obviously, but it's fairly small.
750 if (!F_ISSET(ep
, F_RCV_NORM
)) {
751 if (ep
->rcv_path
!= NULL
&& unlink(ep
->rcv_path
))
752 msgq_str(sp
, M_SYSERR
, ep
->rcv_path
, "242|%s: remove");
753 if (ep
->rcv_mpath
!= NULL
&& unlink(ep
->rcv_mpath
))
754 msgq_str(sp
, M_SYSERR
, ep
->rcv_mpath
, "243|%s: remove");
756 CIRCLEQ_REMOVE(&sp
->gp
->exfq
, ep
, q
);
759 if (ep
->fcntl_fd
!= -1)
760 (void)close(ep
->fcntl_fd
);
761 if (ep
->rcv_fd
!= -1)
762 (void)close(ep
->rcv_fd
);
763 if (ep
->rcv_path
!= NULL
)
765 if (ep
->rcv_mpath
!= NULL
)
774 * Write the file to disk. Historic vi had fairly convoluted
775 * semantics for whether or not writes would happen. That's
778 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
781 file_write(sp
, fm
, tm
, name
, flags
)
787 enum { NEWFILE
, OLDFILE
} mtype
;
795 int fd
, nf
, noname
, oflags
, rval
;
796 char *p
, *s
, *t
, buf
[MAXPATHLEN
+ 64];
803 * Writing '%', or naming the current file explicitly, has the
804 * same semantics as writing without a name.
806 if (name
== NULL
|| !strcmp(name
, frp
->name
)) {
812 /* Can't write files marked read-only, unless forced. */
813 if (!LF_ISSET(FS_FORCE
) && noname
&& O_ISSET(sp
, O_READONLY
)) {
814 msgq(sp
, M_ERR
, LF_ISSET(FS_POSSIBLE
) ?
815 "244|Read-only file, not written; use ! to override" :
816 "245|Read-only file, not written");
820 /* If not forced, not appending, and "writeany" not set ... */
821 if (!LF_ISSET(FS_FORCE
| FS_APPEND
) && !O_ISSET(sp
, O_WRITEANY
)) {
822 /* Don't overwrite anything but the original file. */
823 if ((!noname
|| F_ISSET(frp
, FR_NAMECHANGE
)) &&
825 msgq_str(sp
, M_ERR
, name
,
826 LF_ISSET(FS_POSSIBLE
) ?
827 "246|%s exists, not written; use ! to override" :
828 "247|%s exists, not written");
833 * Don't write part of any existing file. Only test for the
834 * original file, the previous test catches anything else.
836 if (!LF_ISSET(FS_ALL
) && noname
&& !stat(name
, &sb
)) {
837 msgq(sp
, M_ERR
, LF_ISSET(FS_POSSIBLE
) ?
838 "248|Partial file, not written; use ! to override" :
839 "249|Partial file, not written");
845 * Figure out if the file already exists -- if it doesn't, we display
846 * the "new file" message. The stat might not be necessary, but we
847 * just repeat it because it's easier than hacking the previous tests.
848 * The information is only used for the user message and modification
849 * time test, so we can ignore the obvious race condition.
851 * One final test. If we're not forcing or appending the current file,
852 * and we have a saved modification time, object if the file changed
853 * since we last edited or wrote it, and make them force it.
858 if (noname
&& !LF_ISSET(FS_FORCE
| FS_APPEND
) &&
859 ((F_ISSET(ep
, F_DEVSET
) &&
860 (sb
.st_dev
!= ep
->mdev
|| sb
.st_ino
!= ep
->minode
)) ||
861 sb
.st_mtime
!= ep
->mtime
)) {
862 msgq_str(sp
, M_ERR
, name
, LF_ISSET(FS_POSSIBLE
) ?
863 "250|%s: file modified more recently than this copy; use ! to override" :
864 "251|%s: file modified more recently than this copy");
871 /* Set flags to create, write, and either append or truncate. */
872 oflags
= O_CREAT
| O_WRONLY
|
873 (LF_ISSET(FS_APPEND
) ? O_APPEND
: O_TRUNC
);
875 /* Backup the file if requested. */
876 if (!opts_empty(sp
, O_BACKUP
, 1) &&
877 file_backup(sp
, name
, O_STR(sp
, O_BACKUP
)) && !LF_ISSET(FS_FORCE
))
882 if ((fd
= open(name
, oflags
,
883 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
)) < 0) {
884 msgq_str(sp
, M_SYSERR
, name
, "%s");
890 /* Try and get a lock. */
891 if (!noname
&& file_lock(sp
, NULL
, NULL
, fd
, 0) == LOCK_UNAVAIL
)
892 msgq_str(sp
, M_ERR
, name
,
893 "252|%s: write lock was unavailable");
898 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
899 * This bug is fixed in libc 4.6.x.
901 * This code works around this problem for libc 4.5.x users.
902 * Note that this code is harmless if you're using libc 4.6.x.
904 if (LF_ISSET(FS_APPEND
) && lseek(fd
, (off_t
)0, SEEK_END
) < 0) {
905 msgq(sp
, M_SYSERR
, name
);
911 * Use stdio for buffering.
914 * SVR4.2 requires the fdopen mode exactly match the original open
915 * mode, i.e. you have to open with "a" if appending.
917 if ((fp
= fdopen(fd
, LF_ISSET(FS_APPEND
) ? "a" : "w")) == NULL
) {
918 msgq_str(sp
, M_SYSERR
, name
, "%s");
923 /* Build fake addresses, if necessary. */
928 if (db_last(sp
, &to
.lno
))
934 rval
= ex_writefp(sp
, name
, fp
, fm
, tm
, &nlno
, &nch
, 0);
937 * Save the new last modification time -- even if the write fails
938 * we re-init the time. That way the user can clean up the disk
939 * and rewrite without having to force it.
946 ep
->mdev
= sb
.st_dev
;
947 ep
->minode
= sb
.st_ino
;
949 ep
->mtime
= sb
.st_mtime
;
954 * If the write failed, complain loudly. ex_writefp() has already
955 * complained about the actual error, reinforce it if data was lost.
958 if (!LF_ISSET(FS_APPEND
))
959 msgq_str(sp
, M_ERR
, name
,
960 "254|%s: WARNING: FILE TRUNCATED");
965 * Once we've actually written the file, it doesn't matter that the
966 * file name was changed -- if it was, we've already whacked it.
968 F_CLR(frp
, FR_NAMECHANGE
);
971 * If wrote the entire file, and it wasn't by appending it to a file,
972 * clear the modified bit. If the file was written to the original
973 * file name and the file is a temporary, set the "no exit" bit. This
974 * permits the user to write the file and use it in the context of the
975 * filesystem, but still keeps them from discarding their changes by
978 if (LF_ISSET(FS_ALL
) && !LF_ISSET(FS_APPEND
)) {
979 F_CLR(ep
, F_MODIFIED
);
980 if (F_ISSET(frp
, FR_TMPFILE
)) {
982 F_SET(frp
, FR_TMPEXIT
);
984 F_CLR(frp
, FR_TMPEXIT
);
988 p
= msg_print(sp
, name
, &nf
);
992 "256|%s: new file: %lu lines, %lu characters", NULL
);
993 len
= snprintf(buf
, sizeof(buf
), msgstr
, p
, nlno
, nch
);
996 msgstr
= msg_cat(sp
, LF_ISSET(FS_APPEND
) ?
997 "315|%s: appended: %lu lines, %lu characters" :
998 "257|%s: %lu lines, %lu characters", NULL
);
999 len
= snprintf(buf
, sizeof(buf
), msgstr
, p
, nlno
, nch
);
1006 * There's a nasty problem with long path names. Cscope and tags files
1007 * can result in long paths and vi will request a continuation key from
1008 * the user. Unfortunately, the user has typed ahead, and chaos will
1009 * result. If we assume that the characters in the filenames only take
1010 * a single screen column each, we can trim the filename.
1013 if (len
>= sp
->cols
) {
1014 for (s
= buf
, t
= buf
+ strlen(p
); s
< t
&&
1015 (*s
!= '/' || len
>= sp
->cols
- 3); ++s
, --len
);
1019 *--s
= '.'; /* Leading ellipses. */
1024 msgq(sp
, M_INFO
, s
);
1026 FREE_SPACE(sp
, p
, 0);
1032 * Backup the about-to-be-written file.
1035 * We do the backup by copying the entire file. It would be nice to do
1036 * a rename instead, but: (1) both files may not fit and we want to fail
1037 * before doing the rename; (2) the backup file may not be on the same
1038 * disk partition as the file being written; (3) there may be optional
1039 * file information (MACs, DACs, whatever) that we won't get right if we
1040 * recreate the file. So, let's not risk it.
1043 file_backup(sp
, name
, bname
)
1053 int flags
, maxnum
, nr
, num
, nw
, rfd
, wfd
, version
;
1054 char *bp
, *estr
, *p
, *pct
, *slash
, *t
, *wfname
, buf
[8192];
1061 bp
= estr
= wfname
= NULL
;
1064 * Open the current file for reading. Do this first, so that
1065 * we don't exec a shell before the most likely failure point.
1066 * If it doesn't exist, it's okay, there's just nothing to back
1070 if ((rfd
= open(name
, O_RDONLY
, 0)) < 0) {
1071 if (errno
== ENOENT
)
1078 * If the name starts with an 'N' character, add a version number
1079 * to the name. Strip the leading N from the string passed to the
1080 * expansion routines, for no particular reason. It would be nice
1081 * to permit users to put the version number anywhere in the backup
1082 * name, but there isn't a special character that we can use in the
1083 * name, and giving a new character a special meaning leads to ugly
1084 * hacks both here and in the supporting ex routines.
1086 * Shell and file name expand the option's value.
1088 ex_cinit(sp
, &cmd
, 0, 0, 0, 0, 0);
1089 if (bname
[0] == 'N') {
1094 CHAR2INT(sp
, bname
, strlen(bname
) + 1, wp
, wlen
);
1095 if (argv_exp2(sp
, &cmd
, wp
, wlen
- 1))
1099 * 0 args: impossible.
1101 * >1 args: object, too many args.
1103 if (cmd
.argc
!= 1) {
1104 msgq_str(sp
, M_ERR
, bname
,
1105 "258|%s expanded into too many file names");
1111 * If appending a version number, read through the directory, looking
1112 * for file names that match the name followed by a number. Make all
1113 * of the other % characters in name literal, so the user doesn't get
1114 * surprised and sscanf doesn't drop core indirecting through pointers
1115 * that don't exist. If any such files are found, increment its number
1119 GET_SPACE_GOTO(sp
, bp
, blen
, cmd
.argv
[0]->len
* 2 + 50);
1120 INT2CHAR(sp
, cmd
.argv
[0]->bp
, cmd
.argv
[0]->len
+ 1,
1124 for (t
= bp
, slash
= NULL
;
1125 p
[0] != '\0'; *t
++ = *p
++)
1129 } else if (p
[0] == '/')
1136 if (slash
== NULL
) {
1137 dirp
= opendir(".");
1146 INT2CHAR(sp
, cmd
.argv
[0]->bp
, cmd
.argv
[0]->len
+ 1,
1151 for (maxnum
= 0; (dp
= readdir(dirp
)) != NULL
;)
1152 if (sscanf(dp
->d_name
, p
, &num
) == 1 && num
> maxnum
)
1154 (void)closedir(dirp
);
1156 /* Format the backup file name. */
1157 (void)snprintf(pct
, blen
- (pct
- bp
), "%d", maxnum
+ 1);
1161 INT2CHAR(sp
, cmd
.argv
[0]->bp
, cmd
.argv
[0]->len
+ 1,
1165 /* Open the backup file, avoiding lurkers. */
1166 if (stat(wfname
, &sb
) == 0) {
1167 if (!S_ISREG(sb
.st_mode
)) {
1168 msgq_str(sp
, M_ERR
, bname
,
1169 "259|%s: not a regular file");
1172 if (sb
.st_uid
!= getuid()) {
1173 msgq_str(sp
, M_ERR
, bname
, "260|%s: not owned by you");
1176 if (sb
.st_mode
& (S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
)) {
1177 msgq_str(sp
, M_ERR
, bname
,
1178 "261|%s: accessible by a user other than the owner");
1183 flags
= O_CREAT
| O_EXCL
;
1184 if ((wfd
= open(wfname
, flags
| O_WRONLY
, S_IRUSR
| S_IWUSR
)) < 0) {
1189 /* Copy the file's current contents to its backup value. */
1190 while ((nr
= read(rfd
, buf
, sizeof(buf
))) > 0)
1191 for (off
= 0; nr
!= 0; nr
-= nw
, off
+= nw
)
1192 if ((nw
= write(wfd
, buf
+ off
, nr
)) < 0) {
1210 FREE_SPACE(sp
, bp
, blen
);
1217 (void)unlink(wfname
);
1221 msgq_str(sp
, M_SYSERR
, estr
, "%s");
1225 FREE_SPACE(sp
, bp
, blen
);
1231 * Skip the first comment.
1241 for (lno
= 1; !db_get(sp
, lno
, 0, &p
, &len
) && len
== 0; ++lno
);
1245 F_SET(sp
, SC_SCR_TOP
);
1246 while (!db_get(sp
, ++lno
, 0, &p
, &len
))
1247 if (len
< 1 || p
[0] != '#') {
1251 } else if (len
> 1 && p
[0] == '/' && p
[1] == '*') {
1252 F_SET(sp
, SC_SCR_TOP
);
1254 for (; len
> 1; --len
, ++p
)
1255 if (p
[0] == '*' && p
[1] == '/') {
1259 } while (!db_get(sp
, ++lno
, 0, &p
, &len
));
1260 } else if (len
> 1 && p
[0] == '/' && p
[1] == '/') {
1261 F_SET(sp
, SC_SCR_TOP
);
1262 while (!db_get(sp
, ++lno
, 0, &p
, &len
))
1263 if (len
< 1 || p
[0] != '/' || p
[1] != '/') {
1272 * First modification check routine. The :next, :prev, :rewind, :tag,
1273 * :tagpush, :tagpop, ^^ modifications check.
1275 * PUBLIC: int file_m1 __P((SCR *, int, int));
1278 file_m1(sp
, force
, flags
)
1286 /* If no file loaded, return no modifications. */
1291 * If the file has been modified, we'll want to write it back or
1292 * fail. If autowrite is set, we'll write it back automatically,
1293 * unless force is also set. Otherwise, we fail unless forced or
1294 * there's another open screen on this file.
1296 if (F_ISSET(ep
, F_MODIFIED
)) {
1297 if (O_ISSET(sp
, O_AUTOWRITE
)) {
1298 if (!force
&& file_aw(sp
, flags
))
1300 } else if (ep
->refcnt
<= 1 && !force
) {
1301 msgq(sp
, M_ERR
, LF_ISSET(FS_POSSIBLE
) ?
1302 "262|File modified since last complete write; write or use ! to override" :
1303 "263|File modified since last complete write; write or use :edit! to override");
1308 return (file_m3(sp
, force
));
1313 * Second modification check routine. The :edit, :quit, :recover
1314 * modifications check.
1316 * PUBLIC: int file_m2 __P((SCR *, int));
1327 /* If no file loaded, return no modifications. */
1332 * If the file has been modified, we'll want to fail, unless forced
1333 * or there's another open screen on this file.
1335 if (F_ISSET(ep
, F_MODIFIED
) && ep
->refcnt
<= 1 && !force
) {
1337 "264|File modified since last complete write; write or use ! to override");
1341 return (file_m3(sp
, force
));
1346 * Third modification check routine.
1348 * PUBLIC: int file_m3 __P((SCR *, int));
1359 /* If no file loaded, return no modifications. */
1364 * Don't exit while in a temporary files if the file was ever modified.
1365 * The problem is that if the user does a ":wq", we write and quit,
1366 * unlinking the temporary file. Not what the user had in mind at all.
1367 * We permit writing to temporary files, so that user maps using file
1368 * system names work with temporary files.
1370 if (F_ISSET(sp
->frp
, FR_TMPEXIT
) && ep
->refcnt
<= 1 && !force
) {
1372 "265|File is a temporary; exit will discard modifications");
1380 * Autowrite routine. If modified, autowrite is set and the readonly bit
1381 * is not set, write the file. A routine so there's a place to put the
1384 * PUBLIC: int file_aw __P((SCR *, int));
1391 if (!F_ISSET(sp
->ep
, F_MODIFIED
))
1393 if (!O_ISSET(sp
, O_AUTOWRITE
))
1398 * Historic 4BSD vi attempted to write the file if autowrite was set,
1399 * regardless of the writeability of the file (as defined by the file
1400 * readonly flag). System V changed this as some point, not attempting
1401 * autowrite if the file was readonly. This feels like a bug fix to
1402 * me (e.g. the principle of least surprise is violated if readonly is
1403 * set and vi writes the file), so I'm compatible with System V.
1405 if (O_ISSET(sp
, O_READONLY
)) {
1407 "266|File readonly, modifications not auto-written");
1410 return (file_write(sp
, NULL
, NULL
, NULL
, flags
));
1415 * Set the alternate pathname.
1417 * Set the alternate pathname. It's a routine because I wanted some place
1418 * to hang this comment. The alternate pathname (normally referenced using
1419 * the special character '#' during file expansion and in the vi ^^ command)
1420 * is set by almost all ex commands that take file names as arguments. The
1421 * rules go something like this:
1423 * 1: If any ex command takes a file name as an argument (except for the
1424 * :next command), the alternate pathname is set to that file name.
1425 * This excludes the command ":e" and ":w !command" as no file name
1426 * was specified. Note, historically, the :source command did not set
1427 * the alternate pathname. It does in nvi, for consistency.
1429 * 2: However, if any ex command sets the current pathname, e.g. the
1430 * ":e file" or ":rew" commands succeed, then the alternate pathname
1431 * is set to the previous file's current pathname, if it had one.
1432 * This includes the ":file" command and excludes the ":e" command.
1433 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1434 * pathname will be "foo", if it succeeds, the alternate pathname will
1435 * be the previous current pathname. The ":e" command will not set
1436 * the alternate or current pathnames regardless.
1438 * 3: However, if it's a read or write command with a file argument and
1439 * the current pathname has not yet been set, the file name becomes
1440 * the current pathname, and the alternate pathname is unchanged.
1442 * If the user edits a temporary file, there may be times when there is no
1443 * alternative file name. A name argument of NULL turns it off.
1445 * PUBLIC: void set_alt_name __P((SCR *, char *));
1448 set_alt_name(sp
, name
)
1452 if (sp
->alt_name
!= NULL
)
1455 sp
->alt_name
= NULL
;
1456 else if ((sp
->alt_name
= strdup(name
)) == NULL
)
1457 msgq(sp
, M_SYSERR
, NULL
);
1462 * Get an exclusive lock on a file.
1465 * The default locking is flock(2) style, not fcntl(2). The latter is
1466 * known to fail badly on some systems, and its only advantage is that
1467 * it occasionally works over NFS.
1469 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1470 * two-fold: you can't close any file descriptor associated with the file
1471 * without losing all of the locks, and you can't get an exclusive lock
1472 * unless you have the file open for writing. Someone ought to be shot,
1473 * but it's probably too late, they may already have reproduced. To get
1474 * around these problems, nvi opens the files for writing when it can and
1475 * acquires a second file descriptor when it can't. The recovery files
1476 * are examples of the former, they're always opened for writing. The DB
1477 * files can't be opened for writing because the semantics of DB are that
1478 * files opened for writing are flushed back to disk when the DB session
1479 * is ended. So, in that case we have to acquire an extra file descriptor.
1481 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1484 file_lock(sp
, name
, fdp
, fd
, iswrite
)
1487 int *fdp
, fd
, iswrite
;
1489 if (!O_ISSET(sp
, O_LOCKFILES
))
1490 return (LOCK_SUCCESS
);
1492 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1495 * We need to distinguish a lock not being available for the file
1496 * from the file system not supporting locking. Flock is documented
1497 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1498 * they are the former. There's no portable way to do this.
1501 return (flock(fd
, LOCK_EX
| LOCK_NB
) ? errno
== EAGAIN
1503 || errno
== EWOULDBLOCK
1505 ? LOCK_UNAVAIL
: LOCK_FAILED
: LOCK_SUCCESS
);
1507 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1510 int didopen
, sverrno
;
1512 arg
.l_type
= F_WRLCK
;
1513 arg
.l_whence
= 0; /* SEEK_SET */
1514 arg
.l_start
= arg
.l_len
= 0;
1518 * If the file descriptor isn't opened for writing, it must fail.
1519 * If we fail because we can't get a read/write file descriptor,
1520 * we return LOCK_SUCCESS, believing that the file is readonly
1521 * and that will be sufficient to warn the user.
1524 if (name
== NULL
|| fdp
== NULL
)
1525 return (LOCK_FAILED
);
1526 if ((fd
= open(name
, O_RDWR
, 0)) == -1)
1527 return (LOCK_SUCCESS
);
1533 if (!fcntl(fd
, F_SETLK
, &arg
))
1534 return (LOCK_SUCCESS
);
1543 * We need to distinguish a lock not being available for the file
1544 * from the file system not supporting locking. Fcntl is documented
1545 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1546 * and assume they are the former. There's no portable way to do this.
1548 return (errno
== EACCES
|| errno
== EAGAIN
1550 || errno
== EWOULDBLOCK
1552 ? LOCK_UNAVAIL
: LOCK_FAILED
);
1555 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1556 return (LOCK_SUCCESS
);