head	1.16;
access;
symbols
	perseant-exfatfs-base-20250801:1.16
	perseant-exfatfs-base-20240630:1.16
	perseant-exfatfs:1.16.0.36
	perseant-exfatfs-base:1.16
	cjep_sun2x:1.16.0.34
	cjep_sun2x-base:1.16
	cjep_staticlib_x-base1:1.16
	cjep_staticlib_x:1.16.0.32
	cjep_staticlib_x-base:1.16
	phil-wifi-20200421:1.16
	phil-wifi-20200411:1.16
	phil-wifi-20200406:1.16
	pgoyette-compat-merge-20190127:1.16
	pgoyette-compat-20190127:1.16
	pgoyette-compat-20190118:1.16
	pgoyette-compat-1226:1.16
	pgoyette-compat-1126:1.16
	pgoyette-compat-1020:1.16
	pgoyette-compat-0930:1.16
	pgoyette-compat-0906:1.16
	pgoyette-compat-0728:1.16
	pgoyette-compat-0625:1.16
	pgoyette-compat-0521:1.16
	pgoyette-compat-0502:1.16
	pgoyette-compat-0422:1.16
	pgoyette-compat-0415:1.16
	pgoyette-compat-0407:1.16
	pgoyette-compat-0330:1.16
	pgoyette-compat-0322:1.16
	pgoyette-compat-0315:1.16
	pgoyette-compat:1.16.0.30
	pgoyette-compat-base:1.16
	perseant-stdc-iso10646:1.16.0.28
	perseant-stdc-iso10646-base:1.16
	prg-localcount2-base3:1.16
	prg-localcount2-base2:1.16
	prg-localcount2-base1:1.16
	prg-localcount2:1.16.0.26
	prg-localcount2-base:1.16
	pgoyette-localcount-20170426:1.16
	bouyer-socketcan-base1:1.16
	pgoyette-localcount-20170320:1.16
	bouyer-socketcan:1.16.0.24
	bouyer-socketcan-base:1.16
	pgoyette-localcount-20170107:1.16
	pgoyette-localcount-20161104:1.16
	localcount-20160914:1.16
	pgoyette-localcount-20160806:1.16
	pgoyette-localcount-20160726:1.16
	pgoyette-localcount:1.16.0.22
	pgoyette-localcount-base:1.16
	netbsd-5-2-3-RELEASE:1.16
	netbsd-5-1-5-RELEASE:1.16
	yamt-pagecache-base9:1.16
	yamt-pagecache-tag8:1.16
	tls-earlyentropy:1.16.0.18
	tls-earlyentropy-base:1.16
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.16
	riastradh-drm2-base3:1.16
	netbsd-5-2-2-RELEASE:1.16
	netbsd-5-1-4-RELEASE:1.16
	netbsd-5-2-1-RELEASE:1.16
	netbsd-5-1-3-RELEASE:1.16
	agc-symver:1.16.0.20
	agc-symver-base:1.16
	tls-maxphys-base:1.16
	yamt-pagecache-base8:1.16
	netbsd-5-2:1.16.0.16
	yamt-pagecache-base7:1.16
	netbsd-5-2-RELEASE:1.16
	netbsd-5-2-RC1:1.16
	yamt-pagecache-base6:1.16
	yamt-pagecache-base5:1.16
	yamt-pagecache-base4:1.16
	netbsd-5-1-2-RELEASE:1.16
	netbsd-5-1-1-RELEASE:1.16
	yamt-pagecache-base3:1.16
	yamt-pagecache-base2:1.16
	yamt-pagecache:1.16.0.14
	yamt-pagecache-base:1.16
	bouyer-quota2-nbase:1.16
	bouyer-quota2:1.16.0.12
	bouyer-quota2-base:1.16
	matt-nb5-pq3:1.16.0.10
	matt-nb5-pq3-base:1.16
	netbsd-5-1:1.16.0.8
	netbsd-5-1-RELEASE:1.16
	netbsd-5-1-RC4:1.16
	netbsd-5-1-RC3:1.16
	netbsd-5-1-RC2:1.16
	netbsd-5-1-RC1:1.16
	netbsd-5-0-2-RELEASE:1.16
	netbsd-5-0-1-RELEASE:1.16
	jym-xensuspend-nbase:1.16
	netbsd-5-0:1.16.0.6
	netbsd-5-0-RELEASE:1.16
	netbsd-5-0-RC4:1.16
	netbsd-5-0-RC3:1.16
	netbsd-5-0-RC2:1.16
	jym-xensuspend:1.16.0.4
	jym-xensuspend-base:1.16
	netbsd-5-0-RC1:1.16
	netbsd-5:1.16.0.2
	netbsd-5-base:1.16
	matt-mips64-base2:1.15
	matt-mips64:1.15.0.24
	mjf-devfs2:1.15.0.22
	mjf-devfs2-base:1.15
	netbsd-4-0-1-RELEASE:1.15
	wrstuden-revivesa-base-3:1.15
	wrstuden-revivesa-base-2:1.15
	wrstuden-fixsa-newbase:1.15
	wrstuden-revivesa-base-1:1.15
	yamt-pf42-base4:1.15
	yamt-pf42-base3:1.15
	hpcarm-cleanup-nbase:1.15
	yamt-pf42-baseX:1.15
	yamt-pf42-base2:1.15
	wrstuden-revivesa:1.15.0.20
	wrstuden-revivesa-base:1.15
	yamt-pf42:1.15.0.18
	yamt-pf42-base:1.15
	keiichi-mipv6-nbase:1.15
	keiichi-mipv6:1.15.0.16
	keiichi-mipv6-base:1.15
	matt-armv6-nbase:1.15
	matt-armv6-prevmlocking:1.15
	wrstuden-fixsa-base-1:1.15
	netbsd-4-0:1.15.0.14
	netbsd-4-0-RELEASE:1.15
	cube-autoconf:1.15.0.12
	cube-autoconf-base:1.15
	netbsd-4-0-RC5:1.15
	netbsd-4-0-RC4:1.15
	netbsd-4-0-RC3:1.15
	netbsd-4-0-RC2:1.15
	netbsd-4-0-RC1:1.15
	matt-armv6:1.15.0.10
	matt-armv6-base:1.15
	matt-mips64-base:1.15
	hpcarm-cleanup:1.15.0.8
	hpcarm-cleanup-base:1.15
	netbsd-3-1-1-RELEASE:1.12
	netbsd-3-0-3-RELEASE:1.12
	wrstuden-fixsa:1.15.0.6
	wrstuden-fixsa-base:1.15
	abandoned-netbsd-4-base:1.15
	abandoned-netbsd-4:1.15.0.2
	netbsd-3-1:1.12.0.6
	netbsd-3-1-RELEASE:1.12
	netbsd-3-0-2-RELEASE:1.12
	netbsd-3-1-RC4:1.12
	netbsd-3-1-RC3:1.12
	netbsd-3-1-RC2:1.12
	netbsd-3-1-RC1:1.12
	netbsd-4:1.15.0.4
	netbsd-4-base:1.15
	chap-midi-nbase:1.15
	netbsd-3-0-1-RELEASE:1.12
	chap-midi:1.13.0.2
	chap-midi-base:1.15
	netbsd-3-0:1.12.0.4
	netbsd-3-0-RELEASE:1.12
	netbsd-3-0-RC6:1.12
	netbsd-3-0-RC5:1.12
	netbsd-3-0-RC4:1.12
	netbsd-3-0-RC3:1.12
	netbsd-3-0-RC2:1.12
	netbsd-3-0-RC1:1.12
	netbsd-2-0-3-RELEASE:1.11.2.1
	netbsd-2-1:1.11.2.1.0.4
	netbsd-2-1-RELEASE:1.11.2.1
	netbsd-2-1-RC6:1.11.2.1
	netbsd-2-1-RC5:1.11.2.1
	netbsd-2-1-RC4:1.11.2.1
	netbsd-2-1-RC3:1.11.2.1
	netbsd-2-1-RC2:1.11.2.1
	netbsd-2-1-RC1:1.11.2.1
	netbsd-2-0-2-RELEASE:1.11.2.1
	netbsd-3:1.12.0.2
	netbsd-3-base:1.12
	netbsd-2-0-1-RELEASE:1.11.2.1
	netbsd-2:1.11.2.1.0.2
	netbsd-2-base:1.11.2.1
	netbsd-2-0-RELEASE:1.11.2.1
	netbsd-2-0-RC5:1.11.2.1
	netbsd-2-0-RC4:1.11.2.1
	netbsd-2-0-RC3:1.11.2.1
	netbsd-2-0-RC2:1.11.2.1
	netbsd-2-0-RC1:1.11.2.1
	netbsd-2-0:1.11.0.2
	netbsd-2-0-base:1.11
	netbsd-1-6-PATCH002-RELEASE:1.10
	netbsd-1-6-PATCH002:1.10
	netbsd-1-6-PATCH002-RC4:1.10
	netbsd-1-6-PATCH002-RC3:1.10
	netbsd-1-6-PATCH002-RC2:1.10
	netbsd-1-6-PATCH002-RC1:1.10
	netbsd-1-6-PATCH001:1.10
	netbsd-1-6-PATCH001-RELEASE:1.10
	netbsd-1-6-PATCH001-RC3:1.10
	netbsd-1-6-PATCH001-RC2:1.10
	netbsd-1-6-PATCH001-RC1:1.10
	fvdl_fs64_base:1.10
	netbsd-1-6-RELEASE:1.10
	netbsd-1-6-RC3:1.10
	netbsd-1-6-RC2:1.10
	netbsd-1-6-RC1:1.10
	netbsd-1-6:1.10.0.2
	netbsd-1-6-base:1.10
	netbsd-1-5-PATCH003:1.2
	netbsd-1-5-PATCH002:1.2
	netbsd-1-5-PATCH001:1.2
	nvi_1_79:1.1.1.4
	netbsd-1-5-RELEASE:1.2
	netbsd-1-5-BETA2:1.2
	netbsd-1-5-BETA:1.2
	netbsd-1-4-PATCH003:1.2
	netbsd-1-5-ALPHA2:1.2
	netbsd-1-5:1.2.0.10
	netbsd-1-5-base:1.2
	minoura-xpg4dl-base:1.2
	minoura-xpg4dl:1.2.0.8
	netbsd-1-4-PATCH002:1.2
	wrstuden-devbsize-19991221:1.2
	wrstuden-devbsize:1.2.0.6
	wrstuden-devbsize-base:1.2
	comdex-fall-1999:1.2.0.4
	comdex-fall-1999-base:1.2
	netbsd-1-4-PATCH001:1.2
	netbsd-1-4-RELEASE:1.2
	netbsd-1-4:1.2.0.2
	netbsd-1-4-base:1.2
	netbsd-1-3-PATCH003:1.1.1.3
	netbsd-1-3-PATCH003-CANDIDATE2:1.1.1.3
	netbsd-1-3-PATCH003-CANDIDATE1:1.1.1.3
	netbsd-1-3-PATCH003-CANDIDATE0:1.1.1.3
	netbsd-1-3-PATCH002:1.1.1.3
	netbsd-1-3-PATCH001:1.1.1.3
	netbsd-1-3-RELEASE:1.1.1.3
	netbsd-1-3-BETA:1.1.1.3
	netbsd-1-3:1.1.1.3.0.2
	netbsd-1-3-base:1.1.1.3
	netbsd-1-2-PATCH001:1.1.1.3
	netbsd-1-2-RELEASE:1.1.1.3
	netbsd-1-2-BETA:1.1.1.3
	netbsd-1-2:1.1.1.3.0.4
	netbsd-1-2-base:1.1.1.3
	nvi_1_66:1.1.1.3
	BOSTIC:1.1.1
	netbsd-1-1-PATCH001:1.1.1.2
	netbsd-1-1-RELEASE:1.1.1.2
	netbsd-1-1:1.1.1.2.0.4
	netbsd-1-1-base:1.1.1.2
	netbsd-1-0-PATCH06:1.1.1.2
	netbsd-1-0-PATCH05:1.1.1.2
	netbsd-1-0-PATCH04:1.1.1.2
	netbsd-1-0-PATCH03:1.1.1.2
	netbsd-1-0-PATCH02:1.1.1.2
	netbsd-1-0-PATCH1:1.1.1.2
	netbsd-1-0-PATCH0:1.1.1.2
	netbsd-1-0-RELEASE:1.1.1.2
	netbsd-1-0:1.1.1.2.0.2
	nvi-1-34b:1.1.1.2
	nvi-1-33b:1.1.1.1
	bostic-nvi:1.1.1;
locks; strict;
comment	@ * @;


1.16
date	2008.10.29.16.49.34;	author christos;	state dead;
branches;
next	1.15;

1.15
date	2006.05.27.12.03.37;	author simonb;	state Exp;
branches;
next	1.14;

1.14
date	2006.05.27.04.15.42;	author jnemeth;	state Exp;
branches;
next	1.13;

1.13
date	2005.06.07.13.26.26;	author he;	state Exp;
branches
	1.13.2.1;
next	1.12;

1.12
date	2004.04.05.07.19.08;	author aymeric;	state Exp;
branches;
next	1.11;

1.11
date	2003.01.06.20.30.41;	author wiz;	state Exp;
branches
	1.11.2.1;
next	1.10;

1.10
date	2002.04.15.08.31.43;	author pooka;	state Exp;
branches;
next	1.9;

1.9
date	2002.04.09.01.47.31;	author thorpej;	state Exp;
branches;
next	1.8;

1.8
date	2002.03.25.00.13.56;	author simonb;	state Exp;
branches;
next	1.7;

1.7
date	2002.02.09.19.33.53;	author pooka;	state Exp;
branches;
next	1.6;

1.6
date	2002.01.13.11.57.38;	author aymeric;	state Exp;
branches;
next	1.5;

1.5
date	2001.10.17.07.38.48;	author yamt;	state Exp;
branches;
next	1.4;

1.4
date	2001.08.17.21.33.46;	author aymeric;	state Exp;
branches;
next	1.3;

1.3
date	2001.03.31.11.37.45;	author aymeric;	state Exp;
branches;
next	1.2;

1.2
date	98.01.09.08.06.36;	author perry;	state Exp;
branches;
next	1.1;

1.1
date	94.08.17.16.19.02;	author cgd;	state Exp;
branches
	1.1.1.1;
next	;

1.13.2.1
date	2006.06.19.04.17.07;	author chap;	state Exp;
branches;
next	;

1.11.2.1
date	2004.04.08.21.22.46;	author jdc;	state Exp;
branches;
next	;

1.1.1.1
date	94.08.17.16.19.03;	author cgd;	state Exp;
branches;
next	1.1.1.2;

1.1.1.2
date	94.08.17.19.24.45;	author cgd;	state Exp;
branches
	1.1.1.2.2.1;
next	1.1.1.3;

1.1.1.3
date	96.05.20.02.03.49;	author mrg;	state Exp;
branches;
next	1.1.1.4;

1.1.1.4
date	2001.03.31.11.30.01;	author aymeric;	state Exp;
branches;
next	;

1.1.1.2.2.1
date	94.08.17.19.24.45;	author cgd;	state dead;
branches;
next	1.1.1.2.2.2;

1.1.1.2.2.2
date	94.08.17.19.24.46;	author cgd;	state Exp;
branches;
next	;


desc
@@


1.16
log
@bye old vi!
@
text
@/*	$NetBSD: exf.c,v 1.15 2006/05/27 12:03:37 simonb Exp $	*/

/*-
 * Copyright (c) 1992, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 * Copyright (c) 1992, 1993, 1994, 1995, 1996
 *	Keith Bostic.  All rights reserved.
 *
 * See the LICENSE file for redistribution information.
 */

#include "config.h"

#include <sys/cdefs.h>
#ifndef lint
#if 0
static const char sccsid[] = "@@(#)exf.c	10.49 (Berkeley) 10/10/96";
#else
__RCSID("$NetBSD: exf.c,v 1.15 2006/05/27 12:03:37 simonb Exp $");
#endif
#endif /* not lint */

#include <sys/param.h>
#include <sys/types.h>		/* XXX: param.h may not have included types.h */
#include <sys/queue.h>
#include <sys/stat.h>

/*
 * We include <sys/file.h>, because the flock(2) and open(2) #defines
 * were found there on historical systems.  We also include <fcntl.h>
 * because the open(2) #defines are found there on newer systems.
 */
#include <sys/file.h>

#include <bitstring.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "common.h"

static int	file_backup __P((SCR *, char *, char *));
static void	file_cinit __P((SCR *));
static void	file_comment __P((SCR *));
static int	file_spath __P((SCR *, FREF *, struct stat *, int *));

/*
 * file_add --
 *	Insert a file name into the FREF list, if it doesn't already
 *	appear in it.
 *
 * !!!
 * The "if it doesn't already appear" changes vi's semantics slightly.  If
 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
 * will reflect the line/column of the previous edit session.  Historic nvi
 * did not do this.  The change is a logical extension of the change where
 * vi now remembers the last location in any file that it has ever edited,
 * not just the previously edited file.
 *
 * PUBLIC: FREF *file_add __P((SCR *, CHAR_T *));
 */
FREF *
file_add(sp, name)
	SCR *sp;
	CHAR_T *name;
{
	GS *gp;
	FREF *frp, *tfrp;

	/*
	 * Return it if it already exists.  Note that we test against the
	 * user's name, whatever that happens to be, including if it's a
	 * temporary file.
	 *
	 * If the user added a file but was unable to initialize it, there
	 * can be file list entries where the name field is NULL.  Discard
	 * them the next time we see them.
	 */
	gp = sp->gp;
	if (name != NULL)
		for (frp = gp->frefq.cqh_first;
		    frp != (FREF *)&gp->frefq; frp = frp->q.cqe_next) {
			if (frp->name == NULL) {
				tfrp = frp->q.cqe_next;
				CIRCLEQ_REMOVE(&gp->frefq, frp, q);
				if (frp->name != NULL)
					free(frp->name);
				free(frp);
				frp = tfrp;
				continue;
			}
			if (!strcmp(frp->name, name))
				return (frp);
		}

	/* Allocate and initialize the FREF structure. */
	CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
	if (frp == NULL)
		return (NULL);

	/*
	 * If no file name specified, or if the file name is a request
	 * for something temporary, file_init() will allocate the file
	 * name.  Temporary files are always ignored.
	 */
	if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
	    (frp->name = strdup(name)) == NULL) {
		free(frp);
		msgq(sp, M_SYSERR, NULL);
		return (NULL);
	}

	/* Append into the chain of file names. */
	CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);

	return (frp);
}

/*
 * file_init --
 *	Start editing a file, based on the FREF structure.  If successsful,
 *	let go of any previous file.  Don't release the previous file until
 *	absolutely sure we have the new one.
 *
 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
 */
int
file_init(sp, frp, rcv_name, flags)
	SCR *sp;
	FREF *frp;
	char *rcv_name;
	int flags;
{
	EXF *ep;
	RECNOINFO oinfo;
	struct stat sb;
	size_t psize;
	int fd, exists, open_err, readonly;
	char *oname, tname[MAXPATHLEN];

	open_err = readonly = 0;

	/*
	 * If the file is a recovery file, let the recovery code handle it.
	 * Clear the FR_RECOVER flag first -- the recovery code does set up,
	 * and then calls us!  If the recovery call fails, it's probably
	 * because the named file doesn't exist.  So, move boldly forward,
	 * presuming that there's an error message the user will get to see.
	 */
	if (F_ISSET(frp, FR_RECOVER)) {
		F_CLR(frp, FR_RECOVER);
		if (rcv_read(sp, frp) == 0)
			return 0;
	}

	/*
	 * Required FRP initialization; the only flag we keep is the
	 * cursor information.
	 */
	F_CLR(frp, ~FR_CURSORSET);

	/*
	 * Required EXF initialization:
	 *	Flush the line caches.
	 *	Default recover mail file fd to -1.
	 *	Set initial EXF flag bits.
	 */
	CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
	ep->c_lno = ep->c_nlines = OOBLNO;
	ep->rcv_fd = ep->fcntl_fd = -1;
	F_SET(ep, F_FIRSTMODIFY);

	/*
	 * Scan the user's path to find the file that we're going to
	 * try and open.
	 */
	if (file_spath(sp, frp, &sb, &exists)) {
		free(ep);
		return (1);
	}

	/*
	 * If no name or backing file, for whatever reason, create a backing
	 * temporary file, saving the temp file name so we can later unlink
	 * it.  If the user never named this file, copy the temporary file name
	 * to the real name (we display that until the user renames it).
	 */
	oname = frp->name;
	if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
		/*
		 * Don't try to create a temporary support file twice.
		 */
		if (frp->tname != NULL && LF_ISSET(FS_OPENERR))
			goto err;
		if (opts_empty(sp, O_DIRECTORY, 0))
			goto err;
		(void)snprintf(tname, sizeof(tname),
		    "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
		if ((fd = mkstemp(tname)) == -1) {
			msgq(sp, M_SYSERR,
			    "237|Unable to create temporary file");
			goto err;
		}
		(void)close(fd);

		if (frp->name == NULL)
			F_SET(frp, FR_TMPFILE);
		if ((frp->tname = strdup(tname)) == NULL ||
		    frp->name == NULL && (frp->name = strdup(tname)) == NULL) {
			if (frp->tname != NULL)
				free(frp->tname);
			msgq(sp, M_SYSERR, NULL);
			(void)unlink(tname);
			goto err;
		}
		oname = frp->tname;
		psize = 1024;
		if (!LF_ISSET(FS_OPENERR))
			F_SET(frp, FR_NEWFILE);

		time(&ep->mtime);
	} else {
		/*
		 * XXX
		 * A seat of the pants calculation: try to keep the file in
		 * 15 pages or less.  Don't use a page size larger than 10K
		 * (vi should have good locality) or smaller than 1K.
		 */
		psize = ((sb.st_size / 15) + 1023) / 1024;
		if (psize > 10)
			psize = 10;
		if (psize == 0)
			psize = 1;
		psize *= 1024;

		F_SET(ep, F_DEVSET);
		ep->mdev = sb.st_dev;
		ep->minode = sb.st_ino;

		ep->mtime = sb.st_mtime;

		if (!S_ISREG(sb.st_mode))
			msgq_str(sp, M_ERR, oname,
			    "238|Warning: %s is not a regular file");
	}

	/* Set up recovery. */
	memset(&oinfo, 0, sizeof(RECNOINFO));
	oinfo.bval = '\n';			/* Always set. */
	oinfo.psize = psize;
	oinfo.flags = F_ISSET(sp->gp, G_SNAPSHOT) ? R_SNAPSHOT : 0;
	if (rcv_name == NULL) {
		if (!rcv_tmp(sp, ep, frp->name))
			oinfo.bfname = ep->rcv_path;
	} else {
		if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
			msgq(sp, M_SYSERR, NULL);
			goto err;
		}
		oinfo.bfname = ep->rcv_path;
		F_SET(ep, F_MODIFIED);
	}

	/* Open a db structure. */
	if ((ep->db = dbopen(rcv_name == NULL ? oname : NULL,
	    O_NONBLOCK | O_RDONLY,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH,
	    DB_RECNO, &oinfo)) == NULL) {
		msgq_str(sp,
		    M_SYSERR, rcv_name == NULL ? oname : rcv_name, "%s");
		/*
		 * !!!
		 * Historically, vi permitted users to edit files that couldn't
		 * be read.  This isn't useful for single files from a command
		 * line, but it's quite useful for "vi *.c", since you can skip
		 * past files that you can't read.
		 */
		open_err = 1;
		goto oerr;
	}

	/*
	 * Do the remaining things that can cause failure of the new file,
	 * mark and logging initialization.
	 */
	if (mark_init(sp, ep) || log_init(sp, ep))
		goto err;

	/*
	 * Set the alternate file name to be the file we're discarding.
	 *
	 * !!!
	 * Temporary files can't become alternate files, so there's no file
	 * name.  This matches historical practice, although it could only
	 * happen in historical vi as the result of the initial command, i.e.
	 * if vi was executed without a file name.
	 */
	if (LF_ISSET(FS_SETALT))
		set_alt_name(sp, sp->frp == NULL ||
		    F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);

	/*
	 * Close the previous file; if that fails, close the new one and run
	 * for the border.
	 *
	 * !!!
	 * There's a nasty special case.  If the user edits a temporary file,
	 * and then does an ":e! %", we need to re-initialize the backing
	 * file, but we can't change the name.  (It's worse -- we're dealing
	 * with *names* here, we can't even detect that it happened.)  Set a
	 * flag so that the file_end routine ignores the backing information
	 * of the old file if it happens to be the same as the new one.
	 *
	 * !!!
	 * Side-effect: after the call to file_end(), sp->frp may be NULL.
	 */
	if (sp->ep != NULL) {
		F_SET(frp, FR_DONTDELETE);
		if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
			(void)file_end(sp, ep, 1);
			goto err;
		}
		F_CLR(frp, FR_DONTDELETE);
	}

	/*
	 * Lock the file; if it's a recovery file, it should already be
	 * locked.  Note, we acquire the lock after the previous file
	 * has been ended, so that we don't get an "already locked" error
	 * for ":edit!".
	 *
	 * XXX
	 * While the user can't interrupt us between the open and here,
	 * there's a race between the dbopen() and the lock.  Not much
	 * we can do about it.
	 *
	 * XXX
	 * We don't make a big deal of not being able to lock the file.  As
	 * locking rarely works over NFS, and often fails if the file was
	 * mmap(2)'d, it's far too common to do anything like print an error
	 * message, let alone make the file readonly.  At some future time,
	 * when locking is a little more reliable, this should change to be
	 * an error.
	 */
	if (rcv_name == NULL)
		switch (file_lock(sp, oname,
		    &ep->fcntl_fd, ep->db->fd(ep->db), 0)) {
		case LOCK_FAILED:
			F_SET(frp, FR_UNLOCKED);
			break;
		case LOCK_UNAVAIL:
			readonly = 1;
			msgq_str(sp, M_INFO, oname,
			    "239|%s already locked, session is read-only");
			break;
		case LOCK_SUCCESS:
			break;
		}

	/*
	 * Historically, the readonly edit option was set per edit buffer in
	 * vi, unless the -R command-line option was specified or the program
	 * was executed as "view".  (Well, to be truthful, if the letter 'w'
	 * occurred anywhere in the program name, but let's not get into that.)
	 * So, the persistant readonly state has to be stored in the screen
	 * structure, and the edit option value toggles with the contents of
	 * the edit buffer.  If the persistant readonly flag is set, set the
	 * readonly edit option.
	 *
	 * Otherwise, try and figure out if a file is readonly.  This is a
	 * dangerous thing to do.  The kernel is the only arbiter of whether
	 * or not a file is writable, and the best that a user program can
	 * do is guess.  Obvious loopholes are files that are on a file system
	 * mounted readonly (access catches this one on a few systems), or
	 * alternate protection mechanisms, ACL's for example, that we can't
	 * portably check.  Lots of fun, and only here because users whined.
	 *
	 * !!!
	 * Historic vi displayed the readonly message if none of the file
	 * write bits were set, or if an an access(2) call on the path
	 * failed.  This seems reasonable.  If the file is mode 444, root
	 * users may want to know that the owner of the file did not expect
	 * it to be written.
	 *
	 * Historic vi set the readonly bit if no write bits were set for
	 * a file, even if the access call would have succeeded.  This makes
	 * the superuser force the write even when vi expects that it will
	 * succeed.  I'm less supportive of this semantic, but it's historic
	 * practice and the conservative approach to vi'ing files as root.
	 *
	 * It would be nice if there was some way to update this when the user
	 * does a "^Z; chmod ...".  The problem is that we'd first have to
	 * distinguish between readonly bits set because of file permissions
	 * and those set for other reasons.  That's not too hard, but deciding
	 * when to reevaluate the permissions is trickier.  An alternative
	 * might be to turn off the readonly bit if the user forces a write
	 * and it succeeds.
	 *
	 * XXX
	 * Access(2) doesn't consider the effective uid/gid values.  This
	 * probably isn't a problem for vi when it's running standalone.
	 */
	if (readonly || F_ISSET(sp, SC_READONLY) ||
	    !F_ISSET(frp, FR_NEWFILE) &&
	    (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
	    access(frp->name, W_OK)))
		O_SET(sp, O_READONLY);
	else
		O_CLR(sp, O_READONLY);

	/* Switch... */
	++ep->refcnt;
	sp->ep = ep;
	sp->frp = frp;

	/* Set the initial cursor position, queue initial command. */
	file_cinit(sp);

	/* Redraw the screen from scratch, schedule a welcome message. */
	F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);

	if (frp->lno == OOBLNO)
		F_SET(sp, SC_SCR_TOP);

	return (0);

err:	if (frp->name != NULL) {
		free(frp->name);
		frp->name = NULL;
	}
	if (frp->tname != NULL) {
		(void)unlink(frp->tname);
		free(frp->tname);
		frp->tname = NULL;
	}

oerr:	if (F_ISSET(ep, F_RCV_ON))
		(void)unlink(ep->rcv_path);
	if (ep->rcv_path != NULL) {
		free(ep->rcv_path);
		ep->rcv_path = NULL;
	}
	if (ep->db != NULL)
		(void)ep->db->close(ep->db);
	free(ep);

	return (open_err ?
	    file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
}

/*
 * file_spath --
 *	Scan the user's path to find the file that we're going to
 *	try and open.
 */
static int
file_spath(sp, frp, sbp, existsp)
	SCR *sp;
	FREF *frp;
	struct stat *sbp;
	int *existsp;
{
	CHAR_T savech;
	size_t len;
	int found;
	char *name, *p, *t, path[MAXPATHLEN];

	len = 0;	/* XXXGCC -Wuninitialized [dreamcast] */

	/*
	 * If the name is NULL or an explicit reference (i.e., the first
	 * component is . or ..) ignore the O_PATH option.
	 */
	name = frp->name;
	if (name == NULL) {
		*existsp = 0;
		return (0);
	}
	if (name[0] == '/' || name[0] == '.' &&
	    (name[1] == '/' || name[1] == '.' && name[2] == '/')) {
		*existsp = !stat(name, sbp);
		return (0);
	}

	/* Try . */
	if (!stat(name, sbp)) {
		*existsp = 1;
		return (0);
	}

	/* Try the O_PATH option values. */
	for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
		if (*p == ':' || *p == '\0') {
			if (t < p - 1) {
				savech = *p;
				*p = '\0';
				len = snprintf(path,
				    sizeof(path), "%s/%s", t, name);
				*p = savech;
				if (!stat(path, sbp)) {
					found = 1;
					break;
				}
			}
			t = p + 1;
			if (*p == '\0')
				break;
		}

	/* If we found it, build a new pathname and discard the old one. */
	if (found) {
		MALLOC_RET(sp, p, char *, len + 1);
		memcpy(p, path, len + 1);
		free(frp->name);
		frp->name = p;
	}
	*existsp = found;
	return (0);
}

/*
 * file_cinit --
 *	Set up the initial cursor position.
 */
static void
file_cinit(sp)
	SCR *sp;
{
	GS *gp;
	MARK m;
	size_t len;
	int nb;

	/* Set some basic defaults. */
	sp->lno = 1;
	sp->cno = 0;

	/*
	 * Historically, initial commands (the -c option) weren't executed
	 * until a file was loaded, e.g. "vi +10 nofile", followed by an
	 * :edit or :tag command, would execute the +10 on the file loaded
	 * by the subsequent command, (assuming that it existed).  This
	 * applied as well to files loaded using the tag commands, and we
	 * follow that historic practice.  Also, all initial commands were
	 * ex commands and were always executed on the last line of the file.
	 *
	 * Otherwise, if no initial command for this file:
	 *    If in ex mode, move to the last line, first nonblank character.
	 *    If the file has previously been edited, move to the last known
	 *	  position, and check it for validity.
	 *    Otherwise, move to the first line, first nonblank.
	 *
	 * This gets called by the file init code, because we may be in a
	 * file of ex commands and we want to execute them from the right
	 * location in the file.
	 */
	nb = 0;
	gp = sp->gp;
	if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
		if (db_last(sp, &sp->lno))
			return;
		if (sp->lno == 0) {
			sp->lno = 1;
			sp->cno = 0;
		}
		if (ex_run_str(sp,
		    "-c option", gp->c_option, strlen(gp->c_option), 1, 1))
			return;
		gp->c_option = NULL;
	} else if (F_ISSET(sp, SC_EX)) {
		if (db_last(sp, &sp->lno))
			return;
		if (sp->lno == 0) {
			sp->lno = 1;
			sp->cno = 0;
			return;
		}
		nb = 1;
	} else {
		if (F_ISSET(sp->frp, FR_CURSORSET)) {
			sp->lno = sp->frp->lno;
			sp->cno = sp->frp->cno;

			/* If returning to a file in vi, center the line. */
			 F_SET(sp, SC_SCR_CENTER);
		} else {
			if (O_ISSET(sp, O_COMMENT))
				file_comment(sp);
			else
				sp->lno = 1;
			nb = 1;
		}
		if (db_get(sp, sp->lno, 0, NULL, &len)) {
			sp->lno = 1;
			sp->cno = 0;
			return;
		}
		if (!nb && sp->cno > len)
			nb = 1;
	}
	if (nb) {
		sp->cno = 0;
		(void)nonblank(sp, sp->lno, &sp->cno);
	}

	/*
	 * !!!
	 * The initial column is also the most attractive column.
	 */
	sp->rcm = sp->cno;

	/*
	 * !!!
	 * Historically, vi initialized the absolute mark, but ex did not.
	 * Which meant, that if the first command in ex mode was "visual",
	 * or if an ex command was executed first (e.g. vi +10 file) vi was
	 * entered without the mark being initialized.  For consistency, if
	 * the file isn't empty, we initialize it for everyone, believing
	 * that it can't hurt, and is generally useful.  Not initializing it
	 * if the file is empty is historic practice, although it has always
	 * been possible to set (and use) marks in empty vi files.
	 */
	m.lno = sp->lno;
	m.cno = sp->cno;
	(void)mark_set(sp, ABSMARK1, &m, 0);
}

/*
 * file_end --
 *	Stop editing a file.
 *
 * PUBLIC: int file_end __P((SCR *, EXF *, int));
 */
int
file_end(sp, ep, force)
	SCR *sp;
	EXF *ep;
	int force;
{
	FREF *frp;

	/*
	 * !!!
	 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
	 * (If argument ep is NULL, use sp->ep.)
	 *
	 * If multiply referenced, just decrement the count and return.
	 */
	if (ep == NULL)
		ep = sp->ep;
	if (--ep->refcnt != 0)
		return (0);

	/*
	 *
	 * Clean up the FREF structure.
	 *
	 * Save the cursor location.
	 *
	 * XXX
	 * It would be cleaner to do this somewhere else, but by the time
	 * ex or vi knows that we're changing files it's already happened.
	 */
	frp = sp->frp;
	frp->lno = sp->lno;
	frp->cno = sp->cno;
	F_SET(frp, FR_CURSORSET);

	/*
	 * We may no longer need the temporary backing file, so clean it
	 * up.  We don't need the FREF structure either, if the file was
	 * never named, so lose it.
	 *
	 * !!!
	 * Re: FR_DONTDELETE, see the comment above in file_init().
	 */
	if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
		if (unlink(frp->tname))
			msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
		free(frp->tname);
		frp->tname = NULL;
		if (F_ISSET(frp, FR_TMPFILE)) {
			CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
			if (frp->name != NULL)
				free(frp->name);
			free(frp);
		}
		sp->frp = NULL;
	}

	/*
	 * Clean up the EXF structure.
	 *
	 * Close the db structure.
	 */
	if (ep->db->close != NULL && ep->db->close(ep->db) && !force) {
		msgq_str(sp, M_SYSERR, frp->name, "241|%s: close");
		++ep->refcnt;
		return (1);
	}

	/* COMMITTED TO THE CLOSE.  THERE'S NO GOING BACK... */

	/* Stop logging. */
	(void)log_end(sp, ep);

	/* Free up any marks. */
	(void)mark_end(sp, ep);

	/*
	 * Delete recovery files, close the open descriptor, free recovery
	 * memory.  See recover.c for a description of the protocol.
	 *
	 * XXX
	 * Unlink backup file first, we can detect that the recovery file
	 * doesn't reference anything when the user tries to recover it.
	 * There's a race, here, obviously, but it's fairly small.
	 */
	if (!F_ISSET(ep, F_RCV_NORM)) {
		if (ep->rcv_path != NULL && unlink(ep->rcv_path))
			msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
		if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
			msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
	}
	if (ep->fcntl_fd != -1)
		(void)close(ep->fcntl_fd);
	if (ep->rcv_fd != -1)
		(void)close(ep->rcv_fd);
	if (ep->rcv_path != NULL)
		free(ep->rcv_path);
	if (ep->rcv_mpath != NULL)
		free(ep->rcv_mpath);

	free(ep);
	return (0);
}

/*
 * file_write --
 *	Write the file to disk.  Historic vi had fairly convoluted
 *	semantics for whether or not writes would happen.  That's
 *	why all the flags.
 *
 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
 */
int
file_write(sp, fm, tm, name, flags)
	SCR *sp;
	MARK *fm, *tm;
	char *name;
	int flags;
{
	enum { NEWFILE, OLDFILE } mtype;
	struct stat sb;
	EXF *ep;
	FILE *fp;
	FREF *frp;
	MARK from, to;
	size_t len;
	u_long nlno, nch;
	int fd, nf, noname, oflags, rval;
	char *p, *s, *t, buf[MAXPATHLEN + 64];
	const char *msgstr;

	ep = sp->ep;
	frp = sp->frp;

	/*
	 * Writing '%', or naming the current file explicitly, has the
	 * same semantics as writing without a name.
	 */
	if (name == NULL || !strcmp(name, frp->name)) {
		noname = 1;
		name = frp->name;
	} else
		noname = 0;

	/* Can't write files marked read-only, unless forced. */
	if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
		msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
		    "244|Read-only file, not written; use ! to override" :
		    "245|Read-only file, not written");
		return (1);
	}

	/* If not forced, not appending, and "writeany" not set ... */
	if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
		/* Don't overwrite anything but the original file. */
		if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
		    !stat(name, &sb)) {
			msgq_str(sp, M_ERR, name,
			    LF_ISSET(FS_POSSIBLE) ?
			    "246|%s exists, not written; use ! to override" :
			    "247|%s exists, not written");
			return (1);
		}

		/*
		 * Don't write part of any existing file.  Only test for the
		 * original file, the previous test catches anything else.
		 */
		if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
			    "248|Partial file, not written; use ! to override" :
			    "249|Partial file, not written");
			return (1);
		}
	}

	/*
	 * Figure out if the file already exists -- if it doesn't, we display
	 * the "new file" message.  The stat might not be necessary, but we
	 * just repeat it because it's easier than hacking the previous tests.
	 * The information is only used for the user message and modification
	 * time test, so we can ignore the obvious race condition.
	 *
	 * One final test.  If we're not forcing or appending the current file,
	 * and we have a saved modification time, object if the file changed
	 * since we last edited or wrote it, and make them force it.
	 */
	if (stat(name, &sb))
		mtype = NEWFILE;
	else {
		if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
		    (F_ISSET(ep, F_DEVSET) &&
		    (sb.st_dev != ep->mdev || sb.st_ino != ep->minode) ||
		    sb.st_mtime != ep->mtime)) {
			msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
"250|%s: file modified more recently than this copy; use ! to override" :
"251|%s: file modified more recently than this copy");
			return (1);
		}

		mtype = OLDFILE;
	}

	/* Set flags to create, write, and either append or truncate. */
	oflags = O_CREAT | O_WRONLY |
	    (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);

	/* Backup the file if requested. */
	if (!opts_empty(sp, O_BACKUP, 1) &&
	    file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
		return (1);

	/* Open the file. */
	SIGBLOCK;
	if ((fd = open(name, oflags,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
		msgq_str(sp, M_SYSERR, name, "%s");
		SIGUNBLOCK;
		return (1);
	}
	SIGUNBLOCK;

	/* Try and get a lock. */
	if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
		msgq_str(sp, M_ERR, name,
		    "252|%s: write lock was unavailable");

#if __linux__
	/*
	 * XXX
	 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
	 * This bug is fixed in libc 4.6.x.
	 *
	 * This code works around this problem for libc 4.5.x users.
	 * Note that this code is harmless if you're using libc 4.6.x.
	 */
	if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
		msgq(sp, M_SYSERR, "%s", name);
		return (1);
	}
#endif

	/*
	 * Use stdio for buffering.
	 *
	 * XXX
	 * SVR4.2 requires the fdopen mode exactly match the original open
	 * mode, i.e. you have to open with "a" if appending.
	 */
	if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
		msgq_str(sp, M_SYSERR, name, "%s");
		(void)close(fd);
		return (1);
	}

	/* Build fake addresses, if necessary. */
	if (fm == NULL) {
		from.lno = 1;
		from.cno = 0;
		fm = &from;
		if (db_last(sp, &to.lno))
			return (1);
		to.cno = 0;
		tm = &to;
	}

	rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);

	/*
	 * Save the new last modification time -- even if the write fails
	 * we re-init the time.  That way the user can clean up the disk
	 * and rewrite without having to force it.
	 */
	if (noname)
		if (stat(name, &sb))
			time(&ep->mtime);
		else {
			F_SET(ep, F_DEVSET);
			ep->mdev = sb.st_dev;
			ep->minode = sb.st_ino;

			ep->mtime = sb.st_mtime;
		}

	/*
	 * If the write failed, complain loudly.  ex_writefp() has already
	 * complained about the actual error, reinforce it if data was lost.
	 */
	if (rval) {
		if (!LF_ISSET(FS_APPEND))
			msgq_str(sp, M_ERR, name,
			    "254|%s: WARNING: FILE TRUNCATED");
		return (1);
	}

	/*
	 * Once we've actually written the file, it doesn't matter that the
	 * file name was changed -- if it was, we've already whacked it.
	 */
	F_CLR(frp, FR_NAMECHANGE);

	/*
	 * If wrote the entire file, and it wasn't by appending it to a file,
	 * clear the modified bit.  If the file was written to the original
	 * file name and the file is a temporary, set the "no exit" bit.  This
	 * permits the user to write the file and use it in the context of the
	 * filesystem, but still keeps them from discarding their changes by
	 * exiting.
	 */
	if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
		F_CLR(ep, F_MODIFIED);
		if (F_ISSET(frp, FR_TMPFILE))
			if (noname)
				F_SET(frp, FR_TMPEXIT);
			else
				F_CLR(frp, FR_TMPEXIT);
	}

	p = msg_print(sp, name, &nf);
	switch (mtype) {
	case NEWFILE:
		msgstr = msg_cat(sp,
		    "256|%s: new file: %lu lines, %lu characters", NULL);
		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
		break;
	case OLDFILE:
		msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
		    "315|%s: appended: %lu lines, %lu characters" :
		    "257|%s: %lu lines, %lu characters", NULL);
		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
		break;
	default:
		abort();
	}

	/*
	 * There's a nasty problem with long path names.  Cscope and tags files
	 * can result in long paths and vi will request a continuation key from
	 * the user.  Unfortunately, the user has typed ahead, and chaos will
	 * result.  If we assume that the characters in the filenames only take
	 * a single screen column each, we can trim the filename.
	 */
	s = buf;
	if (len >= sp->cols) {
		for (s = buf, t = buf + strlen(p); s < t &&
		    (*s != '/' || len >= sp->cols - 3); ++s, --len);
		if (s == t)
			s = buf;
		else {
			*--s = '.';		/* Leading ellipses. */
			*--s = '.';
			*--s = '.';
		}
	}
	msgq(sp, M_INFO, "%s", s);
	if (nf)
		FREE_SPACE(sp, p, 0);
	return (0);
}

/*
 * file_backup --
 *	Backup the about-to-be-written file.
 *
 * XXX
 * We do the backup by copying the entire file.  It would be nice to do
 * a rename instead, but: (1) both files may not fit and we want to fail
 * before doing the rename; (2) the backup file may not be on the same
 * disk partition as the file being written; (3) there may be optional
 * file information (MACs, DACs, whatever) that we won't get right if we
 * recreate the file.  So, let's not risk it.
 */
static int
file_backup(sp, name, bname)
	SCR *sp;
	char *name, *bname;
{
	struct dirent *dp;
	struct stat sb;
	DIR *dirp;
	EXCMD cmd;
	off_t off;
	size_t blen;
	int flags, maxnum, nr, num, nw, rfd, wfd, version;
	char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];

	rfd = wfd = -1;
	bp = estr = wfname = NULL;

	/*
	 * Open the current file for reading.  Do this first, so that
	 * we don't exec a shell before the most likely failure point.
	 * If it doesn't exist, it's okay, there's just nothing to back
	 * up.
	 */
	errno = 0;
	if ((rfd = open(name, O_RDONLY, 0)) < 0) {
		if (errno == ENOENT)
			return (0);
		estr = name;
		goto err;
	}

	/*
	 * If the name starts with an 'N' character, add a version number
	 * to the name.  Strip the leading N from the string passed to the
	 * expansion routines, for no particular reason.  It would be nice
	 * to permit users to put the version number anywhere in the backup
	 * name, but there isn't a special character that we can use in the
	 * name, and giving a new character a special meaning leads to ugly
	 * hacks both here and in the supporting ex routines.
	 *
	 * Shell and file name expand the option's value.
	 */
	argv_init(sp, &cmd);
	ex_cinit(&cmd, 0, 0, 0, 0, 0, NULL);
	if (bname[0] == 'N') {
		version = 1;
		++bname;
	} else
		version = 0;
	if (argv_exp2(sp, &cmd, bname, strlen(bname)))
		return (1);

	/*
	 *  0 args: impossible.
	 *  1 args: use it.
	 * >1 args: object, too many args.
	 */
	if (cmd.argc != 1) {
		msgq_str(sp, M_ERR, bname,
		    "258|%s expanded into too many file names");
		(void)close(rfd);
		return (1);
	}

	/*
	 * If appending a version number, read through the directory, looking
	 * for file names that match the name followed by a number.  Make all
	 * of the other % characters in name literal, so the user doesn't get
	 * surprised and sscanf doesn't drop core indirecting through pointers
	 * that don't exist.  If any such files are found, increment its number
	 * by one.
	 */
	if (version) {
		GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
		for (t = bp, slash = NULL,
		    p = cmd.argv[0]->bp; p[0] != '\0'; *t++ = *p++)
			if (p[0] == '%') {
				if (p[1] != '%')
					*t++ = '%';
			} else if (p[0] == '/')
				slash = t;
		pct = t;
		*t++ = '%';
		*t++ = 'd';
		*t = '\0';

		if (slash == NULL) {
			dirp = opendir(".");
			p = bp;
		} else {
			*slash = '\0';
			dirp = opendir(bp);
			*slash = '/';
			p = slash + 1;
		}
		if (dirp == NULL) {
			estr = cmd.argv[0]->bp;
			goto err;
		}

		for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
			if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
				maxnum = num;
		(void)closedir(dirp);

		/* Format the backup file name. */
		(void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
		wfname = bp;
	} else {
		bp = NULL;
		wfname = cmd.argv[0]->bp;
	}
	
	/* Open the backup file, avoiding lurkers. */
	if (stat(wfname, &sb) == 0) {
		if (!S_ISREG(sb.st_mode)) {
			msgq_str(sp, M_ERR, bname,
			    "259|%s: not a regular file");
			goto err;
		}
		if (sb.st_uid != getuid()) {
			msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
			goto err;
		}
		if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
			msgq_str(sp, M_ERR, bname,
			   "261|%s: accessible by a user other than the owner");
			goto err;
		}
		flags = O_TRUNC;
	} else
		flags = O_CREAT | O_EXCL;
	if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
		estr = bname;
		goto err;
	}

	/* Copy the file's current contents to its backup value. */
	while ((nr = read(rfd, buf, sizeof(buf))) > 0)
		for (off = 0; nr != 0; nr -= nw, off += nw)
			if ((nw = write(wfd, buf + off, nr)) < 0) {
				estr = wfname;
				goto err;
			}
	if (nr < 0) {
		estr = name;
		goto err;
	}

	if (close(rfd)) {
		estr = name;
		goto err;
	}
	if (close(wfd)) {
		estr = wfname;
		goto err;
	}
	if (bp != NULL)
		FREE_SPACE(sp, bp, blen);
	return (0);

alloc_err:
err:	if (rfd != -1)
		(void)close(rfd);
	if (wfd != -1) {
		(void)unlink(wfname);
		(void)close(wfd);
	}
	if (estr)
		msgq_str(sp, M_SYSERR, estr, "%s");
	if (bp != NULL)
		FREE_SPACE(sp, bp, blen);
	return (1);
}

/*
 * file_comment --
 *	Skip the first comment.
 */
static void
file_comment(sp)
	SCR *sp;
{
	recno_t lno;
	size_t len;
	char *p;

	for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
	if (p == NULL)
		return;
	if (p[0] == '#') {
		F_SET(sp, SC_SCR_TOP);
		while (!db_get(sp, ++lno, 0, &p, &len))
			if (len < 1 || p[0] != '#') {
				sp->lno = lno;
				return;
			}
	} else if (len > 1 && p[0] == '/' && p[1] == '*') {
		F_SET(sp, SC_SCR_TOP);
		do {
			for (; len > 1; --len, ++p)
				if (p[0] == '*' && p[1] == '/') {
					sp->lno = lno;
					return;
				}
		} while (!db_get(sp, ++lno, 0, &p, &len));
	} else if (len > 1 && p[0] == '/' && p[1] == '/') {
		F_SET(sp, SC_SCR_TOP);
		p += 2;
		len -= 2;
		do {
			for (; len > 1; --len, ++p)
				if (p[0] == '/' && p[1] == '/') {
					sp->lno = lno;
					return;
				}
		} while (!db_get(sp, ++lno, 0, &p, &len));
	}
}

/*
 * file_m1 --
 * 	First modification check routine.  The :next, :prev, :rewind, :tag,
 *	:tagpush, :tagpop, ^^ modifications check.
 *
 * PUBLIC: int file_m1 __P((SCR *, int, int));
 */
int
file_m1(sp, force, flags)
	SCR *sp;
	int force, flags;
{
	EXF *ep;

	ep = sp->ep;

	/* If no file loaded, return no modifications. */
	if (ep == NULL)
		return (0);

	/*
	 * If the file has been modified, we'll want to write it back or
	 * fail.  If autowrite is set, we'll write it back automatically,
	 * unless force is also set.  Otherwise, we fail unless forced or
	 * there's another open screen on this file.
	 */
	if (F_ISSET(ep, F_MODIFIED))
		if (O_ISSET(sp, O_AUTOWRITE)) {
			if (!force && file_aw(sp, flags))
				return (1);
		} else if (ep->refcnt <= 1 && !force) {
			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
"262|File modified since last complete write; write or use ! to override" :
"263|File modified since last complete write; write or use :edit! to override");
			return (1);
		}

	return (file_m3(sp, force));
}

/*
 * file_m2 --
 * 	Second modification check routine.  The :edit, :quit, :recover
 *	modifications check.
 *
 * PUBLIC: int file_m2 __P((SCR *, int));
 */
int
file_m2(sp, force)
	SCR *sp;
	int force;
{
	EXF *ep;

	ep = sp->ep;

	/* If no file loaded, return no modifications. */
	if (ep == NULL)
		return (0);

	/*
	 * If the file has been modified, we'll want to fail, unless forced
	 * or there's another open screen on this file.
	 */
	if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
		msgq(sp, M_ERR,
"264|File modified since last complete write; write or use ! to override");
		return (1);
	}

	return (file_m3(sp, force));
}

/*
 * file_m3 --
 * 	Third modification check routine.
 *
 * PUBLIC: int file_m3 __P((SCR *, int));
 */
int
file_m3(sp, force)
	SCR *sp;
	int force;
{
	EXF *ep;

	ep = sp->ep;

	/* If no file loaded, return no modifications. */
	if (ep == NULL)
		return (0);

	/*
	 * Don't exit while in a temporary files if the file was ever modified.
	 * The problem is that if the user does a ":wq", we write and quit,
	 * unlinking the temporary file.  Not what the user had in mind at all.
	 * We permit writing to temporary files, so that user maps using file
	 * system names work with temporary files.
	 */
	if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
		msgq(sp, M_ERR,
		    "265|File is a temporary; exit will discard modifications");
		return (1);
	}
	return (0);
}

/*
 * file_aw --
 *	Autowrite routine.  If modified, autowrite is set and the readonly bit
 *	is not set, write the file.  A routine so there's a place to put the
 *	comment.
 *
 * PUBLIC: int file_aw __P((SCR *, int));
 */
int
file_aw(sp, flags)
	SCR *sp;
	int flags;
{
	if (!F_ISSET(sp->ep, F_MODIFIED))
		return (0);
	if (!O_ISSET(sp, O_AUTOWRITE))
		return (0);

	/*
	 * !!!
	 * Historic 4BSD vi attempted to write the file if autowrite was set,
	 * regardless of the writeability of the file (as defined by the file
	 * readonly flag).  System V changed this as some point, not attempting
	 * autowrite if the file was readonly.  This feels like a bug fix to
	 * me (e.g. the principle of least surprise is violated if readonly is
	 * set and vi writes the file), so I'm compatible with System V.
	 */
	if (O_ISSET(sp, O_READONLY)) {
		msgq(sp, M_INFO,
		    "266|File readonly, modifications not auto-written");
		return (1);
	}
	return (file_write(sp, NULL, NULL, NULL, flags));
}

/*
 * set_alt_name --
 *	Set the alternate pathname.
 *
 * Set the alternate pathname.  It's a routine because I wanted some place
 * to hang this comment.  The alternate pathname (normally referenced using
 * the special character '#' during file expansion and in the vi ^^ command)
 * is set by almost all ex commands that take file names as arguments.  The
 * rules go something like this:
 *
 *    1: If any ex command takes a file name as an argument (except for the
 *	 :next command), the alternate pathname is set to that file name.
 *	 This excludes the command ":e" and ":w !command" as no file name
 *       was specified.  Note, historically, the :source command did not set
 *	 the alternate pathname.  It does in nvi, for consistency.
 *
 *    2: However, if any ex command sets the current pathname, e.g. the
 *	 ":e file" or ":rew" commands succeed, then the alternate pathname
 *	 is set to the previous file's current pathname, if it had one.
 *	 This includes the ":file" command and excludes the ":e" command.
 *	 So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
 *	 pathname will be "foo", if it succeeds, the alternate pathname will
 *	 be the previous current pathname.  The ":e" command will not set
 *       the alternate or current pathnames regardless.
 *
 *    3: However, if it's a read or write command with a file argument and
 *	 the current pathname has not yet been set, the file name becomes
 *	 the current pathname, and the alternate pathname is unchanged.
 *
 * If the user edits a temporary file, there may be times when there is no
 * alternative file name.  A name argument of NULL turns it off.
 *
 * PUBLIC: void set_alt_name __P((SCR *, char *));
 */
void
set_alt_name(sp, name)
	SCR *sp;
	char *name;
{
	if (sp->alt_name != NULL)
		free(sp->alt_name);
	if (name == NULL)
		sp->alt_name = NULL;
	else if ((sp->alt_name = strdup(name)) == NULL)
		msgq(sp, M_SYSERR, NULL);
}

/*
 * file_lock --
 *	Get an exclusive lock on a file.
 *
 * XXX
 * The default locking is flock(2) style, not fcntl(2).  The latter is
 * known to fail badly on some systems, and its only advantage is that
 * it occasionally works over NFS.
 *
 * Furthermore, the semantics of fcntl(2) are wrong.  The problems are
 * two-fold: you can't close any file descriptor associated with the file
 * without losing all of the locks, and you can't get an exclusive lock
 * unless you have the file open for writing.  Someone ought to be shot,
 * but it's probably too late, they may already have reproduced.  To get
 * around these problems, nvi opens the files for writing when it can and
 * acquires a second file descriptor when it can't.  The recovery files
 * are examples of the former, they're always opened for writing.  The DB
 * files can't be opened for writing because the semantics of DB are that
 * files opened for writing are flushed back to disk when the DB session
 * is ended. So, in that case we have to acquire an extra file descriptor.
 *
 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
 */
lockr_t
file_lock(sp, name, fdp, fd, iswrite)
	SCR *sp;
	char *name;
	int *fdp, fd, iswrite;
{
	if (!O_ISSET(sp, O_LOCKFILES))
		return (LOCK_SUCCESS);
	
#ifdef HAVE_LOCK_FLOCK			/* Hurrah!  We've got flock(2). */
	/*
	 * !!!
	 * We need to distinguish a lock not being available for the file
	 * from the file system not supporting locking.  Flock is documented
	 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
	 * they are the former.  There's no portable way to do this.
	 */
	errno = 0;
	return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
#ifdef EWOULDBLOCK
	    || errno == EWOULDBLOCK
#endif
	    ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
#endif
#ifdef HAVE_LOCK_FCNTL			/* Gag me.  We've got fcntl(2). */
{
	struct flock arg;
	int didopen, sverrno;

	arg.l_type = F_WRLCK;
	arg.l_whence = 0;		/* SEEK_SET */
	arg.l_start = arg.l_len = 0;
	arg.l_pid = 0;

	/*
	 * If the file descriptor isn't opened for writing, it must fail.
	 * If we fail because we can't get a read/write file descriptor,
	 * we return LOCK_SUCCESS, believing that the file is readonly
	 * and that will be sufficient to warn the user.
	 */
	if (!iswrite) {
		if (name == NULL || fdp == NULL)
			return (LOCK_FAILED);
		if ((fd = open(name, O_RDWR, 0)) == -1)
			return (LOCK_SUCCESS);
		*fdp = fd;
		didopen = 1;
	}

	errno = 0;
	if (!fcntl(fd, F_SETLK, &arg))
		return (LOCK_SUCCESS);
	if (didopen) {
		sverrno = errno;
		(void)close(fd);
		errno = sverrno;
	}

	/*
	 * !!!
	 * We need to distinguish a lock not being available for the file
	 * from the file system not supporting locking.  Fcntl is documented
	 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
	 * and assume they are the former.  There's no portable way to do this.
	 */
	return (errno == EACCES || errno == EAGAIN
#ifdef EWOULDBLOCK
	|| errno == EWOULDBLOCK
#endif
	?  LOCK_UNAVAIL : LOCK_FAILED);
}
#endif
#if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
	return (LOCK_SUCCESS);
#endif
}
@


1.15
log
@Fix previous Coverity "fix" so that it doesn't break vi completely.
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.14 2006/05/27 04:15:42 jnemeth Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.14 2006/05/27 04:15:42 jnemeth Exp $");
@


1.14
log
@Coverity CID 3135: memory leak
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.13 2005/06/07 13:26:26 he Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.13 2005/06/07 13:26:26 he Exp $");
d182 1
a182 1
	if (file_spath(sp, frp, &sb, &exists))
d185 1
@


1.13
log
@Initialize a local variable to appease -Wuninitialized.
Marked with XXXGCC for dreamcast (found while compiling for it).

Reviewed by lukem.
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.12 2004/04/05 07:19:08 aymeric Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.12 2004/04/05 07:19:08 aymeric Exp $");
d183 1
@


1.13.2.1
log
@Sync with head.
@
text
@d1 1
a1 1
/*	$NetBSD$	*/
d19 1
a19 1
__RCSID("$NetBSD$");
d182 1
a182 2
	if (file_spath(sp, frp, &sb, &exists)) {
		free(ep);
a183 1
	}
@


1.12
log
@Don't fail if asked to recover a file for which there is no recovery file.
Just continue. This matches the man page, the POSIX standard, and even the
comment above that code!
From OpenBSD, via jmc@@openbsd, via wiz@@netbsd.
POSIX part confirmed by kleink@@netbsd
:-)
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.11 2003/01/06 20:30:41 wiz Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.11 2003/01/06 20:30:41 wiz Exp $");
d471 2
@


1.11
log
@writable, not writeable.
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.10 2002/04/15 08:31:43 pooka Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.10 2002/04/15 08:31:43 pooka Exp $");
d157 2
a158 1
		return (rcv_read(sp, frp));
@


1.11.2.1
log
@Pull up revision 1.12 (requested by aymeric in ticket #100)

Don't fail if asked to recover a file for which there is no recovery file.
Just continue. This matches the man page, the POSIX standard, and even the
comment above that code!
From OpenBSD, via jmc@@openbsd, via wiz@@netbsd.
POSIX part confirmed by kleink@@netbsd
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.11 2003/01/06 20:30:41 wiz Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.11 2003/01/06 20:30:41 wiz Exp $");
d157 1
a157 2
		if (rcv_read(sp, frp) == 0)
			return 0;
@


1.10
log
@Fix FreeBSD PR #12801 in such a way that it doesn't create unfortunate
side-effects, like the ones described in bin/15891 and bin/16210.

patch from Sven Verdoolaege (nvi maintainer)
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.9 2002/04/09 01:47:31 thorpej Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD: exf.c,v 1.9 2002/04/09 01:47:31 thorpej Exp $");
d374 1
a374 1
	 * or not a file is writeable, and the best that a user program can
@


1.9
log
@Use __RCSID() and __COPYRIGHT().
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.8 2002/03/25 00:13:56 simonb Exp $	*/
d19 1
a19 1
__RCSID("$NetBSD$");
d423 3
@


1.8
log
@Back out rev 1.6, per discussion with Aymeric Vincent and Antti Kantee.
Rev 1.6 fixes an obscure core-dump problem, but changes the long time
behaviour of cursor positioning when switching files.

"Fixes" PR bin/15891.
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.7 2002/02/09 19:33:53 pooka Exp $	*/
d14 1
d16 1
d18 3
@


1.7
log
@Exit the file_init "recursion" only if we are actually already trying for
a second time. Checking for the plain temp filename was not enough,
as it may be set even though we are calling the function for the
first time.

fixes bin/15474 by Chuck Cranor
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.6 2002/01/13 11:57:38 aymeric Exp $	*/
d417 1
a417 1
	F_SET(sp, SC_SCR_REFORMAT | SC_SCR_TOP | SC_STATUS);
@


1.6
log
@Fix FreeBSD PR #12801, the way nvi 1.81.5 does it.
(vi dumped core when editing a new file after having edited another one)
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.5 2001/10/17 07:38:48 yamt Exp $	*/
d190 1
a190 1
		if (frp->tname != NULL)
@


1.5
log
@fix format string bugs.
pointed by Tomoaki IMAMURA in PR/14271.
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.4 2001/08/17 21:33:46 aymeric Exp $	*/
d417 1
a417 1
	F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);
@


1.4
log
@Prevent nvi from looping infinitely when it can't create a temporary file
because of a weird umask for example.
Make it exit instead.
This differs from the OpenBSD behaviour and is believed to be more correct.

Reported by Thomas Klausner in private e-mail, followed by a small discussion in
tech-userlevel a while ago.
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.3 2001/03/31 11:37:45 aymeric Exp $	*/
d863 1
a863 1
		msgq(sp, M_SYSERR, name);
d980 1
a980 1
	msgq(sp, M_INFO, s);
@


1.3
log
@merge changes after import of nvi 1.79
@
text
@d1 1
a1 1
/*	$NetBSD: exf.c,v 1.2 1998/01/09 08:06:36 perry Exp $	*/
d187 5
d274 1
a274 1
		 */ 
@


1.2
log
@RCS Id Police.
@
text
@d1 1
a1 1
/*	$NetBSD$	*/
d15 1
a15 1
static const char sccsid[] = "@@(#)exf.c	10.35 (Berkeley) 5/16/96";
a34 1
#include <signal.h>
d45 1
d138 1
a138 1
	int fd, open_err, readonly;
d173 7
d186 1
a186 1
	if (LF_ISSET(FS_OPENERR) || oname == NULL || stat(oname, &sb)) {
d212 2
d228 1
d231 1
d353 4
a356 4
         * Historically, the readonly edit option was set per edit buffer in
         * vi, unless the -R command-line option was specified or the program
         * was executed as "view".  (Well, to be truthful, if the letter 'w'
         * occurred anywhere in the program name, but let's not get into that.)
d441 68
d746 1
d749 5
a753 1
	char *p;
a758 1
	frp = sp->frp;
d811 5
a815 9
		mtype = OLDFILE;
		if (!LF_ISSET(FS_FORCE | FS_APPEND)) {
			ep = sp->ep;
			if (noname && ep->mtime != 0 &&
			    (sb.st_dev != sp->ep->mdev ||
			    sb.st_ino != ep->minode ||
			    sb.st_mtime != ep->mtime)) {
				msgq_str(sp, M_ERR, name,
				    LF_ISSET(FS_POSSIBLE) ?
d818 1
a818 2
				return (1);
			}
d820 2
d894 1
a894 2
	if (noname) {
		ep = sp->ep;
d896 1
a896 1
			ep->mtime = 0;
d898 1
d901 1
a903 1
	}
d923 6
a928 5
	 * If wrote the entire file clear the modified bit.  If the file was
	 * written back to the original file name and the file is a temporary,
	 * set the "no exit" bit.  This permits the user to write the file and
	 * use it in the context of the file system, but still keeps them from
	 * losing their changes by exiting.
d930 2
a931 2
	if (LF_ISSET(FS_ALL)) {
		F_CLR(sp->ep, F_MODIFIED);
d942 3
a944 2
		msgq(sp, M_INFO, "256|%s: new file: %lu lines, %lu characters",
		    p, nlno, nch);
d947 4
a950 2
		msgq(sp, M_INFO, "257|%s: %s%lu lines, %lu characters",
		    p, LF_ISSET(FS_APPEND) ? "appended: " : "", nlno, nch);
d952 2
d955 21
d1181 1
a1181 1
	if (p == NULL || len <= 1 || p[0] != '/' || p[1] != '*')
d1183 4
a1186 4
	F_SET(sp, SC_SCR_TOP);
	do {
		for (; len; --len, ++p)
			if (p[0] == '*' && len > 1 && p[1] == '/') {
d1190 21
a1210 1
	} while (!db_get(sp, ++lno, 0, &p, &len));
d1225 4
d1230 1
a1230 1
	if (sp->ep == NULL)
d1239 1
a1239 1
	if (F_ISSET(sp->ep, F_MODIFIED))
d1243 1
a1243 1
		} else if (sp->ep->refcnt <= 1 && !force) {
d1265 4
d1270 1
a1270 1
	if (sp->ep == NULL)
d1277 1
a1277 1
	if (F_ISSET(sp->ep, F_MODIFIED) && sp->ep->refcnt <= 1 && !force) {
d1297 4
d1302 1
a1302 1
	if (sp->ep == NULL)
d1312 1
a1312 1
	if (F_ISSET(sp->frp, FR_TMPEXIT) && sp->ep->refcnt <= 1 && !force) {
d1490 5
a1494 2
	return (errno == EACCES || errno == EAGAIN || errno == EWOULDBLOCK ?
	    LOCK_UNAVAIL : LOCK_FAILED);
@


1.1
log
@Initial revision
@
text
@d1 2
d6 2
d9 1
a9 27
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
d12 2
d15 1
a15 1
static const char sccsid[] = "@@(#)exf.c	8.96 (Berkeley) 8/17/94";
d19 1
a21 1
#include <sys/time.h>
d31 1
a38 1
#include <termios.h>
d41 1
a41 4
#include "compat.h"
#include <db.h>
#include <regex.h>
#include <pathnames.h>
d43 3
a45 2
#include "vi.h"
#include "excmd.h"
d59 2
d67 2
a68 1
	FREF *frp;
d74 4
d79 1
d81 11
a91 2
		for (frp = sp->frefq.cqh_first;
		    frp != (FREF *)&sp->frefq; frp = frp->q.cqe_next)
d94 1
d108 1
a108 1
		FREE(frp, sizeof(FREF));
d114 1
a114 1
	CIRCLEQ_INSERT_TAIL(&sp->frefq, frp, q);
d124 2
d128 1
a128 1
file_init(sp, frp, rcv_name, force)
d132 1
a132 1
	int force;
d138 1
a138 1
	int fd;
d141 2
a169 1
	LIST_INIT(&ep->marks);
d173 11
a183 8
	 * If no name or backing file, create a backing temporary file, saving
	 * the temp file name so we can later unlink it.  If the user never
	 * named this file, copy the temporary file name to the real name (we
	 * display that until the user renames it).
	 */
	if ((oname = frp->name) == NULL || stat(oname, &sb)) {
		(void)snprintf(tname,
		    sizeof(tname), "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
d185 2
a186 1
			msgq(sp, M_SYSERR, "Temporary file");
d202 3
a204 2
		psize = 4 * 1024;
		F_SET(frp, FR_NEWFILE);
d207 4
a210 2
		 * Try to keep it at 10 pages or less per file.  This
		 * isn't friendly on a loaded machine, btw.
d212 6
a217 6
		if (sb.st_size < 40 * 1024)
			psize = 4 * 1024;
		else if (sb.st_size < 320 * 1024)
			psize = 32 * 1024;
		else
			psize = 64 * 1024;
d219 2
d224 2
a225 2
			msgq(sp, M_ERR,
			    "Warning: %s is not a regular file", oname);
d247 14
a260 3
	    O_NONBLOCK | O_RDONLY, DEFFILEMODE, DB_RECNO, &oinfo)) == NULL) {
		msgq(sp, M_SYSERR, rcv_name == NULL ? oname : rcv_name);
		goto err;
d271 15
a285 2
	 * Close the previous file; if that fails, close the new one and
	 * run for the border.
d298 7
a304 4
	F_SET(frp, FR_DONTDELETE);
	if (sp->ep != NULL && file_end(sp, sp->ep, force)) {
		(void)file_end(sp, ep, 1);
		goto err;
a305 1
	F_CLR(frp, FR_DONTDELETE);
d327 1
a327 1
		switch (file_lock(oname,
d333 3
a335 3
			msgq(sp, M_INFO,
			    "%s already locked, session is read-only", oname);
			F_SET(frp, FR_RDONLY);
d342 8
a349 4
	 * The -R flag, or doing a "set readonly" during a session causes
	 * all files edited during the session (using an edit command, or
	 * even using tags) to be marked read-only.  Changing the file name
	 * (see ex/ex_file.c), clears this flag.
d384 2
a385 1
	if (O_ISSET(sp, O_READONLY) || !F_ISSET(frp, FR_NEWFILE) &&
d388 3
a390 1
		F_SET(frp, FR_RDONLY);
d392 1
a392 21
	/*
	 * Set the alternate file name to be the file we've just discarded.
	 *
	 * !!!
	 * If the current file was a temporary file, the call to file_end()
	 * unlinked it and free'd the name.  So, there is no previous file,
	 * and there is no alternate file name.  This matches historical
	 * practice, although in historical vi it could only happen as the
	 * result of the initial command, i.e. if vi was executed without a
	 * file name.
	 */
	set_alt_name(sp, sp->frp == NULL ? NULL : sp->frp->name);

	/*
	 * Switch...
	 *
	 * !!!
	 * Note, because the EXF structure is examine at interrupt time,
	 * the underlying DB structures have to be consistent as soon as
	 * it's assigned to an SCR structure.
	 */
d396 7
d414 3
d423 111
a533 2
	FREE(ep, sizeof(EXF));
	return (1);
d539 2
d551 13
d587 1
a587 1
			msgq(sp, M_SYSERR, "%s: remove", frp->tname);
d591 3
a593 2
			CIRCLEQ_REMOVE(&sp->frefq, frp, q);
			free(frp->name);
d602 1
a602 3
	 * sp->ep MAY NOT BE THE SAME AS THE ARGUMENT ep, SO DON'T USE IT!
	 *
	 * If multiply referenced, just decrement the count and return.
a603 4
	if (--ep->refcnt != 0)
		return (0);

	/* Close the db structure. */
d605 1
a605 1
		msgq(sp, M_ERR, "%s: close: %s", frp->name, strerror(errno));
d629 1
a629 2
			msgq(sp, M_ERR,
			    "%s: remove: %s", ep->rcv_path, strerror(errno));
d631 1
a631 2
			msgq(sp, M_ERR,
			    "%s: remove: %s", ep->rcv_mpath, strerror(errno));
d642 1
a642 1
	FREE(ep, sizeof(EXF));
d651 2
d655 1
a655 1
file_write(sp, ep, fm, tm, name, flags)
a656 1
	EXF *ep;
d661 1
d663 1
d668 2
a669 2
	int btear, fd, noname, oflags, rval;
	char *msg;
d671 4
d676 1
a676 1
	if (name == NULL) {
d683 4
a686 6
	if (!LF_ISSET(FS_FORCE) && noname && F_ISSET(frp, FR_RDONLY)) {
		if (LF_ISSET(FS_POSSIBLE))
			msgq(sp, M_ERR,
			    "Read-only file, not written; use ! to override");
		else
			msgq(sp, M_ERR, "Read-only file, not written");
d695 4
a698 5
			if (LF_ISSET(FS_POSSIBLE))
				msgq(sp, M_ERR,
		"%s exists, not written; use ! to override", name);
			else
				msgq(sp, M_ERR, "%s exists, not written", name);
d707 3
a709 5
			if (LF_ISSET(FS_POSSIBLE))
				msgq(sp, M_ERR,
				    "Use ! to write a partial file");
			else
				msgq(sp, M_ERR, "Partial file, not written");
d721 3
a723 9
	 * If the user is overwriting a file other than the original file, and
	 * O_WRITEANY was what got us here (neither force nor append was set),
	 * display the "existing file" messsage.  Since the FR_NAMECHANGE flag
	 * is cleared on a successful write, the message only appears once when
	 * the user changes a file name.  This is historic practice.
	 *
	 * One final test.  If we're not forcing or appending, and we have a
	 * saved modification time, stop the user if it's been written since
	 * we last edited or wrote it, and make them force it.
d726 1
a726 1
		msg = ": new file";
d728 1
a728 1
		msg = "";
d730 9
a738 5
			if (ep->mtime && sb.st_mtime > ep->mtime) {
				msgq(sp, M_ERR,
			"%s: file modified more recently than this copy%s",
				    name, LF_ISSET(FS_POSSIBLE) ?
				    "; use ! to override" : "");
a740 2
			if (!noname || F_ISSET(frp, FR_NAMECHANGE))
				msg = ": existing file";
d744 8
a751 6
	/* Set flags to either append or truncate. */
	oflags = O_CREAT | O_WRONLY;
	if (LF_ISSET(FS_APPEND))
		oflags |= O_APPEND;
	else
		oflags |= O_TRUNC;
d754 24
a777 1
	if ((fd = open(name, oflags, DEFFILEMODE)) < 0) {
d781 1
d783 9
a791 2
	/* Use stdio for buffering. */
	if ((fp = fdopen(fd, "w")) == NULL) {
a792 1
		msgq(sp, M_SYSERR, name);
d801 1
a801 1
		if (file_lline(sp, ep, &to.lno))
d807 1
a807 5
	/* Turn on the busy message. */
	btear = F_ISSET(sp, S_EXSILENT) ? 0 : !busy_on(sp, "Writing...");
	rval = ex_writefp(sp, ep, name, fp, fm, tm, &nlno, &nch);
	if (btear)
		busy_off(sp);
d814 10
a823 1
	ep->mtime = stat(name, &sb) ? 0 : sb.st_mtime;
d825 4
a828 1
	/* If the write failed, complain loudly. */
d831 2
a832 1
			msgq(sp, M_ERR, "%s: WARNING: file truncated!", name);
d850 1
a850 1
		F_CLR(ep, F_MODIFIED);
d858 15
a872 3
	msgq(sp, M_INFO, "%s%s%s: %lu line%s, %lu characters",
	    INTERRUPTED(sp) ? "Interrupted write: " : "",
	    name, msg, nlno, nlno == 1 ? "" : "s", nch);
d874 171
d1046 38
d1090 2
d1094 1
a1094 1
file_m1(sp, ep, force, flags)
a1095 1
	EXF *ep;
d1098 4
d1108 1
a1108 1
	if (F_ISSET(ep, F_MODIFIED))
d1110 1
a1110 2
			if (!force &&
			    file_write(sp, ep, NULL, NULL, NULL, flags))
d1112 4
a1115 4
		} else if (ep->refcnt <= 1 && !force) {
			msgq(sp, M_ERR,
	"File modified since last complete write; write or use %s to override",
			    LF_ISSET(FS_POSSIBLE) ? "!" : ":edit!");
d1119 1
a1119 1
	return (file_m3(sp, ep, force));
d1126 2
d1130 1
a1130 1
file_m2(sp, ep, force)
a1131 1
	EXF *ep;
d1134 4
d1142 1
a1142 1
	if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
d1144 1
a1144 1
    "File modified since last complete write; write or use ! to override");
d1148 1
a1148 1
	return (file_m3(sp, ep, force));
d1154 2
d1158 1
a1158 1
file_m3(sp, ep, force)
a1159 1
	EXF *ep;
d1162 4
d1173 1
a1173 1
	if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
d1175 1
a1175 1
		    "File is a temporary; exit will discard modifications");
d1182 82
d1266 1
a1266 1
 * 
d1283 2
d1286 3
a1288 2
enum lockt
file_lock(name, fdp, fd, iswrite)
d1290 1
a1290 1
	int fd, *fdp, iswrite;
d1292 4
a1295 2
#if !defined(USE_FCNTL) && defined(LOCK_EX)
					/* Hurrah!  We've got flock(2). */
d1304 8
a1311 5
	return (flock(fd, LOCK_EX | LOCK_NB) ?
	    errno == EAGAIN || errno == EWOULDBLOCK ?
	        LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);

#else					/* Gag me.  We've got fcntl(2). */
d1319 7
a1325 2
	
	/* If the file descriptor isn't opened for writing, it must fail. */
d1330 1
a1330 1
			return (LOCK_FAILED);
d1334 1
a1334 1
		
d1353 4
@


1.1.1.1
log
@new public version of nvi
@
text
@@


1.1.1.2
log
@new public version of nvi
@
text
@d35 1
a35 1
static char sccsid[] = "@@(#)exf.c	8.97 (Berkeley) 8/17/94";
@


1.1.1.2.2.1
log
@file exf.c was added on branch netbsd-1-0 on 1994-08-17 19:24:46 +0000
@
text
@d1 837
@


1.1.1.2.2.2
log
@new public version of nvi
@
text
@a0 837
/*-
 * Copyright (c) 1992, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
static char sccsid[] = "@@(#)exf.c	8.97 (Berkeley) 8/17/94";
#endif /* not lint */

#include <sys/param.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/time.h>

/*
 * We include <sys/file.h>, because the flock(2) and open(2) #defines
 * were found there on historical systems.  We also include <fcntl.h>
 * because the open(2) #defines are found there on newer systems.
 */
#include <sys/file.h>

#include <bitstring.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

#include "compat.h"
#include <db.h>
#include <regex.h>
#include <pathnames.h>

#include "vi.h"
#include "excmd.h"

/*
 * file_add --
 *	Insert a file name into the FREF list, if it doesn't already
 *	appear in it.
 *
 * !!!
 * The "if it doesn't already appear" changes vi's semantics slightly.  If
 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
 * will reflect the line/column of the previous edit session.  Historic nvi
 * did not do this.  The change is a logical extension of the change where
 * vi now remembers the last location in any file that it has ever edited,
 * not just the previously edited file.
 */
FREF *
file_add(sp, name)
	SCR *sp;
	CHAR_T *name;
{
	FREF *frp;

	/*
	 * Return it if it already exists.  Note that we test against the
	 * user's name, whatever that happens to be, including if it's a
	 * temporary file.
	 */
	if (name != NULL)
		for (frp = sp->frefq.cqh_first;
		    frp != (FREF *)&sp->frefq; frp = frp->q.cqe_next)
			if (!strcmp(frp->name, name))
				return (frp);

	/* Allocate and initialize the FREF structure. */
	CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
	if (frp == NULL)
		return (NULL);

	/*
	 * If no file name specified, or if the file name is a request
	 * for something temporary, file_init() will allocate the file
	 * name.  Temporary files are always ignored.
	 */
	if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
	    (frp->name = strdup(name)) == NULL) {
		FREE(frp, sizeof(FREF));
		msgq(sp, M_SYSERR, NULL);
		return (NULL);
	}

	/* Append into the chain of file names. */
	CIRCLEQ_INSERT_TAIL(&sp->frefq, frp, q);

	return (frp);
}

/*
 * file_init --
 *	Start editing a file, based on the FREF structure.  If successsful,
 *	let go of any previous file.  Don't release the previous file until
 *	absolutely sure we have the new one.
 */
int
file_init(sp, frp, rcv_name, force)
	SCR *sp;
	FREF *frp;
	char *rcv_name;
	int force;
{
	EXF *ep;
	RECNOINFO oinfo;
	struct stat sb;
	size_t psize;
	int fd;
	char *oname, tname[MAXPATHLEN];

	/*
	 * If the file is a recovery file, let the recovery code handle it.
	 * Clear the FR_RECOVER flag first -- the recovery code does set up,
	 * and then calls us!  If the recovery call fails, it's probably
	 * because the named file doesn't exist.  So, move boldly forward,
	 * presuming that there's an error message the user will get to see.
	 */
	if (F_ISSET(frp, FR_RECOVER)) {
		F_CLR(frp, FR_RECOVER);
		return (rcv_read(sp, frp));
	}

	/*
	 * Required FRP initialization; the only flag we keep is the
	 * cursor information.
	 */
	F_CLR(frp, ~FR_CURSORSET);

	/*
	 * Required EXF initialization:
	 *	Flush the line caches.
	 *	Default recover mail file fd to -1.
	 *	Set initial EXF flag bits.
	 */
	CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
	ep->c_lno = ep->c_nlines = OOBLNO;
	ep->rcv_fd = ep->fcntl_fd = -1;
	LIST_INIT(&ep->marks);
	F_SET(ep, F_FIRSTMODIFY);

	/*
	 * If no name or backing file, create a backing temporary file, saving
	 * the temp file name so we can later unlink it.  If the user never
	 * named this file, copy the temporary file name to the real name (we
	 * display that until the user renames it).
	 */
	if ((oname = frp->name) == NULL || stat(oname, &sb)) {
		(void)snprintf(tname,
		    sizeof(tname), "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
		if ((fd = mkstemp(tname)) == -1) {
			msgq(sp, M_SYSERR, "Temporary file");
			goto err;
		}
		(void)close(fd);

		if (frp->name == NULL)
			F_SET(frp, FR_TMPFILE);
		if ((frp->tname = strdup(tname)) == NULL ||
		    frp->name == NULL && (frp->name = strdup(tname)) == NULL) {
			if (frp->tname != NULL)
				free(frp->tname);
			msgq(sp, M_SYSERR, NULL);
			(void)unlink(tname);
			goto err;
		}
		oname = frp->tname;
		psize = 4 * 1024;
		F_SET(frp, FR_NEWFILE);
	} else {
		/*
		 * Try to keep it at 10 pages or less per file.  This
		 * isn't friendly on a loaded machine, btw.
		 */
		if (sb.st_size < 40 * 1024)
			psize = 4 * 1024;
		else if (sb.st_size < 320 * 1024)
			psize = 32 * 1024;
		else
			psize = 64 * 1024;

		ep->mtime = sb.st_mtime;

		if (!S_ISREG(sb.st_mode))
			msgq(sp, M_ERR,
			    "Warning: %s is not a regular file", oname);
	}

	/* Set up recovery. */
	memset(&oinfo, 0, sizeof(RECNOINFO));
	oinfo.bval = '\n';			/* Always set. */
	oinfo.psize = psize;
	oinfo.flags = F_ISSET(sp->gp, G_SNAPSHOT) ? R_SNAPSHOT : 0;
	if (rcv_name == NULL) {
		if (!rcv_tmp(sp, ep, frp->name))
			oinfo.bfname = ep->rcv_path;
	} else {
		if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
			msgq(sp, M_SYSERR, NULL);
			goto err;
		}
		oinfo.bfname = ep->rcv_path;
		F_SET(ep, F_MODIFIED);
	}

	/* Open a db structure. */
	if ((ep->db = dbopen(rcv_name == NULL ? oname : NULL,
	    O_NONBLOCK | O_RDONLY, DEFFILEMODE, DB_RECNO, &oinfo)) == NULL) {
		msgq(sp, M_SYSERR, rcv_name == NULL ? oname : rcv_name);
		goto err;
	}

	/*
	 * Do the remaining things that can cause failure of the new file,
	 * mark and logging initialization.
	 */
	if (mark_init(sp, ep) || log_init(sp, ep))
		goto err;

	/*
	 * Close the previous file; if that fails, close the new one and
	 * run for the border.
	 *
	 * !!!
	 * There's a nasty special case.  If the user edits a temporary file,
	 * and then does an ":e! %", we need to re-initialize the backing
	 * file, but we can't change the name.  (It's worse -- we're dealing
	 * with *names* here, we can't even detect that it happened.)  Set a
	 * flag so that the file_end routine ignores the backing information
	 * of the old file if it happens to be the same as the new one.
	 *
	 * !!!
	 * Side-effect: after the call to file_end(), sp->frp may be NULL.
	 */
	F_SET(frp, FR_DONTDELETE);
	if (sp->ep != NULL && file_end(sp, sp->ep, force)) {
		(void)file_end(sp, ep, 1);
		goto err;
	}
	F_CLR(frp, FR_DONTDELETE);

	/*
	 * Lock the file; if it's a recovery file, it should already be
	 * locked.  Note, we acquire the lock after the previous file
	 * has been ended, so that we don't get an "already locked" error
	 * for ":edit!".
	 *
	 * XXX
	 * While the user can't interrupt us between the open and here,
	 * there's a race between the dbopen() and the lock.  Not much
	 * we can do about it.
	 *
	 * XXX
	 * We don't make a big deal of not being able to lock the file.  As
	 * locking rarely works over NFS, and often fails if the file was
	 * mmap(2)'d, it's far too common to do anything like print an error
	 * message, let alone make the file readonly.  At some future time,
	 * when locking is a little more reliable, this should change to be
	 * an error.
	 */
	if (rcv_name == NULL)
		switch (file_lock(oname,
		    &ep->fcntl_fd, ep->db->fd(ep->db), 0)) {
		case LOCK_FAILED:
			F_SET(frp, FR_UNLOCKED);
			break;
		case LOCK_UNAVAIL:
			msgq(sp, M_INFO,
			    "%s already locked, session is read-only", oname);
			F_SET(frp, FR_RDONLY);
			break;
		case LOCK_SUCCESS:
			break;
		}

	/*
	 * The -R flag, or doing a "set readonly" during a session causes
	 * all files edited during the session (using an edit command, or
	 * even using tags) to be marked read-only.  Changing the file name
	 * (see ex/ex_file.c), clears this flag.
	 *
	 * Otherwise, try and figure out if a file is readonly.  This is a
	 * dangerous thing to do.  The kernel is the only arbiter of whether
	 * or not a file is writeable, and the best that a user program can
	 * do is guess.  Obvious loopholes are files that are on a file system
	 * mounted readonly (access catches this one on a few systems), or
	 * alternate protection mechanisms, ACL's for example, that we can't
	 * portably check.  Lots of fun, and only here because users whined.
	 *
	 * !!!
	 * Historic vi displayed the readonly message if none of the file
	 * write bits were set, or if an an access(2) call on the path
	 * failed.  This seems reasonable.  If the file is mode 444, root
	 * users may want to know that the owner of the file did not expect
	 * it to be written.
	 *
	 * Historic vi set the readonly bit if no write bits were set for
	 * a file, even if the access call would have succeeded.  This makes
	 * the superuser force the write even when vi expects that it will
	 * succeed.  I'm less supportive of this semantic, but it's historic
	 * practice and the conservative approach to vi'ing files as root.
	 *
	 * It would be nice if there was some way to update this when the user
	 * does a "^Z; chmod ...".  The problem is that we'd first have to
	 * distinguish between readonly bits set because of file permissions
	 * and those set for other reasons.  That's not too hard, but deciding
	 * when to reevaluate the permissions is trickier.  An alternative
	 * might be to turn off the readonly bit if the user forces a write
	 * and it succeeds.
	 *
	 * XXX
	 * Access(2) doesn't consider the effective uid/gid values.  This
	 * probably isn't a problem for vi when it's running standalone.
	 */
	if (O_ISSET(sp, O_READONLY) || !F_ISSET(frp, FR_NEWFILE) &&
	    (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
	    access(frp->name, W_OK)))
		F_SET(frp, FR_RDONLY);

	/*
	 * Set the alternate file name to be the file we've just discarded.
	 *
	 * !!!
	 * If the current file was a temporary file, the call to file_end()
	 * unlinked it and free'd the name.  So, there is no previous file,
	 * and there is no alternate file name.  This matches historical
	 * practice, although in historical vi it could only happen as the
	 * result of the initial command, i.e. if vi was executed without a
	 * file name.
	 */
	set_alt_name(sp, sp->frp == NULL ? NULL : sp->frp->name);

	/*
	 * Switch...
	 *
	 * !!!
	 * Note, because the EXF structure is examine at interrupt time,
	 * the underlying DB structures have to be consistent as soon as
	 * it's assigned to an SCR structure.
	 */
	++ep->refcnt;
	sp->ep = ep;
	sp->frp = frp;
	return (0);

err:	if (frp->name != NULL) {
		free(frp->name);
		frp->name = NULL;
	}
	if (frp->tname != NULL) {
		(void)unlink(frp->tname);
		free(frp->tname);
		frp->tname = NULL;
	}
	if (ep->rcv_path != NULL) {
		free(ep->rcv_path);
		ep->rcv_path = NULL;
	}
	if (ep->db != NULL)
		(void)ep->db->close(ep->db);
	FREE(ep, sizeof(EXF));
	return (1);
}

/*
 * file_end --
 *	Stop editing a file.
 */
int
file_end(sp, ep, force)
	SCR *sp;
	EXF *ep;
	int force;
{
	FREF *frp;

	/*
	 * Clean up the FREF structure.
	 *
	 * Save the cursor location.
	 *
	 * XXX
	 * It would be cleaner to do this somewhere else, but by the time
	 * ex or vi knows that we're changing files it's already happened.
	 */
	frp = sp->frp;
	frp->lno = sp->lno;
	frp->cno = sp->cno;
	F_SET(frp, FR_CURSORSET);

	/*
	 * We may no longer need the temporary backing file, so clean it
	 * up.  We don't need the FREF structure either, if the file was
	 * never named, so lose it.
	 *
	 * !!!
	 * Re: FR_DONTDELETE, see the comment above in file_init().
	 */
	if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
		if (unlink(frp->tname))
			msgq(sp, M_SYSERR, "%s: remove", frp->tname);
		free(frp->tname);
		frp->tname = NULL;
		if (F_ISSET(frp, FR_TMPFILE)) {
			CIRCLEQ_REMOVE(&sp->frefq, frp, q);
			free(frp->name);
			free(frp);
		}
		sp->frp = NULL;
	}

	/*
	 * Clean up the EXF structure.
	 *
	 * sp->ep MAY NOT BE THE SAME AS THE ARGUMENT ep, SO DON'T USE IT!
	 *
	 * If multiply referenced, just decrement the count and return.
	 */
	if (--ep->refcnt != 0)
		return (0);

	/* Close the db structure. */
	if (ep->db->close != NULL && ep->db->close(ep->db) && !force) {
		msgq(sp, M_ERR, "%s: close: %s", frp->name, strerror(errno));
		++ep->refcnt;
		return (1);
	}

	/* COMMITTED TO THE CLOSE.  THERE'S NO GOING BACK... */

	/* Stop logging. */
	(void)log_end(sp, ep);

	/* Free up any marks. */
	(void)mark_end(sp, ep);

	/*
	 * Delete recovery files, close the open descriptor, free recovery
	 * memory.  See recover.c for a description of the protocol.
	 *
	 * XXX
	 * Unlink backup file first, we can detect that the recovery file
	 * doesn't reference anything when the user tries to recover it.
	 * There's a race, here, obviously, but it's fairly small.
	 */
	if (!F_ISSET(ep, F_RCV_NORM)) {
		if (ep->rcv_path != NULL && unlink(ep->rcv_path))
			msgq(sp, M_ERR,
			    "%s: remove: %s", ep->rcv_path, strerror(errno));
		if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
			msgq(sp, M_ERR,
			    "%s: remove: %s", ep->rcv_mpath, strerror(errno));
	}
	if (ep->fcntl_fd != -1)
		(void)close(ep->fcntl_fd);
	if (ep->rcv_fd != -1)
		(void)close(ep->rcv_fd);
	if (ep->rcv_path != NULL)
		free(ep->rcv_path);
	if (ep->rcv_mpath != NULL)
		free(ep->rcv_mpath);

	FREE(ep, sizeof(EXF));
	return (0);
}

/*
 * file_write --
 *	Write the file to disk.  Historic vi had fairly convoluted
 *	semantics for whether or not writes would happen.  That's
 *	why all the flags.
 */
int
file_write(sp, ep, fm, tm, name, flags)
	SCR *sp;
	EXF *ep;
	MARK *fm, *tm;
	char *name;
	int flags;
{
	struct stat sb;
	FILE *fp;
	FREF *frp;
	MARK from, to;
	u_long nlno, nch;
	int btear, fd, noname, oflags, rval;
	char *msg;

	frp = sp->frp;
	if (name == NULL) {
		noname = 1;
		name = frp->name;
	} else
		noname = 0;

	/* Can't write files marked read-only, unless forced. */
	if (!LF_ISSET(FS_FORCE) && noname && F_ISSET(frp, FR_RDONLY)) {
		if (LF_ISSET(FS_POSSIBLE))
			msgq(sp, M_ERR,
			    "Read-only file, not written; use ! to override");
		else
			msgq(sp, M_ERR, "Read-only file, not written");
		return (1);
	}

	/* If not forced, not appending, and "writeany" not set ... */
	if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
		/* Don't overwrite anything but the original file. */
		if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
		    !stat(name, &sb)) {
			if (LF_ISSET(FS_POSSIBLE))
				msgq(sp, M_ERR,
		"%s exists, not written; use ! to override", name);
			else
				msgq(sp, M_ERR, "%s exists, not written", name);
			return (1);
		}

		/*
		 * Don't write part of any existing file.  Only test for the
		 * original file, the previous test catches anything else.
		 */
		if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
			if (LF_ISSET(FS_POSSIBLE))
				msgq(sp, M_ERR,
				    "Use ! to write a partial file");
			else
				msgq(sp, M_ERR, "Partial file, not written");
			return (1);
		}
	}

	/*
	 * Figure out if the file already exists -- if it doesn't, we display
	 * the "new file" message.  The stat might not be necessary, but we
	 * just repeat it because it's easier than hacking the previous tests.
	 * The information is only used for the user message and modification
	 * time test, so we can ignore the obvious race condition.
	 *
	 * If the user is overwriting a file other than the original file, and
	 * O_WRITEANY was what got us here (neither force nor append was set),
	 * display the "existing file" messsage.  Since the FR_NAMECHANGE flag
	 * is cleared on a successful write, the message only appears once when
	 * the user changes a file name.  This is historic practice.
	 *
	 * One final test.  If we're not forcing or appending, and we have a
	 * saved modification time, stop the user if it's been written since
	 * we last edited or wrote it, and make them force it.
	 */
	if (stat(name, &sb))
		msg = ": new file";
	else {
		msg = "";
		if (!LF_ISSET(FS_FORCE | FS_APPEND)) {
			if (ep->mtime && sb.st_mtime > ep->mtime) {
				msgq(sp, M_ERR,
			"%s: file modified more recently than this copy%s",
				    name, LF_ISSET(FS_POSSIBLE) ?
				    "; use ! to override" : "");
				return (1);
			}
			if (!noname || F_ISSET(frp, FR_NAMECHANGE))
				msg = ": existing file";
		}
	}

	/* Set flags to either append or truncate. */
	oflags = O_CREAT | O_WRONLY;
	if (LF_ISSET(FS_APPEND))
		oflags |= O_APPEND;
	else
		oflags |= O_TRUNC;

	/* Open the file. */
	if ((fd = open(name, oflags, DEFFILEMODE)) < 0) {
		msgq(sp, M_SYSERR, name);
		return (1);
	}

	/* Use stdio for buffering. */
	if ((fp = fdopen(fd, "w")) == NULL) {
		(void)close(fd);
		msgq(sp, M_SYSERR, name);
		return (1);
	}

	/* Build fake addresses, if necessary. */
	if (fm == NULL) {
		from.lno = 1;
		from.cno = 0;
		fm = &from;
		if (file_lline(sp, ep, &to.lno))
			return (1);
		to.cno = 0;
		tm = &to;
	}

	/* Turn on the busy message. */
	btear = F_ISSET(sp, S_EXSILENT) ? 0 : !busy_on(sp, "Writing...");
	rval = ex_writefp(sp, ep, name, fp, fm, tm, &nlno, &nch);
	if (btear)
		busy_off(sp);

	/*
	 * Save the new last modification time -- even if the write fails
	 * we re-init the time.  That way the user can clean up the disk
	 * and rewrite without having to force it.
	 */
	ep->mtime = stat(name, &sb) ? 0 : sb.st_mtime;

	/* If the write failed, complain loudly. */
	if (rval) {
		if (!LF_ISSET(FS_APPEND))
			msgq(sp, M_ERR, "%s: WARNING: file truncated!", name);
		return (1);
	}

	/*
	 * Once we've actually written the file, it doesn't matter that the
	 * file name was changed -- if it was, we've already whacked it.
	 */
	F_CLR(frp, FR_NAMECHANGE);

	/*
	 * If wrote the entire file clear the modified bit.  If the file was
	 * written back to the original file name and the file is a temporary,
	 * set the "no exit" bit.  This permits the user to write the file and
	 * use it in the context of the file system, but still keeps them from
	 * losing their changes by exiting.
	 */
	if (LF_ISSET(FS_ALL)) {
		F_CLR(ep, F_MODIFIED);
		if (F_ISSET(frp, FR_TMPFILE))
			if (noname)
				F_SET(frp, FR_TMPEXIT);
			else
				F_CLR(frp, FR_TMPEXIT);
	}

	msgq(sp, M_INFO, "%s%s%s: %lu line%s, %lu characters",
	    INTERRUPTED(sp) ? "Interrupted write: " : "",
	    name, msg, nlno, nlno == 1 ? "" : "s", nch);

	return (0);
}

/*
 * file_m1 --
 * 	First modification check routine.  The :next, :prev, :rewind, :tag,
 *	:tagpush, :tagpop, ^^ modifications check.
 */
int
file_m1(sp, ep, force, flags)
	SCR *sp;
	EXF *ep;
	int force, flags;
{
	/*
	 * If the file has been modified, we'll want to write it back or
	 * fail.  If autowrite is set, we'll write it back automatically,
	 * unless force is also set.  Otherwise, we fail unless forced or
	 * there's another open screen on this file.
	 */
	if (F_ISSET(ep, F_MODIFIED))
		if (O_ISSET(sp, O_AUTOWRITE)) {
			if (!force &&
			    file_write(sp, ep, NULL, NULL, NULL, flags))
				return (1);
		} else if (ep->refcnt <= 1 && !force) {
			msgq(sp, M_ERR,
	"File modified since last complete write; write or use %s to override",
			    LF_ISSET(FS_POSSIBLE) ? "!" : ":edit!");
			return (1);
		}

	return (file_m3(sp, ep, force));
}

/*
 * file_m2 --
 * 	Second modification check routine.  The :edit, :quit, :recover
 *	modifications check.
 */
int
file_m2(sp, ep, force)
	SCR *sp;
	EXF *ep;
	int force;
{
	/*
	 * If the file has been modified, we'll want to fail, unless forced
	 * or there's another open screen on this file.
	 */
	if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
		msgq(sp, M_ERR,
    "File modified since last complete write; write or use ! to override");
		return (1);
	}

	return (file_m3(sp, ep, force));
}

/*
 * file_m3 --
 * 	Third modification check routine.
 */
int
file_m3(sp, ep, force)
	SCR *sp;
	EXF *ep;
	int force;
{
	/*
	 * Don't exit while in a temporary files if the file was ever modified.
	 * The problem is that if the user does a ":wq", we write and quit,
	 * unlinking the temporary file.  Not what the user had in mind at all.
	 * We permit writing to temporary files, so that user maps using file
	 * system names work with temporary files.
	 */
	if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
		msgq(sp, M_ERR,
		    "File is a temporary; exit will discard modifications");
		return (1);
	}
	return (0);
}

/*
 * file_lock --
 *	Get an exclusive lock on a file.
 * 
 * XXX
 * The default locking is flock(2) style, not fcntl(2).  The latter is
 * known to fail badly on some systems, and its only advantage is that
 * it occasionally works over NFS.
 *
 * Furthermore, the semantics of fcntl(2) are wrong.  The problems are
 * two-fold: you can't close any file descriptor associated with the file
 * without losing all of the locks, and you can't get an exclusive lock
 * unless you have the file open for writing.  Someone ought to be shot,
 * but it's probably too late, they may already have reproduced.  To get
 * around these problems, nvi opens the files for writing when it can and
 * acquires a second file descriptor when it can't.  The recovery files
 * are examples of the former, they're always opened for writing.  The DB
 * files can't be opened for writing because the semantics of DB are that
 * files opened for writing are flushed back to disk when the DB session
 * is ended. So, in that case we have to acquire an extra file descriptor.
 */
enum lockt
file_lock(name, fdp, fd, iswrite)
	char *name;
	int fd, *fdp, iswrite;
{
#if !defined(USE_FCNTL) && defined(LOCK_EX)
					/* Hurrah!  We've got flock(2). */
	/*
	 * !!!
	 * We need to distinguish a lock not being available for the file
	 * from the file system not supporting locking.  Flock is documented
	 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
	 * they are the former.  There's no portable way to do this.
	 */
	errno = 0;
	return (flock(fd, LOCK_EX | LOCK_NB) ?
	    errno == EAGAIN || errno == EWOULDBLOCK ?
	        LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);

#else					/* Gag me.  We've got fcntl(2). */
	struct flock arg;
	int didopen, sverrno;

	arg.l_type = F_WRLCK;
	arg.l_whence = 0;		/* SEEK_SET */
	arg.l_start = arg.l_len = 0;
	arg.l_pid = 0;
	
	/* If the file descriptor isn't opened for writing, it must fail. */
	if (!iswrite) {
		if (name == NULL || fdp == NULL)
			return (LOCK_FAILED);
		if ((fd = open(name, O_RDWR, 0)) == -1)
			return (LOCK_FAILED);
		*fdp = fd;
		didopen = 1;
	}
		
	errno = 0;
	if (!fcntl(fd, F_SETLK, &arg))
		return (LOCK_SUCCESS);
	if (didopen) {
		sverrno = errno;
		(void)close(fd);
		errno = sverrno;
	}

	/*
	 * !!!
	 * We need to distinguish a lock not being available for the file
	 * from the file system not supporting locking.  Fcntl is documented
	 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
	 * and assume they are the former.  There's no portable way to do this.
	 */
	return (errno == EACCES || errno == EAGAIN || errno == EWOULDBLOCK ?
	    LOCK_UNAVAIL : LOCK_FAILED);
#endif
}
@


1.1.1.3
log
@import of nvi 1.66
@
text
@a3 2
 * Copyright (c) 1992, 1993, 1994, 1995, 1996
 *	Keith Bostic.  All rights reserved.
d5 27
a31 1
 * See the LICENSE file for redistribution information.
a33 2
#include "config.h"

d35 1
a35 1
static const char sccsid[] = "@@(#)exf.c	10.35 (Berkeley) 5/16/96";
a38 1
#include <sys/types.h>		/* XXX: param.h may not have included types.h */
d41 1
a50 1
#include <dirent.h>
d58 1
d61 4
a64 1
#include "common.h"
d66 2
a67 3
static int	file_backup __P((SCR *, char *, char *));
static void	file_cinit __P((SCR *));
static void	file_comment __P((SCR *));
a80 2
 *
 * PUBLIC: FREF *file_add __P((SCR *, CHAR_T *));
d87 1
a87 2
	GS *gp;
	FREF *frp, *tfrp;
a92 4
	 *
	 * If the user added a file but was unable to initialize it, there
	 * can be file list entries where the name field is NULL.  Discard
	 * them the next time we see them.
a93 1
	gp = sp->gp;
d95 2
a96 11
		for (frp = gp->frefq.cqh_first;
		    frp != (FREF *)&gp->frefq; frp = frp->q.cqe_next) {
			if (frp->name == NULL) {
				tfrp = frp->q.cqe_next;
				CIRCLEQ_REMOVE(&gp->frefq, frp, q);
				if (frp->name != NULL)
					free(frp->name);
				free(frp);
				frp = tfrp;
				continue;
			}
a98 1
		}
d112 1
a112 1
		free(frp);
d118 1
a118 1
	CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);
a127 2
 *
 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
d130 1
a130 1
file_init(sp, frp, rcv_name, flags)
d134 1
a134 1
	int flags;
d140 1
a140 1
	int fd, open_err, readonly;
a142 2
	open_err = readonly = 0;

d170 1
d174 8
a181 11
	 * If no name or backing file, for whatever reason, create a backing
	 * temporary file, saving the temp file name so we can later unlink
	 * it.  If the user never named this file, copy the temporary file name
	 * to the real name (we display that until the user renames it).
	 */
	oname = frp->name;
	if (LF_ISSET(FS_OPENERR) || oname == NULL || stat(oname, &sb)) {
		if (opts_empty(sp, O_DIRECTORY, 0))
			goto err;
		(void)snprintf(tname, sizeof(tname),
		    "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
d183 1
a183 2
			msgq(sp, M_SYSERR,
			    "237|Unable to create temporary file");
d199 2
a200 3
		psize = 1024;
		if (!LF_ISSET(FS_OPENERR))
			F_SET(frp, FR_NEWFILE);
d203 2
a204 4
		 * XXX
		 * A seat of the pants calculation: try to keep the file in
		 * 15 pages or less.  Don't use a page size larger than 10K
		 * (vi should have good locality) or smaller than 1K.
d206 6
a211 6
		psize = ((sb.st_size / 15) + 1023) / 1024;
		if (psize > 10)
			psize = 10;
		if (psize == 0)
			psize = 1;
		psize *= 1024;
a212 2
		ep->mdev = sb.st_dev;
		ep->minode = sb.st_ino;
d216 2
a217 2
			msgq_str(sp, M_ERR, oname,
			    "238|Warning: %s is not a regular file");
d239 3
a241 14
	    O_NONBLOCK | O_RDONLY,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH,
	    DB_RECNO, &oinfo)) == NULL) {
		msgq_str(sp,
		    M_SYSERR, rcv_name == NULL ? oname : rcv_name, "%s");
		/*
		 * !!!
		 * Historically, vi permitted users to edit files that couldn't
		 * be read.  This isn't useful for single files from a command
		 * line, but it's quite useful for "vi *.c", since you can skip
		 * past files that you can't read.
		 */ 
		open_err = 1;
		goto oerr;
d252 2
a253 15
	 * Set the alternate file name to be the file we're discarding.
	 *
	 * !!!
	 * Temporary files can't become alternate files, so there's no file
	 * name.  This matches historical practice, although it could only
	 * happen in historical vi as the result of the initial command, i.e.
	 * if vi was executed without a file name.
	 */
	if (LF_ISSET(FS_SETALT))
		set_alt_name(sp, sp->frp == NULL ||
		    F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);

	/*
	 * Close the previous file; if that fails, close the new one and run
	 * for the border.
d266 4
a269 7
	if (sp->ep != NULL) {
		F_SET(frp, FR_DONTDELETE);
		if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
			(void)file_end(sp, ep, 1);
			goto err;
		}
		F_CLR(frp, FR_DONTDELETE);
d271 1
d293 1
a293 1
		switch (file_lock(sp, oname,
d299 3
a301 3
			readonly = 1;
			msgq_str(sp, M_INFO, oname,
			    "239|%s already locked, session is read-only");
d308 4
a311 8
         * Historically, the readonly edit option was set per edit buffer in
         * vi, unless the -R command-line option was specified or the program
         * was executed as "view".  (Well, to be truthful, if the letter 'w'
         * occurred anywhere in the program name, but let's not get into that.)
	 * So, the persistant readonly state has to be stored in the screen
	 * structure, and the edit option value toggles with the contents of
	 * the edit buffer.  If the persistant readonly flag is set, set the
	 * readonly edit option.
d346 1
a346 2
	if (readonly || F_ISSET(sp, SC_READONLY) ||
	    !F_ISSET(frp, FR_NEWFILE) &&
d349 14
a362 3
		O_SET(sp, O_READONLY);
	else
		O_CLR(sp, O_READONLY);
d364 8
a371 1
	/* Switch... */
a374 7

	/* Set the initial cursor position, queue initial command. */
	file_cinit(sp);

	/* Redraw the screen from scratch, schedule a welcome message. */
	F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);

a385 3

oerr:	if (F_ISSET(ep, F_RCV_ON))
		(void)unlink(ep->rcv_path);
d392 2
a393 111
	free(ep);

	return (open_err ?
	    file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
}

/*
 * file_cinit --
 *	Set up the initial cursor position.
 */
static void
file_cinit(sp)
	SCR *sp;
{
	GS *gp;
	MARK m;
	size_t len;
	int nb;

	/* Set some basic defaults. */
	sp->lno = 1;
	sp->cno = 0;

	/*
	 * Historically, initial commands (the -c option) weren't executed
	 * until a file was loaded, e.g. "vi +10 nofile", followed by an
	 * :edit or :tag command, would execute the +10 on the file loaded
	 * by the subsequent command, (assuming that it existed).  This
	 * applied as well to files loaded using the tag commands, and we
	 * follow that historic practice.  Also, all initial commands were
	 * ex commands and were always executed on the last line of the file.
	 *
	 * Otherwise, if no initial command for this file:
	 *    If in ex mode, move to the last line, first nonblank character.
	 *    If the file has previously been edited, move to the last known
	 *	  position, and check it for validity.
	 *    Otherwise, move to the first line, first nonblank.
	 *
	 * This gets called by the file init code, because we may be in a
	 * file of ex commands and we want to execute them from the right
	 * location in the file.
	 */
	nb = 0;
	gp = sp->gp;
	if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
		if (db_last(sp, &sp->lno))
			return;
		if (sp->lno == 0) {
			sp->lno = 1;
			sp->cno = 0;
		}
		if (ex_run_str(sp,
		    "-c option", gp->c_option, strlen(gp->c_option), 1, 1))
			return;
		gp->c_option = NULL;
	} else if (F_ISSET(sp, SC_EX)) {
		if (db_last(sp, &sp->lno))
			return;
		if (sp->lno == 0) {
			sp->lno = 1;
			sp->cno = 0;
			return;
		}
		nb = 1;
	} else {
		if (F_ISSET(sp->frp, FR_CURSORSET)) {
			sp->lno = sp->frp->lno;
			sp->cno = sp->frp->cno;

			/* If returning to a file in vi, center the line. */
			 F_SET(sp, SC_SCR_CENTER);
		} else {
			if (O_ISSET(sp, O_COMMENT))
				file_comment(sp);
			else
				sp->lno = 1;
			nb = 1;
		}
		if (db_get(sp, sp->lno, 0, NULL, &len)) {
			sp->lno = 1;
			sp->cno = 0;
			return;
		}
		if (!nb && sp->cno > len)
			nb = 1;
	}
	if (nb) {
		sp->cno = 0;
		(void)nonblank(sp, sp->lno, &sp->cno);
	}

	/*
	 * !!!
	 * The initial column is also the most attractive column.
	 */
	sp->rcm = sp->cno;

	/*
	 * !!!
	 * Historically, vi initialized the absolute mark, but ex did not.
	 * Which meant, that if the first command in ex mode was "visual",
	 * or if an ex command was executed first (e.g. vi +10 file) vi was
	 * entered without the mark being initialized.  For consistency, if
	 * the file isn't empty, we initialize it for everyone, believing
	 * that it can't hurt, and is generally useful.  Not initializing it
	 * if the file is empty is historic practice, although it has always
	 * been possible to set (and use) marks in empty vi files.
	 */
	m.lno = sp->lno;
	m.cno = sp->cno;
	(void)mark_set(sp, ABSMARK1, &m, 0);
a398 2
 *
 * PUBLIC: int file_end __P((SCR *, EXF *, int));
a408 13
	 * !!!
	 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
	 * (If argument ep is NULL, use sp->ep.)
	 *
	 * If multiply referenced, just decrement the count and return.
	 */
	if (ep == NULL)
		ep = sp->ep;
	if (--ep->refcnt != 0)
		return (0);

	/*
	 *
d432 1
a432 1
			msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
d436 2
a437 3
			CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
			if (frp->name != NULL)
				free(frp->name);
d446 3
a448 1
	 * Close the db structure.
d450 4
d455 1
a455 1
		msgq_str(sp, M_SYSERR, frp->name, "241|%s: close");
d479 2
a480 1
			msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
d482 2
a483 1
			msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
d494 1
a494 1
	free(ep);
a502 2
 *
 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
d505 1
a505 1
file_write(sp, fm, tm, name, flags)
d507 1
a511 1
	enum { NEWFILE, OLDFILE } mtype;
a512 1
	EXF *ep;
d517 2
a518 2
	int fd, nf, noname, oflags, rval;
	char *p;
a519 4
	/*
	 * Writing '%', or naming the current file explicitly, has the
	 * same semantics as writing without a name.
	 */
d521 1
a521 1
	if (name == NULL || !strcmp(name, frp->name)) {
d528 6
a533 4
	if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
		msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
		    "244|Read-only file, not written; use ! to override" :
		    "245|Read-only file, not written");
d542 5
a546 4
			msgq_str(sp, M_ERR, name,
			    LF_ISSET(FS_POSSIBLE) ?
			    "246|%s exists, not written; use ! to override" :
			    "247|%s exists, not written");
d555 5
a559 3
			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
			    "248|Partial file, not written; use ! to override" :
			    "249|Partial file, not written");
d571 9
a579 3
	 * One final test.  If we're not forcing or appending the current file,
	 * and we have a saved modification time, object if the file changed
	 * since we last edited or wrote it, and make them force it.
d582 1
a582 1
		mtype = NEWFILE;
d584 1
a584 1
		mtype = OLDFILE;
d586 5
a590 9
			ep = sp->ep;
			if (noname && ep->mtime != 0 &&
			    (sb.st_dev != sp->ep->mdev ||
			    sb.st_ino != ep->minode ||
			    sb.st_mtime != ep->mtime)) {
				msgq_str(sp, M_ERR, name,
				    LF_ISSET(FS_POSSIBLE) ?
"250|%s: file modified more recently than this copy; use ! to override" :
"251|%s: file modified more recently than this copy");
d593 2
d598 6
a603 8
	/* Set flags to create, write, and either append or truncate. */
	oflags = O_CREAT | O_WRONLY |
	    (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);

	/* Backup the file if requested. */
	if (!opts_empty(sp, O_BACKUP, 1) &&
	    file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
		return (1);
d606 1
a606 24
	SIGBLOCK;
	if ((fd = open(name, oflags,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
		msgq_str(sp, M_SYSERR, name, "%s");
		SIGUNBLOCK;
		return (1);
	}
	SIGUNBLOCK;

	/* Try and get a lock. */
	if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
		msgq_str(sp, M_ERR, name,
		    "252|%s: write lock was unavailable");

#if __linux__
	/*
	 * XXX
	 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
	 * This bug is fixed in libc 4.6.x.
	 *
	 * This code works around this problem for libc 4.5.x users.
	 * Note that this code is harmless if you're using libc 4.6.x.
	 */
	if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
a609 1
#endif
d611 2
a612 9
	/*
	 * Use stdio for buffering.
	 *
	 * XXX
	 * SVR4.2 requires the fdopen mode exactly match the original open
	 * mode, i.e. you have to open with "a" if appending.
	 */
	if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
		msgq_str(sp, M_SYSERR, name, "%s");
d614 1
d623 1
a623 1
		if (db_last(sp, &to.lno))
d629 5
a633 1
	rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
d640 1
a640 10
	if (noname) {
		ep = sp->ep;
		if (stat(name, &sb))
			ep->mtime = 0;
		else {
			ep->mdev = sb.st_dev;
			ep->minode = sb.st_ino;
			ep->mtime = sb.st_mtime;
		}
	}
d642 1
a642 4
	/*
	 * If the write failed, complain loudly.  ex_writefp() has already
	 * complained about the actual error, reinforce it if data was lost.
	 */
d645 1
a645 2
			msgq_str(sp, M_ERR, name,
			    "254|%s: WARNING: FILE TRUNCATED");
d663 1
a663 1
		F_CLR(sp->ep, F_MODIFIED);
d671 3
a673 127
	p = msg_print(sp, name, &nf);
	switch (mtype) {
	case NEWFILE:
		msgq(sp, M_INFO, "256|%s: new file: %lu lines, %lu characters",
		    p, nlno, nch);
		break;
	case OLDFILE:
		msgq(sp, M_INFO, "257|%s: %s%lu lines, %lu characters",
		    p, LF_ISSET(FS_APPEND) ? "appended: " : "", nlno, nch);
		break;
	}
	if (nf)
		FREE_SPACE(sp, p, 0);
	return (0);
}

/*
 * file_backup --
 *	Backup the about-to-be-written file.
 *
 * XXX
 * We do the backup by copying the entire file.  It would be nice to do
 * a rename instead, but: (1) both files may not fit and we want to fail
 * before doing the rename; (2) the backup file may not be on the same
 * disk partition as the file being written; (3) there may be optional
 * file information (MACs, DACs, whatever) that we won't get right if we
 * recreate the file.  So, let's not risk it.
 */
static int
file_backup(sp, name, bname)
	SCR *sp;
	char *name, *bname;
{
	struct dirent *dp;
	struct stat sb;
	DIR *dirp;
	EXCMD cmd;
	off_t off;
	size_t blen;
	int flags, maxnum, nr, num, nw, rfd, wfd, version;
	char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];

	rfd = wfd = -1;
	bp = estr = wfname = NULL;

	/*
	 * Open the current file for reading.  Do this first, so that
	 * we don't exec a shell before the most likely failure point.
	 * If it doesn't exist, it's okay, there's just nothing to back
	 * up.
	 */
	errno = 0;
	if ((rfd = open(name, O_RDONLY, 0)) < 0) {
		if (errno == ENOENT)
			return (0);
		estr = name;
		goto err;
	}

	/*
	 * If the name starts with an 'N' character, add a version number
	 * to the name.  Strip the leading N from the string passed to the
	 * expansion routines, for no particular reason.  It would be nice
	 * to permit users to put the version number anywhere in the backup
	 * name, but there isn't a special character that we can use in the
	 * name, and giving a new character a special meaning leads to ugly
	 * hacks both here and in the supporting ex routines.
	 *
	 * Shell and file name expand the option's value.
	 */
	argv_init(sp, &cmd);
	ex_cinit(&cmd, 0, 0, 0, 0, 0, NULL);
	if (bname[0] == 'N') {
		version = 1;
		++bname;
	} else
		version = 0;
	if (argv_exp2(sp, &cmd, bname, strlen(bname)))
		return (1);

	/*
	 *  0 args: impossible.
	 *  1 args: use it.
	 * >1 args: object, too many args.
	 */
	if (cmd.argc != 1) {
		msgq_str(sp, M_ERR, bname,
		    "258|%s expanded into too many file names");
		(void)close(rfd);
		return (1);
	}

	/*
	 * If appending a version number, read through the directory, looking
	 * for file names that match the name followed by a number.  Make all
	 * of the other % characters in name literal, so the user doesn't get
	 * surprised and sscanf doesn't drop core indirecting through pointers
	 * that don't exist.  If any such files are found, increment its number
	 * by one.
	 */
	if (version) {
		GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
		for (t = bp, slash = NULL,
		    p = cmd.argv[0]->bp; p[0] != '\0'; *t++ = *p++)
			if (p[0] == '%') {
				if (p[1] != '%')
					*t++ = '%';
			} else if (p[0] == '/')
				slash = t;
		pct = t;
		*t++ = '%';
		*t++ = 'd';
		*t = '\0';

		if (slash == NULL) {
			dirp = opendir(".");
			p = bp;
		} else {
			*slash = '\0';
			dirp = opendir(bp);
			*slash = '/';
			p = slash + 1;
		}
		if (dirp == NULL) {
			estr = cmd.argv[0]->bp;
			goto err;
		}
a674 59
		for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
			if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
				maxnum = num;
		(void)closedir(dirp);

		/* Format the backup file name. */
		(void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
		wfname = bp;
	} else {
		bp = NULL;
		wfname = cmd.argv[0]->bp;
	}
	
	/* Open the backup file, avoiding lurkers. */
	if (stat(wfname, &sb) == 0) {
		if (!S_ISREG(sb.st_mode)) {
			msgq_str(sp, M_ERR, bname,
			    "259|%s: not a regular file");
			goto err;
		}
		if (sb.st_uid != getuid()) {
			msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
			goto err;
		}
		if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
			msgq_str(sp, M_ERR, bname,
			   "261|%s: accessible by a user other than the owner");
			goto err;
		}
		flags = O_TRUNC;
	} else
		flags = O_CREAT | O_EXCL;
	if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
		estr = bname;
		goto err;
	}

	/* Copy the file's current contents to its backup value. */
	while ((nr = read(rfd, buf, sizeof(buf))) > 0)
		for (off = 0; nr != 0; nr -= nw, off += nw)
			if ((nw = write(wfd, buf + off, nr)) < 0) {
				estr = wfname;
				goto err;
			}
	if (nr < 0) {
		estr = name;
		goto err;
	}

	if (close(rfd)) {
		estr = name;
		goto err;
	}
	if (close(wfd)) {
		estr = wfname;
		goto err;
	}
	if (bp != NULL)
		FREE_SPACE(sp, bp, blen);
a675 38

alloc_err:
err:	if (rfd != -1)
		(void)close(rfd);
	if (wfd != -1) {
		(void)unlink(wfname);
		(void)close(wfd);
	}
	if (estr)
		msgq_str(sp, M_SYSERR, estr, "%s");
	if (bp != NULL)
		FREE_SPACE(sp, bp, blen);
	return (1);
}

/*
 * file_comment --
 *	Skip the first comment.
 */
static void
file_comment(sp)
	SCR *sp;
{
	recno_t lno;
	size_t len;
	char *p;

	for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
	if (p == NULL || len <= 1 || p[0] != '/' || p[1] != '*')
		return;
	F_SET(sp, SC_SCR_TOP);
	do {
		for (; len; --len, ++p)
			if (p[0] == '*' && len > 1 && p[1] == '/') {
				sp->lno = lno;
				return;
			}
	} while (!db_get(sp, ++lno, 0, &p, &len));
a681 2
 *
 * PUBLIC: int file_m1 __P((SCR *, int, int));
d684 1
a684 1
file_m1(sp, force, flags)
d686 1
a688 4
	/* If no file loaded, return no modifications. */
	if (sp->ep == NULL)
		return (0);

d695 1
a695 1
	if (F_ISSET(sp->ep, F_MODIFIED))
d697 2
a698 1
			if (!force && file_aw(sp, flags))
d700 4
a703 4
		} else if (sp->ep->refcnt <= 1 && !force) {
			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
"262|File modified since last complete write; write or use ! to override" :
"263|File modified since last complete write; write or use :edit! to override");
d707 1
a707 1
	return (file_m3(sp, force));
a713 2
 *
 * PUBLIC: int file_m2 __P((SCR *, int));
d716 1
a716 1
file_m2(sp, force)
d718 1
a720 4
	/* If no file loaded, return no modifications. */
	if (sp->ep == NULL)
		return (0);

d725 1
a725 1
	if (F_ISSET(sp->ep, F_MODIFIED) && sp->ep->refcnt <= 1 && !force) {
d727 1
a727 1
"264|File modified since last complete write; write or use ! to override");
d731 1
a731 1
	return (file_m3(sp, force));
a736 2
 *
 * PUBLIC: int file_m3 __P((SCR *, int));
d739 1
a739 1
file_m3(sp, force)
d741 1
a743 4
	/* If no file loaded, return no modifications. */
	if (sp->ep == NULL)
		return (0);

d751 1
a751 1
	if (F_ISSET(sp->frp, FR_TMPEXIT) && sp->ep->refcnt <= 1 && !force) {
d753 1
a753 1
		    "265|File is a temporary; exit will discard modifications");
a759 82
 * file_aw --
 *	Autowrite routine.  If modified, autowrite is set and the readonly bit
 *	is not set, write the file.  A routine so there's a place to put the
 *	comment.
 *
 * PUBLIC: int file_aw __P((SCR *, int));
 */
int
file_aw(sp, flags)
	SCR *sp;
	int flags;
{
	if (!F_ISSET(sp->ep, F_MODIFIED))
		return (0);
	if (!O_ISSET(sp, O_AUTOWRITE))
		return (0);

	/*
	 * !!!
	 * Historic 4BSD vi attempted to write the file if autowrite was set,
	 * regardless of the writeability of the file (as defined by the file
	 * readonly flag).  System V changed this as some point, not attempting
	 * autowrite if the file was readonly.  This feels like a bug fix to
	 * me (e.g. the principle of least surprise is violated if readonly is
	 * set and vi writes the file), so I'm compatible with System V.
	 */
	if (O_ISSET(sp, O_READONLY)) {
		msgq(sp, M_INFO,
		    "266|File readonly, modifications not auto-written");
		return (1);
	}
	return (file_write(sp, NULL, NULL, NULL, flags));
}

/*
 * set_alt_name --
 *	Set the alternate pathname.
 *
 * Set the alternate pathname.  It's a routine because I wanted some place
 * to hang this comment.  The alternate pathname (normally referenced using
 * the special character '#' during file expansion and in the vi ^^ command)
 * is set by almost all ex commands that take file names as arguments.  The
 * rules go something like this:
 *
 *    1: If any ex command takes a file name as an argument (except for the
 *	 :next command), the alternate pathname is set to that file name.
 *	 This excludes the command ":e" and ":w !command" as no file name
 *       was specified.  Note, historically, the :source command did not set
 *	 the alternate pathname.  It does in nvi, for consistency.
 *
 *    2: However, if any ex command sets the current pathname, e.g. the
 *	 ":e file" or ":rew" commands succeed, then the alternate pathname
 *	 is set to the previous file's current pathname, if it had one.
 *	 This includes the ":file" command and excludes the ":e" command.
 *	 So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
 *	 pathname will be "foo", if it succeeds, the alternate pathname will
 *	 be the previous current pathname.  The ":e" command will not set
 *       the alternate or current pathnames regardless.
 *
 *    3: However, if it's a read or write command with a file argument and
 *	 the current pathname has not yet been set, the file name becomes
 *	 the current pathname, and the alternate pathname is unchanged.
 *
 * If the user edits a temporary file, there may be times when there is no
 * alternative file name.  A name argument of NULL turns it off.
 *
 * PUBLIC: void set_alt_name __P((SCR *, char *));
 */
void
set_alt_name(sp, name)
	SCR *sp;
	char *name;
{
	if (sp->alt_name != NULL)
		free(sp->alt_name);
	if (name == NULL)
		sp->alt_name = NULL;
	else if ((sp->alt_name = strdup(name)) == NULL)
		msgq(sp, M_SYSERR, NULL);
}

/*
d762 1
a762 1
 *
a778 2
 *
 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
d780 2
a781 3
lockr_t
file_lock(sp, name, fdp, fd, iswrite)
	SCR *sp;
d783 1
a783 1
	int *fdp, fd, iswrite;
d785 2
a786 4
	if (!O_ISSET(sp, O_LOCKFILES))
		return (LOCK_SUCCESS);
	
#ifdef HAVE_LOCK_FLOCK			/* Hurrah!  We've got flock(2). */
d795 5
a799 8
	return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
#ifdef EWOULDBLOCK
	    || errno == EWOULDBLOCK
#endif
	    ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
#endif
#ifdef HAVE_LOCK_FCNTL			/* Gag me.  We've got fcntl(2). */
{
d807 2
a808 7

	/*
	 * If the file descriptor isn't opened for writing, it must fail.
	 * If we fail because we can't get a read/write file descriptor,
	 * we return LOCK_SUCCESS, believing that the file is readonly
	 * and that will be sufficient to warn the user.
	 */
d813 1
a813 1
			return (LOCK_SUCCESS);
d817 1
a817 1

a835 4
}
#endif
#if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
	return (LOCK_SUCCESS);
@


1.1.1.4
log
@import of nvi 1.79
@
text
@d13 1
a13 1
static const char sccsid[] = "@@(#)exf.c	10.49 (Berkeley) 10/10/96";
d33 1
a43 1
static int	file_spath __P((SCR *, FREF *, struct stat *, int *));
d136 1
a136 1
	int fd, exists, open_err, readonly;
a170 7
	 * Scan the user's path to find the file that we're going to
	 * try and open.
	 */
	if (file_spath(sp, frp, &sb, &exists))
		return (1);

	/*
d177 1
a177 1
	if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
a202 2

		time(&ep->mtime);
a216 1
		F_SET(ep, F_DEVSET);
a218 1

a427 68
 * file_spath --
 *	Scan the user's path to find the file that we're going to
 *	try and open.
 */
static int
file_spath(sp, frp, sbp, existsp)
	SCR *sp;
	FREF *frp;
	struct stat *sbp;
	int *existsp;
{
	CHAR_T savech;
	size_t len;
	int found;
	char *name, *p, *t, path[MAXPATHLEN];

	/*
	 * If the name is NULL or an explicit reference (i.e., the first
	 * component is . or ..) ignore the O_PATH option.
	 */
	name = frp->name;
	if (name == NULL) {
		*existsp = 0;
		return (0);
	}
	if (name[0] == '/' || name[0] == '.' &&
	    (name[1] == '/' || name[1] == '.' && name[2] == '/')) {
		*existsp = !stat(name, sbp);
		return (0);
	}

	/* Try . */
	if (!stat(name, sbp)) {
		*existsp = 1;
		return (0);
	}

	/* Try the O_PATH option values. */
	for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
		if (*p == ':' || *p == '\0') {
			if (t < p - 1) {
				savech = *p;
				*p = '\0';
				len = snprintf(path,
				    sizeof(path), "%s/%s", t, name);
				*p = savech;
				if (!stat(path, sbp)) {
					found = 1;
					break;
				}
			}
			t = p + 1;
			if (*p == '\0')
				break;
		}

	/* If we found it, build a new pathname and discard the old one. */
	if (found) {
		MALLOC_RET(sp, p, char *, len + 1);
		memcpy(p, path, len + 1);
		free(frp->name);
		frp->name = p;
	}
	*existsp = found;
	return (0);
}

/*
a664 1
	size_t len;
d667 1
a667 5
	char *p, *s, *t, buf[MAXPATHLEN + 64];
	const char *msgstr;

	ep = sp->ep;
	frp = sp->frp;
d673 1
d726 9
a734 5
		if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
		    (F_ISSET(ep, F_DEVSET) &&
		    (sb.st_dev != ep->mdev || sb.st_ino != ep->minode) ||
		    sb.st_mtime != ep->mtime)) {
			msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
d737 2
a738 1
			return (1);
a739 2

		mtype = OLDFILE;
d812 2
a813 1
	if (noname)
d815 1
a815 1
			time(&ep->mtime);
a816 1
			F_SET(ep, F_DEVSET);
a818 1

d821 1
d841 5
a845 6
	 * If wrote the entire file, and it wasn't by appending it to a file,
	 * clear the modified bit.  If the file was written to the original
	 * file name and the file is a temporary, set the "no exit" bit.  This
	 * permits the user to write the file and use it in the context of the
	 * filesystem, but still keeps them from discarding their changes by
	 * exiting.
d847 2
a848 2
	if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
		F_CLR(ep, F_MODIFIED);
d859 2
a860 3
		msgstr = msg_cat(sp,
		    "256|%s: new file: %lu lines, %lu characters", NULL);
		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
d863 2
a864 4
		msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
		    "315|%s: appended: %lu lines, %lu characters" :
		    "257|%s: %lu lines, %lu characters", NULL);
		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
a865 2
	default:
		abort();
a866 21

	/*
	 * There's a nasty problem with long path names.  Cscope and tags files
	 * can result in long paths and vi will request a continuation key from
	 * the user.  Unfortunately, the user has typed ahead, and chaos will
	 * result.  If we assume that the characters in the filenames only take
	 * a single screen column each, we can trim the filename.
	 */
	s = buf;
	if (len >= sp->cols) {
		for (s = buf, t = buf + strlen(p); s < t &&
		    (*s != '/' || len >= sp->cols - 3); ++s, --len);
		if (s == t)
			s = buf;
		else {
			*--s = '.';		/* Leading ellipses. */
			*--s = '.';
			*--s = '.';
		}
	}
	msgq(sp, M_INFO, s);
d1072 1
a1072 1
	if (p == NULL)
d1074 4
a1077 4
	if (p[0] == '#') {
		F_SET(sp, SC_SCR_TOP);
		while (!db_get(sp, ++lno, 0, &p, &len))
			if (len < 1 || p[0] != '#') {
d1081 1
a1081 21
	} else if (len > 1 && p[0] == '/' && p[1] == '*') {
		F_SET(sp, SC_SCR_TOP);
		do {
			for (; len > 1; --len, ++p)
				if (p[0] == '*' && p[1] == '/') {
					sp->lno = lno;
					return;
				}
		} while (!db_get(sp, ++lno, 0, &p, &len));
	} else if (len > 1 && p[0] == '/' && p[1] == '/') {
		F_SET(sp, SC_SCR_TOP);
		p += 2;
		len -= 2;
		do {
			for (; len > 1; --len, ++p)
				if (p[0] == '/' && p[1] == '/') {
					sp->lno = lno;
					return;
				}
		} while (!db_get(sp, ++lno, 0, &p, &len));
	}
a1095 4
	EXF *ep;

	ep = sp->ep;

d1097 1
a1097 1
	if (ep == NULL)
d1106 1
a1106 1
	if (F_ISSET(ep, F_MODIFIED))
d1110 1
a1110 1
		} else if (ep->refcnt <= 1 && !force) {
a1131 4
	EXF *ep;

	ep = sp->ep;

d1133 1
a1133 1
	if (ep == NULL)
d1140 1
a1140 1
	if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
a1159 4
	EXF *ep;

	ep = sp->ep;

d1161 1
a1161 1
	if (ep == NULL)
d1171 1
a1171 1
	if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
d1349 2
a1350 5
	return (errno == EACCES || errno == EAGAIN
#ifdef EWOULDBLOCK
	|| errno == EWOULDBLOCK
#endif
	?  LOCK_UNAVAIL : LOCK_FAILED);
@

