xref: /openbsd/usr.bin/vi/common/exf.c (revision b15051c7)
1 /*	$OpenBSD: exf.c,v 1.50 2024/02/15 00:55:01 jsg Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1992, 1993, 1994, 1995, 1996
7  *	Keith Bostic.  All rights reserved.
8  *
9  * See the LICENSE file for redistribution information.
10  */
11 
12 #include "config.h"
13 
14 #include <sys/queue.h>
15 #include <sys/stat.h>
16 #include <sys/time.h>
17 
18 /*
19  * We include <sys/file.h>, because the flock(2) and open(2) #defines
20  * were found there on historical systems.  We also include <fcntl.h>
21  * because the open(2) #defines are found there on newer systems.
22  */
23 #include <sys/file.h>
24 
25 #include <bitstring.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <time.h>
35 #include <unistd.h>
36 
37 #include "common.h"
38 
39 static int	file_backup(SCR *, char *, char *);
40 static void	file_cinit(SCR *);
41 static void	file_comment(SCR *);
42 static int	file_spath(SCR *, FREF *, struct stat *, int *);
43 
44 /*
45  * file_add --
46  *	Insert a file name into the FREF list, if it doesn't already
47  *	appear in it.
48  *
49  * !!!
50  * The "if it doesn't already appear" changes vi's semantics slightly.  If
51  * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
52  * will reflect the line/column of the previous edit session.  Historic nvi
53  * did not do this.  The change is a logical extension of the change where
54  * vi now remembers the last location in any file that it has ever edited,
55  * not just the previously edited file.
56  *
57  * PUBLIC: FREF *file_add(SCR *, CHAR_T *);
58  */
59 FREF *
file_add(SCR * sp,CHAR_T * name)60 file_add(SCR *sp, CHAR_T *name)
61 {
62 	GS *gp;
63 	FREF *frp, *tfrp;
64 
65 	/*
66 	 * Return it if it already exists.  Note that we test against the
67 	 * user's name, whatever that happens to be, including if it's a
68 	 * temporary file.
69 	 *
70 	 * If the user added a file but was unable to initialize it, there
71 	 * can be file list entries where the name field is NULL.  Discard
72 	 * them the next time we see them.
73 	 */
74 	gp = sp->gp;
75 	if (name != NULL)
76 		TAILQ_FOREACH_SAFE(frp, &gp->frefq, q, tfrp) {
77 			if (frp->name == NULL) {
78 				TAILQ_REMOVE(&gp->frefq, frp, q);
79 				free(frp->name);
80 				free(frp);
81 				continue;
82 			}
83 			if (!strcmp(frp->name, name))
84 				return (frp);
85 		}
86 
87 	/* Allocate and initialize the FREF structure. */
88 	CALLOC(sp, frp, 1, sizeof(FREF));
89 	if (frp == NULL)
90 		return (NULL);
91 
92 	/*
93 	 * If no file name specified, or if the file name is a request
94 	 * for something temporary, file_init() will allocate the file
95 	 * name.  Temporary files are always ignored.
96 	 */
97 	if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
98 	    (frp->name = strdup(name)) == NULL) {
99 		free(frp);
100 		msgq(sp, M_SYSERR, NULL);
101 		return (NULL);
102 	}
103 
104 	/* Append into the chain of file names. */
105 	TAILQ_INSERT_TAIL(&gp->frefq, frp, q);
106 
107 	return (frp);
108 }
109 
110 /*
111  * file_init --
112  *	Start editing a file, based on the FREF structure.  If successsful,
113  *	let go of any previous file.  Don't release the previous file until
114  *	absolutely sure we have the new one.
115  *
116  * PUBLIC: int file_init(SCR *, FREF *, char *, int);
117  */
118 int
file_init(SCR * sp,FREF * frp,char * rcv_name,int flags)119 file_init(SCR *sp, FREF *frp, char *rcv_name, int flags)
120 {
121 	EXF *ep;
122 	RECNOINFO oinfo;
123 	struct stat sb;
124 	size_t psize;
125 	int fd, exists, open_err, readonly;
126 	char *oname, tname[] = "/tmp/vi.XXXXXXXXXX";
127 
128 	open_err = readonly = 0;
129 
130 	/*
131 	 * If the file is a recovery file, let the recovery code handle it.
132 	 * Clear the FR_RECOVER flag first -- the recovery code does set up,
133 	 * and then calls us!  If the recovery call fails, it's probably
134 	 * because the named file doesn't exist.  So, move boldly forward,
135 	 * presuming that there's an error message the user will get to see.
136 	 */
137 	if (F_ISSET(frp, FR_RECOVER)) {
138 		F_CLR(frp, FR_RECOVER);
139 		if (rcv_read(sp, frp) == 0)
140 			return (0);		/* successful recovery */
141 	}
142 
143 	/*
144 	 * Required FRP initialization; the only flag we keep is the
145 	 * cursor information.
146 	 */
147 	F_CLR(frp, ~FR_CURSORSET);
148 
149 	/*
150 	 * Required EXF initialization:
151 	 *	Flush the line caches.
152 	 *	Default recover mail file fd to -1.
153 	 *	Set initial EXF flag bits.
154 	 */
155 	CALLOC_RET(sp, ep, 1, sizeof(EXF));
156 	ep->c_lno = ep->c_nlines = OOBLNO;
157 	ep->rcv_fd = ep->fcntl_fd = -1;
158 	F_SET(ep, F_FIRSTMODIFY);
159 
160 	/*
161 	 * Scan the user's path to find the file that we're going to
162 	 * try and open.
163 	 */
164 	if (file_spath(sp, frp, &sb, &exists)) {
165 		free(ep);
166 		return (1);
167 	}
168 
169 	/*
170 	 * If no name or backing file, for whatever reason, create a backing
171 	 * temporary file, saving the temp file name so we can later unlink
172 	 * it.  If the user never named this file, copy the temporary file name
173 	 * to the real name (we display that until the user renames it).
174 	 */
175 	oname = frp->name;
176 
177 	/*
178 	 * User is editing a named file that doesn't exist yet other than as a
179 	 * temporary file.
180 	 */
181 	if (!exists && oname != NULL && frp->tname != NULL) {
182 		free(ep);
183 		return (1);
184 	}
185 
186 	if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
187 		/*
188 		 * Don't try to create a temporary support file twice.
189 		 */
190 		if (frp->tname != NULL)
191 			goto err;
192 		fd = mkstemp(tname);
193 		if (fd == -1 || fstat(fd, &sb) == -1 ||
194 		    fchmod(fd, S_IRUSR | S_IWUSR) == -1) {
195 			msgq(sp, M_SYSERR,
196 			    "Unable to create temporary file");
197 			if (fd != -1) {
198 				close(fd);
199 				(void)unlink(tname);
200 			}
201 			goto err;
202 		}
203 		(void)close(fd);
204 
205 		if (frp->name == NULL)
206 			F_SET(frp, FR_TMPFILE);
207 		if ((frp->tname = strdup(tname)) == NULL ||
208 		    (frp->name == NULL && (frp->name = strdup(tname)) == NULL)) {
209 			free(frp->tname);
210 			frp->tname = NULL;
211 			msgq(sp, M_SYSERR, NULL);
212 			(void)unlink(tname);
213 			goto err;
214 		}
215 		oname = frp->tname;
216 		psize = 1024;
217 		if (!LF_ISSET(FS_OPENERR))
218 			F_SET(frp, FR_NEWFILE);
219 	} else {
220 		/*
221 		 * XXX
222 		 * A seat of the pants calculation: try to keep the file in
223 		 * 15 pages or less.  Don't use a page size larger than 10K
224 		 * (vi should have good locality) or smaller than 1K.
225 		 */
226 		psize = ((sb.st_size / 15) + 1023) / 1024;
227 		if (psize > 10)
228 			psize = 10;
229 		if (psize == 0)
230 			psize = 1;
231 		psize *= 1024;
232 
233 		if (!S_ISREG(sb.st_mode))
234 			msgq_str(sp, M_ERR, oname,
235 			    "Warning: %s is not a regular file");
236 	}
237 
238 	/* Save device, inode and modification time. */
239 	F_SET(ep, F_DEVSET);
240 	ep->mdev = sb.st_dev;
241 	ep->minode = sb.st_ino;
242 
243 	ep->mtim = sb.st_mtim;
244 
245 	/* Set up recovery. */
246 	memset(&oinfo, 0, sizeof(RECNOINFO));
247 	oinfo.bval = '\n';			/* Always set. */
248 	oinfo.psize = psize;
249 	oinfo.flags = F_ISSET(sp->gp, G_SNAPSHOT) ? R_SNAPSHOT : 0;
250 	if (rcv_name == NULL) {
251 		if (!rcv_tmp(sp, ep, frp->name))
252 			oinfo.bfname = ep->rcv_path;
253 	} else {
254 		if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
255 			msgq(sp, M_SYSERR, NULL);
256 			goto err;
257 		}
258 		oinfo.bfname = ep->rcv_path;
259 		F_SET(ep, F_MODIFIED);
260 	}
261 
262 	/* Open a db structure. */
263 	if ((ep->db = dbopen(rcv_name == NULL ? oname : NULL,
264 	    O_NONBLOCK | O_RDONLY,
265 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH,
266 	    DB_RECNO, &oinfo)) == NULL) {
267 		msgq_str(sp,
268 		    M_SYSERR, rcv_name == NULL ? oname : rcv_name, "%s");
269 		/*
270 		 * !!!
271 		 * Historically, vi permitted users to edit files that couldn't
272 		 * be read.  This isn't useful for single files from a command
273 		 * line, but it's quite useful for "vi *.c", since you can skip
274 		 * past files that you can't read.
275 		 */
276 		open_err = 1;
277 		goto oerr;
278 	}
279 
280 	/*
281 	 * Do the remaining things that can cause failure of the new file,
282 	 * mark and logging initialization.
283 	 */
284 	if (mark_init(sp, ep) || log_init(sp, ep))
285 		goto err;
286 
287 	/*
288 	 * Set the alternate file name to be the file we're discarding.
289 	 *
290 	 * !!!
291 	 * Temporary files can't become alternate files, so there's no file
292 	 * name.  This matches historical practice, although it could only
293 	 * happen in historical vi as the result of the initial command, i.e.
294 	 * if vi was executed without a file name.
295 	 */
296 	if (LF_ISSET(FS_SETALT))
297 		set_alt_name(sp, sp->frp == NULL ||
298 		    F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
299 
300 	/*
301 	 * Close the previous file; if that fails, close the new one and run
302 	 * for the border.
303 	 *
304 	 * !!!
305 	 * There's a nasty special case.  If the user edits a temporary file,
306 	 * and then does an ":e! %", we need to re-initialize the backing
307 	 * file, but we can't change the name.  (It's worse -- we're dealing
308 	 * with *names* here, we can't even detect that it happened.)  Set a
309 	 * flag so that the file_end routine ignores the backing information
310 	 * of the old file if it happens to be the same as the new one.
311 	 *
312 	 * !!!
313 	 * Side-effect: after the call to file_end(), sp->frp may be NULL.
314 	 */
315 	if (sp->ep != NULL) {
316 		F_SET(frp, FR_DONTDELETE);
317 		if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
318 			(void)file_end(sp, ep, 1);
319 			goto err;
320 		}
321 		F_CLR(frp, FR_DONTDELETE);
322 	}
323 
324 	/*
325 	 * Lock the file; if it's a recovery file, it should already be
326 	 * locked.  Note, we acquire the lock after the previous file
327 	 * has been ended, so that we don't get an "already locked" error
328 	 * for ":edit!".
329 	 *
330 	 * XXX
331 	 * While the user can't interrupt us between the open and here,
332 	 * there's a race between the dbopen() and the lock.  Not much
333 	 * we can do about it.
334 	 *
335 	 * XXX
336 	 * We don't make a big deal of not being able to lock the file.  As
337 	 * locking rarely works over NFS, and often fails if the file was
338 	 * mmap(2)'d, it's far too common to do anything like print an error
339 	 * message, let alone make the file readonly.  At some future time,
340 	 * when locking is a little more reliable, this should change to be
341 	 * an error.
342 	 */
343 	if (rcv_name == NULL && !O_ISSET(sp, O_READONLY))
344 		switch (file_lock(sp, oname,
345 		    &ep->fcntl_fd, ep->db->fd(ep->db), 0)) {
346 		case LOCK_FAILED:
347 			F_SET(frp, FR_UNLOCKED);
348 			break;
349 		case LOCK_UNAVAIL:
350 			readonly = 1;
351 			msgq_str(sp, M_INFO, oname,
352 			    "%s already locked, session is read-only");
353 			break;
354 		case LOCK_SUCCESS:
355 			break;
356 		}
357 
358 	/*
359          * Historically, the readonly edit option was set per edit buffer in
360          * vi, unless the -R command-line option was specified or the program
361          * was executed as "view".  (Well, to be truthful, if the letter 'w'
362          * occurred anywhere in the program name, but let's not get into that.)
363 	 * So, the persistent readonly state has to be stored in the screen
364 	 * structure, and the edit option value toggles with the contents of
365 	 * the edit buffer.  If the persistent readonly flag is set, set the
366 	 * readonly edit option.
367 	 *
368 	 * Otherwise, try and figure out if a file is readonly.  This is a
369 	 * dangerous thing to do.  The kernel is the only arbiter of whether
370 	 * or not a file is writeable, and the best that a user program can
371 	 * do is guess.  Obvious loopholes are files that are on a file system
372 	 * mounted readonly (access catches this one on a few systems), or
373 	 * alternate protection mechanisms, ACL's for example, that we can't
374 	 * portably check.  Lots of fun, and only here because users whined.
375 	 *
376 	 * !!!
377 	 * Historic vi displayed the readonly message if none of the file
378 	 * write bits were set, or if an an access(2) call on the path
379 	 * failed.  This seems reasonable.  If the file is mode 444, root
380 	 * users may want to know that the owner of the file did not expect
381 	 * it to be written.
382 	 *
383 	 * Historic vi set the readonly bit if no write bits were set for
384 	 * a file, even if the access call would have succeeded.  This makes
385 	 * the superuser force the write even when vi expects that it will
386 	 * succeed.  I'm less supportive of this semantic, but it's historic
387 	 * practice and the conservative approach to vi'ing files as root.
388 	 *
389 	 * It would be nice if there was some way to update this when the user
390 	 * does a "^Z; chmod ...".  The problem is that we'd first have to
391 	 * distinguish between readonly bits set because of file permissions
392 	 * and those set for other reasons.  That's not too hard, but deciding
393 	 * when to reevaluate the permissions is trickier.  An alternative
394 	 * might be to turn off the readonly bit if the user forces a write
395 	 * and it succeeds.
396 	 *
397 	 * XXX
398 	 * Access(2) doesn't consider the effective uid/gid values.  This
399 	 * probably isn't a problem for vi when it's running standalone.
400 	 */
401 	if (readonly || F_ISSET(sp, SC_READONLY) ||
402 	    (!F_ISSET(frp, FR_NEWFILE) &&
403 	    (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
404 	    access(frp->name, W_OK))))
405 		O_SET(sp, O_READONLY);
406 	else
407 		O_CLR(sp, O_READONLY);
408 
409 	/* Switch... */
410 	++ep->refcnt;
411 	sp->ep = ep;
412 	sp->frp = frp;
413 
414 	/* Set the initial cursor position, queue initial command. */
415 	file_cinit(sp);
416 
417 	/* Redraw the screen from scratch, schedule a welcome message. */
418 	F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);
419 
420 	return (0);
421 
422 err:
423 	free(frp->name);
424 	frp->name = NULL;
425 	if (frp->tname != NULL) {
426 		(void)unlink(frp->tname);
427 		free(frp->tname);
428 		frp->tname = NULL;
429 	}
430 
431 oerr:	if (F_ISSET(ep, F_RCV_ON))
432 		(void)unlink(ep->rcv_path);
433 	free(ep->rcv_path);
434 	ep->rcv_path = NULL;
435 	if (ep->db != NULL)
436 		(void)ep->db->close(ep->db);
437 	free(ep);
438 
439 	return (open_err ?
440 	    file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
441 }
442 
443 /*
444  * file_spath --
445  *	Scan the user's path to find the file that we're going to
446  *	try and open.
447  */
448 static int
file_spath(SCR * sp,FREF * frp,struct stat * sbp,int * existsp)449 file_spath(SCR *sp, FREF *frp, struct stat *sbp, int *existsp)
450 {
451 	CHAR_T savech;
452 	size_t len;
453 	int found;
454 	char *name, *p, *t, path[PATH_MAX];
455 
456 	/*
457 	 * If the name is NULL or an explicit reference (i.e., the first
458 	 * component is . or ..) ignore the O_PATH option.
459 	 */
460 	name = frp->name;
461 	if (name == NULL) {
462 		*existsp = 0;
463 		return (0);
464 	}
465 	if (name[0] == '/' || (name[0] == '.' &&
466 	    (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
467 		*existsp = !stat(name, sbp);
468 		return (0);
469 	}
470 
471 	/* Try . */
472 	if (!stat(name, sbp)) {
473 		*existsp = 1;
474 		return (0);
475 	}
476 
477 	/* Try the O_PATH option values. */
478 	for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
479 		if (*p == ':' || *p == '\0') {
480 			if (t < p - 1) {
481 				savech = *p;
482 				*p = '\0';
483 				len = snprintf(path,
484 				    sizeof(path), "%s/%s", t, name);
485 				if (len >= sizeof(path))
486 					len = sizeof(path) - 1;
487 				*p = savech;
488 				if (!stat(path, sbp)) {
489 					found = 1;
490 					break;
491 				}
492 			}
493 			t = p + 1;
494 			if (*p == '\0')
495 				break;
496 		}
497 
498 	/* If we found it, build a new pathname and discard the old one. */
499 	if (found) {
500 		MALLOC_RET(sp, p, len + 1);
501 		memcpy(p, path, len + 1);
502 		free(frp->name);
503 		frp->name = p;
504 	}
505 	*existsp = found;
506 	return (0);
507 }
508 
509 /*
510  * file_cinit --
511  *	Set up the initial cursor position.
512  */
513 static void
file_cinit(SCR * sp)514 file_cinit(SCR *sp)
515 {
516 	GS *gp;
517 	MARK m;
518 	size_t len;
519 	int nb;
520 
521 	/* Set some basic defaults. */
522 	sp->lno = 1;
523 	sp->cno = 0;
524 
525 	/*
526 	 * Historically, initial commands (the -c option) weren't executed
527 	 * until a file was loaded, e.g. "vi +10 nofile", followed by an
528 	 * :edit or :tag command, would execute the +10 on the file loaded
529 	 * by the subsequent command, (assuming that it existed).  This
530 	 * applied as well to files loaded using the tag commands, and we
531 	 * follow that historic practice.  Also, all initial commands were
532 	 * ex commands and were always executed on the last line of the file.
533 	 *
534 	 * Otherwise, if no initial command for this file:
535 	 *    If in ex mode, move to the last line, first nonblank character.
536 	 *    If the file has previously been edited, move to the last known
537 	 *	  position, and check it for validity.
538 	 *    Otherwise, move to the first line, first nonblank.
539 	 *
540 	 * This gets called by the file init code, because we may be in a
541 	 * file of ex commands and we want to execute them from the right
542 	 * location in the file.
543 	 */
544 	nb = 0;
545 	gp = sp->gp;
546 	if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
547 		if (db_last(sp, &sp->lno))
548 			return;
549 		if (sp->lno == 0) {
550 			sp->lno = 1;
551 			sp->cno = 0;
552 		}
553 		if (ex_run_str(sp,
554 		    "-c option", gp->c_option, strlen(gp->c_option), 1, 1))
555 			return;
556 		gp->c_option = NULL;
557 	} else if (F_ISSET(sp, SC_EX)) {
558 		if (db_last(sp, &sp->lno))
559 			return;
560 		if (sp->lno == 0) {
561 			sp->lno = 1;
562 			sp->cno = 0;
563 			return;
564 		}
565 		nb = 1;
566 	} else {
567 		if (F_ISSET(sp->frp, FR_CURSORSET)) {
568 			sp->lno = sp->frp->lno;
569 			sp->cno = sp->frp->cno;
570 
571 			/* If returning to a file in vi, center the line. */
572 			 F_SET(sp, SC_SCR_CENTER);
573 		} else {
574 			if (O_ISSET(sp, O_COMMENT))
575 				file_comment(sp);
576 			else
577 				sp->lno = 1;
578 			nb = 1;
579 		}
580 		if (db_get(sp, sp->lno, 0, NULL, &len)) {
581 			sp->lno = 1;
582 			sp->cno = 0;
583 			return;
584 		}
585 		if (!nb && sp->cno > len)
586 			nb = 1;
587 	}
588 	if (nb) {
589 		sp->cno = 0;
590 		(void)nonblank(sp, sp->lno, &sp->cno);
591 	}
592 
593 	/*
594 	 * !!!
595 	 * The initial column is also the most attractive column.
596 	 */
597 	sp->rcm = sp->cno;
598 
599 	/*
600 	 * !!!
601 	 * Historically, vi initialized the absolute mark, but ex did not.
602 	 * Which meant, that if the first command in ex mode was "visual",
603 	 * or if an ex command was executed first (e.g. vi +10 file) vi was
604 	 * entered without the mark being initialized.  For consistency, if
605 	 * the file isn't empty, we initialize it for everyone, believing
606 	 * that it can't hurt, and is generally useful.  Not initializing it
607 	 * if the file is empty is historic practice, although it has always
608 	 * been possible to set (and use) marks in empty vi files.
609 	 */
610 	m.lno = sp->lno;
611 	m.cno = sp->cno;
612 	(void)mark_set(sp, ABSMARK1, &m, 0);
613 }
614 
615 /*
616  * file_end --
617  *	Stop editing a file.
618  *
619  * PUBLIC: int file_end(SCR *, EXF *, int);
620  */
621 int
file_end(SCR * sp,EXF * ep,int force)622 file_end(SCR *sp, EXF *ep, int force)
623 {
624 	FREF *frp;
625 
626 	/*
627 	 * !!!
628 	 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
629 	 * (If argument ep is NULL, use sp->ep.)
630 	 *
631 	 * If multiply referenced, just decrement the count and return.
632 	 */
633 	if (ep == NULL)
634 		ep = sp->ep;
635 	if (--ep->refcnt != 0)
636 		return (0);
637 
638 	/*
639 	 *
640 	 * Clean up the FREF structure.
641 	 *
642 	 * Save the cursor location.
643 	 *
644 	 * XXX
645 	 * It would be cleaner to do this somewhere else, but by the time
646 	 * ex or vi knows that we're changing files it's already happened.
647 	 */
648 	frp = sp->frp;
649 	frp->lno = sp->lno;
650 	frp->cno = sp->cno;
651 	F_SET(frp, FR_CURSORSET);
652 
653 	/*
654 	 * We may no longer need the temporary backing file, so clean it
655 	 * up.  We don't need the FREF structure either, if the file was
656 	 * never named, so lose it.
657 	 *
658 	 * !!!
659 	 * Re: FR_DONTDELETE, see the comment above in file_init().
660 	 */
661 	if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
662 		if (unlink(frp->tname))
663 			msgq_str(sp, M_SYSERR, frp->tname, "%s: remove");
664 		free(frp->tname);
665 		frp->tname = NULL;
666 		if (F_ISSET(frp, FR_TMPFILE)) {
667 			TAILQ_REMOVE(&sp->gp->frefq, frp, q);
668 			free(frp->name);
669 			free(frp);
670 			frp = NULL;
671 		}
672 		sp->frp = NULL;
673 	}
674 
675 	/*
676 	 * Clean up the EXF structure.
677 	 *
678 	 * Close the db structure.
679 	 */
680 	if (ep->db->close != NULL && ep->db->close(ep->db) && !force) {
681 		if (frp)
682 			msgq_str(sp, M_SYSERR, frp->name, "%s: close");
683 		else
684 			msgq(sp, M_SYSERR, "close");
685 		++ep->refcnt;
686 		return (1);
687 	}
688 
689 	/* COMMITTED TO THE CLOSE.  THERE'S NO GOING BACK... */
690 
691 	/* Stop logging. */
692 	(void)log_end(sp, ep);
693 
694 	/* Free up any marks. */
695 	(void)mark_end(sp, ep);
696 
697 	/*
698 	 * Delete recovery files, close the open descriptor, free recovery
699 	 * memory.  See recover.c for a description of the protocol.
700 	 *
701 	 * XXX
702 	 * Unlink backup file first, we can detect that the recovery file
703 	 * doesn't reference anything when the user tries to recover it.
704 	 * There's a race, here, obviously, but it's fairly small.
705 	 */
706 	if (!F_ISSET(ep, F_RCV_NORM)) {
707 		if (ep->rcv_path != NULL && unlink(ep->rcv_path))
708 			msgq_str(sp, M_SYSERR, ep->rcv_path, "%s: remove");
709 		if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
710 			msgq_str(sp, M_SYSERR, ep->rcv_mpath, "%s: remove");
711 	}
712 	if (ep->fcntl_fd != -1)
713 		(void)close(ep->fcntl_fd);
714 	if (ep->rcv_fd != -1)
715 		(void)close(ep->rcv_fd);
716 	free(ep->rcv_path);
717 	free(ep->rcv_mpath);
718 	free(ep);
719 	return (0);
720 }
721 
722 /*
723  * file_write --
724  *	Write the file to disk.  Historic vi had fairly convoluted
725  *	semantics for whether or not writes would happen.  That's
726  *	why all the flags.
727  *
728  * PUBLIC: int file_write(SCR *, MARK *, MARK *, char *, int);
729  */
730 int
file_write(SCR * sp,MARK * fm,MARK * tm,char * name,int flags)731 file_write(SCR *sp, MARK *fm, MARK *tm, char *name, int flags)
732 {
733 	enum { NEWFILE, OLDFILE } mtype;
734 	struct stat sb;
735 	EXF *ep;
736 	FILE *fp;
737 	FREF *frp;
738 	MARK from, to;
739 	size_t len;
740 	u_long nlno, nch;
741 	int fd, nf, noname, oflags, rval;
742 	char *p, *s, *t, buf[PATH_MAX + 64];
743 	const char *msgstr;
744 
745 	ep = sp->ep;
746 	frp = sp->frp;
747 
748 	/*
749 	 * Writing '%', or naming the current file explicitly, has the
750 	 * same semantics as writing without a name.
751 	 */
752 	if (name == NULL || !strcmp(name, frp->name)) {
753 		noname = 1;
754 		name = frp->name;
755 	} else
756 		noname = 0;
757 
758 	/* Can't write files marked read-only, unless forced. */
759 	if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
760 		msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
761 		    "Read-only file, not written; use ! to override" :
762 		    "Read-only file, not written");
763 		return (1);
764 	}
765 
766 	/* If not forced, not appending, and "writeany" not set ... */
767 	if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
768 		/* Don't overwrite anything but the original file. */
769 		if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
770 		    !stat(name, &sb)) {
771 			msgq_str(sp, M_ERR, name,
772 			    LF_ISSET(FS_POSSIBLE) ?
773 			    "%s exists, not written; use ! to override" :
774 			    "%s exists, not written");
775 			return (1);
776 		}
777 
778 		/*
779 		 * Don't write part of any existing file.  Only test for the
780 		 * original file, the previous test catches anything else.
781 		 */
782 		if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
783 			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
784 			    "Partial file, not written; use ! to override" :
785 			    "Partial file, not written");
786 			return (1);
787 		}
788 	}
789 
790 	/*
791 	 * Figure out if the file already exists -- if it doesn't, we display
792 	 * the "new file" message.  The stat might not be necessary, but we
793 	 * just repeat it because it's easier than hacking the previous tests.
794 	 * The information is only used for the user message and modification
795 	 * time test, so we can ignore the obvious race condition.
796 	 *
797 	 * One final test.  If we're not forcing or appending the current file,
798 	 * and we have a saved modification time, object if the file changed
799 	 * since we last edited or wrote it, and make them force it.
800 	 */
801 	if (stat(name, &sb))
802 		mtype = NEWFILE;
803 	else {
804 		if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
805 		    ((F_ISSET(ep, F_DEVSET) &&
806 		    (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
807 		    timespeccmp(&sb.st_mtim, &ep->mtim, !=))) {
808 			msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
809 "%s: file modified more recently than this copy; use ! to override" :
810 "%s: file modified more recently than this copy");
811 			return (1);
812 		}
813 
814 		mtype = OLDFILE;
815 	}
816 
817 	/* Set flags to create, write, and either append or truncate. */
818 	oflags = O_CREAT | O_WRONLY |
819 	    (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
820 
821 	/* Backup the file if requested. */
822 	if (!opts_empty(sp, O_BACKUP, 1) &&
823 	    file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
824 		return (1);
825 
826 	/* Open the file. */
827 	if ((fd = open(name, oflags,
828 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
829 		msgq_str(sp, M_SYSERR, name, "%s");
830 		return (1);
831 	}
832 
833 	/* Try and get a lock. */
834 	if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
835 		msgq_str(sp, M_ERR, name,
836 		    "%s: write lock was unavailable");
837 
838 	/*
839 	 * Use stdio for buffering.
840 	 *
841 	 * XXX
842 	 * SVR4.2 requires the fdopen mode exactly match the original open
843 	 * mode, i.e. you have to open with "a" if appending.
844 	 */
845 	if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
846 		msgq_str(sp, M_SYSERR, name, "%s");
847 		(void)close(fd);
848 		return (1);
849 	}
850 
851 	/* Build fake addresses, if necessary. */
852 	if (fm == NULL) {
853 		from.lno = 1;
854 		from.cno = 0;
855 		fm = &from;
856 		if (db_last(sp, &to.lno)) {
857 			(void)fclose(fp);
858 			return (1);
859 		}
860 		to.cno = 0;
861 		tm = &to;
862 	}
863 
864 	rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
865 
866 	/*
867 	 * Save the new last modification time -- even if the write fails
868 	 * we re-init the time.  That way the user can clean up the disk
869 	 * and rewrite without having to force it.
870 	 */
871 	if (noname) {
872 		if (stat(name, &sb))
873 			(void)clock_gettime(CLOCK_REALTIME, &ep->mtim);
874 		else {
875 			F_SET(ep, F_DEVSET);
876 			ep->mdev = sb.st_dev;
877 			ep->minode = sb.st_ino;
878 
879 			ep->mtim = sb.st_mtim;
880 		}
881 	}
882 
883 	/*
884 	 * If the write failed, complain loudly.  ex_writefp() has already
885 	 * complained about the actual error, reinforce it if data was lost.
886 	 */
887 	if (rval) {
888 		if (!LF_ISSET(FS_APPEND))
889 			msgq_str(sp, M_ERR, name,
890 			    "%s: WARNING: FILE TRUNCATED");
891 		return (1);
892 	}
893 
894 	/*
895 	 * Once we've actually written the file, it doesn't matter that the
896 	 * file name was changed -- if it was, we've already whacked it.
897 	 */
898 	F_CLR(frp, FR_NAMECHANGE);
899 
900 	/*
901 	 * If wrote the entire file, and it wasn't by appending it to a file,
902 	 * clear the modified bit.  If the file was written to the original
903 	 * file name and the file is a temporary, set the "no exit" bit.  This
904 	 * permits the user to write the file and use it in the context of the
905 	 * filesystem, but still keeps them from discarding their changes by
906 	 * exiting.
907 	 */
908 	if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
909 		F_CLR(ep, F_MODIFIED);
910 		if (F_ISSET(frp, FR_TMPFILE)) {
911 			if (noname)
912 				F_SET(frp, FR_TMPEXIT);
913 			else
914 				F_CLR(frp, FR_TMPEXIT);
915 		}
916 	}
917 
918 	p = msg_print(sp, name, &nf);
919 	switch (mtype) {
920 	case NEWFILE:
921 		len = snprintf(buf, sizeof(buf),
922 		    "%s: new file: %lu lines, %lu characters", p, nlno, nch);
923 		if (len >= sizeof(buf))
924 			len = sizeof(buf) - 1;
925 		break;
926 	case OLDFILE:
927 		msgstr = LF_ISSET(FS_APPEND) ?
928 		    "%s: appended: %lu lines, %lu characters" :
929 		    "%s: %lu lines, %lu characters";
930 		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
931 		if (len >= sizeof(buf))
932 			len = sizeof(buf) - 1;
933 		break;
934 	default:
935 		abort();
936 	}
937 
938 	/*
939 	 * There's a nasty problem with long path names.  Tags files
940 	 * can result in long paths and vi will request a continuation key from
941 	 * the user.  Unfortunately, the user has typed ahead, and chaos will
942 	 * result.  If we assume that the characters in the filenames only take
943 	 * a single screen column each, we can trim the filename.
944 	 */
945 	s = buf;
946 	if (len >= sp->cols) {
947 		for (s = buf, t = buf + strlen(p); s < t &&
948 		    (*s != '/' || len >= sp->cols - 3); ++s, --len);
949 		if (s == t)
950 			s = buf;
951 		else {
952 			*--s = '.';		/* Leading ellipses. */
953 			*--s = '.';
954 			*--s = '.';
955 		}
956 	}
957 	msgq(sp, M_INFO, "%s", s);
958 	if (nf)
959 		FREE_SPACE(sp, p, 0);
960 	return (0);
961 }
962 
963 /*
964  * file_backup --
965  *	Backup the about-to-be-written file.
966  *
967  * XXX
968  * We do the backup by copying the entire file.  It would be nice to do
969  * a rename instead, but: (1) both files may not fit and we want to fail
970  * before doing the rename; (2) the backup file may not be on the same
971  * disk partition as the file being written; (3) there may be optional
972  * file information (MACs, DACs, whatever) that we won't get right if we
973  * recreate the file.  So, let's not risk it.
974  */
975 static int
file_backup(SCR * sp,char * name,char * bname)976 file_backup(SCR *sp, char *name, char *bname)
977 {
978 	struct dirent *dp;
979 	struct stat sb;
980 	DIR *dirp;
981 	EXCMD cmd;
982 	off_t off;
983 	size_t blen;
984 	int flags, maxnum, nr, num, nw, rfd, wfd, version;
985 	char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];
986 
987 	rfd = wfd = -1;
988 	bp = estr = wfname = NULL;
989 
990 	/*
991 	 * Open the current file for reading.  Do this first, so that
992 	 * we don't exec a shell before the most likely failure point.
993 	 * If it doesn't exist, it's okay, there's just nothing to back
994 	 * up.
995 	 */
996 	errno = 0;
997 	if ((rfd = open(name, O_RDONLY)) < 0) {
998 		if (errno == ENOENT)
999 			return (0);
1000 		estr = name;
1001 		goto err;
1002 	}
1003 
1004 	/*
1005 	 * If the name starts with an 'N' character, add a version number
1006 	 * to the name.  Strip the leading N from the string passed to the
1007 	 * expansion routines, for no particular reason.  It would be nice
1008 	 * to permit users to put the version number anywhere in the backup
1009 	 * name, but there isn't a special character that we can use in the
1010 	 * name, and giving a new character a special meaning leads to ugly
1011 	 * hacks both here and in the supporting ex routines.
1012 	 *
1013 	 * Shell and file name expand the option's value.
1014 	 */
1015 	argv_init(sp, &cmd);
1016 	ex_cinit(&cmd, 0, 0, 0, 0, 0, NULL);
1017 	if (bname[0] == 'N') {
1018 		version = 1;
1019 		++bname;
1020 	} else
1021 		version = 0;
1022 	if (argv_exp2(sp, &cmd, bname, strlen(bname))) {
1023 		(void)close(rfd);
1024 		return (1);
1025 	}
1026 
1027 	/*
1028 	 *  0 args: impossible.
1029 	 *  1 args: use it.
1030 	 * >1 args: object, too many args.
1031 	 */
1032 	if (cmd.argc != 1) {
1033 		msgq_str(sp, M_ERR, bname,
1034 		    "%s expanded into too many file names");
1035 		(void)close(rfd);
1036 		return (1);
1037 	}
1038 
1039 	/*
1040 	 * If appending a version number, read through the directory, looking
1041 	 * for file names that match the name followed by a number.  Make all
1042 	 * of the other % characters in name literal, so the user doesn't get
1043 	 * surprised and sscanf doesn't drop core indirecting through pointers
1044 	 * that don't exist.  If any such files are found, increment its number
1045 	 * by one.
1046 	 */
1047 	if (version) {
1048 		GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1049 		for (t = bp, slash = NULL,
1050 		    p = cmd.argv[0]->bp; p[0] != '\0'; *t++ = *p++)
1051 			if (p[0] == '%') {
1052 				if (p[1] != '%')
1053 					*t++ = '%';
1054 			} else if (p[0] == '/')
1055 				slash = t;
1056 		pct = t;
1057 		*t++ = '%';
1058 		*t++ = 'd';
1059 		*t = '\0';
1060 
1061 		if (slash == NULL) {
1062 			dirp = opendir(".");
1063 			p = bp;
1064 		} else {
1065 			*slash = '\0';
1066 			dirp = opendir(bp);
1067 			*slash = '/';
1068 			p = slash + 1;
1069 		}
1070 		if (dirp == NULL) {
1071 			estr = cmd.argv[0]->bp;
1072 			goto err;
1073 		}
1074 
1075 		for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1076 			if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1077 				maxnum = num;
1078 		(void)closedir(dirp);
1079 
1080 		/* Format the backup file name. */
1081 		(void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1082 		wfname = bp;
1083 	} else {
1084 		bp = NULL;
1085 		wfname = cmd.argv[0]->bp;
1086 	}
1087 
1088 	/* Open the backup file, avoiding lurkers. */
1089 	if (stat(wfname, &sb) == 0) {
1090 		if (!S_ISREG(sb.st_mode)) {
1091 			msgq_str(sp, M_ERR, bname,
1092 			    "%s: not a regular file");
1093 			goto err;
1094 		}
1095 		if (sb.st_uid != getuid()) {
1096 			msgq_str(sp, M_ERR, bname, "%s: not owned by you");
1097 			goto err;
1098 		}
1099 		if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1100 			msgq_str(sp, M_ERR, bname,
1101 			   "%s: accessible by a user other than the owner");
1102 			goto err;
1103 		}
1104 		flags = O_TRUNC;
1105 	} else
1106 		flags = O_CREAT | O_EXCL;
1107 	if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0 ||
1108 	    fchmod(wfd, S_IRUSR | S_IWUSR) < 0) {
1109 		if (wfd != -1) {
1110 			close(wfd);
1111 			(void)unlink(wfname);
1112 		}
1113 		estr = bname;
1114 		goto err;
1115 	}
1116 
1117 	/* Copy the file's current contents to its backup value. */
1118 	while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1119 		for (off = 0; nr != 0; nr -= nw, off += nw)
1120 			if ((nw = write(wfd, buf + off, nr)) < 0) {
1121 				estr = wfname;
1122 				goto err;
1123 			}
1124 	if (nr < 0) {
1125 		estr = name;
1126 		goto err;
1127 	}
1128 
1129 	if (close(rfd)) {
1130 		estr = name;
1131 		goto err;
1132 	}
1133 	if (close(wfd)) {
1134 		estr = wfname;
1135 		goto err;
1136 	}
1137 	if (bp != NULL)
1138 		FREE_SPACE(sp, bp, blen);
1139 	return (0);
1140 
1141 alloc_err:
1142 err:	if (rfd != -1)
1143 		(void)close(rfd);
1144 	if (wfd != -1) {
1145 		(void)unlink(wfname);
1146 		(void)close(wfd);
1147 	}
1148 	if (estr)
1149 		msgq_str(sp, M_SYSERR, estr, "%s");
1150 	if (bp != NULL)
1151 		FREE_SPACE(sp, bp, blen);
1152 	return (1);
1153 }
1154 
1155 /*
1156  * file_comment --
1157  *	Skip the first comment.
1158  */
1159 static void
file_comment(SCR * sp)1160 file_comment(SCR *sp)
1161 {
1162 	recno_t lno;
1163 	size_t len;
1164 	char *p;
1165 
1166 	for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1167 	if (p == NULL)
1168 		return;
1169 	if (p[0] == '#') {
1170 		F_SET(sp, SC_SCR_TOP);
1171 		while (!db_get(sp, ++lno, 0, &p, &len))
1172 			if (len < 1 || p[0] != '#') {
1173 				sp->lno = lno;
1174 				return;
1175 			}
1176 	} else if (len > 1 && p[0] == '/' && p[1] == '*') {
1177 		F_SET(sp, SC_SCR_TOP);
1178 		do {
1179 			for (; len > 1; --len, ++p)
1180 				if (p[0] == '*' && p[1] == '/') {
1181 					sp->lno = lno;
1182 					return;
1183 				}
1184 		} while (!db_get(sp, ++lno, 0, &p, &len));
1185 	} else if (len > 1 && p[0] == '/' && p[1] == '/') {
1186 		F_SET(sp, SC_SCR_TOP);
1187 		p += 2;
1188 		len -= 2;
1189 		do {
1190 			for (; len > 1; --len, ++p)
1191 				if (p[0] == '/' && p[1] == '/') {
1192 					sp->lno = lno;
1193 					return;
1194 				}
1195 		} while (!db_get(sp, ++lno, 0, &p, &len));
1196 	}
1197 }
1198 
1199 /*
1200  * file_m1 --
1201  * 	First modification check routine.  The :next, :prev, :rewind, :tag,
1202  *	:tagpush, :tagpop, ^^ modifications check.
1203  *
1204  * PUBLIC: int file_m1(SCR *, int, int);
1205  */
1206 int
file_m1(SCR * sp,int force,int flags)1207 file_m1(SCR *sp, int force, int flags)
1208 {
1209 	EXF *ep;
1210 
1211 	ep = sp->ep;
1212 
1213 	/* If no file loaded, return no modifications. */
1214 	if (ep == NULL)
1215 		return (0);
1216 
1217 	/*
1218 	 * If the file has been modified, we'll want to write it back or
1219 	 * fail.  If autowrite is set, we'll write it back automatically,
1220 	 * unless force is also set.  Otherwise, we fail unless forced or
1221 	 * there's another open screen on this file.
1222 	 */
1223 	if (F_ISSET(ep, F_MODIFIED)) {
1224 		if (O_ISSET(sp, O_AUTOWRITE)) {
1225 			if (!force && file_aw(sp, flags))
1226 				return (1);
1227 		} else if (ep->refcnt <= 1 && !force) {
1228 			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1229 "File modified since last complete write; write or use ! to override" :
1230 "File modified since last complete write; write or use :edit! to override");
1231 			return (1);
1232 		}
1233 	}
1234 
1235 	return (file_m3(sp, force));
1236 }
1237 
1238 /*
1239  * file_m2 --
1240  * 	Second modification check routine.  The :edit, :quit, :recover
1241  *	modifications check.
1242  *
1243  * PUBLIC: int file_m2(SCR *, int);
1244  */
1245 int
file_m2(SCR * sp,int force)1246 file_m2(SCR *sp, int force)
1247 {
1248 	EXF *ep;
1249 
1250 	ep = sp->ep;
1251 
1252 	/* If no file loaded, return no modifications. */
1253 	if (ep == NULL)
1254 		return (0);
1255 
1256 	/*
1257 	 * If the file has been modified, we'll want to fail, unless forced
1258 	 * or there's another open screen on this file.
1259 	 */
1260 	if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1261 		msgq(sp, M_ERR,
1262 "File modified since last complete write; write or use ! to override");
1263 		return (1);
1264 	}
1265 
1266 	return (file_m3(sp, force));
1267 }
1268 
1269 /*
1270  * file_m3 --
1271  * 	Third modification check routine.
1272  *
1273  * PUBLIC: int file_m3(SCR *, int);
1274  */
1275 int
file_m3(SCR * sp,int force)1276 file_m3(SCR *sp, int force)
1277 {
1278 	EXF *ep;
1279 
1280 	ep = sp->ep;
1281 
1282 	/* If no file loaded, return no modifications. */
1283 	if (ep == NULL)
1284 		return (0);
1285 
1286 	/*
1287 	 * Don't exit while in a temporary files if the file was ever modified.
1288 	 * The problem is that if the user does a ":wq", we write and quit,
1289 	 * unlinking the temporary file.  Not what the user had in mind at all.
1290 	 * We permit writing to temporary files, so that user maps using file
1291 	 * system names work with temporary files.
1292 	 */
1293 	if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1294 		msgq(sp, M_ERR,
1295 		    "File is a temporary; exit will discard modifications");
1296 		return (1);
1297 	}
1298 	return (0);
1299 }
1300 
1301 /*
1302  * file_aw --
1303  *	Autowrite routine.  If modified, autowrite is set and the readonly bit
1304  *	is not set, write the file.  A routine so there's a place to put the
1305  *	comment.
1306  *
1307  * PUBLIC: int file_aw(SCR *, int);
1308  */
1309 int
file_aw(SCR * sp,int flags)1310 file_aw(SCR *sp, int flags)
1311 {
1312 	if (!F_ISSET(sp->ep, F_MODIFIED))
1313 		return (0);
1314 	if (!O_ISSET(sp, O_AUTOWRITE))
1315 		return (0);
1316 
1317 	/*
1318 	 * !!!
1319 	 * Historic 4BSD vi attempted to write the file if autowrite was set,
1320 	 * regardless of the writeability of the file (as defined by the file
1321 	 * readonly flag).  System V changed this as some point, not attempting
1322 	 * autowrite if the file was readonly.  This feels like a bug fix to
1323 	 * me (e.g. the principle of least surprise is violated if readonly is
1324 	 * set and vi writes the file), so I'm compatible with System V.
1325 	 */
1326 	if (O_ISSET(sp, O_READONLY)) {
1327 		msgq(sp, M_INFO,
1328 		    "File readonly, modifications not auto-written");
1329 		return (1);
1330 	}
1331 	return (file_write(sp, NULL, NULL, NULL, flags));
1332 }
1333 
1334 /*
1335  * set_alt_name --
1336  *	Set the alternate pathname.
1337  *
1338  * Set the alternate pathname.  It's a routine because I wanted some place
1339  * to hang this comment.  The alternate pathname (normally referenced using
1340  * the special character '#' during file expansion and in the vi ^^ command)
1341  * is set by almost all ex commands that take file names as arguments.  The
1342  * rules go something like this:
1343  *
1344  *    1: If any ex command takes a file name as an argument (except for the
1345  *	 :next command), the alternate pathname is set to that file name.
1346  *	 This excludes the command ":e" and ":w !command" as no file name
1347  *       was specified.  Note, historically, the :source command did not set
1348  *	 the alternate pathname.  It does in nvi, for consistency.
1349  *
1350  *    2: However, if any ex command sets the current pathname, e.g. the
1351  *	 ":e file" or ":rew" commands succeed, then the alternate pathname
1352  *	 is set to the previous file's current pathname, if it had one.
1353  *	 This includes the ":file" command and excludes the ":e" command.
1354  *	 So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1355  *	 pathname will be "foo", if it succeeds, the alternate pathname will
1356  *	 be the previous current pathname.  The ":e" command will not set
1357  *       the alternate or current pathnames regardless.
1358  *
1359  *    3: However, if it's a read or write command with a file argument and
1360  *	 the current pathname has not yet been set, the file name becomes
1361  *	 the current pathname, and the alternate pathname is unchanged.
1362  *
1363  * If the user edits a temporary file, there may be times when there is no
1364  * alternative file name.  A name argument of NULL turns it off.
1365  *
1366  * PUBLIC: void set_alt_name(SCR *, char *);
1367  */
1368 void
set_alt_name(SCR * sp,char * name)1369 set_alt_name(SCR *sp, char *name)
1370 {
1371 	free(sp->alt_name);
1372 	if (name == NULL)
1373 		sp->alt_name = NULL;
1374 	else if ((sp->alt_name = strdup(name)) == NULL)
1375 		msgq(sp, M_SYSERR, NULL);
1376 }
1377 
1378 /*
1379  * file_lock --
1380  *	Get an exclusive lock on a file.
1381  *
1382  * PUBLIC: lockr_t file_lock(SCR *, char *, int *, int, int);
1383  */
1384 lockr_t
file_lock(SCR * sp,char * name,int * fdp,int fd,int iswrite)1385 file_lock(SCR *sp, char *name, int *fdp, int fd, int iswrite)
1386 {
1387 	if (!O_ISSET(sp, O_LOCKFILES))
1388 		return (LOCK_SUCCESS);
1389 
1390 	/* Set close-on-exec flag so locks are not inherited by shell cmd. */
1391 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
1392 		msgq_str(sp, M_SYSERR, name, "%s");
1393 
1394 	/*
1395 	 * !!!
1396 	 * We need to distinguish a lock not being available for the file
1397 	 * from the file system not supporting locking.  Flock is documented
1398 	 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1399 	 * they are the former.  There's no portable way to do this.
1400 	 */
1401 	errno = 0;
1402 	return (flock(fd, LOCK_EX | LOCK_NB) ?
1403 	    errno == EAGAIN || errno == EWOULDBLOCK ? LOCK_UNAVAIL : LOCK_FAILED :
1404 	    LOCK_SUCCESS);
1405 }
1406