add a .gitignore file
[nvi.git] / common / exf.c
blobd24db997e0d522e02ca91f1787ed7c0f68e399e3
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 *));
47 * file_add --
48 * Insert a file name into the FREF list, if it doesn't already
49 * appear in it.
51 * !!!
52 * The "if it doesn't already appear" changes vi's semantics slightly. If
53 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
54 * will reflect the line/column of the previous edit session. Historic nvi
55 * did not do this. The change is a logical extension of the change where
56 * vi now remembers the last location in any file that it has ever edited,
57 * not just the previously edited file.
59 * PUBLIC: FREF *file_add __P((SCR *, char *));
61 FREF *
62 file_add(SCR *sp, char *name)
64 GS *gp;
65 FREF *frp, *tfrp;
68 * Return it if it already exists. Note that we test against the
69 * user's name, whatever that happens to be, including if it's a
70 * temporary file.
72 * If the user added a file but was unable to initialize it, there
73 * can be file list entries where the name field is NULL. Discard
74 * them the next time we see them.
76 gp = sp->gp;
77 if (name != NULL)
78 for (frp = gp->frefq.cqh_first;
79 frp != (FREF *)&gp->frefq; frp = frp->q.cqe_next) {
80 if (frp->name == NULL) {
81 tfrp = frp->q.cqe_next;
82 CIRCLEQ_REMOVE(&gp->frefq, frp, q);
83 if (frp->name != NULL)
84 free(frp->name);
85 free(frp);
86 frp = tfrp;
87 continue;
89 if (!strcmp(frp->name, name))
90 return (frp);
93 /* Allocate and initialize the FREF structure. */
94 CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
95 if (frp == NULL)
96 return (NULL);
99 * If no file name specified, or if the file name is a request
100 * for something temporary, file_init() will allocate the file
101 * name. Temporary files are always ignored.
103 if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
104 (frp->name = strdup(name)) == NULL) {
105 free(frp);
106 msgq(sp, M_SYSERR, NULL);
107 return (NULL);
110 /* Append into the chain of file names. */
111 CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);
113 return (frp);
117 * file_init --
118 * Start editing a file, based on the FREF structure. If successsful,
119 * let go of any previous file. Don't release the previous file until
120 * absolutely sure we have the new one.
122 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
125 file_init(SCR *sp, FREF *frp, char *rcv_name, int flags)
127 EXF *ep;
128 struct stat sb;
129 size_t psize;
130 int fd, exists, open_err, readonly, stolen;
131 char *oname, tname[MAXPATHLEN];
133 stolen = open_err = readonly = 0;
136 * If the file is a recovery file, let the recovery code handle it.
137 * Clear the FR_RECOVER flag first -- the recovery code does set up,
138 * and then calls us! If the recovery call fails, it's probably
139 * because the named file doesn't exist. So, move boldly forward,
140 * presuming that there's an error message the user will get to see.
142 if (F_ISSET(frp, FR_RECOVER)) {
143 F_CLR(frp, FR_RECOVER);
144 return (rcv_read(sp, frp));
148 * Required FRP initialization; the only flag we keep is the
149 * cursor information.
151 F_CLR(frp, ~FR_CURSORSET);
154 * Scan the user's path to find the file that we're going to
155 * try and open.
157 if (file_spath(sp, frp, &sb, &exists))
158 return (1);
161 * Check whether we already have this file opened in some
162 * other screen.
164 if (exists) {
165 EXF *exfp;
166 for (exfp = sp->gp->exfq.cqh_first;
167 exfp != (EXF *)&sp->gp->exfq; exfp = exfp->q.cqe_next) {
168 if (exfp->mdev == sb.st_dev &&
169 exfp->minode == sb.st_ino &&
170 (exfp != sp->ep || exfp->refcnt > 1)) {
171 ep = exfp;
172 goto postinit;
178 * Required EXF initialization:
179 * Flush the line caches.
180 * Default recover mail file fd to -1.
181 * Set initial EXF flag bits.
183 CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
184 CIRCLEQ_INIT(&ep->scrq);
185 sp->c_lno = ep->c_nlines = OOBLNO;
186 ep->rcv_fd = ep->fcntl_fd = -1;
187 F_SET(ep, F_FIRSTMODIFY);
190 * If no name or backing file, for whatever reason, create a backing
191 * temporary file, saving the temp file name so we can later unlink
192 * it. If the user never named this file, copy the temporary file name
193 * to the real name (we display that until the user renames it).
195 oname = frp->name;
196 if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
197 if (opts_empty(sp, O_TMP_DIRECTORY, 0))
198 goto err;
199 (void)snprintf(tname, sizeof(tname),
200 "%s/vi.XXXXXX", O_STR(sp, O_TMP_DIRECTORY));
201 if ((fd = mkstemp(tname)) == -1) {
202 msgq(sp, M_SYSERR,
203 "237|Unable to create temporary file");
204 goto err;
206 (void)close(fd);
208 if (frp->name == NULL)
209 F_SET(frp, FR_TMPFILE);
210 if ((frp->tname = strdup(tname)) == NULL ||
211 (frp->name == NULL &&
212 (frp->name = strdup(tname)) == NULL)) {
213 if (frp->tname != NULL) {
214 free(frp->tname);
216 msgq(sp, M_SYSERR, NULL);
217 (void)unlink(tname);
218 goto err;
220 oname = frp->tname;
221 psize = 1024;
222 if (!LF_ISSET(FS_OPENERR))
223 F_SET(frp, FR_NEWFILE);
225 time(&ep->mtime);
226 } else {
228 * XXX
229 * A seat of the pants calculation: try to keep the file in
230 * 15 pages or less. Don't use a page size larger than 10K
231 * (vi should have good locality) or smaller than 1K.
233 psize = ((sb.st_size / 15) + 1023) / 1024;
234 if (psize > 10)
235 psize = 10;
236 if (psize == 0)
237 psize = 1;
238 psize *= 1024;
240 F_SET(ep, F_DEVSET);
241 ep->mdev = sb.st_dev;
242 ep->minode = sb.st_ino;
244 ep->mtime = sb.st_mtime;
246 if (!S_ISREG(sb.st_mode))
247 msgq_str(sp, M_ERR, oname,
248 "238|Warning: %s is not a regular file");
251 /* Set up recovery. */
252 if (rcv_name == NULL) {
253 /* ep->rcv_path NULL if rcv_tmp fails */
254 rcv_tmp(sp, ep, frp->name);
255 } else {
256 if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
257 msgq(sp, M_SYSERR, NULL);
258 goto err;
260 F_SET(ep, F_MODIFIED);
263 if (db_init(sp, ep, rcv_name, oname, psize, &open_err)) {
264 if (open_err && !LF_ISSET(FS_OPENERR))
265 goto oerr;
266 goto err;
270 * Do the remaining things that can cause failure of the new file,
271 * mark and logging initialization.
273 if (mark_init(sp, ep) || log_init(sp, ep))
274 goto err;
276 postinit:
278 * Set the alternate file name to be the file we're discarding.
280 * !!!
281 * Temporary files can't become alternate files, so there's no file
282 * name. This matches historical practice, although it could only
283 * happen in historical vi as the result of the initial command, i.e.
284 * if vi was executed without a file name.
286 if (LF_ISSET(FS_SETALT))
287 set_alt_name(sp, sp->frp == NULL ||
288 F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
291 * Close the previous file; if that fails, close the new one and run
292 * for the border.
294 * !!!
295 * There's a nasty special case. If the user edits a temporary file,
296 * and then does an ":e! %", we need to re-initialize the backing
297 * file, but we can't change the name. (It's worse -- we're dealing
298 * with *names* here, we can't even detect that it happened.) Set a
299 * flag so that the file_end routine ignores the backing information
300 * of the old file if it happens to be the same as the new one.
302 * !!!
303 * Side-effect: after the call to file_end(), sp->frp may be NULL.
305 if (sp->ep != NULL) {
306 F_SET(frp, FR_DONTDELETE);
307 if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
308 (void)file_end(sp, ep, 1);
309 goto err;
311 sp->ep = NULL;
312 F_CLR(frp, FR_DONTDELETE);
316 * Lock the file; if it's a recovery file, it should already be
317 * locked. Note, we acquire the lock after the previous file
318 * has been ended, so that we don't get an "already locked" error
319 * for ":edit!".
321 * XXX
322 * While the user can't interrupt us between the open and here,
323 * there's a race between the dbopen() and the lock. Not much
324 * we can do about it.
326 * XXX
327 * We don't make a big deal of not being able to lock the file. As
328 * locking rarely works over NFS, and often fails if the file was
329 * mmap(2)'d, it's far too common to do anything like print an error
330 * message, let alone make the file readonly. At some future time,
331 * when locking is a little more reliable, this should change to be
332 * an error.
334 if (rcv_name == NULL && ep->refcnt == 0) {
335 if ((ep->fd = open(oname, O_RDWR)) == -1)
336 goto no_lock;
338 switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 1)) {
339 case LOCK_FAILED:
340 no_lock:
341 F_SET(frp, FR_UNLOCKED);
342 break;
343 case LOCK_UNAVAIL:
344 readonly = 1;
345 msgq_str(sp, M_INFO, oname,
346 "239|%s already locked, session is read-only");
347 break;
348 case LOCK_SUCCESS:
349 break;
354 * Historically, the readonly edit option was set per edit buffer in
355 * vi, unless the -R command-line option was specified or the program
356 * was executed as "view". (Well, to be truthful, if the letter 'w'
357 * occurred anywhere in the program name, but let's not get into that.)
358 * So, the persistant readonly state has to be stored in the screen
359 * structure, and the edit option value toggles with the contents of
360 * the edit buffer. If the persistant readonly flag is set, set the
361 * readonly edit option.
363 * Otherwise, try and figure out if a file is readonly. This is a
364 * dangerous thing to do. The kernel is the only arbiter of whether
365 * or not a file is writeable, and the best that a user program can
366 * do is guess. Obvious loopholes are files that are on a file system
367 * mounted readonly (access catches this one on a few systems), or
368 * alternate protection mechanisms, ACL's for example, that we can't
369 * portably check. Lots of fun, and only here because users whined.
371 * !!!
372 * Historic vi displayed the readonly message if none of the file
373 * write bits were set, or if an an access(2) call on the path
374 * failed. This seems reasonable. If the file is mode 444, root
375 * users may want to know that the owner of the file did not expect
376 * it to be written.
378 * Historic vi set the readonly bit if no write bits were set for
379 * a file, even if the access call would have succeeded. This makes
380 * the superuser force the write even when vi expects that it will
381 * succeed. I'm less supportive of this semantic, but it's historic
382 * practice and the conservative approach to vi'ing files as root.
384 * It would be nice if there was some way to update this when the user
385 * does a "^Z; chmod ...". The problem is that we'd first have to
386 * distinguish between readonly bits set because of file permissions
387 * and those set for other reasons. That's not too hard, but deciding
388 * when to reevaluate the permissions is trickier. An alternative
389 * might be to turn off the readonly bit if the user forces a write
390 * and it succeeds.
392 * XXX
393 * Access(2) doesn't consider the effective uid/gid values. This
394 * probably isn't a problem for vi when it's running standalone.
396 if (readonly || F_ISSET(sp, SC_READONLY) ||
397 (!F_ISSET(frp, FR_NEWFILE) &&
398 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
399 access(frp->name, W_OK))))
400 O_SET(sp, O_READONLY);
401 else
402 O_CLR(sp, O_READONLY);
404 /* Switch... */
405 ++ep->refcnt;
406 CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq);
407 sp->ep = ep;
408 sp->frp = frp;
410 /* Set the initial cursor position, queue initial command. */
411 file_cinit(sp);
413 /* Report conversion errors again. */
414 F_CLR(sp, SC_CONV_ERROR);
416 /* Redraw the screen from scratch, schedule a welcome message. */
417 F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);
419 if (frp->lno == OOBLNO)
420 F_SET(sp, SC_SCR_TOP);
422 /* Append into the chain of file structures. */
423 if (ep->refcnt == 1)
424 CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q);
426 return (0);
428 err: if (frp->name != NULL) {
429 free(frp->name);
430 frp->name = NULL;
432 if (frp->tname != NULL) {
433 (void)unlink(frp->tname);
434 free(frp->tname);
435 frp->tname = NULL;
438 oerr: if (F_ISSET(ep, F_RCV_ON))
439 (void)unlink(ep->rcv_path);
440 if (ep->rcv_path != NULL) {
441 free(ep->rcv_path);
442 ep->rcv_path = NULL;
444 if (ep->db != NULL) {
445 (void)db_close(ep->db);
446 ep->db = NULL;
448 free(ep);
450 return (open_err && !LF_ISSET(FS_OPENERR) ?
451 file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
455 * file_spath --
456 * Scan the user's path to find the file that we're going to
457 * try and open.
459 static int
460 file_spath(SCR *sp, FREF *frp, struct stat *sbp, int *existsp)
462 CHAR_T savech;
463 size_t len;
464 int found;
465 char *name, *p, *t, path[MAXPATHLEN];
468 * If the name is NULL or an explicit reference (i.e., the first
469 * component is . or ..) ignore the O_PATH option.
471 name = frp->name;
472 if (name == NULL) {
473 *existsp = 0;
474 return (0);
476 if (name[0] == '/' || (name[0] == '.' &&
477 (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
478 *existsp = !stat(name, sbp);
479 return (0);
482 /* Try . */
483 if (!stat(name, sbp)) {
484 *existsp = 1;
485 return (0);
488 /* Try the O_PATH option values. */
489 for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
490 if (*p == ':' || *p == '\0') {
491 if (t < p - 1) {
492 savech = *p;
493 *p = '\0';
494 len = snprintf(path,
495 sizeof(path), "%s/%s", t, name);
496 *p = savech;
497 if (!stat(path, sbp)) {
498 found = 1;
499 break;
502 t = p + 1;
503 if (*p == '\0')
504 break;
507 /* If we found it, build a new pathname and discard the old one. */
508 if (found) {
509 MALLOC_RET(sp, p, char *, len + 1);
510 memcpy(p, path, len + 1);
511 free(frp->name);
512 frp->name = p;
514 *existsp = found;
515 return (0);
519 * file_cinit --
520 * Set up the initial cursor position.
522 static void
523 file_cinit(SCR *sp)
525 GS *gp;
526 MARK m;
527 size_t len;
528 int nb;
529 CHAR_T *wp;
530 size_t wlen;
532 /* Set some basic defaults. */
533 sp->lno = 1;
534 sp->cno = 0;
537 * Historically, initial commands (the -c option) weren't executed
538 * until a file was loaded, e.g. "vi +10 nofile", followed by an
539 * :edit or :tag command, would execute the +10 on the file loaded
540 * by the subsequent command, (assuming that it existed). This
541 * applied as well to files loaded using the tag commands, and we
542 * follow that historic practice. Also, all initial commands were
543 * ex commands and were always executed on the last line of the file.
545 * Otherwise, if no initial command for this file:
546 * If in ex mode, move to the last line, first nonblank character.
547 * If the file has previously been edited, move to the last known
548 * position, and check it for validity.
549 * Otherwise, move to the first line, first nonblank.
551 * This gets called by the file init code, because we may be in a
552 * file of ex commands and we want to execute them from the right
553 * location in the file.
555 nb = 0;
556 gp = sp->gp;
557 if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
558 if (db_last(sp, &sp->lno))
559 return;
560 if (sp->lno == 0) {
561 sp->lno = 1;
562 sp->cno = 0;
564 CHAR2INT(sp, gp->c_option, strlen(gp->c_option) + 1,
565 wp, wlen);
566 if (ex_run_str(sp, "-c option", wp, wlen - 1, 1, 1))
567 return;
568 gp->c_option = NULL;
569 } else if (F_ISSET(sp, SC_EX)) {
570 if (db_last(sp, &sp->lno))
571 return;
572 if (sp->lno == 0) {
573 sp->lno = 1;
574 sp->cno = 0;
575 return;
577 nb = 1;
578 } else {
579 if (F_ISSET(sp->frp, FR_CURSORSET)) {
580 sp->lno = sp->frp->lno;
581 sp->cno = sp->frp->cno;
583 /* If returning to a file in vi, center the line. */
584 F_SET(sp, SC_SCR_CENTER);
585 } else {
586 if (O_ISSET(sp, O_COMMENT))
587 file_comment(sp);
588 else
589 sp->lno = 1;
590 nb = 1;
592 if (db_get(sp, sp->lno, 0, NULL, &len)) {
593 sp->lno = 1;
594 sp->cno = 0;
595 return;
597 if (!nb && sp->cno > len)
598 nb = 1;
600 if (nb) {
601 sp->cno = 0;
602 (void)nonblank(sp, sp->lno, &sp->cno);
606 * !!!
607 * The initial column is also the most attractive column.
609 sp->rcm = sp->cno;
612 * !!!
613 * Historically, vi initialized the absolute mark, but ex did not.
614 * Which meant, that if the first command in ex mode was "visual",
615 * or if an ex command was executed first (e.g. vi +10 file) vi was
616 * entered without the mark being initialized. For consistency, if
617 * the file isn't empty, we initialize it for everyone, believing
618 * that it can't hurt, and is generally useful. Not initializing it
619 * if the file is empty is historic practice, although it has always
620 * been possible to set (and use) marks in empty vi files.
622 m.lno = sp->lno;
623 m.cno = sp->cno;
624 (void)mark_set(sp, ABSMARK1, &m, 0);
628 * file_end --
629 * Stop editing a file.
631 * PUBLIC: int file_end __P((SCR *, EXF *, int));
634 file_end(SCR *sp, EXF *ep, int force)
636 FREF *frp;
639 * !!!
640 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
641 * (If argument ep is NULL, use sp->ep.)
643 * If multiply referenced, just decrement the count and return.
645 if (ep == NULL)
646 ep = sp->ep;
647 CIRCLEQ_REMOVE(&ep->scrq, sp, eq);
648 if (--ep->refcnt != 0)
649 return (0);
653 * Clean up the FREF structure.
655 * Save the cursor location.
657 * XXX
658 * It would be cleaner to do this somewhere else, but by the time
659 * ex or vi knows that we're changing files it's already happened.
661 frp = sp->frp;
662 frp->lno = sp->lno;
663 frp->cno = sp->cno;
664 F_SET(frp, FR_CURSORSET);
667 * We may no longer need the temporary backing file, so clean it
668 * up. We don't need the FREF structure either, if the file was
669 * never named, so lose it.
671 * !!!
672 * Re: FR_DONTDELETE, see the comment above in file_init().
674 if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
675 if (unlink(frp->tname))
676 msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
677 free(frp->tname);
678 frp->tname = NULL;
679 if (F_ISSET(frp, FR_TMPFILE)) {
680 CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
681 if (frp->name != NULL)
682 free(frp->name);
683 free(frp);
685 sp->frp = NULL;
689 * Clean up the EXF structure.
691 * Close the db structure.
693 if (ep->db->close != NULL) {
694 if ((sp->db_error = db_close(ep->db)) != 0 &&
695 !force) {
696 msgq_str(sp, M_DBERR, frp->name, "241|%s: close");
697 CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq);
698 ++ep->refcnt;
699 return (1);
701 ep->db = NULL;
704 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
706 /* Stop logging. */
707 (void)log_end(sp, ep);
709 /* Free up any marks. */
710 (void)mark_end(sp, ep);
712 if (ep->env) {
713 DB_ENV *env;
715 db_env_close(ep->env, 0);
716 ep->env = 0;
717 if ((sp->db_error = db_env_create(&env, 0)))
718 msgq(sp, M_DBERR, "env_create");
719 if ((sp->db_error = db_env_remove(env, ep->env_path, 0)))
720 msgq(sp, M_DBERR, "env->remove");
721 if (ep->env_path != NULL && rmdir(ep->env_path))
722 msgq_str(sp, M_SYSERR, ep->env_path, "242|%s: remove");
726 * Delete recovery files, close the open descriptor, free recovery
727 * memory. See recover.c for a description of the protocol.
729 * XXX
730 * Unlink backup file first, we can detect that the recovery file
731 * doesn't reference anything when the user tries to recover it.
732 * There's a race, here, obviously, but it's fairly small.
734 if (!F_ISSET(ep, F_RCV_NORM)) {
735 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
736 msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
737 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
738 msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
740 CIRCLEQ_REMOVE(&sp->gp->exfq, ep, q);
741 if (ep->fd != -1)
742 (void)close(ep->fd);
743 if (ep->fcntl_fd != -1)
744 (void)close(ep->fcntl_fd);
745 if (ep->rcv_fd != -1)
746 (void)close(ep->rcv_fd);
747 if (ep->env_path != NULL)
748 free(ep->env_path);
749 if (ep->rcv_path != NULL)
750 free(ep->rcv_path);
751 if (ep->rcv_mpath != NULL)
752 free(ep->rcv_mpath);
754 free(ep);
755 return (0);
759 * file_write --
760 * Write the file to disk. Historic vi had fairly convoluted
761 * semantics for whether or not writes would happen. That's
762 * why all the flags.
764 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
767 file_write(SCR *sp, MARK *fm, MARK *tm, char *name, int flags)
769 enum { NEWFILE, OLDFILE } mtype;
770 struct stat sb;
771 EXF *ep;
772 FILE *fp;
773 FREF *frp;
774 MARK from, to;
775 size_t len;
776 u_long nlno, nch;
777 int fd, nf, noname, oflags, rval;
778 char *p, *s, *t, buf[MAXPATHLEN + 64];
779 const char *msgstr;
781 ep = sp->ep;
782 frp = sp->frp;
785 * Writing '%', or naming the current file explicitly, has the
786 * same semantics as writing without a name.
788 if (name == NULL || !strcmp(name, frp->name)) {
789 noname = 1;
790 name = frp->name;
791 } else
792 noname = 0;
794 /* Can't write files marked read-only, unless forced. */
795 if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
796 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
797 "244|Read-only file, not written; use ! to override" :
798 "245|Read-only file, not written");
799 return (1);
802 /* If not forced, not appending, and "writeany" not set ... */
803 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
804 /* Don't overwrite anything but the original file. */
805 if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
806 !stat(name, &sb)) {
807 msgq_str(sp, M_ERR, name,
808 LF_ISSET(FS_POSSIBLE) ?
809 "246|%s exists, not written; use ! to override" :
810 "247|%s exists, not written");
811 return (1);
815 * Don't write part of any existing file. Only test for the
816 * original file, the previous test catches anything else.
818 if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
819 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
820 "248|Partial file, not written; use ! to override" :
821 "249|Partial file, not written");
822 return (1);
827 * Figure out if the file already exists -- if it doesn't, we display
828 * the "new file" message. The stat might not be necessary, but we
829 * just repeat it because it's easier than hacking the previous tests.
830 * The information is only used for the user message and modification
831 * time test, so we can ignore the obvious race condition.
833 * One final test. If we're not forcing or appending the current file,
834 * and we have a saved modification time, object if the file changed
835 * since we last edited or wrote it, and make them force it.
837 if (stat(name, &sb))
838 mtype = NEWFILE;
839 else {
840 if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
841 ((F_ISSET(ep, F_DEVSET) &&
842 (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
843 sb.st_mtime != ep->mtime)) {
844 msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
845 "250|%s: file modified more recently than this copy; use ! to override" :
846 "251|%s: file modified more recently than this copy");
847 return (1);
850 mtype = OLDFILE;
853 /* Set flags to create, write, and either append or truncate. */
854 oflags = O_CREAT | O_WRONLY |
855 (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
857 /* Backup the file if requested. */
858 if (!opts_empty(sp, O_BACKUP, 1) &&
859 file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
860 return (1);
862 /* Open the file. */
863 SIGBLOCK;
864 if ((fd = open(name, oflags,
865 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
866 msgq_str(sp, M_SYSERR, name, "%s");
867 SIGUNBLOCK;
868 return (1);
870 SIGUNBLOCK;
872 /* Try and get a lock. */
873 if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
874 msgq_str(sp, M_ERR, name,
875 "252|%s: write lock was unavailable");
877 #if __linux__
879 * XXX
880 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
881 * This bug is fixed in libc 4.6.x.
883 * This code works around this problem for libc 4.5.x users.
884 * Note that this code is harmless if you're using libc 4.6.x.
886 if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
887 msgq(sp, M_SYSERR, name);
888 return (1);
890 #endif
893 * Use stdio for buffering.
895 * XXX
896 * SVR4.2 requires the fdopen mode exactly match the original open
897 * mode, i.e. you have to open with "a" if appending.
899 if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
900 msgq_str(sp, M_SYSERR, name, "%s");
901 (void)close(fd);
902 return (1);
905 /* Build fake addresses, if necessary. */
906 if (fm == NULL) {
907 from.lno = 1;
908 from.cno = 0;
909 fm = &from;
910 if (db_last(sp, &to.lno))
911 return (1);
912 to.cno = 0;
913 tm = &to;
916 rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
919 * Save the new last modification time -- even if the write fails
920 * we re-init the time. That way the user can clean up the disk
921 * and rewrite without having to force it.
923 if (noname) {
924 if (stat(name, &sb))
925 time(&ep->mtime);
926 else {
927 F_SET(ep, F_DEVSET);
928 ep->mdev = sb.st_dev;
929 ep->minode = sb.st_ino;
931 ep->mtime = sb.st_mtime;
936 * If the write failed, complain loudly. ex_writefp() has already
937 * complained about the actual error, reinforce it if data was lost.
939 if (rval) {
940 if (!LF_ISSET(FS_APPEND))
941 msgq_str(sp, M_ERR, name,
942 "254|%s: WARNING: FILE TRUNCATED");
943 return (1);
947 * Once we've actually written the file, it doesn't matter that the
948 * file name was changed -- if it was, we've already whacked it.
950 F_CLR(frp, FR_NAMECHANGE);
953 * If wrote the entire file, and it wasn't by appending it to a file,
954 * clear the modified bit. If the file was written to the original
955 * file name and the file is a temporary, set the "no exit" bit. This
956 * permits the user to write the file and use it in the context of the
957 * filesystem, but still keeps them from discarding their changes by
958 * exiting.
960 if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
961 F_CLR(ep, F_MODIFIED);
962 if (F_ISSET(frp, FR_TMPFILE)) {
963 if (noname)
964 F_SET(frp, FR_TMPEXIT);
965 else
966 F_CLR(frp, FR_TMPEXIT);
970 p = msg_print(sp, name, &nf);
971 switch (mtype) {
972 case NEWFILE:
973 msgstr = msg_cat(sp,
974 "256|%s: new file: %lu lines, %lu characters", NULL);
975 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
976 break;
977 case OLDFILE:
978 msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
979 "315|%s: appended: %lu lines, %lu characters" :
980 "257|%s: %lu lines, %lu characters", NULL);
981 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
982 break;
983 default:
984 abort();
988 * There's a nasty problem with long path names. Cscope and tags files
989 * can result in long paths and vi will request a continuation key from
990 * the user. Unfortunately, the user has typed ahead, and chaos will
991 * result. If we assume that the characters in the filenames only take
992 * a single screen column each, we can trim the filename.
994 s = buf;
995 if (len >= sp->cols) {
996 for (s = buf, t = buf + strlen(p); s < t &&
997 (*s != '/' || len >= sp->cols - 3); ++s, --len);
998 if (s == t)
999 s = buf;
1000 else {
1001 *--s = '.'; /* Leading ellipses. */
1002 *--s = '.';
1003 *--s = '.';
1006 msgq(sp, M_INFO, s);
1007 if (nf)
1008 FREE_SPACE(sp, p, 0);
1009 return (0);
1013 * file_backup --
1014 * Backup the about-to-be-written file.
1016 * XXX
1017 * We do the backup by copying the entire file. It would be nice to do
1018 * a rename instead, but: (1) both files may not fit and we want to fail
1019 * before doing the rename; (2) the backup file may not be on the same
1020 * disk partition as the file being written; (3) there may be optional
1021 * file information (MACs, DACs, whatever) that we won't get right if we
1022 * recreate the file. So, let's not risk it.
1024 static int
1025 file_backup(SCR *sp, char *name, char *bname)
1027 struct dirent *dp;
1028 struct stat sb;
1029 DIR *dirp;
1030 EXCMD cmd;
1031 off_t off;
1032 size_t blen;
1033 int flags, maxnum, nr, num, nw, rfd, wfd, version;
1034 char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];
1035 CHAR_T *wp;
1036 size_t wlen;
1037 size_t nlen;
1038 char *d = NULL;
1040 rfd = wfd = -1;
1041 bp = estr = wfname = NULL;
1044 * Open the current file for reading. Do this first, so that
1045 * we don't exec a shell before the most likely failure point.
1046 * If it doesn't exist, it's okay, there's just nothing to back
1047 * up.
1049 errno = 0;
1050 if ((rfd = open(name, O_RDONLY, 0)) < 0) {
1051 if (errno == ENOENT)
1052 return (0);
1053 estr = name;
1054 goto err;
1058 * If the name starts with an 'N' character, add a version number
1059 * to the name. Strip the leading N from the string passed to the
1060 * expansion routines, for no particular reason. It would be nice
1061 * to permit users to put the version number anywhere in the backup
1062 * name, but there isn't a special character that we can use in the
1063 * name, and giving a new character a special meaning leads to ugly
1064 * hacks both here and in the supporting ex routines.
1066 * Shell and file name expand the option's value.
1068 ex_cinit(sp, &cmd, 0, 0, 0, 0, 0);
1069 if (bname[0] == 'N') {
1070 version = 1;
1071 ++bname;
1072 } else
1073 version = 0;
1074 CHAR2INT(sp, bname, strlen(bname) + 1, wp, wlen);
1075 if (argv_exp2(sp, &cmd, wp, wlen - 1))
1076 return (1);
1079 * 0 args: impossible.
1080 * 1 args: use it.
1081 * >1 args: object, too many args.
1083 if (cmd.argc != 1) {
1084 msgq_str(sp, M_ERR, bname,
1085 "258|%s expanded into too many file names");
1086 (void)close(rfd);
1087 return (1);
1091 * If appending a version number, read through the directory, looking
1092 * for file names that match the name followed by a number. Make all
1093 * of the other % characters in name literal, so the user doesn't get
1094 * surprised and sscanf doesn't drop core indirecting through pointers
1095 * that don't exist. If any such files are found, increment its number
1096 * by one.
1098 if (version) {
1099 GET_SPACE_GOTOC(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1100 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1101 p, nlen);
1102 d = strdup(p);
1103 p = d;
1104 for (t = bp, slash = NULL;
1105 p[0] != '\0'; *t++ = *p++)
1106 if (p[0] == '%') {
1107 if (p[1] != '%')
1108 *t++ = '%';
1109 } else if (p[0] == '/')
1110 slash = t;
1111 pct = t;
1112 *t++ = '%';
1113 *t++ = 'd';
1114 *t = '\0';
1116 if (slash == NULL) {
1117 dirp = opendir(".");
1118 p = bp;
1119 } else {
1120 *slash = '\0';
1121 dirp = opendir(bp);
1122 *slash = '/';
1123 p = slash + 1;
1125 if (dirp == NULL) {
1126 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1127 estr, nlen);
1128 goto err;
1131 for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1132 if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1133 maxnum = num;
1134 (void)closedir(dirp);
1136 /* Format the backup file name. */
1137 (void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1138 wfname = bp;
1139 } else {
1140 bp = NULL;
1141 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1142 wfname, nlen);
1145 /* Open the backup file, avoiding lurkers. */
1146 if (stat(wfname, &sb) == 0) {
1147 if (!S_ISREG(sb.st_mode)) {
1148 msgq_str(sp, M_ERR, bname,
1149 "259|%s: not a regular file");
1150 goto err;
1152 if (sb.st_uid != getuid()) {
1153 msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
1154 goto err;
1156 if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1157 msgq_str(sp, M_ERR, bname,
1158 "261|%s: accessible by a user other than the owner");
1159 goto err;
1161 flags = O_TRUNC;
1162 } else
1163 flags = O_CREAT | O_EXCL;
1164 if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
1165 estr = bname;
1166 goto err;
1169 /* Copy the file's current contents to its backup value. */
1170 while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1171 for (off = 0; nr != 0; nr -= nw, off += nw)
1172 if ((nw = write(wfd, buf + off, nr)) < 0) {
1173 estr = wfname;
1174 goto err;
1176 if (nr < 0) {
1177 estr = name;
1178 goto err;
1181 if (close(rfd)) {
1182 estr = name;
1183 goto err;
1185 if (close(wfd)) {
1186 estr = wfname;
1187 goto err;
1189 if (bp != NULL)
1190 FREE_SPACE(sp, bp, blen);
1191 return (0);
1193 alloc_err:
1194 err: if (rfd != -1)
1195 (void)close(rfd);
1196 if (wfd != -1) {
1197 (void)unlink(wfname);
1198 (void)close(wfd);
1200 if (estr)
1201 msgq_str(sp, M_SYSERR, estr, "%s");
1202 if (d != NULL)
1203 free(d);
1204 if (bp != NULL)
1205 FREE_SPACE(sp, bp, blen);
1206 return (1);
1210 * file_comment --
1211 * Skip the first comment.
1213 static void
1214 file_comment(SCR *sp)
1216 db_recno_t lno;
1217 size_t len;
1218 CHAR_T *p;
1220 for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1221 if (p == NULL)
1222 return;
1223 if (p[0] == '#') {
1224 F_SET(sp, SC_SCR_TOP);
1225 while (!db_get(sp, ++lno, 0, &p, &len))
1226 if (len < 1 || p[0] != '#') {
1227 sp->lno = lno;
1228 return;
1230 } else if (len > 1 && p[0] == '/' && p[1] == '*') {
1231 F_SET(sp, SC_SCR_TOP);
1232 do {
1233 for (; len > 1; --len, ++p)
1234 if (p[0] == '*' && p[1] == '/') {
1235 sp->lno = lno;
1236 return;
1238 } while (!db_get(sp, ++lno, 0, &p, &len));
1239 } else if (len > 1 && p[0] == '/' && p[1] == '/') {
1240 F_SET(sp, SC_SCR_TOP);
1241 while (!db_get(sp, ++lno, 0, &p, &len))
1242 if (len < 1 || p[0] != '/' || p[1] != '/') {
1243 sp->lno = lno;
1244 return;
1250 * file_m1 --
1251 * First modification check routine. The :next, :prev, :rewind, :tag,
1252 * :tagpush, :tagpop, ^^ modifications check.
1254 * PUBLIC: int file_m1 __P((SCR *, int, int));
1257 file_m1(SCR *sp, int force, int flags)
1259 EXF *ep;
1261 ep = sp->ep;
1263 /* If no file loaded, return no modifications. */
1264 if (ep == NULL)
1265 return (0);
1268 * If the file has been modified, we'll want to write it back or
1269 * fail. If autowrite is set, we'll write it back automatically,
1270 * unless force is also set. Otherwise, we fail unless forced or
1271 * there's another open screen on this file.
1273 if (F_ISSET(ep, F_MODIFIED)) {
1274 if (O_ISSET(sp, O_AUTOWRITE)) {
1275 if (!force && file_aw(sp, flags))
1276 return (1);
1277 } else if (ep->refcnt <= 1 && !force) {
1278 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1279 "262|File modified since last complete write; write or use ! to override" :
1280 "263|File modified since last complete write; write or use :edit! to override");
1281 return (1);
1285 return (file_m3(sp, force));
1289 * file_m2 --
1290 * Second modification check routine. The :edit, :quit, :recover
1291 * modifications check.
1293 * PUBLIC: int file_m2 __P((SCR *, int));
1296 file_m2(SCR *sp, int force)
1298 EXF *ep;
1300 ep = sp->ep;
1302 /* If no file loaded, return no modifications. */
1303 if (ep == NULL)
1304 return (0);
1307 * If the file has been modified, we'll want to fail, unless forced
1308 * or there's another open screen on this file.
1310 if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1311 msgq(sp, M_ERR,
1312 "264|File modified since last complete write; write or use ! to override");
1313 return (1);
1316 return (file_m3(sp, force));
1320 * file_m3 --
1321 * Third modification check routine.
1323 * PUBLIC: int file_m3 __P((SCR *, int));
1326 file_m3(SCR *sp, int force)
1328 EXF *ep;
1330 ep = sp->ep;
1332 /* If no file loaded, return no modifications. */
1333 if (ep == NULL)
1334 return (0);
1337 * Don't exit while in a temporary files if the file was ever modified.
1338 * The problem is that if the user does a ":wq", we write and quit,
1339 * unlinking the temporary file. Not what the user had in mind at all.
1340 * We permit writing to temporary files, so that user maps using file
1341 * system names work with temporary files.
1343 if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1344 msgq(sp, M_ERR,
1345 "265|File is a temporary; exit will discard modifications");
1346 return (1);
1348 return (0);
1352 * file_aw --
1353 * Autowrite routine. If modified, autowrite is set and the readonly bit
1354 * is not set, write the file. A routine so there's a place to put the
1355 * comment.
1357 * PUBLIC: int file_aw __P((SCR *, int));
1360 file_aw(SCR *sp, int flags)
1362 if (!F_ISSET(sp->ep, F_MODIFIED))
1363 return (0);
1364 if (!O_ISSET(sp, O_AUTOWRITE))
1365 return (0);
1368 * !!!
1369 * Historic 4BSD vi attempted to write the file if autowrite was set,
1370 * regardless of the writeability of the file (as defined by the file
1371 * readonly flag). System V changed this as some point, not attempting
1372 * autowrite if the file was readonly. This feels like a bug fix to
1373 * me (e.g. the principle of least surprise is violated if readonly is
1374 * set and vi writes the file), so I'm compatible with System V.
1376 if (O_ISSET(sp, O_READONLY)) {
1377 msgq(sp, M_INFO,
1378 "266|File readonly, modifications not auto-written");
1379 return (1);
1381 return (file_write(sp, NULL, NULL, NULL, flags));
1385 * set_alt_name --
1386 * Set the alternate pathname.
1388 * Set the alternate pathname. It's a routine because I wanted some place
1389 * to hang this comment. The alternate pathname (normally referenced using
1390 * the special character '#' during file expansion and in the vi ^^ command)
1391 * is set by almost all ex commands that take file names as arguments. The
1392 * rules go something like this:
1394 * 1: If any ex command takes a file name as an argument (except for the
1395 * :next command), the alternate pathname is set to that file name.
1396 * This excludes the command ":e" and ":w !command" as no file name
1397 * was specified. Note, historically, the :source command did not set
1398 * the alternate pathname. It does in nvi, for consistency.
1400 * 2: However, if any ex command sets the current pathname, e.g. the
1401 * ":e file" or ":rew" commands succeed, then the alternate pathname
1402 * is set to the previous file's current pathname, if it had one.
1403 * This includes the ":file" command and excludes the ":e" command.
1404 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1405 * pathname will be "foo", if it succeeds, the alternate pathname will
1406 * be the previous current pathname. The ":e" command will not set
1407 * the alternate or current pathnames regardless.
1409 * 3: However, if it's a read or write command with a file argument and
1410 * the current pathname has not yet been set, the file name becomes
1411 * the current pathname, and the alternate pathname is unchanged.
1413 * If the user edits a temporary file, there may be times when there is no
1414 * alternative file name. A name argument of NULL turns it off.
1416 * PUBLIC: void set_alt_name __P((SCR *, char *));
1418 void
1419 set_alt_name(SCR *sp, char *name)
1421 if (sp->alt_name != NULL)
1422 free(sp->alt_name);
1423 if (name == NULL)
1424 sp->alt_name = NULL;
1425 else if ((sp->alt_name = strdup(name)) == NULL)
1426 msgq(sp, M_SYSERR, NULL);
1430 * file_lock --
1431 * Get an exclusive lock on a file and set close-on-exec flag
1433 * XXX
1434 * The default locking is flock(2) style, not fcntl(2). The latter is
1435 * known to fail badly on some systems, and its only advantage is that
1436 * it occasionally works over NFS.
1438 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1439 * two-fold: you can't close any file descriptor associated with the file
1440 * without losing all of the locks, and you can't get an exclusive lock
1441 * unless you have the file open for writing. Someone ought to be shot,
1442 * but it's probably too late, they may already have reproduced. To get
1443 * around these problems, nvi opens the files for writing when it can and
1444 * acquires a second file descriptor when it can't. The recovery files
1445 * are examples of the former, they're always opened for writing. The DB
1446 * files can't be opened for writing because the semantics of DB are that
1447 * files opened for writing are flushed back to disk when the DB session
1448 * is ended. So, in that case we have to acquire an extra file descriptor.
1450 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1452 lockr_t
1453 file_lock(SCR *sp, char *name, int *fdp, int fd, int iswrite)
1455 fcntl(fd, F_SETFD, 1);
1457 if (!O_ISSET(sp, O_LOCKFILES))
1458 return (LOCK_SUCCESS);
1460 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1462 * !!!
1463 * We need to distinguish a lock not being available for the file
1464 * from the file system not supporting locking. Flock is documented
1465 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1466 * they are the former. There's no portable way to do this.
1468 errno = 0;
1469 return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
1470 #ifdef EWOULDBLOCK
1471 || errno == EWOULDBLOCK
1472 #endif
1473 ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
1474 #endif
1475 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1477 struct flock arg;
1478 int didopen, sverrno;
1480 arg.l_type = F_WRLCK;
1481 arg.l_whence = 0; /* SEEK_SET */
1482 arg.l_start = arg.l_len = 0;
1483 arg.l_pid = 0;
1486 * If the file descriptor isn't opened for writing, it must fail.
1487 * If we fail because we can't get a read/write file descriptor,
1488 * we return LOCK_SUCCESS, believing that the file is readonly
1489 * and that will be sufficient to warn the user.
1491 if (!iswrite) {
1492 if (name == NULL || fdp == NULL)
1493 return (LOCK_FAILED);
1494 if ((fd = open(name, O_RDWR, 0)) == -1)
1495 return (LOCK_SUCCESS);
1496 *fdp = fd;
1497 didopen = 1;
1500 errno = 0;
1501 if (!fcntl(fd, F_SETLK, &arg))
1502 return (LOCK_SUCCESS);
1503 if (didopen) {
1504 sverrno = errno;
1505 (void)close(fd);
1506 errno = sverrno;
1510 * !!!
1511 * We need to distinguish a lock not being available for the file
1512 * from the file system not supporting locking. Fcntl is documented
1513 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1514 * and assume they are the former. There's no portable way to do this.
1516 return (errno == EACCES || errno == EAGAIN
1517 #ifdef EWOULDBLOCK
1518 || errno == EWOULDBLOCK
1519 #endif
1520 ? LOCK_UNAVAIL : LOCK_FAILED);
1522 #endif
1523 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1524 return (LOCK_SUCCESS);
1525 #endif