75c3d9fa7c07d7ed18bb7200862e2311228feb67
[nvi.git] / common / exf.c
blob75c3d9fa7c07d7ed18bb7200862e2311228feb67
1 /*-
2 * Copyright (c) 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1992, 1993, 1994, 1995, 1996
5 * Keith Bostic. All rights reserved.
7 * See the LICENSE file for redistribution information.
8 */
10 #include "config.h"
12 #ifndef lint
13 static const char sccsid[] = "$Id: exf.c,v 10.72 2003/08/10 09:44:01 skimo Exp $ (Berkeley) $Date: 2003/08/10 09:44:01 $";
14 #endif /* not lint */
16 #include <sys/param.h>
17 #include <sys/types.h> /* XXX: param.h may not have included types.h */
18 #include <sys/queue.h>
19 #include <sys/stat.h>
22 * We include <sys/file.h>, because the flock(2) and open(2) #defines
23 * were found there on historical systems. We also include <fcntl.h>
24 * because the open(2) #defines are found there on newer systems.
26 #include <sys/file.h>
28 #include <bitstring.h>
29 #include <dirent.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <time.h>
39 #include "common.h"
41 static int file_backup __P((SCR *, char *, char *));
42 static void file_cinit __P((SCR *));
43 static void file_comment __P((SCR *));
44 static int file_spath __P((SCR *, FREF *, struct stat *, int *));
45 static int db_setup __P((SCR *sp, EXF *ep));
48 * file_add --
49 * Insert a file name into the FREF list, if it doesn't already
50 * appear in it.
52 * !!!
53 * The "if it doesn't already appear" changes vi's semantics slightly. If
54 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
55 * will reflect the line/column of the previous edit session. Historic nvi
56 * did not do this. The change is a logical extension of the change where
57 * vi now remembers the last location in any file that it has ever edited,
58 * not just the previously edited file.
60 * PUBLIC: FREF *file_add __P((SCR *, char *));
62 FREF *
63 file_add(SCR *sp, char *name)
65 GS *gp;
66 FREF *frp, *tfrp;
69 * Return it if it already exists. Note that we test against the
70 * user's name, whatever that happens to be, including if it's a
71 * temporary file.
73 * If the user added a file but was unable to initialize it, there
74 * can be file list entries where the name field is NULL. Discard
75 * them the next time we see them.
77 gp = sp->gp;
78 if (name != NULL)
79 for (frp = gp->frefq.cqh_first;
80 frp != (FREF *)&gp->frefq; frp = frp->q.cqe_next) {
81 if (frp->name == NULL) {
82 tfrp = frp->q.cqe_next;
83 CIRCLEQ_REMOVE(&gp->frefq, frp, q);
84 if (frp->name != NULL)
85 free(frp->name);
86 free(frp);
87 frp = tfrp;
88 continue;
90 if (!strcmp(frp->name, name))
91 return (frp);
94 /* Allocate and initialize the FREF structure. */
95 CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
96 if (frp == NULL)
97 return (NULL);
100 * If no file name specified, or if the file name is a request
101 * for something temporary, file_init() will allocate the file
102 * name. Temporary files are always ignored.
104 if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
105 (frp->name = strdup(name)) == NULL) {
106 free(frp);
107 msgq(sp, M_SYSERR, NULL);
108 return (NULL);
111 /* Append into the chain of file names. */
112 CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);
114 return (frp);
118 * file_init --
119 * Start editing a file, based on the FREF structure. If successsful,
120 * let go of any previous file. Don't release the previous file until
121 * absolutely sure we have the new one.
123 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
126 file_init(SCR *sp, FREF *frp, char *rcv_name, int flags)
128 EXF *ep;
129 struct stat sb;
130 size_t psize;
131 int fd, exists, open_err, readonly, stolen;
132 char *oname, tname[MAXPATHLEN];
134 stolen = open_err = readonly = 0;
137 * If the file is a recovery file, let the recovery code handle it.
138 * Clear the FR_RECOVER flag first -- the recovery code does set up,
139 * and then calls us! If the recovery call fails, it's probably
140 * because the named file doesn't exist. So, move boldly forward,
141 * presuming that there's an error message the user will get to see.
143 if (F_ISSET(frp, FR_RECOVER)) {
144 F_CLR(frp, FR_RECOVER);
145 return (rcv_read(sp, frp));
149 * Required FRP initialization; the only flag we keep is the
150 * cursor information.
152 F_CLR(frp, ~FR_CURSORSET);
155 * Scan the user's path to find the file that we're going to
156 * try and open.
158 if (file_spath(sp, frp, &sb, &exists))
159 return (1);
162 * Check whether we already have this file opened in some
163 * other screen.
165 if (exists) {
166 EXF *exfp;
167 for (exfp = sp->gp->exfq.cqh_first;
168 exfp != (EXF *)&sp->gp->exfq; exfp = exfp->q.cqe_next) {
169 if (exfp->mdev == sb.st_dev &&
170 exfp->minode == sb.st_ino &&
171 (exfp != sp->ep || exfp->refcnt > 1)) {
172 ep = exfp;
173 goto postinit;
179 * Required EXF initialization:
180 * Flush the line caches.
181 * Default recover mail file fd to -1.
182 * Set initial EXF flag bits.
184 CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
185 CIRCLEQ_INIT(&ep->scrq);
186 sp->c_lno = ep->c_nlines = OOBLNO;
187 ep->rcv_fd = ep->fcntl_fd = -1;
188 F_SET(ep, F_FIRSTMODIFY);
191 * If no name or backing file, for whatever reason, create a backing
192 * temporary file, saving the temp file name so we can later unlink
193 * it. If the user never named this file, copy the temporary file name
194 * to the real name (we display that until the user renames it).
196 oname = frp->name;
197 if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
198 if (opts_empty(sp, O_TMP_DIRECTORY, 0))
199 goto err;
200 (void)snprintf(tname, sizeof(tname),
201 "%s/vi.XXXXXX", O_STR(sp, O_TMP_DIRECTORY));
202 if ((fd = mkstemp(tname)) == -1) {
203 msgq(sp, M_SYSERR,
204 "237|Unable to create temporary file");
205 goto err;
207 (void)close(fd);
209 if (frp->name == NULL)
210 F_SET(frp, FR_TMPFILE);
211 if ((frp->tname = strdup(tname)) == NULL ||
212 (frp->name == NULL &&
213 (frp->name = strdup(tname)) == NULL)) {
214 if (frp->tname != NULL) {
215 free(frp->tname);
217 msgq(sp, M_SYSERR, NULL);
218 (void)unlink(tname);
219 goto err;
221 oname = frp->tname;
222 psize = 1024;
223 if (!LF_ISSET(FS_OPENERR))
224 F_SET(frp, FR_NEWFILE);
226 time(&ep->mtime);
227 } else {
229 * XXX
230 * A seat of the pants calculation: try to keep the file in
231 * 15 pages or less. Don't use a page size larger than 10K
232 * (vi should have good locality) or smaller than 1K.
234 psize = ((sb.st_size / 15) + 1023) / 1024;
235 if (psize > 10)
236 psize = 10;
237 if (psize == 0)
238 psize = 1;
239 psize *= 1024;
241 F_SET(ep, F_DEVSET);
242 ep->mdev = sb.st_dev;
243 ep->minode = sb.st_ino;
245 ep->mtime = sb.st_mtime;
247 if (!S_ISREG(sb.st_mode))
248 msgq_str(sp, M_ERR, oname,
249 "238|Warning: %s is not a regular file");
252 /* Set up recovery. */
253 if (rcv_name == NULL) {
254 /* ep->rcv_path NULL if rcv_tmp fails */
255 rcv_tmp(sp, ep, frp->name);
256 } else {
257 if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
258 msgq(sp, M_SYSERR, NULL);
259 goto err;
261 F_SET(ep, F_MODIFIED);
264 if (db_setup(sp, ep))
265 goto err;
267 /* Open a db structure. */
268 if ((sp->db_error = db_create(&ep->db, 0, 0)) != 0) {
269 msgq(sp, M_DBERR, "db_create");
270 goto err;
273 ep->db->set_re_delim(ep->db, '\n'); /* Always set. */
274 ep->db->set_pagesize(ep->db, psize);
275 ep->db->set_flags(ep->db, DB_RENUMBER | DB_SNAPSHOT);
276 if (rcv_name == NULL)
277 ep->db->set_re_source(ep->db, oname);
280 * Don't let db use mmap when using fcntl for locking
282 #ifdef HAVE_LOCK_FCNTL
283 #define NOMMAPIFFCNTL DB_NOMMAP
284 #else
285 #define NOMMAPIFFCNTL 0
286 #endif
288 #define _DB_OPEN_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
290 if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO,
291 ((rcv_name == 0) ? DB_TRUNCATE : 0) | VI_DB_THREAD | NOMMAPIFFCNTL,
292 _DB_OPEN_MODE)) != 0) {
293 msgq_str(sp,
294 M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s");
296 * !!!
297 * Historically, vi permitted users to edit files that couldn't
298 * be read. This isn't useful for single files from a command
299 * line, but it's quite useful for "vi *.c", since you can skip
300 * past files that you can't read.
302 ep->db = NULL; /* Don't close it; it wasn't opened */
304 if (LF_ISSET(FS_OPENERR))
305 goto err;
307 open_err = 1;
308 goto oerr;
311 /* re_source is loaded into the database.
312 * Close it and reopen it in the environment.
314 if ((sp->db_error = ep->db->close(ep->db, 0))) {
315 msgq(sp, M_DBERR, "close");
316 goto err;
318 if ((sp->db_error = db_create(&ep->db, ep->env, 0)) != 0) {
319 msgq(sp, M_DBERR, "db_create 2");
320 goto err;
322 if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO,
323 VI_DB_THREAD | NOMMAPIFFCNTL, _DB_OPEN_MODE)) != 0) {
324 msgq_str(sp,
325 M_DBERR, ep->rcv_path, "%s");
326 goto err;
330 * Do the remaining things that can cause failure of the new file,
331 * mark and logging initialization.
333 if (mark_init(sp, ep) || log_init(sp, ep))
334 goto err;
336 postinit:
338 * Set the alternate file name to be the file we're discarding.
340 * !!!
341 * Temporary files can't become alternate files, so there's no file
342 * name. This matches historical practice, although it could only
343 * happen in historical vi as the result of the initial command, i.e.
344 * if vi was executed without a file name.
346 if (LF_ISSET(FS_SETALT))
347 set_alt_name(sp, sp->frp == NULL ||
348 F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
351 * Close the previous file; if that fails, close the new one and run
352 * for the border.
354 * !!!
355 * There's a nasty special case. If the user edits a temporary file,
356 * and then does an ":e! %", we need to re-initialize the backing
357 * file, but we can't change the name. (It's worse -- we're dealing
358 * with *names* here, we can't even detect that it happened.) Set a
359 * flag so that the file_end routine ignores the backing information
360 * of the old file if it happens to be the same as the new one.
362 * !!!
363 * Side-effect: after the call to file_end(), sp->frp may be NULL.
365 if (sp->ep != NULL) {
366 F_SET(frp, FR_DONTDELETE);
367 if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
368 (void)file_end(sp, ep, 1);
369 goto err;
371 sp->ep = NULL;
372 F_CLR(frp, FR_DONTDELETE);
376 * Lock the file; if it's a recovery file, it should already be
377 * locked. Note, we acquire the lock after the previous file
378 * has been ended, so that we don't get an "already locked" error
379 * for ":edit!".
381 * XXX
382 * While the user can't interrupt us between the open and here,
383 * there's a race between the dbopen() and the lock. Not much
384 * we can do about it.
386 * XXX
387 * We don't make a big deal of not being able to lock the file. As
388 * locking rarely works over NFS, and often fails if the file was
389 * mmap(2)'d, it's far too common to do anything like print an error
390 * message, let alone make the file readonly. At some future time,
391 * when locking is a little more reliable, this should change to be
392 * an error.
394 if (rcv_name == NULL && ep->refcnt == 0) {
395 if ((ep->fd = open(oname, O_RDWR)) == -1)
396 goto no_lock;
398 switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 1)) {
399 case LOCK_FAILED:
400 no_lock:
401 F_SET(frp, FR_UNLOCKED);
402 break;
403 case LOCK_UNAVAIL:
404 readonly = 1;
405 msgq_str(sp, M_INFO, oname,
406 "239|%s already locked, session is read-only");
407 break;
408 case LOCK_SUCCESS:
409 break;
414 * Historically, the readonly edit option was set per edit buffer in
415 * vi, unless the -R command-line option was specified or the program
416 * was executed as "view". (Well, to be truthful, if the letter 'w'
417 * occurred anywhere in the program name, but let's not get into that.)
418 * So, the persistant readonly state has to be stored in the screen
419 * structure, and the edit option value toggles with the contents of
420 * the edit buffer. If the persistant readonly flag is set, set the
421 * readonly edit option.
423 * Otherwise, try and figure out if a file is readonly. This is a
424 * dangerous thing to do. The kernel is the only arbiter of whether
425 * or not a file is writeable, and the best that a user program can
426 * do is guess. Obvious loopholes are files that are on a file system
427 * mounted readonly (access catches this one on a few systems), or
428 * alternate protection mechanisms, ACL's for example, that we can't
429 * portably check. Lots of fun, and only here because users whined.
431 * !!!
432 * Historic vi displayed the readonly message if none of the file
433 * write bits were set, or if an an access(2) call on the path
434 * failed. This seems reasonable. If the file is mode 444, root
435 * users may want to know that the owner of the file did not expect
436 * it to be written.
438 * Historic vi set the readonly bit if no write bits were set for
439 * a file, even if the access call would have succeeded. This makes
440 * the superuser force the write even when vi expects that it will
441 * succeed. I'm less supportive of this semantic, but it's historic
442 * practice and the conservative approach to vi'ing files as root.
444 * It would be nice if there was some way to update this when the user
445 * does a "^Z; chmod ...". The problem is that we'd first have to
446 * distinguish between readonly bits set because of file permissions
447 * and those set for other reasons. That's not too hard, but deciding
448 * when to reevaluate the permissions is trickier. An alternative
449 * might be to turn off the readonly bit if the user forces a write
450 * and it succeeds.
452 * XXX
453 * Access(2) doesn't consider the effective uid/gid values. This
454 * probably isn't a problem for vi when it's running standalone.
456 if (readonly || F_ISSET(sp, SC_READONLY) ||
457 (!F_ISSET(frp, FR_NEWFILE) &&
458 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
459 access(frp->name, W_OK))))
460 O_SET(sp, O_READONLY);
461 else
462 O_CLR(sp, O_READONLY);
464 /* Switch... */
465 ++ep->refcnt;
466 CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq);
467 sp->ep = ep;
468 sp->frp = frp;
470 /* Set the initial cursor position, queue initial command. */
471 file_cinit(sp);
473 /* Report conversion errors again. */
474 F_CLR(sp, SC_CONV_ERROR);
476 /* Redraw the screen from scratch, schedule a welcome message. */
477 F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);
479 if (frp->lno == OOBLNO)
480 F_SET(sp, SC_SCR_TOP);
482 /* Append into the chain of file structures. */
483 if (ep->refcnt == 1)
484 CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q);
486 return (0);
488 err: if (frp->name != NULL) {
489 free(frp->name);
490 frp->name = NULL;
492 if (frp->tname != NULL) {
493 (void)unlink(frp->tname);
494 free(frp->tname);
495 frp->tname = NULL;
498 oerr: if (F_ISSET(ep, F_RCV_ON))
499 (void)unlink(ep->rcv_path);
500 if (ep->rcv_path != NULL) {
501 free(ep->rcv_path);
502 ep->rcv_path = NULL;
504 if (ep->db != NULL) {
505 (void)ep->db->close(ep->db, DB_NOSYNC);
506 ep->db = NULL;
508 free(ep);
510 return (open_err && !LF_ISSET(FS_OPENERR) ?
511 file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
515 * file_spath --
516 * Scan the user's path to find the file that we're going to
517 * try and open.
519 static int
520 file_spath(SCR *sp, FREF *frp, struct stat *sbp, int *existsp)
522 CHAR_T savech;
523 size_t len;
524 int found;
525 char *name, *p, *t, path[MAXPATHLEN];
528 * If the name is NULL or an explicit reference (i.e., the first
529 * component is . or ..) ignore the O_PATH option.
531 name = frp->name;
532 if (name == NULL) {
533 *existsp = 0;
534 return (0);
536 if (name[0] == '/' || (name[0] == '.' &&
537 (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
538 *existsp = !stat(name, sbp);
539 return (0);
542 /* Try . */
543 if (!stat(name, sbp)) {
544 *existsp = 1;
545 return (0);
548 /* Try the O_PATH option values. */
549 for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
550 if (*p == ':' || *p == '\0') {
551 if (t < p - 1) {
552 savech = *p;
553 *p = '\0';
554 len = snprintf(path,
555 sizeof(path), "%s/%s", t, name);
556 *p = savech;
557 if (!stat(path, sbp)) {
558 found = 1;
559 break;
562 t = p + 1;
563 if (*p == '\0')
564 break;
567 /* If we found it, build a new pathname and discard the old one. */
568 if (found) {
569 MALLOC_RET(sp, p, char *, len + 1);
570 memcpy(p, path, len + 1);
571 free(frp->name);
572 frp->name = p;
574 *existsp = found;
575 return (0);
579 * file_cinit --
580 * Set up the initial cursor position.
582 static void
583 file_cinit(SCR *sp)
585 GS *gp;
586 MARK m;
587 size_t len;
588 int nb;
589 CHAR_T *wp;
590 size_t wlen;
592 /* Set some basic defaults. */
593 sp->lno = 1;
594 sp->cno = 0;
597 * Historically, initial commands (the -c option) weren't executed
598 * until a file was loaded, e.g. "vi +10 nofile", followed by an
599 * :edit or :tag command, would execute the +10 on the file loaded
600 * by the subsequent command, (assuming that it existed). This
601 * applied as well to files loaded using the tag commands, and we
602 * follow that historic practice. Also, all initial commands were
603 * ex commands and were always executed on the last line of the file.
605 * Otherwise, if no initial command for this file:
606 * If in ex mode, move to the last line, first nonblank character.
607 * If the file has previously been edited, move to the last known
608 * position, and check it for validity.
609 * Otherwise, move to the first line, first nonblank.
611 * This gets called by the file init code, because we may be in a
612 * file of ex commands and we want to execute them from the right
613 * location in the file.
615 nb = 0;
616 gp = sp->gp;
617 if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
618 if (db_last(sp, &sp->lno))
619 return;
620 if (sp->lno == 0) {
621 sp->lno = 1;
622 sp->cno = 0;
624 CHAR2INT(sp, gp->c_option, strlen(gp->c_option) + 1,
625 wp, wlen);
626 if (ex_run_str(sp, "-c option", wp, wlen - 1, 1, 1))
627 return;
628 gp->c_option = NULL;
629 } else if (F_ISSET(sp, SC_EX)) {
630 if (db_last(sp, &sp->lno))
631 return;
632 if (sp->lno == 0) {
633 sp->lno = 1;
634 sp->cno = 0;
635 return;
637 nb = 1;
638 } else {
639 if (F_ISSET(sp->frp, FR_CURSORSET)) {
640 sp->lno = sp->frp->lno;
641 sp->cno = sp->frp->cno;
643 /* If returning to a file in vi, center the line. */
644 F_SET(sp, SC_SCR_CENTER);
645 } else {
646 if (O_ISSET(sp, O_COMMENT))
647 file_comment(sp);
648 else
649 sp->lno = 1;
650 nb = 1;
652 if (db_get(sp, sp->lno, 0, NULL, &len)) {
653 sp->lno = 1;
654 sp->cno = 0;
655 return;
657 if (!nb && sp->cno > len)
658 nb = 1;
660 if (nb) {
661 sp->cno = 0;
662 (void)nonblank(sp, sp->lno, &sp->cno);
666 * !!!
667 * The initial column is also the most attractive column.
669 sp->rcm = sp->cno;
672 * !!!
673 * Historically, vi initialized the absolute mark, but ex did not.
674 * Which meant, that if the first command in ex mode was "visual",
675 * or if an ex command was executed first (e.g. vi +10 file) vi was
676 * entered without the mark being initialized. For consistency, if
677 * the file isn't empty, we initialize it for everyone, believing
678 * that it can't hurt, and is generally useful. Not initializing it
679 * if the file is empty is historic practice, although it has always
680 * been possible to set (and use) marks in empty vi files.
682 m.lno = sp->lno;
683 m.cno = sp->cno;
684 (void)mark_set(sp, ABSMARK1, &m, 0);
688 * file_end --
689 * Stop editing a file.
691 * PUBLIC: int file_end __P((SCR *, EXF *, int));
694 file_end(SCR *sp, EXF *ep, int force)
696 FREF *frp;
699 * !!!
700 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
701 * (If argument ep is NULL, use sp->ep.)
703 * If multiply referenced, just decrement the count and return.
705 if (ep == NULL)
706 ep = sp->ep;
707 CIRCLEQ_REMOVE(&ep->scrq, sp, eq);
708 if (--ep->refcnt != 0)
709 return (0);
713 * Clean up the FREF structure.
715 * Save the cursor location.
717 * XXX
718 * It would be cleaner to do this somewhere else, but by the time
719 * ex or vi knows that we're changing files it's already happened.
721 frp = sp->frp;
722 frp->lno = sp->lno;
723 frp->cno = sp->cno;
724 F_SET(frp, FR_CURSORSET);
727 * We may no longer need the temporary backing file, so clean it
728 * up. We don't need the FREF structure either, if the file was
729 * never named, so lose it.
731 * !!!
732 * Re: FR_DONTDELETE, see the comment above in file_init().
734 if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
735 if (unlink(frp->tname))
736 msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
737 free(frp->tname);
738 frp->tname = NULL;
739 if (F_ISSET(frp, FR_TMPFILE)) {
740 CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
741 if (frp->name != NULL)
742 free(frp->name);
743 free(frp);
745 sp->frp = NULL;
749 * Clean up the EXF structure.
751 * Close the db structure.
753 if (ep->db->close != NULL) {
754 if ((sp->db_error = ep->db->close(ep->db, DB_NOSYNC)) != 0 &&
755 !force) {
756 msgq_str(sp, M_DBERR, frp->name, "241|%s: close");
757 CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq);
758 ++ep->refcnt;
759 return (1);
761 ep->db = NULL;
764 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
766 /* Stop logging. */
767 (void)log_end(sp, ep);
769 /* Free up any marks. */
770 (void)mark_end(sp, ep);
772 if (ep->env) {
773 DB_ENV *env;
775 ep->env->close(ep->env, 0);
776 ep->env = 0;
777 if ((sp->db_error = db_env_create(&env, 0)))
778 msgq(sp, M_DBERR, "env_create");
779 if ((sp->db_error = db_env_remove(env, ep->env_path, 0)))
780 msgq(sp, M_DBERR, "env->remove");
781 if (ep->env_path != NULL && rmdir(ep->env_path))
782 msgq_str(sp, M_SYSERR, ep->env_path, "242|%s: remove");
786 * Delete recovery files, close the open descriptor, free recovery
787 * memory. See recover.c for a description of the protocol.
789 * XXX
790 * Unlink backup file first, we can detect that the recovery file
791 * doesn't reference anything when the user tries to recover it.
792 * There's a race, here, obviously, but it's fairly small.
794 if (!F_ISSET(ep, F_RCV_NORM)) {
795 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
796 msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
797 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
798 msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
800 CIRCLEQ_REMOVE(&sp->gp->exfq, ep, q);
801 if (ep->fd != -1)
802 (void)close(ep->fd);
803 if (ep->fcntl_fd != -1)
804 (void)close(ep->fcntl_fd);
805 if (ep->rcv_fd != -1)
806 (void)close(ep->rcv_fd);
807 if (ep->env_path != NULL)
808 free(ep->env_path);
809 if (ep->rcv_path != NULL)
810 free(ep->rcv_path);
811 if (ep->rcv_mpath != NULL)
812 free(ep->rcv_mpath);
814 free(ep);
815 return (0);
819 * file_write --
820 * Write the file to disk. Historic vi had fairly convoluted
821 * semantics for whether or not writes would happen. That's
822 * why all the flags.
824 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
827 file_write(SCR *sp, MARK *fm, MARK *tm, char *name, int flags)
829 enum { NEWFILE, OLDFILE } mtype;
830 struct stat sb;
831 EXF *ep;
832 FILE *fp;
833 FREF *frp;
834 MARK from, to;
835 size_t len;
836 u_long nlno, nch;
837 int fd, nf, noname, oflags, rval;
838 char *p, *s, *t, buf[MAXPATHLEN + 64];
839 const char *msgstr;
841 ep = sp->ep;
842 frp = sp->frp;
845 * Writing '%', or naming the current file explicitly, has the
846 * same semantics as writing without a name.
848 if (name == NULL || !strcmp(name, frp->name)) {
849 noname = 1;
850 name = frp->name;
851 } else
852 noname = 0;
854 /* Can't write files marked read-only, unless forced. */
855 if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
856 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
857 "244|Read-only file, not written; use ! to override" :
858 "245|Read-only file, not written");
859 return (1);
862 /* If not forced, not appending, and "writeany" not set ... */
863 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
864 /* Don't overwrite anything but the original file. */
865 if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
866 !stat(name, &sb)) {
867 msgq_str(sp, M_ERR, name,
868 LF_ISSET(FS_POSSIBLE) ?
869 "246|%s exists, not written; use ! to override" :
870 "247|%s exists, not written");
871 return (1);
875 * Don't write part of any existing file. Only test for the
876 * original file, the previous test catches anything else.
878 if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
879 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
880 "248|Partial file, not written; use ! to override" :
881 "249|Partial file, not written");
882 return (1);
887 * Figure out if the file already exists -- if it doesn't, we display
888 * the "new file" message. The stat might not be necessary, but we
889 * just repeat it because it's easier than hacking the previous tests.
890 * The information is only used for the user message and modification
891 * time test, so we can ignore the obvious race condition.
893 * One final test. If we're not forcing or appending the current file,
894 * and we have a saved modification time, object if the file changed
895 * since we last edited or wrote it, and make them force it.
897 if (stat(name, &sb))
898 mtype = NEWFILE;
899 else {
900 if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
901 ((F_ISSET(ep, F_DEVSET) &&
902 (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
903 sb.st_mtime != ep->mtime)) {
904 msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
905 "250|%s: file modified more recently than this copy; use ! to override" :
906 "251|%s: file modified more recently than this copy");
907 return (1);
910 mtype = OLDFILE;
913 /* Set flags to create, write, and either append or truncate. */
914 oflags = O_CREAT | O_WRONLY |
915 (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
917 /* Backup the file if requested. */
918 if (!opts_empty(sp, O_BACKUP, 1) &&
919 file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
920 return (1);
922 /* Open the file. */
923 SIGBLOCK;
924 if ((fd = open(name, oflags,
925 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
926 msgq_str(sp, M_SYSERR, name, "%s");
927 SIGUNBLOCK;
928 return (1);
930 SIGUNBLOCK;
932 /* Try and get a lock. */
933 if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
934 msgq_str(sp, M_ERR, name,
935 "252|%s: write lock was unavailable");
937 #if __linux__
939 * XXX
940 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
941 * This bug is fixed in libc 4.6.x.
943 * This code works around this problem for libc 4.5.x users.
944 * Note that this code is harmless if you're using libc 4.6.x.
946 if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
947 msgq(sp, M_SYSERR, name);
948 return (1);
950 #endif
953 * Use stdio for buffering.
955 * XXX
956 * SVR4.2 requires the fdopen mode exactly match the original open
957 * mode, i.e. you have to open with "a" if appending.
959 if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
960 msgq_str(sp, M_SYSERR, name, "%s");
961 (void)close(fd);
962 return (1);
965 /* Build fake addresses, if necessary. */
966 if (fm == NULL) {
967 from.lno = 1;
968 from.cno = 0;
969 fm = &from;
970 if (db_last(sp, &to.lno))
971 return (1);
972 to.cno = 0;
973 tm = &to;
976 rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
979 * Save the new last modification time -- even if the write fails
980 * we re-init the time. That way the user can clean up the disk
981 * and rewrite without having to force it.
983 if (noname) {
984 if (stat(name, &sb))
985 time(&ep->mtime);
986 else {
987 F_SET(ep, F_DEVSET);
988 ep->mdev = sb.st_dev;
989 ep->minode = sb.st_ino;
991 ep->mtime = sb.st_mtime;
996 * If the write failed, complain loudly. ex_writefp() has already
997 * complained about the actual error, reinforce it if data was lost.
999 if (rval) {
1000 if (!LF_ISSET(FS_APPEND))
1001 msgq_str(sp, M_ERR, name,
1002 "254|%s: WARNING: FILE TRUNCATED");
1003 return (1);
1007 * Once we've actually written the file, it doesn't matter that the
1008 * file name was changed -- if it was, we've already whacked it.
1010 F_CLR(frp, FR_NAMECHANGE);
1013 * If wrote the entire file, and it wasn't by appending it to a file,
1014 * clear the modified bit. If the file was written to the original
1015 * file name and the file is a temporary, set the "no exit" bit. This
1016 * permits the user to write the file and use it in the context of the
1017 * filesystem, but still keeps them from discarding their changes by
1018 * exiting.
1020 if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
1021 F_CLR(ep, F_MODIFIED);
1022 if (F_ISSET(frp, FR_TMPFILE)) {
1023 if (noname)
1024 F_SET(frp, FR_TMPEXIT);
1025 else
1026 F_CLR(frp, FR_TMPEXIT);
1030 p = msg_print(sp, name, &nf);
1031 switch (mtype) {
1032 case NEWFILE:
1033 msgstr = msg_cat(sp,
1034 "256|%s: new file: %lu lines, %lu characters", NULL);
1035 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1036 break;
1037 case OLDFILE:
1038 msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
1039 "315|%s: appended: %lu lines, %lu characters" :
1040 "257|%s: %lu lines, %lu characters", NULL);
1041 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1042 break;
1043 default:
1044 abort();
1048 * There's a nasty problem with long path names. Cscope and tags files
1049 * can result in long paths and vi will request a continuation key from
1050 * the user. Unfortunately, the user has typed ahead, and chaos will
1051 * result. If we assume that the characters in the filenames only take
1052 * a single screen column each, we can trim the filename.
1054 s = buf;
1055 if (len >= sp->cols) {
1056 for (s = buf, t = buf + strlen(p); s < t &&
1057 (*s != '/' || len >= sp->cols - 3); ++s, --len);
1058 if (s == t)
1059 s = buf;
1060 else {
1061 *--s = '.'; /* Leading ellipses. */
1062 *--s = '.';
1063 *--s = '.';
1066 msgq(sp, M_INFO, s);
1067 if (nf)
1068 FREE_SPACE(sp, p, 0);
1069 return (0);
1073 * file_backup --
1074 * Backup the about-to-be-written file.
1076 * XXX
1077 * We do the backup by copying the entire file. It would be nice to do
1078 * a rename instead, but: (1) both files may not fit and we want to fail
1079 * before doing the rename; (2) the backup file may not be on the same
1080 * disk partition as the file being written; (3) there may be optional
1081 * file information (MACs, DACs, whatever) that we won't get right if we
1082 * recreate the file. So, let's not risk it.
1084 static int
1085 file_backup(SCR *sp, char *name, char *bname)
1087 struct dirent *dp;
1088 struct stat sb;
1089 DIR *dirp;
1090 EXCMD cmd;
1091 off_t off;
1092 size_t blen;
1093 int flags, maxnum, nr, num, nw, rfd, wfd, version;
1094 char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];
1095 CHAR_T *wp;
1096 size_t wlen;
1097 size_t nlen;
1098 char *d = NULL;
1100 rfd = wfd = -1;
1101 bp = estr = wfname = NULL;
1104 * Open the current file for reading. Do this first, so that
1105 * we don't exec a shell before the most likely failure point.
1106 * If it doesn't exist, it's okay, there's just nothing to back
1107 * up.
1109 errno = 0;
1110 if ((rfd = open(name, O_RDONLY, 0)) < 0) {
1111 if (errno == ENOENT)
1112 return (0);
1113 estr = name;
1114 goto err;
1118 * If the name starts with an 'N' character, add a version number
1119 * to the name. Strip the leading N from the string passed to the
1120 * expansion routines, for no particular reason. It would be nice
1121 * to permit users to put the version number anywhere in the backup
1122 * name, but there isn't a special character that we can use in the
1123 * name, and giving a new character a special meaning leads to ugly
1124 * hacks both here and in the supporting ex routines.
1126 * Shell and file name expand the option's value.
1128 ex_cinit(sp, &cmd, 0, 0, 0, 0, 0);
1129 if (bname[0] == 'N') {
1130 version = 1;
1131 ++bname;
1132 } else
1133 version = 0;
1134 CHAR2INT(sp, bname, strlen(bname) + 1, wp, wlen);
1135 if (argv_exp2(sp, &cmd, wp, wlen - 1))
1136 return (1);
1139 * 0 args: impossible.
1140 * 1 args: use it.
1141 * >1 args: object, too many args.
1143 if (cmd.argc != 1) {
1144 msgq_str(sp, M_ERR, bname,
1145 "258|%s expanded into too many file names");
1146 (void)close(rfd);
1147 return (1);
1151 * If appending a version number, read through the directory, looking
1152 * for file names that match the name followed by a number. Make all
1153 * of the other % characters in name literal, so the user doesn't get
1154 * surprised and sscanf doesn't drop core indirecting through pointers
1155 * that don't exist. If any such files are found, increment its number
1156 * by one.
1158 if (version) {
1159 GET_SPACE_GOTOC(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1160 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1161 p, nlen);
1162 d = strdup(p);
1163 p = d;
1164 for (t = bp, slash = NULL;
1165 p[0] != '\0'; *t++ = *p++)
1166 if (p[0] == '%') {
1167 if (p[1] != '%')
1168 *t++ = '%';
1169 } else if (p[0] == '/')
1170 slash = t;
1171 pct = t;
1172 *t++ = '%';
1173 *t++ = 'd';
1174 *t = '\0';
1176 if (slash == NULL) {
1177 dirp = opendir(".");
1178 p = bp;
1179 } else {
1180 *slash = '\0';
1181 dirp = opendir(bp);
1182 *slash = '/';
1183 p = slash + 1;
1185 if (dirp == NULL) {
1186 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1187 estr, nlen);
1188 goto err;
1191 for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1192 if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1193 maxnum = num;
1194 (void)closedir(dirp);
1196 /* Format the backup file name. */
1197 (void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1198 wfname = bp;
1199 } else {
1200 bp = NULL;
1201 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1202 wfname, nlen);
1205 /* Open the backup file, avoiding lurkers. */
1206 if (stat(wfname, &sb) == 0) {
1207 if (!S_ISREG(sb.st_mode)) {
1208 msgq_str(sp, M_ERR, bname,
1209 "259|%s: not a regular file");
1210 goto err;
1212 if (sb.st_uid != getuid()) {
1213 msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
1214 goto err;
1216 if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1217 msgq_str(sp, M_ERR, bname,
1218 "261|%s: accessible by a user other than the owner");
1219 goto err;
1221 flags = O_TRUNC;
1222 } else
1223 flags = O_CREAT | O_EXCL;
1224 if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
1225 estr = bname;
1226 goto err;
1229 /* Copy the file's current contents to its backup value. */
1230 while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1231 for (off = 0; nr != 0; nr -= nw, off += nw)
1232 if ((nw = write(wfd, buf + off, nr)) < 0) {
1233 estr = wfname;
1234 goto err;
1236 if (nr < 0) {
1237 estr = name;
1238 goto err;
1241 if (close(rfd)) {
1242 estr = name;
1243 goto err;
1245 if (close(wfd)) {
1246 estr = wfname;
1247 goto err;
1249 if (bp != NULL)
1250 FREE_SPACE(sp, bp, blen);
1251 return (0);
1253 alloc_err:
1254 err: if (rfd != -1)
1255 (void)close(rfd);
1256 if (wfd != -1) {
1257 (void)unlink(wfname);
1258 (void)close(wfd);
1260 if (estr)
1261 msgq_str(sp, M_SYSERR, estr, "%s");
1262 if (d != NULL)
1263 free(d);
1264 if (bp != NULL)
1265 FREE_SPACE(sp, bp, blen);
1266 return (1);
1270 * file_comment --
1271 * Skip the first comment.
1273 static void
1274 file_comment(SCR *sp)
1276 db_recno_t lno;
1277 size_t len;
1278 CHAR_T *p;
1280 for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1281 if (p == NULL)
1282 return;
1283 if (p[0] == '#') {
1284 F_SET(sp, SC_SCR_TOP);
1285 while (!db_get(sp, ++lno, 0, &p, &len))
1286 if (len < 1 || p[0] != '#') {
1287 sp->lno = lno;
1288 return;
1290 } else if (len > 1 && p[0] == '/' && p[1] == '*') {
1291 F_SET(sp, SC_SCR_TOP);
1292 do {
1293 for (; len > 1; --len, ++p)
1294 if (p[0] == '*' && p[1] == '/') {
1295 sp->lno = lno;
1296 return;
1298 } while (!db_get(sp, ++lno, 0, &p, &len));
1299 } else if (len > 1 && p[0] == '/' && p[1] == '/') {
1300 F_SET(sp, SC_SCR_TOP);
1301 while (!db_get(sp, ++lno, 0, &p, &len))
1302 if (len < 1 || p[0] != '/' || p[1] != '/') {
1303 sp->lno = lno;
1304 return;
1310 * file_m1 --
1311 * First modification check routine. The :next, :prev, :rewind, :tag,
1312 * :tagpush, :tagpop, ^^ modifications check.
1314 * PUBLIC: int file_m1 __P((SCR *, int, int));
1317 file_m1(SCR *sp, int force, int flags)
1319 EXF *ep;
1321 ep = sp->ep;
1323 /* If no file loaded, return no modifications. */
1324 if (ep == NULL)
1325 return (0);
1328 * If the file has been modified, we'll want to write it back or
1329 * fail. If autowrite is set, we'll write it back automatically,
1330 * unless force is also set. Otherwise, we fail unless forced or
1331 * there's another open screen on this file.
1333 if (F_ISSET(ep, F_MODIFIED)) {
1334 if (O_ISSET(sp, O_AUTOWRITE)) {
1335 if (!force && file_aw(sp, flags))
1336 return (1);
1337 } else if (ep->refcnt <= 1 && !force) {
1338 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1339 "262|File modified since last complete write; write or use ! to override" :
1340 "263|File modified since last complete write; write or use :edit! to override");
1341 return (1);
1345 return (file_m3(sp, force));
1349 * file_m2 --
1350 * Second modification check routine. The :edit, :quit, :recover
1351 * modifications check.
1353 * PUBLIC: int file_m2 __P((SCR *, int));
1356 file_m2(SCR *sp, int force)
1358 EXF *ep;
1360 ep = sp->ep;
1362 /* If no file loaded, return no modifications. */
1363 if (ep == NULL)
1364 return (0);
1367 * If the file has been modified, we'll want to fail, unless forced
1368 * or there's another open screen on this file.
1370 if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1371 msgq(sp, M_ERR,
1372 "264|File modified since last complete write; write or use ! to override");
1373 return (1);
1376 return (file_m3(sp, force));
1380 * file_m3 --
1381 * Third modification check routine.
1383 * PUBLIC: int file_m3 __P((SCR *, int));
1386 file_m3(SCR *sp, int force)
1388 EXF *ep;
1390 ep = sp->ep;
1392 /* If no file loaded, return no modifications. */
1393 if (ep == NULL)
1394 return (0);
1397 * Don't exit while in a temporary files if the file was ever modified.
1398 * The problem is that if the user does a ":wq", we write and quit,
1399 * unlinking the temporary file. Not what the user had in mind at all.
1400 * We permit writing to temporary files, so that user maps using file
1401 * system names work with temporary files.
1403 if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1404 msgq(sp, M_ERR,
1405 "265|File is a temporary; exit will discard modifications");
1406 return (1);
1408 return (0);
1412 * file_aw --
1413 * Autowrite routine. If modified, autowrite is set and the readonly bit
1414 * is not set, write the file. A routine so there's a place to put the
1415 * comment.
1417 * PUBLIC: int file_aw __P((SCR *, int));
1420 file_aw(SCR *sp, int flags)
1422 if (!F_ISSET(sp->ep, F_MODIFIED))
1423 return (0);
1424 if (!O_ISSET(sp, O_AUTOWRITE))
1425 return (0);
1428 * !!!
1429 * Historic 4BSD vi attempted to write the file if autowrite was set,
1430 * regardless of the writeability of the file (as defined by the file
1431 * readonly flag). System V changed this as some point, not attempting
1432 * autowrite if the file was readonly. This feels like a bug fix to
1433 * me (e.g. the principle of least surprise is violated if readonly is
1434 * set and vi writes the file), so I'm compatible with System V.
1436 if (O_ISSET(sp, O_READONLY)) {
1437 msgq(sp, M_INFO,
1438 "266|File readonly, modifications not auto-written");
1439 return (1);
1441 return (file_write(sp, NULL, NULL, NULL, flags));
1445 * set_alt_name --
1446 * Set the alternate pathname.
1448 * Set the alternate pathname. It's a routine because I wanted some place
1449 * to hang this comment. The alternate pathname (normally referenced using
1450 * the special character '#' during file expansion and in the vi ^^ command)
1451 * is set by almost all ex commands that take file names as arguments. The
1452 * rules go something like this:
1454 * 1: If any ex command takes a file name as an argument (except for the
1455 * :next command), the alternate pathname is set to that file name.
1456 * This excludes the command ":e" and ":w !command" as no file name
1457 * was specified. Note, historically, the :source command did not set
1458 * the alternate pathname. It does in nvi, for consistency.
1460 * 2: However, if any ex command sets the current pathname, e.g. the
1461 * ":e file" or ":rew" commands succeed, then the alternate pathname
1462 * is set to the previous file's current pathname, if it had one.
1463 * This includes the ":file" command and excludes the ":e" command.
1464 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1465 * pathname will be "foo", if it succeeds, the alternate pathname will
1466 * be the previous current pathname. The ":e" command will not set
1467 * the alternate or current pathnames regardless.
1469 * 3: However, if it's a read or write command with a file argument and
1470 * the current pathname has not yet been set, the file name becomes
1471 * the current pathname, and the alternate pathname is unchanged.
1473 * If the user edits a temporary file, there may be times when there is no
1474 * alternative file name. A name argument of NULL turns it off.
1476 * PUBLIC: void set_alt_name __P((SCR *, char *));
1478 void
1479 set_alt_name(SCR *sp, char *name)
1481 if (sp->alt_name != NULL)
1482 free(sp->alt_name);
1483 if (name == NULL)
1484 sp->alt_name = NULL;
1485 else if ((sp->alt_name = strdup(name)) == NULL)
1486 msgq(sp, M_SYSERR, NULL);
1490 * file_lock --
1491 * Get an exclusive lock on a file and set close-on-exec flag
1493 * XXX
1494 * The default locking is flock(2) style, not fcntl(2). The latter is
1495 * known to fail badly on some systems, and its only advantage is that
1496 * it occasionally works over NFS.
1498 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1499 * two-fold: you can't close any file descriptor associated with the file
1500 * without losing all of the locks, and you can't get an exclusive lock
1501 * unless you have the file open for writing. Someone ought to be shot,
1502 * but it's probably too late, they may already have reproduced. To get
1503 * around these problems, nvi opens the files for writing when it can and
1504 * acquires a second file descriptor when it can't. The recovery files
1505 * are examples of the former, they're always opened for writing. The DB
1506 * files can't be opened for writing because the semantics of DB are that
1507 * files opened for writing are flushed back to disk when the DB session
1508 * is ended. So, in that case we have to acquire an extra file descriptor.
1510 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1512 lockr_t
1513 file_lock(SCR *sp, char *name, int *fdp, int fd, int iswrite)
1515 fcntl(fd, F_SETFD, 1);
1517 if (!O_ISSET(sp, O_LOCKFILES))
1518 return (LOCK_SUCCESS);
1520 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1522 * !!!
1523 * We need to distinguish a lock not being available for the file
1524 * from the file system not supporting locking. Flock is documented
1525 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1526 * they are the former. There's no portable way to do this.
1528 errno = 0;
1529 return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
1530 #ifdef EWOULDBLOCK
1531 || errno == EWOULDBLOCK
1532 #endif
1533 ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
1534 #endif
1535 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1537 struct flock arg;
1538 int didopen, sverrno;
1540 arg.l_type = F_WRLCK;
1541 arg.l_whence = 0; /* SEEK_SET */
1542 arg.l_start = arg.l_len = 0;
1543 arg.l_pid = 0;
1546 * If the file descriptor isn't opened for writing, it must fail.
1547 * If we fail because we can't get a read/write file descriptor,
1548 * we return LOCK_SUCCESS, believing that the file is readonly
1549 * and that will be sufficient to warn the user.
1551 if (!iswrite) {
1552 if (name == NULL || fdp == NULL)
1553 return (LOCK_FAILED);
1554 if ((fd = open(name, O_RDWR, 0)) == -1)
1555 return (LOCK_SUCCESS);
1556 *fdp = fd;
1557 didopen = 1;
1560 errno = 0;
1561 if (!fcntl(fd, F_SETLK, &arg))
1562 return (LOCK_SUCCESS);
1563 if (didopen) {
1564 sverrno = errno;
1565 (void)close(fd);
1566 errno = sverrno;
1570 * !!!
1571 * We need to distinguish a lock not being available for the file
1572 * from the file system not supporting locking. Fcntl is documented
1573 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1574 * and assume they are the former. There's no portable way to do this.
1576 return (errno == EACCES || errno == EAGAIN
1577 #ifdef EWOULDBLOCK
1578 || errno == EWOULDBLOCK
1579 #endif
1580 ? LOCK_UNAVAIL : LOCK_FAILED);
1582 #endif
1583 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1584 return (LOCK_SUCCESS);
1585 #endif
1588 #ifdef USE_DB4_LOGGING
1589 #define VI_DB_INIT_LOG DB_INIT_LOG
1590 #else
1591 #define VI_DB_INIT_LOG 0
1592 #endif
1594 static int
1595 db_setup(SCR *sp, EXF *ep)
1597 char path[MAXPATHLEN];
1598 int fd;
1599 DB_ENV *env;
1601 (void)snprintf(path, sizeof(path), "%s/vi.XXXXXX", O_STR(sp, O_RECDIR));
1602 if ((fd = mkstemp(path)) == -1) {
1603 msgq(sp, M_SYSERR, "%s", path);
1604 goto err;
1606 (void)close(fd);
1607 (void)unlink(path);
1608 if (mkdir(path, S_IRWXU)) {
1609 msgq(sp, M_SYSERR, "%s", path);
1610 goto err;
1612 if (db_env_create(&env, 0)) {
1613 msgq(sp, M_ERR, "env_create");
1614 goto err;
1616 #ifdef USE_DB4_LOGGING
1617 if ((sp->db_error = vi_db_init_recover(env))) {
1618 msgq(sp, M_DBERR, "init_recover");
1619 goto err;
1621 if ((sp->db_error = __vi_init_recover(env))) {
1622 msgq(sp, M_DBERR, "init_recover");
1623 goto err;
1625 #endif
1626 if ((sp->db_error = db_env_open(env, path,
1627 DB_PRIVATE | DB_CREATE | DB_INIT_MPOOL | VI_DB_THREAD
1628 | VI_DB_INIT_LOG, 0)) != 0) {
1629 msgq(sp, M_DBERR, "env->open");
1630 goto err;
1633 if ((ep->env_path = strdup(path)) == NULL) {
1634 msgq(sp, M_SYSERR, NULL);
1635 (void)rmdir(path);
1636 goto err;
1638 ep->env = env;
1639 return 0;
1640 err:
1641 return 1;