Expand PMF_FN_* macros.
[netbsd-mini2440.git] / dist / nvi / common / exf.c
blobab1c24fedcc61152a768d3b8ba0f460417597a24
1 /* $NetBSD: exf.c,v 1.3 2008/12/09 18:26:20 christos Exp $ */
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.
9 * See the LICENSE file for redistribution information.
12 #include "config.h"
14 #ifndef lint
15 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";
16 #endif /* not lint */
18 #include <sys/param.h>
19 #include <sys/types.h> /* XXX: param.h may not have included types.h */
20 #include <sys/queue.h>
21 #include <sys/stat.h>
24 * We include <sys/file.h>, because the flock(2) and open(2) #defines
25 * were found there on historical systems. We also include <fcntl.h>
26 * because the open(2) #defines are found there on newer systems.
28 #include <sys/file.h>
30 #include <bitstring.h>
31 #include <dirent.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <limits.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <time.h>
41 #include "common.h"
42 #include "dbinternal.h"
44 static int file_backup __P((SCR *, const char *, const char *));
45 static void file_cinit __P((SCR *));
46 static void file_comment __P((SCR *));
47 static int file_spath __P((SCR *, FREF *, struct stat *, int *));
48 static int db_setup __P((SCR *sp, EXF *ep));
51 * file_add --
52 * Insert a file name into the FREF list, if it doesn't already
53 * appear in it.
55 * !!!
56 * The "if it doesn't already appear" changes vi's semantics slightly. If
57 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
58 * will reflect the line/column of the previous edit session. Historic nvi
59 * did not do this. The change is a logical extension of the change where
60 * vi now remembers the last location in any file that it has ever edited,
61 * not just the previously edited file.
63 * PUBLIC: FREF *file_add __P((SCR *, char *));
65 FREF *
66 file_add(SCR *sp, const char *name)
68 GS *gp;
69 FREF *frp, *tfrp;
72 * Return it if it already exists. Note that we test against the
73 * user's name, whatever that happens to be, including if it's a
74 * temporary file.
76 * If the user added a file but was unable to initialize it, there
77 * can be file list entries where the name field is NULL. Discard
78 * them the next time we see them.
80 gp = sp->gp;
81 if (name != NULL)
82 for (frp = gp->frefq.cqh_first;
83 frp != (FREF *)(void *)&gp->frefq; frp = frp->q.cqe_next) {
84 if (frp->name == NULL) {
85 tfrp = frp->q.cqe_next;
86 CIRCLEQ_REMOVE(&gp->frefq, frp, q);
87 if (frp->name != NULL)
88 free(frp->name);
89 free(frp);
90 frp = tfrp;
91 continue;
93 if (!strcmp(frp->name, name))
94 return (frp);
97 /* Allocate and initialize the FREF structure. */
98 CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
99 if (frp == NULL)
100 return (NULL);
103 * If no file name specified, or if the file name is a request
104 * for something temporary, file_init() will allocate the file
105 * name. Temporary files are always ignored.
107 if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
108 (frp->name = strdup(name)) == NULL) {
109 free(frp);
110 msgq(sp, M_SYSERR, NULL);
111 return (NULL);
114 /* Append into the chain of file names. */
115 CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);
117 return (frp);
121 * file_init --
122 * Start editing a file, based on the FREF structure. If successsful,
123 * let go of any previous file. Don't release the previous file until
124 * absolutely sure we have the new one.
126 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
129 file_init(SCR *sp, FREF *frp, char *rcv_name, int flags)
131 EXF *ep;
132 struct stat sb;
133 size_t psize;
134 int fd, exists, open_err, readonly, stolen;
135 char *oname = NULL, tname[MAXPATHLEN];
137 stolen = open_err = readonly = 0;
140 * If the file is a recovery file, let the recovery code handle it.
141 * Clear the FR_RECOVER flag first -- the recovery code does set up,
142 * and then calls us! If the recovery call fails, it's probably
143 * because the named file doesn't exist. So, move boldly forward,
144 * presuming that there's an error message the user will get to see.
146 if (F_ISSET(frp, FR_RECOVER)) {
147 F_CLR(frp, FR_RECOVER);
148 return (rcv_read(sp, frp));
152 * Required FRP initialization; the only flag we keep is the
153 * cursor information.
155 F_CLR(frp, ~FR_CURSORSET);
158 * Scan the user's path to find the file that we're going to
159 * try and open.
161 if (file_spath(sp, frp, &sb, &exists))
162 return (1);
165 * Check whether we already have this file opened in some
166 * other screen.
168 if (exists) {
169 EXF *exfp;
170 for (exfp = sp->gp->exfq.cqh_first;
171 exfp != (EXF *)&sp->gp->exfq; exfp = exfp->q.cqe_next) {
172 if (exfp->mdev == sb.st_dev &&
173 exfp->minode == sb.st_ino &&
174 (exfp != sp->ep || exfp->refcnt > 1)) {
175 ep = exfp;
176 goto postinit;
182 * Required EXF initialization:
183 * Flush the line caches.
184 * Default recover mail file fd to -1.
185 * Set initial EXF flag bits.
187 CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
188 CIRCLEQ_INIT(&ep->scrq);
189 sp->c_lno = ep->c_nlines = OOBLNO;
190 ep->fd = ep->rcv_fd = ep->fcntl_fd = -1;
191 F_SET(ep, F_FIRSTMODIFY);
194 * If no name or backing file, for whatever reason, create a backing
195 * temporary file, saving the temp file name so we can later unlink
196 * it. If the user never named this file, copy the temporary file name
197 * to the real name (we display that until the user renames it).
199 oname = frp->name;
200 if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
201 if (opts_empty(sp, O_TMP_DIRECTORY, 0))
202 goto err;
203 (void)snprintf(tname, sizeof(tname),
204 "%s/vi.XXXXXX", O_STR(sp, O_TMP_DIRECTORY));
205 if ((fd = mkstemp(tname)) == -1) {
206 msgq(sp, M_SYSERR,
207 "237|Unable to create temporary file");
208 goto err;
210 (void)close(fd);
212 if (frp->name == NULL)
213 F_SET(frp, FR_TMPFILE);
214 if ((frp->tname = strdup(tname)) == NULL ||
215 (frp->name == NULL &&
216 (frp->name = strdup(tname)) == NULL)) {
217 if (frp->tname != NULL) {
218 free(frp->tname);
220 msgq(sp, M_SYSERR, NULL);
221 (void)unlink(tname);
222 goto err;
224 oname = frp->tname;
225 psize = 1024;
226 if (!LF_ISSET(FS_OPENERR))
227 F_SET(frp, FR_NEWFILE);
229 time(&ep->mtime);
230 } else {
232 * XXX
233 * A seat of the pants calculation: try to keep the file in
234 * 15 pages or less. Don't use a page size larger than 10K
235 * (vi should have good locality) or smaller than 1K.
237 psize = ((sb.st_size / 15) + 1023) / 1024;
238 if (psize > 10)
239 psize = 10;
240 if (psize == 0)
241 psize = 1;
242 psize *= 1024;
244 F_SET(ep, F_DEVSET);
245 ep->mdev = sb.st_dev;
246 ep->minode = sb.st_ino;
248 ep->mtime = sb.st_mtime;
250 if (!S_ISREG(sb.st_mode))
251 msgq_str(sp, M_ERR, oname,
252 "238|Warning: %s is not a regular file");
255 /* Set up recovery. */
256 if (rcv_name == NULL) {
257 /* ep->rcv_path NULL if rcv_tmp fails */
258 rcv_tmp(sp, ep, frp->name);
259 } else {
260 if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
261 msgq(sp, M_SYSERR, NULL);
262 goto err;
264 F_SET(ep, F_MODIFIED);
267 if (db_setup(sp, ep))
268 goto err;
270 /* Open a db structure. */
271 if ((sp->db_error = db_create(&ep->db, 0, 0)) != 0) {
272 msgq(sp, M_DBERR, "db_create");
273 goto err;
276 ep->db->set_re_delim(ep->db, '\n'); /* Always set. */
277 ep->db->set_pagesize(ep->db, psize);
278 ep->db->set_flags(ep->db, DB_RENUMBER | DB_SNAPSHOT);
279 if (rcv_name == NULL)
280 ep->db->set_re_source(ep->db, oname);
283 * Don't let db use mmap when using fcntl for locking
285 #ifdef HAVE_LOCK_FCNTL
286 #define NOMMAPIFFCNTL DB_NOMMAP
287 #else
288 #define NOMMAPIFFCNTL 0
289 #endif
291 #define _DB_OPEN_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
293 if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO,
294 ((rcv_name == 0) ? DB_TRUNCATE : 0) | VI_DB_THREAD | NOMMAPIFFCNTL,
295 _DB_OPEN_MODE)) != 0) {
296 msgq_str(sp,
297 M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s");
299 * !!!
300 * Historically, vi permitted users to edit files that couldn't
301 * be read. This isn't useful for single files from a command
302 * line, but it's quite useful for "vi *.c", since you can skip
303 * past files that you can't read.
305 ep->db = NULL; /* Don't close it; it wasn't opened */
307 if (LF_ISSET(FS_OPENERR))
308 goto err;
310 open_err = 1;
311 goto oerr;
314 /* re_source is loaded into the database.
315 * Close it and reopen it in the environment.
317 if ((sp->db_error = ep->db->close(ep->db, 0))) {
318 msgq(sp, M_DBERR, "close");
319 goto err;
321 if ((sp->db_error = db_create(&ep->db, ep->env, 0)) != 0) {
322 msgq(sp, M_DBERR, "db_create 2");
323 goto err;
325 if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO,
326 VI_DB_THREAD | NOMMAPIFFCNTL, _DB_OPEN_MODE)) != 0) {
327 msgq_str(sp,
328 M_DBERR, ep->rcv_path, "%s");
329 goto err;
333 * Do the remaining things that can cause failure of the new file,
334 * mark and logging initialization.
336 if (mark_init(sp, ep) || log_init(sp, ep))
337 goto err;
339 postinit:
341 * Set the alternate file name to be the file we're discarding.
343 * !!!
344 * Temporary files can't become alternate files, so there's no file
345 * name. This matches historical practice, although it could only
346 * happen in historical vi as the result of the initial command, i.e.
347 * if vi was executed without a file name.
349 if (LF_ISSET(FS_SETALT))
350 set_alt_name(sp, sp->frp == NULL ||
351 F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
354 * Close the previous file; if that fails, close the new one and run
355 * for the border.
357 * !!!
358 * There's a nasty special case. If the user edits a temporary file,
359 * and then does an ":e! %", we need to re-initialize the backing
360 * file, but we can't change the name. (It's worse -- we're dealing
361 * with *names* here, we can't even detect that it happened.) Set a
362 * flag so that the file_end routine ignores the backing information
363 * of the old file if it happens to be the same as the new one.
365 * !!!
366 * Side-effect: after the call to file_end(), sp->frp may be NULL.
368 if (sp->ep != NULL) {
369 F_SET(frp, FR_DONTDELETE);
370 if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
371 (void)file_end(sp, ep, 1);
372 goto err;
374 sp->ep = NULL;
375 F_CLR(frp, FR_DONTDELETE);
379 * Lock the file; if it's a recovery file, it should already be
380 * locked. Note, we acquire the lock after the previous file
381 * has been ended, so that we don't get an "already locked" error
382 * for ":edit!".
384 * XXX
385 * While the user can't interrupt us between the open and here,
386 * there's a race between the dbopen() and the lock. Not much
387 * we can do about it.
389 * XXX
390 * We don't make a big deal of not being able to lock the file. As
391 * locking rarely works over NFS, and often fails if the file was
392 * mmap(2)'d, it's far too common to do anything like print an error
393 * message, let alone make the file readonly. At some future time,
394 * when locking is a little more reliable, this should change to be
395 * an error.
397 if (rcv_name == NULL && ep->refcnt == 0) {
398 if ((ep->fd = open(oname, O_RDWR)) == -1)
399 goto no_lock;
401 switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 1)) {
402 case LOCK_FAILED:
403 no_lock:
404 F_SET(frp, FR_UNLOCKED);
405 break;
406 case LOCK_UNAVAIL:
407 readonly = 1;
408 msgq_str(sp, M_INFO, oname,
409 "239|%s already locked, session is read-only");
410 break;
411 case LOCK_SUCCESS:
412 break;
417 * Historically, the readonly edit option was set per edit buffer in
418 * vi, unless the -R command-line option was specified or the program
419 * was executed as "view". (Well, to be truthful, if the letter 'w'
420 * occurred anywhere in the program name, but let's not get into that.)
421 * So, the persistant readonly state has to be stored in the screen
422 * structure, and the edit option value toggles with the contents of
423 * the edit buffer. If the persistant readonly flag is set, set the
424 * readonly edit option.
426 * Otherwise, try and figure out if a file is readonly. This is a
427 * dangerous thing to do. The kernel is the only arbiter of whether
428 * or not a file is writeable, and the best that a user program can
429 * do is guess. Obvious loopholes are files that are on a file system
430 * mounted readonly (access catches this one on a few systems), or
431 * alternate protection mechanisms, ACL's for example, that we can't
432 * portably check. Lots of fun, and only here because users whined.
434 * !!!
435 * Historic vi displayed the readonly message if none of the file
436 * write bits were set, or if an an access(2) call on the path
437 * failed. This seems reasonable. If the file is mode 444, root
438 * users may want to know that the owner of the file did not expect
439 * it to be written.
441 * Historic vi set the readonly bit if no write bits were set for
442 * a file, even if the access call would have succeeded. This makes
443 * the superuser force the write even when vi expects that it will
444 * succeed. I'm less supportive of this semantic, but it's historic
445 * practice and the conservative approach to vi'ing files as root.
447 * It would be nice if there was some way to update this when the user
448 * does a "^Z; chmod ...". The problem is that we'd first have to
449 * distinguish between readonly bits set because of file permissions
450 * and those set for other reasons. That's not too hard, but deciding
451 * when to reevaluate the permissions is trickier. An alternative
452 * might be to turn off the readonly bit if the user forces a write
453 * and it succeeds.
455 * XXX
456 * Access(2) doesn't consider the effective uid/gid values. This
457 * probably isn't a problem for vi when it's running standalone.
459 if (readonly || F_ISSET(sp, SC_READONLY) ||
460 (!F_ISSET(frp, FR_NEWFILE) &&
461 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
462 access(frp->name, W_OK))))
463 O_SET(sp, O_READONLY);
464 else
465 O_CLR(sp, O_READONLY);
467 /* Switch... */
468 ++ep->refcnt;
469 CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq);
470 sp->ep = ep;
471 sp->frp = frp;
473 /* Set the initial cursor position, queue initial command. */
474 file_cinit(sp);
476 /* Report conversion errors again. */
477 F_CLR(sp, SC_CONV_ERROR);
479 /* Redraw the screen from scratch, schedule a welcome message. */
480 F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);
482 if (frp->lno == OOBLNO)
483 F_SET(sp, SC_SCR_TOP);
485 /* Append into the chain of file structures. */
486 if (ep->refcnt == 1)
487 CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q);
489 return (0);
491 err: if (frp->name != NULL) {
492 free(frp->name);
493 frp->name = NULL;
495 if (frp->tname != NULL) {
496 (void)unlink(frp->tname);
497 free(frp->tname);
498 frp->tname = NULL;
501 oerr: if (F_ISSET(ep, F_RCV_ON))
502 (void)unlink(ep->rcv_path);
503 if (ep->rcv_path != NULL) {
504 free(ep->rcv_path);
505 ep->rcv_path = NULL;
507 if (ep->db != NULL) {
508 (void)ep->db->close(ep->db, DB_NOSYNC);
509 ep->db = NULL;
511 free(ep);
513 return (open_err && !LF_ISSET(FS_OPENERR) ?
514 file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
518 * file_spath --
519 * Scan the user's path to find the file that we're going to
520 * try and open.
522 static int
523 file_spath(SCR *sp, FREF *frp, struct stat *sbp, int *existsp)
525 size_t len;
526 int found;
527 char *name, path[MAXPATHLEN];
528 const char *p, *t;
531 * If the name is NULL or an explicit reference (i.e., the first
532 * component is . or ..) ignore the O_PATH option.
534 name = frp->name;
535 if (name == NULL) {
536 *existsp = 0;
537 return (0);
539 if (name[0] == '/' || (name[0] == '.' &&
540 (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
541 *existsp = !stat(name, sbp);
542 return (0);
545 /* Try . */
546 if (!stat(name, sbp)) {
547 *existsp = 1;
548 return (0);
551 /* Try the O_PATH option values. */
552 for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
553 if (*p == ':' || *p == '\0') {
554 if (t < p - 1) {
555 len = snprintf(path, sizeof(path), "%.*s/%s",
556 (int)(p - t), t, name);
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 char *q;
570 MALLOC_RET(sp, q, char *, len + 1);
571 memcpy(q, path, len + 1);
572 free(frp->name);
573 frp->name = q;
575 *existsp = found;
576 return (0);
580 * file_cinit --
581 * Set up the initial cursor position.
583 static void
584 file_cinit(SCR *sp)
586 GS *gp;
587 MARK m;
588 size_t len;
589 int nb;
590 const CHAR_T *wp;
591 size_t wlen;
593 /* Set some basic defaults. */
594 sp->lno = 1;
595 sp->cno = 0;
598 * Historically, initial commands (the -c option) weren't executed
599 * until a file was loaded, e.g. "vi +10 nofile", followed by an
600 * :edit or :tag command, would execute the +10 on the file loaded
601 * by the subsequent command, (assuming that it existed). This
602 * applied as well to files loaded using the tag commands, and we
603 * follow that historic practice. Also, all initial commands were
604 * ex commands and were always executed on the last line of the file.
606 * Otherwise, if no initial command for this file:
607 * If in ex mode, move to the last line, first nonblank character.
608 * If the file has previously been edited, move to the last known
609 * position, and check it for validity.
610 * Otherwise, move to the first line, first nonblank.
612 * This gets called by the file init code, because we may be in a
613 * file of ex commands and we want to execute them from the right
614 * location in the file.
616 nb = 0;
617 gp = sp->gp;
618 if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
619 if (db_last(sp, &sp->lno))
620 return;
621 if (sp->lno == 0) {
622 sp->lno = 1;
623 sp->cno = 0;
625 CHAR2INT(sp, gp->c_option, strlen(gp->c_option) + 1,
626 wp, wlen);
627 if (ex_run_str(sp, "-c option", wp, wlen - 1, 1, 1))
628 return;
629 gp->c_option = NULL;
630 } else if (F_ISSET(sp, SC_EX)) {
631 if (db_last(sp, &sp->lno))
632 return;
633 if (sp->lno == 0) {
634 sp->lno = 1;
635 sp->cno = 0;
636 return;
638 nb = 1;
639 } else {
640 if (F_ISSET(sp->frp, FR_CURSORSET)) {
641 sp->lno = sp->frp->lno;
642 sp->cno = sp->frp->cno;
644 /* If returning to a file in vi, center the line. */
645 F_SET(sp, SC_SCR_CENTER);
646 } else {
647 if (O_ISSET(sp, O_COMMENT))
648 file_comment(sp);
649 else
650 sp->lno = 1;
651 nb = 1;
653 if (db_get(sp, sp->lno, 0, NULL, &len)) {
654 sp->lno = 1;
655 sp->cno = 0;
656 return;
658 if (!nb && sp->cno > len)
659 nb = 1;
661 if (nb) {
662 sp->cno = 0;
663 (void)nonblank(sp, sp->lno, &sp->cno);
667 * !!!
668 * The initial column is also the most attractive column.
670 sp->rcm = sp->cno;
673 * !!!
674 * Historically, vi initialized the absolute mark, but ex did not.
675 * Which meant, that if the first command in ex mode was "visual",
676 * or if an ex command was executed first (e.g. vi +10 file) vi was
677 * entered without the mark being initialized. For consistency, if
678 * the file isn't empty, we initialize it for everyone, believing
679 * that it can't hurt, and is generally useful. Not initializing it
680 * if the file is empty is historic practice, although it has always
681 * been possible to set (and use) marks in empty vi files.
683 m.lno = sp->lno;
684 m.cno = sp->cno;
685 (void)mark_set(sp, ABSMARK1, &m, 0);
689 * file_end --
690 * Stop editing a file.
692 * PUBLIC: int file_end __P((SCR *, EXF *, int));
695 file_end(SCR *sp, EXF *ep, int force)
697 FREF *frp;
700 * !!!
701 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
702 * (If argument ep is NULL, use sp->ep.)
704 * If multiply referenced, just decrement the count and return.
706 if (ep == NULL)
707 ep = sp->ep;
708 CIRCLEQ_REMOVE(&ep->scrq, sp, eq);
709 if (--ep->refcnt != 0)
710 return (0);
714 * Clean up the FREF structure.
716 * Save the cursor location.
718 * XXX
719 * It would be cleaner to do this somewhere else, but by the time
720 * ex or vi knows that we're changing files it's already happened.
722 frp = sp->frp;
723 frp->lno = sp->lno;
724 frp->cno = sp->cno;
725 F_SET(frp, FR_CURSORSET);
728 * We may no longer need the temporary backing file, so clean it
729 * up. We don't need the FREF structure either, if the file was
730 * never named, so lose it.
732 * !!!
733 * Re: FR_DONTDELETE, see the comment above in file_init().
735 if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
736 if (unlink(frp->tname))
737 msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
738 free(frp->tname);
739 frp->tname = NULL;
740 if (F_ISSET(frp, FR_TMPFILE)) {
741 CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
742 if (frp->name != NULL)
743 free(frp->name);
744 free(frp);
746 sp->frp = NULL;
750 * Clean up the EXF structure.
752 * Close the db structure.
754 if (ep->db->close != NULL) {
755 if ((sp->db_error = ep->db->close(ep->db, DB_NOSYNC)) != 0 &&
756 !force) {
757 msgq_str(sp, M_DBERR, frp->name, "241|%s: close");
758 CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq);
759 ++ep->refcnt;
760 return (1);
762 ep->db = NULL;
765 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
767 /* Stop logging. */
768 (void)log_end(sp, ep);
770 /* Free up any marks. */
771 (void)mark_end(sp, ep);
773 if (ep->env) {
774 DB_ENV *env;
776 ep->env->close(ep->env, 0);
777 ep->env = 0;
778 if ((sp->db_error = db_env_create(&env, 0)))
779 msgq(sp, M_DBERR, "env_create");
780 if ((sp->db_error = db_env_remove(env, ep->env_path, 0)))
781 msgq(sp, M_DBERR, "env->remove");
782 if (ep->env_path != NULL && rmdir(ep->env_path))
783 msgq_str(sp, M_SYSERR, ep->env_path, "242|%s: remove");
787 * Delete recovery files, close the open descriptor, free recovery
788 * memory. See recover.c for a description of the protocol.
790 * XXX
791 * Unlink backup file first, we can detect that the recovery file
792 * doesn't reference anything when the user tries to recover it.
793 * There's a race, here, obviously, but it's fairly small.
795 if (!F_ISSET(ep, F_RCV_NORM)) {
796 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
797 msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
798 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
799 msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
801 CIRCLEQ_REMOVE(&sp->gp->exfq, ep, q);
802 if (ep->fd != -1)
803 (void)close(ep->fd);
804 if (ep->fcntl_fd != -1)
805 (void)close(ep->fcntl_fd);
806 if (ep->rcv_fd != -1)
807 (void)close(ep->rcv_fd);
808 if (ep->env_path != NULL)
809 free(ep->env_path);
810 if (ep->rcv_path != NULL)
811 free(ep->rcv_path);
812 if (ep->rcv_mpath != NULL)
813 free(ep->rcv_mpath);
815 free(ep);
816 return (0);
820 * file_write --
821 * Write the file to disk. Historic vi had fairly convoluted
822 * semantics for whether or not writes would happen. That's
823 * why all the flags.
825 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
828 file_write(SCR *sp, MARK *fm, MARK *tm, char *name, int flags)
830 enum { NEWFILE, OLDFILE } mtype;
831 struct stat sb;
832 EXF *ep;
833 FILE *fp;
834 FREF *frp;
835 MARK from, to;
836 size_t len;
837 u_long nlno, nch;
838 int fd, nf, noname, oflags, rval;
839 char *p, *s, *t, buf[MAXPATHLEN + 64];
840 const char *msgstr;
842 ep = sp->ep;
843 frp = sp->frp;
846 * Writing '%', or naming the current file explicitly, has the
847 * same semantics as writing without a name.
849 if (name == NULL || !strcmp(name, frp->name)) {
850 noname = 1;
851 name = frp->name;
852 } else
853 noname = 0;
855 /* Can't write files marked read-only, unless forced. */
856 if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
857 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
858 "244|Read-only file, not written; use ! to override" :
859 "245|Read-only file, not written");
860 return (1);
863 /* If not forced, not appending, and "writeany" not set ... */
864 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
865 /* Don't overwrite anything but the original file. */
866 if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
867 !stat(name, &sb)) {
868 msgq_str(sp, M_ERR, name,
869 LF_ISSET(FS_POSSIBLE) ?
870 "246|%s exists, not written; use ! to override" :
871 "247|%s exists, not written");
872 return (1);
876 * Don't write part of any existing file. Only test for the
877 * original file, the previous test catches anything else.
879 if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
880 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
881 "248|Partial file, not written; use ! to override" :
882 "249|Partial file, not written");
883 return (1);
888 * Figure out if the file already exists -- if it doesn't, we display
889 * the "new file" message. The stat might not be necessary, but we
890 * just repeat it because it's easier than hacking the previous tests.
891 * The information is only used for the user message and modification
892 * time test, so we can ignore the obvious race condition.
894 * One final test. If we're not forcing or appending the current file,
895 * and we have a saved modification time, object if the file changed
896 * since we last edited or wrote it, and make them force it.
898 if (stat(name, &sb))
899 mtype = NEWFILE;
900 else {
901 if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
902 ((F_ISSET(ep, F_DEVSET) &&
903 (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
904 sb.st_mtime != ep->mtime)) {
905 msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
906 "250|%s: file modified more recently than this copy; use ! to override" :
907 "251|%s: file modified more recently than this copy");
908 return (1);
911 mtype = OLDFILE;
914 /* Set flags to create, write, and either append or truncate. */
915 oflags = O_CREAT | O_WRONLY |
916 (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
918 /* Backup the file if requested. */
919 if (!opts_empty(sp, O_BACKUP, 1) &&
920 file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
921 return (1);
923 /* Open the file. */
924 SIGBLOCK;
925 if ((fd = open(name, oflags,
926 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
927 msgq_str(sp, M_SYSERR, name, "%s");
928 SIGUNBLOCK;
929 return (1);
931 SIGUNBLOCK;
933 /* Try and get a lock. */
934 if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
935 msgq_str(sp, M_ERR, name,
936 "252|%s: write lock was unavailable");
938 #if __linux__
940 * XXX
941 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
942 * This bug is fixed in libc 4.6.x.
944 * This code works around this problem for libc 4.5.x users.
945 * Note that this code is harmless if you're using libc 4.6.x.
947 if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
948 msgq(sp, M_SYSERR, "%s", name);
949 return (1);
951 #endif
954 * Use stdio for buffering.
956 * XXX
957 * SVR4.2 requires the fdopen mode exactly match the original open
958 * mode, i.e. you have to open with "a" if appending.
960 if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
961 msgq_str(sp, M_SYSERR, name, "%s");
962 (void)close(fd);
963 return (1);
966 /* Build fake addresses, if necessary. */
967 if (fm == NULL) {
968 from.lno = 1;
969 from.cno = 0;
970 fm = &from;
971 if (db_last(sp, &to.lno))
972 return (1);
973 to.cno = 0;
974 tm = &to;
977 rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
980 * Save the new last modification time -- even if the write fails
981 * we re-init the time. That way the user can clean up the disk
982 * and rewrite without having to force it.
984 if (noname) {
985 if (stat(name, &sb))
986 time(&ep->mtime);
987 else {
988 F_SET(ep, F_DEVSET);
989 ep->mdev = sb.st_dev;
990 ep->minode = sb.st_ino;
992 ep->mtime = sb.st_mtime;
997 * If the write failed, complain loudly. ex_writefp() has already
998 * complained about the actual error, reinforce it if data was lost.
1000 if (rval) {
1001 if (!LF_ISSET(FS_APPEND))
1002 msgq_str(sp, M_ERR, name,
1003 "254|%s: WARNING: FILE TRUNCATED");
1004 return (1);
1008 * Once we've actually written the file, it doesn't matter that the
1009 * file name was changed -- if it was, we've already whacked it.
1011 F_CLR(frp, FR_NAMECHANGE);
1014 * If wrote the entire file, and it wasn't by appending it to a file,
1015 * clear the modified bit. If the file was written to the original
1016 * file name and the file is a temporary, set the "no exit" bit. This
1017 * permits the user to write the file and use it in the context of the
1018 * filesystem, but still keeps them from discarding their changes by
1019 * exiting.
1021 if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
1022 F_CLR(ep, F_MODIFIED);
1023 if (F_ISSET(frp, FR_TMPFILE)) {
1024 if (noname)
1025 F_SET(frp, FR_TMPEXIT);
1026 else
1027 F_CLR(frp, FR_TMPEXIT);
1031 p = msg_print(sp, name, &nf);
1032 switch (mtype) {
1033 case NEWFILE:
1034 msgstr = msg_cat(sp,
1035 "256|%s: new file: %lu lines, %lu characters", NULL);
1036 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1037 break;
1038 case OLDFILE:
1039 msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
1040 "315|%s: appended: %lu lines, %lu characters" :
1041 "257|%s: %lu lines, %lu characters", NULL);
1042 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1043 break;
1044 default:
1045 abort();
1049 * There's a nasty problem with long path names. Cscope and tags files
1050 * can result in long paths and vi will request a continuation key from
1051 * the user. Unfortunately, the user has typed ahead, and chaos will
1052 * result. If we assume that the characters in the filenames only take
1053 * a single screen column each, we can trim the filename.
1055 s = buf;
1056 if (len >= sp->cols) {
1057 for (s = buf, t = buf + strlen(p); s < t &&
1058 (*s != '/' || len >= sp->cols - 3); ++s, --len);
1059 if (s == t)
1060 s = buf;
1061 else {
1062 *--s = '.'; /* Leading ellipses. */
1063 *--s = '.';
1064 *--s = '.';
1067 msgq(sp, M_INFO, "%s", s);
1068 if (nf)
1069 FREE_SPACE(sp, p, 0);
1070 return (0);
1074 * file_backup --
1075 * Backup the about-to-be-written file.
1077 * XXX
1078 * We do the backup by copying the entire file. It would be nice to do
1079 * a rename instead, but: (1) both files may not fit and we want to fail
1080 * before doing the rename; (2) the backup file may not be on the same
1081 * disk partition as the file being written; (3) there may be optional
1082 * file information (MACs, DACs, whatever) that we won't get right if we
1083 * recreate the file. So, let's not risk it.
1085 static int
1086 file_backup(SCR *sp, const char *name, const char *bname)
1088 struct dirent *dp;
1089 struct stat sb;
1090 DIR *dirp;
1091 EXCMD cmd;
1092 off_t off;
1093 size_t blen;
1094 int flags, maxnum, nr, num, nw, rfd, wfd, version;
1095 char *bp, *pct, *slash, *t, buf[8192];
1096 const char *p, *estr, *wfname;
1097 const CHAR_T *wp;
1098 size_t wlen;
1099 size_t nlen;
1100 char *d = NULL;
1102 rfd = wfd = -1;
1103 estr = wfname = NULL;
1104 bp = NULL;
1107 * Open the current file for reading. Do this first, so that
1108 * we don't exec a shell before the most likely failure point.
1109 * If it doesn't exist, it's okay, there's just nothing to back
1110 * up.
1112 errno = 0;
1113 if ((rfd = open(name, O_RDONLY, 0)) < 0) {
1114 if (errno == ENOENT)
1115 return (0);
1116 estr = name;
1117 goto err;
1121 * If the name starts with an 'N' character, add a version number
1122 * to the name. Strip the leading N from the string passed to the
1123 * expansion routines, for no particular reason. It would be nice
1124 * to permit users to put the version number anywhere in the backup
1125 * name, but there isn't a special character that we can use in the
1126 * name, and giving a new character a special meaning leads to ugly
1127 * hacks both here and in the supporting ex routines.
1129 * Shell and file name expand the option's value.
1131 ex_cinit(sp, &cmd, 0, 0, 0, 0, 0);
1132 if (bname[0] == 'N') {
1133 version = 1;
1134 ++bname;
1135 } else
1136 version = 0;
1137 CHAR2INT(sp, bname, strlen(bname) + 1, wp, wlen);
1138 if (argv_exp2(sp, &cmd, wp, wlen - 1))
1139 return (1);
1142 * 0 args: impossible.
1143 * 1 args: use it.
1144 * >1 args: object, too many args.
1146 if (cmd.argc != 1) {
1147 msgq_str(sp, M_ERR, bname,
1148 "258|%s expanded into too many file names");
1149 (void)close(rfd);
1150 return (1);
1154 * If appending a version number, read through the directory, looking
1155 * for file names that match the name followed by a number. Make all
1156 * of the other % characters in name literal, so the user doesn't get
1157 * surprised and sscanf doesn't drop core indirecting through pointers
1158 * that don't exist. If any such files are found, increment its number
1159 * by one.
1161 if (version) {
1162 GET_SPACE_GOTOC(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1163 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1164 p, nlen);
1165 d = strdup(p);
1166 p = d;
1167 for (t = bp, slash = NULL;
1168 p[0] != '\0'; *t++ = *p++)
1169 if (p[0] == '%') {
1170 if (p[1] != '%')
1171 *t++ = '%';
1172 } else if (p[0] == '/')
1173 slash = t;
1174 pct = t;
1175 *t++ = '%';
1176 *t++ = 'd';
1177 *t = '\0';
1179 if (slash == NULL) {
1180 dirp = opendir(".");
1181 p = bp;
1182 } else {
1183 *slash = '\0';
1184 dirp = opendir(bp);
1185 *slash = '/';
1186 p = slash + 1;
1188 if (dirp == NULL) {
1189 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1190 estr, nlen);
1191 goto err;
1194 for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1195 if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1196 maxnum = num;
1197 (void)closedir(dirp);
1199 /* Format the backup file name. */
1200 (void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1201 wfname = bp;
1202 } else {
1203 bp = NULL;
1204 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1205 wfname, nlen);
1208 /* Open the backup file, avoiding lurkers. */
1209 if (stat(wfname, &sb) == 0) {
1210 if (!S_ISREG(sb.st_mode)) {
1211 msgq_str(sp, M_ERR, bname,
1212 "259|%s: not a regular file");
1213 goto err;
1215 if (sb.st_uid != getuid()) {
1216 msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
1217 goto err;
1219 if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1220 msgq_str(sp, M_ERR, bname,
1221 "261|%s: accessible by a user other than the owner");
1222 goto err;
1224 flags = O_TRUNC;
1225 } else
1226 flags = O_CREAT | O_EXCL;
1227 if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
1228 estr = bname;
1229 goto err;
1232 /* Copy the file's current contents to its backup value. */
1233 while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1234 for (off = 0; nr != 0; nr -= nw, off += nw)
1235 if ((nw = write(wfd, buf + off, nr)) < 0) {
1236 estr = wfname;
1237 goto err;
1239 if (nr < 0) {
1240 estr = name;
1241 goto err;
1244 if (close(rfd)) {
1245 estr = name;
1246 goto err;
1248 if (close(wfd)) {
1249 estr = wfname;
1250 goto err;
1252 if (bp != NULL)
1253 FREE_SPACE(sp, bp, blen);
1254 return (0);
1256 alloc_err:
1257 err: if (rfd != -1)
1258 (void)close(rfd);
1259 if (wfd != -1) {
1260 (void)unlink(wfname);
1261 (void)close(wfd);
1263 if (estr)
1264 msgq_str(sp, M_SYSERR, estr, "%s");
1265 if (d != NULL)
1266 free(d);
1267 if (bp != NULL)
1268 FREE_SPACE(sp, bp, blen);
1269 return (1);
1273 * file_comment --
1274 * Skip the first comment.
1276 static void
1277 file_comment(SCR *sp)
1279 db_recno_t lno;
1280 size_t len;
1281 CHAR_T *p;
1283 for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1284 if (p == NULL)
1285 return;
1286 if (p[0] == '#') {
1287 F_SET(sp, SC_SCR_TOP);
1288 while (!db_get(sp, ++lno, 0, &p, &len))
1289 if (len < 1 || p[0] != '#') {
1290 sp->lno = lno;
1291 return;
1293 } else if (len > 1 && p[0] == '/' && p[1] == '*') {
1294 F_SET(sp, SC_SCR_TOP);
1295 do {
1296 for (; len > 1; --len, ++p)
1297 if (p[0] == '*' && p[1] == '/') {
1298 sp->lno = lno;
1299 return;
1301 } while (!db_get(sp, ++lno, 0, &p, &len));
1302 } else if (len > 1 && p[0] == '/' && p[1] == '/') {
1303 F_SET(sp, SC_SCR_TOP);
1304 while (!db_get(sp, ++lno, 0, &p, &len))
1305 if (len < 1 || p[0] != '/' || p[1] != '/') {
1306 sp->lno = lno;
1307 return;
1313 * file_m1 --
1314 * First modification check routine. The :next, :prev, :rewind, :tag,
1315 * :tagpush, :tagpop, ^^ modifications check.
1317 * PUBLIC: int file_m1 __P((SCR *, int, int));
1320 file_m1(SCR *sp, int force, int flags)
1322 EXF *ep;
1324 ep = sp->ep;
1326 /* If no file loaded, return no modifications. */
1327 if (ep == NULL)
1328 return (0);
1331 * If the file has been modified, we'll want to write it back or
1332 * fail. If autowrite is set, we'll write it back automatically,
1333 * unless force is also set. Otherwise, we fail unless forced or
1334 * there's another open screen on this file.
1336 if (F_ISSET(ep, F_MODIFIED)) {
1337 if (O_ISSET(sp, O_AUTOWRITE)) {
1338 if (!force && file_aw(sp, flags))
1339 return (1);
1340 } else if (ep->refcnt <= 1 && !force) {
1341 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1342 "262|File modified since last complete write; write or use ! to override" :
1343 "263|File modified since last complete write; write or use :edit! to override");
1344 return (1);
1348 return (file_m3(sp, force));
1352 * file_m2 --
1353 * Second modification check routine. The :edit, :quit, :recover
1354 * modifications check.
1356 * PUBLIC: int file_m2 __P((SCR *, int));
1359 file_m2(SCR *sp, int force)
1361 EXF *ep;
1363 ep = sp->ep;
1365 /* If no file loaded, return no modifications. */
1366 if (ep == NULL)
1367 return (0);
1370 * If the file has been modified, we'll want to fail, unless forced
1371 * or there's another open screen on this file.
1373 if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1374 msgq(sp, M_ERR,
1375 "264|File modified since last complete write; write or use ! to override");
1376 return (1);
1379 return (file_m3(sp, force));
1383 * file_m3 --
1384 * Third modification check routine.
1386 * PUBLIC: int file_m3 __P((SCR *, int));
1389 file_m3(SCR *sp, int force)
1391 EXF *ep;
1393 ep = sp->ep;
1395 /* If no file loaded, return no modifications. */
1396 if (ep == NULL)
1397 return (0);
1400 * Don't exit while in a temporary files if the file was ever modified.
1401 * The problem is that if the user does a ":wq", we write and quit,
1402 * unlinking the temporary file. Not what the user had in mind at all.
1403 * We permit writing to temporary files, so that user maps using file
1404 * system names work with temporary files.
1406 if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1407 msgq(sp, M_ERR,
1408 "265|File is a temporary; exit will discard modifications");
1409 return (1);
1411 return (0);
1415 * file_aw --
1416 * Autowrite routine. If modified, autowrite is set and the readonly bit
1417 * is not set, write the file. A routine so there's a place to put the
1418 * comment.
1420 * PUBLIC: int file_aw __P((SCR *, int));
1423 file_aw(SCR *sp, int flags)
1425 if (!F_ISSET(sp->ep, F_MODIFIED))
1426 return (0);
1427 if (!O_ISSET(sp, O_AUTOWRITE))
1428 return (0);
1431 * !!!
1432 * Historic 4BSD vi attempted to write the file if autowrite was set,
1433 * regardless of the writeability of the file (as defined by the file
1434 * readonly flag). System V changed this as some point, not attempting
1435 * autowrite if the file was readonly. This feels like a bug fix to
1436 * me (e.g. the principle of least surprise is violated if readonly is
1437 * set and vi writes the file), so I'm compatible with System V.
1439 if (O_ISSET(sp, O_READONLY)) {
1440 msgq(sp, M_INFO,
1441 "266|File readonly, modifications not auto-written");
1442 return (1);
1444 return (file_write(sp, NULL, NULL, NULL, flags));
1448 * set_alt_name --
1449 * Set the alternate pathname.
1451 * Set the alternate pathname. It's a routine because I wanted some place
1452 * to hang this comment. The alternate pathname (normally referenced using
1453 * the special character '#' during file expansion and in the vi ^^ command)
1454 * is set by almost all ex commands that take file names as arguments. The
1455 * rules go something like this:
1457 * 1: If any ex command takes a file name as an argument (except for the
1458 * :next command), the alternate pathname is set to that file name.
1459 * This excludes the command ":e" and ":w !command" as no file name
1460 * was specified. Note, historically, the :source command did not set
1461 * the alternate pathname. It does in nvi, for consistency.
1463 * 2: However, if any ex command sets the current pathname, e.g. the
1464 * ":e file" or ":rew" commands succeed, then the alternate pathname
1465 * is set to the previous file's current pathname, if it had one.
1466 * This includes the ":file" command and excludes the ":e" command.
1467 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1468 * pathname will be "foo", if it succeeds, the alternate pathname will
1469 * be the previous current pathname. The ":e" command will not set
1470 * the alternate or current pathnames regardless.
1472 * 3: However, if it's a read or write command with a file argument and
1473 * the current pathname has not yet been set, the file name becomes
1474 * the current pathname, and the alternate pathname is unchanged.
1476 * If the user edits a temporary file, there may be times when there is no
1477 * alternative file name. A name argument of NULL turns it off.
1479 * PUBLIC: void set_alt_name __P((SCR *, char *));
1481 void
1482 set_alt_name(SCR *sp, const char *name)
1484 if (sp->alt_name != NULL)
1485 free(sp->alt_name);
1486 if (name == NULL)
1487 sp->alt_name = NULL;
1488 else if ((sp->alt_name = strdup(name)) == NULL)
1489 msgq(sp, M_SYSERR, NULL);
1493 * file_lock --
1494 * Get an exclusive lock on a file and set close-on-exec flag
1496 * XXX
1497 * The default locking is flock(2) style, not fcntl(2). The latter is
1498 * known to fail badly on some systems, and its only advantage is that
1499 * it occasionally works over NFS.
1501 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1502 * two-fold: you can't close any file descriptor associated with the file
1503 * without losing all of the locks, and you can't get an exclusive lock
1504 * unless you have the file open for writing. Someone ought to be shot,
1505 * but it's probably too late, they may already have reproduced. To get
1506 * around these problems, nvi opens the files for writing when it can and
1507 * acquires a second file descriptor when it can't. The recovery files
1508 * are examples of the former, they're always opened for writing. The DB
1509 * files can't be opened for writing because the semantics of DB are that
1510 * files opened for writing are flushed back to disk when the DB session
1511 * is ended. So, in that case we have to acquire an extra file descriptor.
1513 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1515 lockr_t
1516 file_lock(SCR *sp, char *name, int *fdp, int fd, int iswrite)
1518 fcntl(fd, F_SETFD, 1);
1520 if (!O_ISSET(sp, O_LOCKFILES))
1521 return (LOCK_SUCCESS);
1523 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1525 * !!!
1526 * We need to distinguish a lock not being available for the file
1527 * from the file system not supporting locking. Flock is documented
1528 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1529 * they are the former. There's no portable way to do this.
1531 errno = 0;
1532 return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
1533 #ifdef EWOULDBLOCK
1534 || errno == EWOULDBLOCK
1535 #endif
1536 ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
1537 #endif
1538 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1540 struct flock arg;
1541 int didopen, sverrno;
1543 arg.l_type = F_WRLCK;
1544 arg.l_whence = 0; /* SEEK_SET */
1545 arg.l_start = arg.l_len = 0;
1546 arg.l_pid = 0;
1549 * If the file descriptor isn't opened for writing, it must fail.
1550 * If we fail because we can't get a read/write file descriptor,
1551 * we return LOCK_SUCCESS, believing that the file is readonly
1552 * and that will be sufficient to warn the user.
1554 if (!iswrite) {
1555 if (name == NULL || fdp == NULL)
1556 return (LOCK_FAILED);
1557 if ((fd = open(name, O_RDWR, 0)) == -1)
1558 return (LOCK_SUCCESS);
1559 *fdp = fd;
1560 didopen = 1;
1563 errno = 0;
1564 if (!fcntl(fd, F_SETLK, &arg))
1565 return (LOCK_SUCCESS);
1566 if (didopen) {
1567 sverrno = errno;
1568 (void)close(fd);
1569 errno = sverrno;
1573 * !!!
1574 * We need to distinguish a lock not being available for the file
1575 * from the file system not supporting locking. Fcntl is documented
1576 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1577 * and assume they are the former. There's no portable way to do this.
1579 return (errno == EACCES || errno == EAGAIN
1580 #ifdef EWOULDBLOCK
1581 || errno == EWOULDBLOCK
1582 #endif
1583 ? LOCK_UNAVAIL : LOCK_FAILED);
1585 #endif
1586 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1587 return (LOCK_SUCCESS);
1588 #endif
1591 #ifdef USE_DB4_LOGGING
1592 #define VI_DB_INIT_LOG DB_INIT_LOG
1593 #else
1594 #define VI_DB_INIT_LOG 0
1595 #endif
1597 static int
1598 db_setup(SCR *sp, EXF *ep)
1600 char path[MAXPATHLEN];
1601 int fd;
1602 DB_ENV *env;
1604 (void)snprintf(path, sizeof(path), "%s/vi.XXXXXX", O_STR(sp, O_RECDIR));
1605 if ((fd = mkstemp(path)) == -1) {
1606 msgq(sp, M_SYSERR, "%s", path);
1607 goto err;
1609 (void)close(fd);
1610 (void)unlink(path);
1611 if (mkdir(path, S_IRWXU)) {
1612 msgq(sp, M_SYSERR, "%s", path);
1613 goto err;
1615 if (db_env_create(&env, 0)) {
1616 msgq(sp, M_ERR, "env_create");
1617 goto err;
1619 #ifdef USE_DB4_LOGGING
1620 if ((sp->db_error = vi_db_init_recover(env))) {
1621 msgq(sp, M_DBERR, "init_recover");
1622 goto err;
1624 if ((sp->db_error = __vi_init_recover(env))) {
1625 msgq(sp, M_DBERR, "init_recover");
1626 goto err;
1628 #endif
1629 if ((sp->db_error = db_env_open(env, path,
1630 DB_PRIVATE | DB_CREATE | DB_INIT_MPOOL | VI_DB_THREAD
1631 | VI_DB_INIT_LOG, 0)) != 0) {
1632 msgq(sp, M_DBERR, "env->open");
1633 goto err;
1636 if ((ep->env_path = strdup(path)) == NULL) {
1637 msgq(sp, M_SYSERR, NULL);
1638 (void)rmdir(path);
1639 goto err;
1641 ep->env = env;
1642 return 0;
1643 err:
1644 return 1;