Move open back to where it belongs.
[nvi.git] / common / exf.c
blob2c327f08a8c7caaa676f7689ee69c4dac7a1b5ec
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.60 2000/09/01 09:43:02 skimo Exp $ (Berkeley) $Date: 2000/09/01 09:43:02 $";
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(sp, name)
63 SCR *sp;
64 char *name;
66 GS *gp;
67 FREF *frp, *tfrp;
70 * Return it if it already exists. Note that we test against the
71 * user's name, whatever that happens to be, including if it's a
72 * temporary file.
74 * If the user added a file but was unable to initialize it, there
75 * can be file list entries where the name field is NULL. Discard
76 * them the next time we see them.
78 gp = sp->gp;
79 if (name != NULL)
80 for (frp = gp->frefq.cqh_first;
81 frp != (FREF *)&gp->frefq; frp = frp->q.cqe_next) {
82 if (frp->name == NULL) {
83 tfrp = frp->q.cqe_next;
84 CIRCLEQ_REMOVE(&gp->frefq, frp, q);
85 if (frp->name != NULL)
86 free(frp->name);
87 free(frp);
88 frp = tfrp;
89 continue;
91 if (!strcmp(frp->name, name))
92 return (frp);
95 /* Allocate and initialize the FREF structure. */
96 CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
97 if (frp == NULL)
98 return (NULL);
101 * If no file name specified, or if the file name is a request
102 * for something temporary, file_init() will allocate the file
103 * name. Temporary files are always ignored.
105 if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
106 (frp->name = strdup(name)) == NULL) {
107 free(frp);
108 msgq(sp, M_SYSERR, NULL);
109 return (NULL);
112 /* Append into the chain of file names. */
113 CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);
115 return (frp);
119 * file_init --
120 * Start editing a file, based on the FREF structure. If successsful,
121 * let go of any previous file. Don't release the previous file until
122 * absolutely sure we have the new one.
124 * PUBLIC: int file_init __P((SCR *, FREF *, char *, int));
127 file_init(sp, frp, rcv_name, flags)
128 SCR *sp;
129 FREF *frp;
130 char *rcv_name;
131 int flags;
133 EXF *ep;
134 struct stat sb;
135 size_t psize;
136 int fd, exists, open_err, readonly, stolen;
137 char *oname, tname[MAXPATHLEN];
139 stolen = open_err = readonly = 0;
142 * If the file is a recovery file, let the recovery code handle it.
143 * Clear the FR_RECOVER flag first -- the recovery code does set up,
144 * and then calls us! If the recovery call fails, it's probably
145 * because the named file doesn't exist. So, move boldly forward,
146 * presuming that there's an error message the user will get to see.
148 if (F_ISSET(frp, FR_RECOVER)) {
149 F_CLR(frp, FR_RECOVER);
150 return (rcv_read(sp, frp));
154 * Required FRP initialization; the only flag we keep is the
155 * cursor information.
157 F_CLR(frp, ~FR_CURSORSET);
160 * Scan the user's path to find the file that we're going to
161 * try and open.
163 if (file_spath(sp, frp, &sb, &exists))
164 return (1);
167 * Check whether we already have this file opened in some
168 * other screen.
170 if (exists) {
171 EXF *exfp;
172 for (exfp = sp->gp->exfq.cqh_first;
173 exfp != (EXF *)&sp->gp->exfq; exfp = exfp->q.cqe_next) {
174 if (exfp->mdev == sb.st_dev &&
175 exfp->minode == sb.st_ino &&
176 (exfp != sp->ep || exfp->refcnt > 1)) {
177 ep = exfp;
178 goto postinit;
184 * Required EXF initialization:
185 * Flush the line caches.
186 * Default recover mail file fd to -1.
187 * Set initial EXF flag bits.
189 CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
190 ep->c_lno = ep->c_nlines = OOBLNO;
191 ep->rcv_fd = ep->fcntl_fd = -1;
192 F_SET(ep, F_FIRSTMODIFY);
195 * If no name or backing file, for whatever reason, create a backing
196 * temporary file, saving the temp file name so we can later unlink
197 * it. If the user never named this file, copy the temporary file name
198 * to the real name (we display that until the user renames it).
200 oname = frp->name;
201 if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
202 if (opts_empty(sp, O_DIRECTORY, 0))
203 goto err;
204 (void)snprintf(tname, sizeof(tname),
205 "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
206 if ((fd = mkstemp(tname)) == -1) {
207 msgq(sp, M_SYSERR,
208 "237|Unable to create temporary file");
209 goto err;
211 (void)close(fd);
213 if (frp->name == NULL)
214 F_SET(frp, FR_TMPFILE);
215 if ((frp->tname = strdup(tname)) == NULL ||
216 (frp->name == NULL &&
217 (frp->name = strdup(tname)) == NULL)) {
218 if (frp->tname != NULL) {
219 free(frp->tname);
221 msgq(sp, M_SYSERR, NULL);
222 (void)unlink(tname);
223 goto err;
225 oname = frp->tname;
226 psize = 1024;
227 if (!LF_ISSET(FS_OPENERR))
228 F_SET(frp, FR_NEWFILE);
230 time(&ep->mtime);
231 } else {
233 * XXX
234 * A seat of the pants calculation: try to keep the file in
235 * 15 pages or less. Don't use a page size larger than 10K
236 * (vi should have good locality) or smaller than 1K.
238 psize = ((sb.st_size / 15) + 1023) / 1024;
239 if (psize > 10)
240 psize = 10;
241 if (psize == 0)
242 psize = 1;
243 psize *= 1024;
245 F_SET(ep, F_DEVSET);
246 ep->mdev = sb.st_dev;
247 ep->minode = sb.st_ino;
249 ep->mtime = sb.st_mtime;
251 if (!S_ISREG(sb.st_mode))
252 msgq_str(sp, M_ERR, oname,
253 "238|Warning: %s is not a regular file");
256 /* Set up recovery. */
257 if (rcv_name == NULL) {
258 /* ep->rcv_path NULL if rcv_tmp fails */
259 rcv_tmp(sp, ep, frp->name);
260 } else {
261 if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
262 msgq(sp, M_SYSERR, NULL);
263 goto err;
265 F_SET(ep, F_MODIFIED);
268 /* Open a db structure. */
269 if ((sp->db_error = db_create(&ep->db, sp->gp->env, 0)) != 0) {
270 /* XXXX */
271 fprintf(stderr, "db_create %d\n", sp->db_error);
272 goto err;
275 ep->db->set_re_delim(ep->db, '\n'); /* Always set. */
276 ep->db->set_pagesize(ep->db, psize);
277 ep->db->set_flags(ep->db, DB_RENUMBER |
278 (F_ISSET(sp->gp, G_SNAPSHOT) ? DB_SNAPSHOT : 0));
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 if ((sp->db_error = ep->db->open(ep->db, ep->rcv_path, NULL, DB_RECNO,
292 ((rcv_name == 0) ? DB_TRUNCATE : 0) | DB_THREAD | NOMMAPIFFCNTL,
293 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) != 0) {
294 msgq_str(sp,
295 M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s");
297 * !!!
298 * Historically, vi permitted users to edit files that couldn't
299 * be read. This isn't useful for single files from a command
300 * line, but it's quite useful for "vi *.c", since you can skip
301 * past files that you can't read.
303 ep->db = NULL; /* Don't close it; it wasn't opened */
305 if (LF_ISSET(FS_OPENERR))
306 goto err;
308 open_err = 1;
309 goto oerr;
313 * Do the remaining things that can cause failure of the new file,
314 * mark and logging initialization.
316 if (mark_init(sp, ep) || log_init(sp, ep))
317 goto err;
319 postinit:
321 * Set the alternate file name to be the file we're discarding.
323 * !!!
324 * Temporary files can't become alternate files, so there's no file
325 * name. This matches historical practice, although it could only
326 * happen in historical vi as the result of the initial command, i.e.
327 * if vi was executed without a file name.
329 if (LF_ISSET(FS_SETALT))
330 set_alt_name(sp, sp->frp == NULL ||
331 F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
334 * Close the previous file; if that fails, close the new one and run
335 * for the border.
337 * !!!
338 * There's a nasty special case. If the user edits a temporary file,
339 * and then does an ":e! %", we need to re-initialize the backing
340 * file, but we can't change the name. (It's worse -- we're dealing
341 * with *names* here, we can't even detect that it happened.) Set a
342 * flag so that the file_end routine ignores the backing information
343 * of the old file if it happens to be the same as the new one.
345 * !!!
346 * Side-effect: after the call to file_end(), sp->frp may be NULL.
348 if (sp->ep != NULL) {
349 F_SET(frp, FR_DONTDELETE);
350 if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
351 (void)file_end(sp, ep, 1);
352 goto err;
354 sp->ep = NULL;
355 F_CLR(frp, FR_DONTDELETE);
359 * Lock the file; if it's a recovery file, it should already be
360 * locked. Note, we acquire the lock after the previous file
361 * has been ended, so that we don't get an "already locked" error
362 * for ":edit!".
364 * XXX
365 * While the user can't interrupt us between the open and here,
366 * there's a race between the dbopen() and the lock. Not much
367 * we can do about it.
369 * XXX
370 * We don't make a big deal of not being able to lock the file. As
371 * locking rarely works over NFS, and often fails if the file was
372 * mmap(2)'d, it's far too common to do anything like print an error
373 * message, let alone make the file readonly. At some future time,
374 * when locking is a little more reliable, this should change to be
375 * an error.
377 if (rcv_name == NULL && ep->refcnt == 0) {
378 if ((ep->fd = open(oname, O_RDWR)) == -1)
379 goto no_lock;
381 switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 1)) {
382 case LOCK_FAILED:
383 no_lock:
384 F_SET(frp, FR_UNLOCKED);
385 break;
386 case LOCK_UNAVAIL:
387 readonly = 1;
388 msgq_str(sp, M_INFO, oname,
389 "239|%s already locked, session is read-only");
390 break;
391 case LOCK_SUCCESS:
392 break;
397 * Historically, the readonly edit option was set per edit buffer in
398 * vi, unless the -R command-line option was specified or the program
399 * was executed as "view". (Well, to be truthful, if the letter 'w'
400 * occurred anywhere in the program name, but let's not get into that.)
401 * So, the persistant readonly state has to be stored in the screen
402 * structure, and the edit option value toggles with the contents of
403 * the edit buffer. If the persistant readonly flag is set, set the
404 * readonly edit option.
406 * Otherwise, try and figure out if a file is readonly. This is a
407 * dangerous thing to do. The kernel is the only arbiter of whether
408 * or not a file is writeable, and the best that a user program can
409 * do is guess. Obvious loopholes are files that are on a file system
410 * mounted readonly (access catches this one on a few systems), or
411 * alternate protection mechanisms, ACL's for example, that we can't
412 * portably check. Lots of fun, and only here because users whined.
414 * !!!
415 * Historic vi displayed the readonly message if none of the file
416 * write bits were set, or if an an access(2) call on the path
417 * failed. This seems reasonable. If the file is mode 444, root
418 * users may want to know that the owner of the file did not expect
419 * it to be written.
421 * Historic vi set the readonly bit if no write bits were set for
422 * a file, even if the access call would have succeeded. This makes
423 * the superuser force the write even when vi expects that it will
424 * succeed. I'm less supportive of this semantic, but it's historic
425 * practice and the conservative approach to vi'ing files as root.
427 * It would be nice if there was some way to update this when the user
428 * does a "^Z; chmod ...". The problem is that we'd first have to
429 * distinguish between readonly bits set because of file permissions
430 * and those set for other reasons. That's not too hard, but deciding
431 * when to reevaluate the permissions is trickier. An alternative
432 * might be to turn off the readonly bit if the user forces a write
433 * and it succeeds.
435 * XXX
436 * Access(2) doesn't consider the effective uid/gid values. This
437 * probably isn't a problem for vi when it's running standalone.
439 if (readonly || F_ISSET(sp, SC_READONLY) ||
440 (!F_ISSET(frp, FR_NEWFILE) &&
441 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
442 access(frp->name, W_OK))))
443 O_SET(sp, O_READONLY);
444 else
445 O_CLR(sp, O_READONLY);
447 /* Switch... */
448 ++ep->refcnt;
449 sp->ep = ep;
450 sp->frp = frp;
452 /* Set the initial cursor position, queue initial command. */
453 file_cinit(sp);
455 /* Redraw the screen from scratch, schedule a welcome message. */
456 F_SET(sp, SC_SCR_REFORMAT | SC_SCR_TOP | SC_STATUS);
458 /* Append into the chain of file structures. */
459 if (ep->refcnt == 1)
460 CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q);
462 return (0);
464 err: if (frp->name != NULL) {
465 free(frp->name);
466 frp->name = NULL;
468 if (frp->tname != NULL) {
469 (void)unlink(frp->tname);
470 free(frp->tname);
471 frp->tname = NULL;
474 oerr: if (F_ISSET(ep, F_RCV_ON))
475 (void)unlink(ep->rcv_path);
476 if (ep->rcv_path != NULL) {
477 free(ep->rcv_path);
478 ep->rcv_path = NULL;
480 if (ep->db != NULL) {
481 (void)ep->db->close(ep->db, DB_NOSYNC);
482 ep->db = NULL;
484 free(ep);
486 return (open_err && !LF_ISSET(FS_OPENERR) ?
487 file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
491 * file_spath --
492 * Scan the user's path to find the file that we're going to
493 * try and open.
495 static int
496 file_spath(sp, frp, sbp, existsp)
497 SCR *sp;
498 FREF *frp;
499 struct stat *sbp;
500 int *existsp;
502 CHAR_T savech;
503 size_t len;
504 int found;
505 char *name, *p, *t, path[MAXPATHLEN];
508 * If the name is NULL or an explicit reference (i.e., the first
509 * component is . or ..) ignore the O_PATH option.
511 name = frp->name;
512 if (name == NULL) {
513 *existsp = 0;
514 return (0);
516 if (name[0] == '/' || (name[0] == '.' &&
517 (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
518 *existsp = !stat(name, sbp);
519 return (0);
522 /* Try . */
523 if (!stat(name, sbp)) {
524 *existsp = 1;
525 return (0);
528 /* Try the O_PATH option values. */
529 for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
530 if (*p == ':' || *p == '\0') {
531 if (t < p - 1) {
532 savech = *p;
533 *p = '\0';
534 len = snprintf(path,
535 sizeof(path), "%s/%s", t, name);
536 *p = savech;
537 if (!stat(path, sbp)) {
538 found = 1;
539 break;
542 t = p + 1;
543 if (*p == '\0')
544 break;
547 /* If we found it, build a new pathname and discard the old one. */
548 if (found) {
549 MALLOC_RET(sp, p, char *, len + 1);
550 memcpy(p, path, len + 1);
551 free(frp->name);
552 frp->name = p;
554 *existsp = found;
555 return (0);
559 * file_cinit --
560 * Set up the initial cursor position.
562 static void
563 file_cinit(sp)
564 SCR *sp;
566 GS *gp;
567 MARK m;
568 size_t len;
569 int nb;
570 CHAR_T *wp;
571 size_t wlen;
573 /* Set some basic defaults. */
574 sp->lno = 1;
575 sp->cno = 0;
578 * Historically, initial commands (the -c option) weren't executed
579 * until a file was loaded, e.g. "vi +10 nofile", followed by an
580 * :edit or :tag command, would execute the +10 on the file loaded
581 * by the subsequent command, (assuming that it existed). This
582 * applied as well to files loaded using the tag commands, and we
583 * follow that historic practice. Also, all initial commands were
584 * ex commands and were always executed on the last line of the file.
586 * Otherwise, if no initial command for this file:
587 * If in ex mode, move to the last line, first nonblank character.
588 * If the file has previously been edited, move to the last known
589 * position, and check it for validity.
590 * Otherwise, move to the first line, first nonblank.
592 * This gets called by the file init code, because we may be in a
593 * file of ex commands and we want to execute them from the right
594 * location in the file.
596 nb = 0;
597 gp = sp->gp;
598 if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
599 if (db_last(sp, &sp->lno))
600 return;
601 if (sp->lno == 0) {
602 sp->lno = 1;
603 sp->cno = 0;
605 CHAR2INT(sp, gp->c_option, strlen(gp->c_option) + 1,
606 wp, wlen);
607 if (ex_run_str(sp, "-c option", wp, wlen - 1, 1, 1))
608 return;
609 gp->c_option = NULL;
610 } else if (F_ISSET(sp, SC_EX)) {
611 if (db_last(sp, &sp->lno))
612 return;
613 if (sp->lno == 0) {
614 sp->lno = 1;
615 sp->cno = 0;
616 return;
618 nb = 1;
619 } else {
620 if (F_ISSET(sp->frp, FR_CURSORSET)) {
621 sp->lno = sp->frp->lno;
622 sp->cno = sp->frp->cno;
624 /* If returning to a file in vi, center the line. */
625 F_SET(sp, SC_SCR_CENTER);
626 } else {
627 if (O_ISSET(sp, O_COMMENT))
628 file_comment(sp);
629 else
630 sp->lno = 1;
631 nb = 1;
633 if (db_get(sp, sp->lno, 0, NULL, &len)) {
634 sp->lno = 1;
635 sp->cno = 0;
636 return;
638 if (!nb && sp->cno > len)
639 nb = 1;
641 if (nb) {
642 sp->cno = 0;
643 (void)nonblank(sp, sp->lno, &sp->cno);
647 * !!!
648 * The initial column is also the most attractive column.
650 sp->rcm = sp->cno;
653 * !!!
654 * Historically, vi initialized the absolute mark, but ex did not.
655 * Which meant, that if the first command in ex mode was "visual",
656 * or if an ex command was executed first (e.g. vi +10 file) vi was
657 * entered without the mark being initialized. For consistency, if
658 * the file isn't empty, we initialize it for everyone, believing
659 * that it can't hurt, and is generally useful. Not initializing it
660 * if the file is empty is historic practice, although it has always
661 * been possible to set (and use) marks in empty vi files.
663 m.lno = sp->lno;
664 m.cno = sp->cno;
665 (void)mark_set(sp, ABSMARK1, &m, 0);
669 * file_end --
670 * Stop editing a file.
672 * PUBLIC: int file_end __P((SCR *, EXF *, int));
675 file_end(sp, ep, force)
676 SCR *sp;
677 EXF *ep;
678 int force;
680 FREF *frp;
683 * !!!
684 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
685 * (If argument ep is NULL, use sp->ep.)
687 * If multiply referenced, just decrement the count and return.
689 if (ep == NULL)
690 ep = sp->ep;
691 if (--ep->refcnt != 0)
692 return (0);
696 * Clean up the FREF structure.
698 * Save the cursor location.
700 * XXX
701 * It would be cleaner to do this somewhere else, but by the time
702 * ex or vi knows that we're changing files it's already happened.
704 frp = sp->frp;
705 frp->lno = sp->lno;
706 frp->cno = sp->cno;
707 F_SET(frp, FR_CURSORSET);
710 * We may no longer need the temporary backing file, so clean it
711 * up. We don't need the FREF structure either, if the file was
712 * never named, so lose it.
714 * !!!
715 * Re: FR_DONTDELETE, see the comment above in file_init().
717 if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
718 if (unlink(frp->tname))
719 msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
720 free(frp->tname);
721 frp->tname = NULL;
722 if (F_ISSET(frp, FR_TMPFILE)) {
723 CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
724 if (frp->name != NULL)
725 free(frp->name);
726 free(frp);
728 sp->frp = NULL;
732 * Clean up the EXF structure.
734 * Close the db structure.
736 if (ep->db->close != NULL) {
737 if ((sp->db_error = ep->db->close(ep->db, DB_NOSYNC)) != 0 &&
738 !force) {
739 msgq_str(sp, M_DBERR, frp->name, "241|%s: close");
740 ++ep->refcnt;
741 return (1);
743 ep->db = NULL;
746 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
748 /* Stop logging. */
749 (void)log_end(sp, ep);
751 /* Free up any marks. */
752 (void)mark_end(sp, ep);
755 * Delete recovery files, close the open descriptor, free recovery
756 * memory. See recover.c for a description of the protocol.
758 * XXX
759 * Unlink backup file first, we can detect that the recovery file
760 * doesn't reference anything when the user tries to recover it.
761 * There's a race, here, obviously, but it's fairly small.
763 if (!F_ISSET(ep, F_RCV_NORM)) {
764 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
765 msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
766 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
767 msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
769 CIRCLEQ_REMOVE(&sp->gp->exfq, ep, q);
770 if (ep->fd != -1)
771 (void)close(ep->fd);
772 if (ep->fcntl_fd != -1)
773 (void)close(ep->fcntl_fd);
774 if (ep->rcv_fd != -1)
775 (void)close(ep->rcv_fd);
776 if (ep->rcv_path != NULL)
777 free(ep->rcv_path);
778 if (ep->rcv_mpath != NULL)
779 free(ep->rcv_mpath);
781 free(ep);
782 return (0);
786 * file_write --
787 * Write the file to disk. Historic vi had fairly convoluted
788 * semantics for whether or not writes would happen. That's
789 * why all the flags.
791 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
794 file_write(sp, fm, tm, name, flags)
795 SCR *sp;
796 MARK *fm, *tm;
797 char *name;
798 int flags;
800 enum { NEWFILE, OLDFILE } mtype;
801 struct stat sb;
802 EXF *ep;
803 FILE *fp;
804 FREF *frp;
805 MARK from, to;
806 size_t len;
807 u_long nlno, nch;
808 int fd, nf, noname, oflags, rval;
809 char *p, *s, *t, buf[MAXPATHLEN + 64];
810 const char *msgstr;
812 ep = sp->ep;
813 frp = sp->frp;
816 * Writing '%', or naming the current file explicitly, has the
817 * same semantics as writing without a name.
819 if (name == NULL || !strcmp(name, frp->name)) {
820 noname = 1;
821 name = frp->name;
822 } else
823 noname = 0;
825 /* Can't write files marked read-only, unless forced. */
826 if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
827 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
828 "244|Read-only file, not written; use ! to override" :
829 "245|Read-only file, not written");
830 return (1);
833 /* If not forced, not appending, and "writeany" not set ... */
834 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
835 /* Don't overwrite anything but the original file. */
836 if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
837 !stat(name, &sb)) {
838 msgq_str(sp, M_ERR, name,
839 LF_ISSET(FS_POSSIBLE) ?
840 "246|%s exists, not written; use ! to override" :
841 "247|%s exists, not written");
842 return (1);
846 * Don't write part of any existing file. Only test for the
847 * original file, the previous test catches anything else.
849 if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
850 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
851 "248|Partial file, not written; use ! to override" :
852 "249|Partial file, not written");
853 return (1);
858 * Figure out if the file already exists -- if it doesn't, we display
859 * the "new file" message. The stat might not be necessary, but we
860 * just repeat it because it's easier than hacking the previous tests.
861 * The information is only used for the user message and modification
862 * time test, so we can ignore the obvious race condition.
864 * One final test. If we're not forcing or appending the current file,
865 * and we have a saved modification time, object if the file changed
866 * since we last edited or wrote it, and make them force it.
868 if (stat(name, &sb))
869 mtype = NEWFILE;
870 else {
871 if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
872 ((F_ISSET(ep, F_DEVSET) &&
873 (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
874 sb.st_mtime != ep->mtime)) {
875 msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
876 "250|%s: file modified more recently than this copy; use ! to override" :
877 "251|%s: file modified more recently than this copy");
878 return (1);
881 mtype = OLDFILE;
884 /* Set flags to create, write, and either append or truncate. */
885 oflags = O_CREAT | O_WRONLY |
886 (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
888 /* Backup the file if requested. */
889 if (!opts_empty(sp, O_BACKUP, 1) &&
890 file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
891 return (1);
893 /* Open the file. */
894 SIGBLOCK;
895 if ((fd = open(name, oflags,
896 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
897 msgq_str(sp, M_SYSERR, name, "%s");
898 SIGUNBLOCK;
899 return (1);
901 SIGUNBLOCK;
903 /* Try and get a lock. */
904 if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
905 msgq_str(sp, M_ERR, name,
906 "252|%s: write lock was unavailable");
908 #if __linux__
910 * XXX
911 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
912 * This bug is fixed in libc 4.6.x.
914 * This code works around this problem for libc 4.5.x users.
915 * Note that this code is harmless if you're using libc 4.6.x.
917 if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
918 msgq(sp, M_SYSERR, name);
919 return (1);
921 #endif
924 * Use stdio for buffering.
926 * XXX
927 * SVR4.2 requires the fdopen mode exactly match the original open
928 * mode, i.e. you have to open with "a" if appending.
930 if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
931 msgq_str(sp, M_SYSERR, name, "%s");
932 (void)close(fd);
933 return (1);
936 /* Build fake addresses, if necessary. */
937 if (fm == NULL) {
938 from.lno = 1;
939 from.cno = 0;
940 fm = &from;
941 if (db_last(sp, &to.lno))
942 return (1);
943 to.cno = 0;
944 tm = &to;
947 rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
950 * Save the new last modification time -- even if the write fails
951 * we re-init the time. That way the user can clean up the disk
952 * and rewrite without having to force it.
954 if (noname) {
955 if (stat(name, &sb))
956 time(&ep->mtime);
957 else {
958 F_SET(ep, F_DEVSET);
959 ep->mdev = sb.st_dev;
960 ep->minode = sb.st_ino;
962 ep->mtime = sb.st_mtime;
967 * If the write failed, complain loudly. ex_writefp() has already
968 * complained about the actual error, reinforce it if data was lost.
970 if (rval) {
971 if (!LF_ISSET(FS_APPEND))
972 msgq_str(sp, M_ERR, name,
973 "254|%s: WARNING: FILE TRUNCATED");
974 return (1);
978 * Once we've actually written the file, it doesn't matter that the
979 * file name was changed -- if it was, we've already whacked it.
981 F_CLR(frp, FR_NAMECHANGE);
984 * If wrote the entire file, and it wasn't by appending it to a file,
985 * clear the modified bit. If the file was written to the original
986 * file name and the file is a temporary, set the "no exit" bit. This
987 * permits the user to write the file and use it in the context of the
988 * filesystem, but still keeps them from discarding their changes by
989 * exiting.
991 if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
992 F_CLR(ep, F_MODIFIED);
993 if (F_ISSET(frp, FR_TMPFILE)) {
994 if (noname)
995 F_SET(frp, FR_TMPEXIT);
996 else
997 F_CLR(frp, FR_TMPEXIT);
1001 p = msg_print(sp, name, &nf);
1002 switch (mtype) {
1003 case NEWFILE:
1004 msgstr = msg_cat(sp,
1005 "256|%s: new file: %lu lines, %lu characters", NULL);
1006 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1007 break;
1008 case OLDFILE:
1009 msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
1010 "315|%s: appended: %lu lines, %lu characters" :
1011 "257|%s: %lu lines, %lu characters", NULL);
1012 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1013 break;
1014 default:
1015 abort();
1019 * There's a nasty problem with long path names. Cscope and tags files
1020 * can result in long paths and vi will request a continuation key from
1021 * the user. Unfortunately, the user has typed ahead, and chaos will
1022 * result. If we assume that the characters in the filenames only take
1023 * a single screen column each, we can trim the filename.
1025 s = buf;
1026 if (len >= sp->cols) {
1027 for (s = buf, t = buf + strlen(p); s < t &&
1028 (*s != '/' || len >= sp->cols - 3); ++s, --len);
1029 if (s == t)
1030 s = buf;
1031 else {
1032 *--s = '.'; /* Leading ellipses. */
1033 *--s = '.';
1034 *--s = '.';
1037 msgq(sp, M_INFO, s);
1038 if (nf)
1039 FREE_SPACE(sp, p, 0);
1040 return (0);
1044 * file_backup --
1045 * Backup the about-to-be-written file.
1047 * XXX
1048 * We do the backup by copying the entire file. It would be nice to do
1049 * a rename instead, but: (1) both files may not fit and we want to fail
1050 * before doing the rename; (2) the backup file may not be on the same
1051 * disk partition as the file being written; (3) there may be optional
1052 * file information (MACs, DACs, whatever) that we won't get right if we
1053 * recreate the file. So, let's not risk it.
1055 static int
1056 file_backup(sp, name, bname)
1057 SCR *sp;
1058 char *name, *bname;
1060 struct dirent *dp;
1061 struct stat sb;
1062 DIR *dirp;
1063 EXCMD cmd;
1064 off_t off;
1065 size_t blen;
1066 int flags, maxnum, nr, num, nw, rfd, wfd, version;
1067 char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];
1068 CHAR_T *wp;
1069 size_t wlen;
1070 size_t nlen;
1071 char *d = NULL;
1073 rfd = wfd = -1;
1074 bp = estr = wfname = NULL;
1077 * Open the current file for reading. Do this first, so that
1078 * we don't exec a shell before the most likely failure point.
1079 * If it doesn't exist, it's okay, there's just nothing to back
1080 * up.
1082 errno = 0;
1083 if ((rfd = open(name, O_RDONLY, 0)) < 0) {
1084 if (errno == ENOENT)
1085 return (0);
1086 estr = name;
1087 goto err;
1091 * If the name starts with an 'N' character, add a version number
1092 * to the name. Strip the leading N from the string passed to the
1093 * expansion routines, for no particular reason. It would be nice
1094 * to permit users to put the version number anywhere in the backup
1095 * name, but there isn't a special character that we can use in the
1096 * name, and giving a new character a special meaning leads to ugly
1097 * hacks both here and in the supporting ex routines.
1099 * Shell and file name expand the option's value.
1101 ex_cinit(sp, &cmd, 0, 0, 0, 0, 0);
1102 if (bname[0] == 'N') {
1103 version = 1;
1104 ++bname;
1105 } else
1106 version = 0;
1107 CHAR2INT(sp, bname, strlen(bname) + 1, wp, wlen);
1108 if (argv_exp2(sp, &cmd, wp, wlen - 1))
1109 return (1);
1112 * 0 args: impossible.
1113 * 1 args: use it.
1114 * >1 args: object, too many args.
1116 if (cmd.argc != 1) {
1117 msgq_str(sp, M_ERR, bname,
1118 "258|%s expanded into too many file names");
1119 (void)close(rfd);
1120 return (1);
1124 * If appending a version number, read through the directory, looking
1125 * for file names that match the name followed by a number. Make all
1126 * of the other % characters in name literal, so the user doesn't get
1127 * surprised and sscanf doesn't drop core indirecting through pointers
1128 * that don't exist. If any such files are found, increment its number
1129 * by one.
1131 if (version) {
1132 GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1133 INT2CHAR(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1134 p, nlen);
1135 d = strdup(p);
1136 p = d;
1137 for (t = bp, slash = NULL;
1138 p[0] != '\0'; *t++ = *p++)
1139 if (p[0] == '%') {
1140 if (p[1] != '%')
1141 *t++ = '%';
1142 } else if (p[0] == '/')
1143 slash = t;
1144 pct = t;
1145 *t++ = '%';
1146 *t++ = 'd';
1147 *t = '\0';
1149 if (slash == NULL) {
1150 dirp = opendir(".");
1151 p = bp;
1152 } else {
1153 *slash = '\0';
1154 dirp = opendir(bp);
1155 *slash = '/';
1156 p = slash + 1;
1158 if (dirp == NULL) {
1159 INT2CHAR(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1160 estr, nlen);
1161 goto err;
1164 for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1165 if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1166 maxnum = num;
1167 (void)closedir(dirp);
1169 /* Format the backup file name. */
1170 (void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1171 wfname = bp;
1172 } else {
1173 bp = NULL;
1174 INT2CHAR(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1175 wfname, nlen);
1178 /* Open the backup file, avoiding lurkers. */
1179 if (stat(wfname, &sb) == 0) {
1180 if (!S_ISREG(sb.st_mode)) {
1181 msgq_str(sp, M_ERR, bname,
1182 "259|%s: not a regular file");
1183 goto err;
1185 if (sb.st_uid != getuid()) {
1186 msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
1187 goto err;
1189 if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1190 msgq_str(sp, M_ERR, bname,
1191 "261|%s: accessible by a user other than the owner");
1192 goto err;
1194 flags = O_TRUNC;
1195 } else
1196 flags = O_CREAT | O_EXCL;
1197 if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
1198 estr = bname;
1199 goto err;
1202 /* Copy the file's current contents to its backup value. */
1203 while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1204 for (off = 0; nr != 0; nr -= nw, off += nw)
1205 if ((nw = write(wfd, buf + off, nr)) < 0) {
1206 estr = wfname;
1207 goto err;
1209 if (nr < 0) {
1210 estr = name;
1211 goto err;
1214 if (close(rfd)) {
1215 estr = name;
1216 goto err;
1218 if (close(wfd)) {
1219 estr = wfname;
1220 goto err;
1222 if (bp != NULL)
1223 FREE_SPACE(sp, bp, blen);
1224 return (0);
1226 alloc_err:
1227 err: if (rfd != -1)
1228 (void)close(rfd);
1229 if (wfd != -1) {
1230 (void)unlink(wfname);
1231 (void)close(wfd);
1233 if (estr)
1234 msgq_str(sp, M_SYSERR, estr, "%s");
1235 if (d != NULL)
1236 free(d);
1237 if (bp != NULL)
1238 FREE_SPACE(sp, bp, blen);
1239 return (1);
1243 * file_comment --
1244 * Skip the first comment.
1246 static void
1247 file_comment(sp)
1248 SCR *sp;
1250 db_recno_t lno;
1251 size_t len;
1252 CHAR_T *p;
1254 for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1255 if (p == NULL)
1256 return;
1257 if (p[0] == '#') {
1258 F_SET(sp, SC_SCR_TOP);
1259 while (!db_get(sp, ++lno, 0, &p, &len))
1260 if (len < 1 || p[0] != '#') {
1261 sp->lno = lno;
1262 return;
1264 } else if (len > 1 && p[0] == '/' && p[1] == '*') {
1265 F_SET(sp, SC_SCR_TOP);
1266 do {
1267 for (; len > 1; --len, ++p)
1268 if (p[0] == '*' && p[1] == '/') {
1269 sp->lno = lno;
1270 return;
1272 } while (!db_get(sp, ++lno, 0, &p, &len));
1273 } else if (len > 1 && p[0] == '/' && p[1] == '/') {
1274 F_SET(sp, SC_SCR_TOP);
1275 while (!db_get(sp, ++lno, 0, &p, &len))
1276 if (len < 1 || p[0] != '/' || p[1] != '/') {
1277 sp->lno = lno;
1278 return;
1284 * file_m1 --
1285 * First modification check routine. The :next, :prev, :rewind, :tag,
1286 * :tagpush, :tagpop, ^^ modifications check.
1288 * PUBLIC: int file_m1 __P((SCR *, int, int));
1291 file_m1(sp, force, flags)
1292 SCR *sp;
1293 int force, flags;
1295 EXF *ep;
1297 ep = sp->ep;
1299 /* If no file loaded, return no modifications. */
1300 if (ep == NULL)
1301 return (0);
1304 * If the file has been modified, we'll want to write it back or
1305 * fail. If autowrite is set, we'll write it back automatically,
1306 * unless force is also set. Otherwise, we fail unless forced or
1307 * there's another open screen on this file.
1309 if (F_ISSET(ep, F_MODIFIED)) {
1310 if (O_ISSET(sp, O_AUTOWRITE)) {
1311 if (!force && file_aw(sp, flags))
1312 return (1);
1313 } else if (ep->refcnt <= 1 && !force) {
1314 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1315 "262|File modified since last complete write; write or use ! to override" :
1316 "263|File modified since last complete write; write or use :edit! to override");
1317 return (1);
1321 return (file_m3(sp, force));
1325 * file_m2 --
1326 * Second modification check routine. The :edit, :quit, :recover
1327 * modifications check.
1329 * PUBLIC: int file_m2 __P((SCR *, int));
1332 file_m2(sp, force)
1333 SCR *sp;
1334 int force;
1336 EXF *ep;
1338 ep = sp->ep;
1340 /* If no file loaded, return no modifications. */
1341 if (ep == NULL)
1342 return (0);
1345 * If the file has been modified, we'll want to fail, unless forced
1346 * or there's another open screen on this file.
1348 if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1349 msgq(sp, M_ERR,
1350 "264|File modified since last complete write; write or use ! to override");
1351 return (1);
1354 return (file_m3(sp, force));
1358 * file_m3 --
1359 * Third modification check routine.
1361 * PUBLIC: int file_m3 __P((SCR *, int));
1364 file_m3(sp, force)
1365 SCR *sp;
1366 int force;
1368 EXF *ep;
1370 ep = sp->ep;
1372 /* If no file loaded, return no modifications. */
1373 if (ep == NULL)
1374 return (0);
1377 * Don't exit while in a temporary files if the file was ever modified.
1378 * The problem is that if the user does a ":wq", we write and quit,
1379 * unlinking the temporary file. Not what the user had in mind at all.
1380 * We permit writing to temporary files, so that user maps using file
1381 * system names work with temporary files.
1383 if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1384 msgq(sp, M_ERR,
1385 "265|File is a temporary; exit will discard modifications");
1386 return (1);
1388 return (0);
1392 * file_aw --
1393 * Autowrite routine. If modified, autowrite is set and the readonly bit
1394 * is not set, write the file. A routine so there's a place to put the
1395 * comment.
1397 * PUBLIC: int file_aw __P((SCR *, int));
1400 file_aw(sp, flags)
1401 SCR *sp;
1402 int flags;
1404 if (!F_ISSET(sp->ep, F_MODIFIED))
1405 return (0);
1406 if (!O_ISSET(sp, O_AUTOWRITE))
1407 return (0);
1410 * !!!
1411 * Historic 4BSD vi attempted to write the file if autowrite was set,
1412 * regardless of the writeability of the file (as defined by the file
1413 * readonly flag). System V changed this as some point, not attempting
1414 * autowrite if the file was readonly. This feels like a bug fix to
1415 * me (e.g. the principle of least surprise is violated if readonly is
1416 * set and vi writes the file), so I'm compatible with System V.
1418 if (O_ISSET(sp, O_READONLY)) {
1419 msgq(sp, M_INFO,
1420 "266|File readonly, modifications not auto-written");
1421 return (1);
1423 return (file_write(sp, NULL, NULL, NULL, flags));
1427 * set_alt_name --
1428 * Set the alternate pathname.
1430 * Set the alternate pathname. It's a routine because I wanted some place
1431 * to hang this comment. The alternate pathname (normally referenced using
1432 * the special character '#' during file expansion and in the vi ^^ command)
1433 * is set by almost all ex commands that take file names as arguments. The
1434 * rules go something like this:
1436 * 1: If any ex command takes a file name as an argument (except for the
1437 * :next command), the alternate pathname is set to that file name.
1438 * This excludes the command ":e" and ":w !command" as no file name
1439 * was specified. Note, historically, the :source command did not set
1440 * the alternate pathname. It does in nvi, for consistency.
1442 * 2: However, if any ex command sets the current pathname, e.g. the
1443 * ":e file" or ":rew" commands succeed, then the alternate pathname
1444 * is set to the previous file's current pathname, if it had one.
1445 * This includes the ":file" command and excludes the ":e" command.
1446 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1447 * pathname will be "foo", if it succeeds, the alternate pathname will
1448 * be the previous current pathname. The ":e" command will not set
1449 * the alternate or current pathnames regardless.
1451 * 3: However, if it's a read or write command with a file argument and
1452 * the current pathname has not yet been set, the file name becomes
1453 * the current pathname, and the alternate pathname is unchanged.
1455 * If the user edits a temporary file, there may be times when there is no
1456 * alternative file name. A name argument of NULL turns it off.
1458 * PUBLIC: void set_alt_name __P((SCR *, char *));
1460 void
1461 set_alt_name(sp, name)
1462 SCR *sp;
1463 char *name;
1465 if (sp->alt_name != NULL)
1466 free(sp->alt_name);
1467 if (name == NULL)
1468 sp->alt_name = NULL;
1469 else if ((sp->alt_name = strdup(name)) == NULL)
1470 msgq(sp, M_SYSERR, NULL);
1474 * file_lock --
1475 * Get an exclusive lock on a file.
1477 * XXX
1478 * The default locking is flock(2) style, not fcntl(2). The latter is
1479 * known to fail badly on some systems, and its only advantage is that
1480 * it occasionally works over NFS.
1482 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1483 * two-fold: you can't close any file descriptor associated with the file
1484 * without losing all of the locks, and you can't get an exclusive lock
1485 * unless you have the file open for writing. Someone ought to be shot,
1486 * but it's probably too late, they may already have reproduced. To get
1487 * around these problems, nvi opens the files for writing when it can and
1488 * acquires a second file descriptor when it can't. The recovery files
1489 * are examples of the former, they're always opened for writing. The DB
1490 * files can't be opened for writing because the semantics of DB are that
1491 * files opened for writing are flushed back to disk when the DB session
1492 * is ended. So, in that case we have to acquire an extra file descriptor.
1494 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1496 lockr_t
1497 file_lock(sp, name, fdp, fd, iswrite)
1498 SCR *sp;
1499 char *name;
1500 int *fdp, fd, iswrite;
1502 if (!O_ISSET(sp, O_LOCKFILES))
1503 return (LOCK_SUCCESS);
1505 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1507 * !!!
1508 * We need to distinguish a lock not being available for the file
1509 * from the file system not supporting locking. Flock is documented
1510 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1511 * they are the former. There's no portable way to do this.
1513 errno = 0;
1514 return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
1515 #ifdef EWOULDBLOCK
1516 || errno == EWOULDBLOCK
1517 #endif
1518 ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
1519 #endif
1520 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1522 struct flock arg;
1523 int didopen, sverrno;
1525 arg.l_type = F_WRLCK;
1526 arg.l_whence = 0; /* SEEK_SET */
1527 arg.l_start = arg.l_len = 0;
1528 arg.l_pid = 0;
1531 * If the file descriptor isn't opened for writing, it must fail.
1532 * If we fail because we can't get a read/write file descriptor,
1533 * we return LOCK_SUCCESS, believing that the file is readonly
1534 * and that will be sufficient to warn the user.
1536 if (!iswrite) {
1537 if (name == NULL || fdp == NULL)
1538 return (LOCK_FAILED);
1539 if ((fd = open(name, O_RDWR, 0)) == -1)
1540 return (LOCK_SUCCESS);
1541 *fdp = fd;
1542 didopen = 1;
1545 errno = 0;
1546 if (!fcntl(fd, F_SETLK, &arg))
1547 return (LOCK_SUCCESS);
1548 if (didopen) {
1549 sverrno = errno;
1550 (void)close(fd);
1551 errno = sverrno;
1555 * !!!
1556 * We need to distinguish a lock not being available for the file
1557 * from the file system not supporting locking. Fcntl is documented
1558 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1559 * and assume they are the former. There's no portable way to do this.
1561 return (errno == EACCES || errno == EAGAIN
1562 #ifdef EWOULDBLOCK
1563 || errno == EWOULDBLOCK
1564 #endif
1565 ? LOCK_UNAVAIL : LOCK_FAILED);
1567 #endif
1568 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1569 return (LOCK_SUCCESS);
1570 #endif