NULLify closed db and don't call db_last on a closed db in ip_refresh
[nvi.git] / common / exf.c
blob48e7aed12cda07df1a350a99f7381728af27f352
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.57 2000/07/19 18:31:51 skimo Exp $ (Berkeley) $Date: 2000/07/19 18:31:51 $";
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;
137 char *oname, tname[MAXPATHLEN];
139 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);
282 if ((sp->db_error = ep->db->open(ep->db, ep->rcv_path, NULL,
283 DB_RECNO, ((rcv_name == 0) ? DB_TRUNCATE : 0),
284 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) != 0) {
285 msgq_str(sp,
286 M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s");
288 * !!!
289 * Historically, vi permitted users to edit files that couldn't
290 * be read. This isn't useful for single files from a command
291 * line, but it's quite useful for "vi *.c", since you can skip
292 * past files that you can't read.
294 open_err = 1;
295 ep->db = NULL; /* Don't close it */
296 goto oerr;
300 * Do the remaining things that can cause failure of the new file,
301 * mark and logging initialization.
303 if (mark_init(sp, ep) || log_init(sp, ep))
304 goto err;
306 postinit:
308 * Set the alternate file name to be the file we're discarding.
310 * !!!
311 * Temporary files can't become alternate files, so there's no file
312 * name. This matches historical practice, although it could only
313 * happen in historical vi as the result of the initial command, i.e.
314 * if vi was executed without a file name.
316 if (LF_ISSET(FS_SETALT))
317 set_alt_name(sp, sp->frp == NULL ||
318 F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
321 * Close the previous file; if that fails, close the new one and run
322 * for the border.
324 * !!!
325 * There's a nasty special case. If the user edits a temporary file,
326 * and then does an ":e! %", we need to re-initialize the backing
327 * file, but we can't change the name. (It's worse -- we're dealing
328 * with *names* here, we can't even detect that it happened.) Set a
329 * flag so that the file_end routine ignores the backing information
330 * of the old file if it happens to be the same as the new one.
332 * !!!
333 * Side-effect: after the call to file_end(), sp->frp may be NULL.
335 if (sp->ep != NULL) {
336 F_SET(frp, FR_DONTDELETE);
337 if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
338 (void)file_end(sp, ep, 1);
339 goto err;
341 F_CLR(frp, FR_DONTDELETE);
345 * Lock the file; if it's a recovery file, it should already be
346 * locked. Note, we acquire the lock after the previous file
347 * has been ended, so that we don't get an "already locked" error
348 * for ":edit!".
350 * XXX
351 * While the user can't interrupt us between the open and here,
352 * there's a race between the dbopen() and the lock. Not much
353 * we can do about it.
355 * XXX
356 * We don't make a big deal of not being able to lock the file. As
357 * locking rarely works over NFS, and often fails if the file was
358 * mmap(2)'d, it's far too common to do anything like print an error
359 * message, let alone make the file readonly. At some future time,
360 * when locking is a little more reliable, this should change to be
361 * an error.
363 if (rcv_name == NULL && ep->refcnt == 0) {
364 if ((ep->fd = open(oname, O_RDONLY)) == -1)
365 goto no_lock;
367 /* DB 3 appears to not return the fd of re_source
368 if (ep->db->fd(ep->db, &fd) != 0)
369 goto no_lock;
372 switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 0)) {
373 case LOCK_FAILED:
374 no_lock:
375 F_SET(frp, FR_UNLOCKED);
376 break;
377 case LOCK_UNAVAIL:
378 readonly = 1;
379 msgq_str(sp, M_INFO, oname,
380 "239|%s already locked, session is read-only");
381 break;
382 case LOCK_SUCCESS:
383 break;
388 * Historically, the readonly edit option was set per edit buffer in
389 * vi, unless the -R command-line option was specified or the program
390 * was executed as "view". (Well, to be truthful, if the letter 'w'
391 * occurred anywhere in the program name, but let's not get into that.)
392 * So, the persistant readonly state has to be stored in the screen
393 * structure, and the edit option value toggles with the contents of
394 * the edit buffer. If the persistant readonly flag is set, set the
395 * readonly edit option.
397 * Otherwise, try and figure out if a file is readonly. This is a
398 * dangerous thing to do. The kernel is the only arbiter of whether
399 * or not a file is writeable, and the best that a user program can
400 * do is guess. Obvious loopholes are files that are on a file system
401 * mounted readonly (access catches this one on a few systems), or
402 * alternate protection mechanisms, ACL's for example, that we can't
403 * portably check. Lots of fun, and only here because users whined.
405 * !!!
406 * Historic vi displayed the readonly message if none of the file
407 * write bits were set, or if an an access(2) call on the path
408 * failed. This seems reasonable. If the file is mode 444, root
409 * users may want to know that the owner of the file did not expect
410 * it to be written.
412 * Historic vi set the readonly bit if no write bits were set for
413 * a file, even if the access call would have succeeded. This makes
414 * the superuser force the write even when vi expects that it will
415 * succeed. I'm less supportive of this semantic, but it's historic
416 * practice and the conservative approach to vi'ing files as root.
418 * It would be nice if there was some way to update this when the user
419 * does a "^Z; chmod ...". The problem is that we'd first have to
420 * distinguish between readonly bits set because of file permissions
421 * and those set for other reasons. That's not too hard, but deciding
422 * when to reevaluate the permissions is trickier. An alternative
423 * might be to turn off the readonly bit if the user forces a write
424 * and it succeeds.
426 * XXX
427 * Access(2) doesn't consider the effective uid/gid values. This
428 * probably isn't a problem for vi when it's running standalone.
430 if (readonly || F_ISSET(sp, SC_READONLY) ||
431 (!F_ISSET(frp, FR_NEWFILE) &&
432 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
433 access(frp->name, W_OK))))
434 O_SET(sp, O_READONLY);
435 else
436 O_CLR(sp, O_READONLY);
438 /* Switch... */
439 ++ep->refcnt;
440 sp->ep = ep;
441 sp->frp = frp;
443 /* Set the initial cursor position, queue initial command. */
444 file_cinit(sp);
446 /* Redraw the screen from scratch, schedule a welcome message. */
447 F_SET(sp, SC_SCR_REFORMAT | SC_SCR_TOP | SC_STATUS);
449 /* Append into the chain of file structures. */
450 if (ep->refcnt == 1)
451 CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q);
453 return (0);
455 err: if (frp->name != NULL) {
456 free(frp->name);
457 frp->name = NULL;
459 if (frp->tname != NULL) {
460 (void)unlink(frp->tname);
461 free(frp->tname);
462 frp->tname = NULL;
465 oerr: if (F_ISSET(ep, F_RCV_ON))
466 (void)unlink(ep->rcv_path);
467 if (ep->rcv_path != NULL) {
468 free(ep->rcv_path);
469 ep->rcv_path = NULL;
471 if (ep->db != NULL) {
472 (void)ep->db->close(ep->db, DB_NOSYNC);
473 ep->db = NULL;
475 free(ep);
477 return (open_err && !LF_ISSET(FS_OPENERR) ?
478 file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
482 * file_spath --
483 * Scan the user's path to find the file that we're going to
484 * try and open.
486 static int
487 file_spath(sp, frp, sbp, existsp)
488 SCR *sp;
489 FREF *frp;
490 struct stat *sbp;
491 int *existsp;
493 CHAR_T savech;
494 size_t len;
495 int found;
496 char *name, *p, *t, path[MAXPATHLEN];
499 * If the name is NULL or an explicit reference (i.e., the first
500 * component is . or ..) ignore the O_PATH option.
502 name = frp->name;
503 if (name == NULL) {
504 *existsp = 0;
505 return (0);
507 if (name[0] == '/' || (name[0] == '.' &&
508 (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
509 *existsp = !stat(name, sbp);
510 return (0);
513 /* Try . */
514 if (!stat(name, sbp)) {
515 *existsp = 1;
516 return (0);
519 /* Try the O_PATH option values. */
520 for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
521 if (*p == ':' || *p == '\0') {
522 if (t < p - 1) {
523 savech = *p;
524 *p = '\0';
525 len = snprintf(path,
526 sizeof(path), "%s/%s", t, name);
527 *p = savech;
528 if (!stat(path, sbp)) {
529 found = 1;
530 break;
533 t = p + 1;
534 if (*p == '\0')
535 break;
538 /* If we found it, build a new pathname and discard the old one. */
539 if (found) {
540 MALLOC_RET(sp, p, char *, len + 1);
541 memcpy(p, path, len + 1);
542 free(frp->name);
543 frp->name = p;
545 *existsp = found;
546 return (0);
550 * file_cinit --
551 * Set up the initial cursor position.
553 static void
554 file_cinit(sp)
555 SCR *sp;
557 GS *gp;
558 MARK m;
559 size_t len;
560 int nb;
561 CHAR_T *wp;
562 size_t wlen;
564 /* Set some basic defaults. */
565 sp->lno = 1;
566 sp->cno = 0;
569 * Historically, initial commands (the -c option) weren't executed
570 * until a file was loaded, e.g. "vi +10 nofile", followed by an
571 * :edit or :tag command, would execute the +10 on the file loaded
572 * by the subsequent command, (assuming that it existed). This
573 * applied as well to files loaded using the tag commands, and we
574 * follow that historic practice. Also, all initial commands were
575 * ex commands and were always executed on the last line of the file.
577 * Otherwise, if no initial command for this file:
578 * If in ex mode, move to the last line, first nonblank character.
579 * If the file has previously been edited, move to the last known
580 * position, and check it for validity.
581 * Otherwise, move to the first line, first nonblank.
583 * This gets called by the file init code, because we may be in a
584 * file of ex commands and we want to execute them from the right
585 * location in the file.
587 nb = 0;
588 gp = sp->gp;
589 if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
590 if (db_last(sp, &sp->lno))
591 return;
592 if (sp->lno == 0) {
593 sp->lno = 1;
594 sp->cno = 0;
596 CHAR2INT(sp, gp->c_option, strlen(gp->c_option) + 1,
597 wp, wlen);
598 if (ex_run_str(sp, "-c option", wp, wlen - 1, 1, 1))
599 return;
600 gp->c_option = NULL;
601 } else if (F_ISSET(sp, SC_EX)) {
602 if (db_last(sp, &sp->lno))
603 return;
604 if (sp->lno == 0) {
605 sp->lno = 1;
606 sp->cno = 0;
607 return;
609 nb = 1;
610 } else {
611 if (F_ISSET(sp->frp, FR_CURSORSET)) {
612 sp->lno = sp->frp->lno;
613 sp->cno = sp->frp->cno;
615 /* If returning to a file in vi, center the line. */
616 F_SET(sp, SC_SCR_CENTER);
617 } else {
618 if (O_ISSET(sp, O_COMMENT))
619 file_comment(sp);
620 else
621 sp->lno = 1;
622 nb = 1;
624 if (db_get(sp, sp->lno, 0, NULL, &len)) {
625 sp->lno = 1;
626 sp->cno = 0;
627 return;
629 if (!nb && sp->cno > len)
630 nb = 1;
632 if (nb) {
633 sp->cno = 0;
634 (void)nonblank(sp, sp->lno, &sp->cno);
638 * !!!
639 * The initial column is also the most attractive column.
641 sp->rcm = sp->cno;
644 * !!!
645 * Historically, vi initialized the absolute mark, but ex did not.
646 * Which meant, that if the first command in ex mode was "visual",
647 * or if an ex command was executed first (e.g. vi +10 file) vi was
648 * entered without the mark being initialized. For consistency, if
649 * the file isn't empty, we initialize it for everyone, believing
650 * that it can't hurt, and is generally useful. Not initializing it
651 * if the file is empty is historic practice, although it has always
652 * been possible to set (and use) marks in empty vi files.
654 m.lno = sp->lno;
655 m.cno = sp->cno;
656 (void)mark_set(sp, ABSMARK1, &m, 0);
660 * file_end --
661 * Stop editing a file.
663 * PUBLIC: int file_end __P((SCR *, EXF *, int));
666 file_end(sp, ep, force)
667 SCR *sp;
668 EXF *ep;
669 int force;
671 FREF *frp;
674 * !!!
675 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
676 * (If argument ep is NULL, use sp->ep.)
678 * If multiply referenced, just decrement the count and return.
680 if (ep == NULL)
681 ep = sp->ep;
682 if (--ep->refcnt != 0)
683 return (0);
687 * Clean up the FREF structure.
689 * Save the cursor location.
691 * XXX
692 * It would be cleaner to do this somewhere else, but by the time
693 * ex or vi knows that we're changing files it's already happened.
695 frp = sp->frp;
696 frp->lno = sp->lno;
697 frp->cno = sp->cno;
698 F_SET(frp, FR_CURSORSET);
701 * We may no longer need the temporary backing file, so clean it
702 * up. We don't need the FREF structure either, if the file was
703 * never named, so lose it.
705 * !!!
706 * Re: FR_DONTDELETE, see the comment above in file_init().
708 if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
709 if (unlink(frp->tname))
710 msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
711 free(frp->tname);
712 frp->tname = NULL;
713 if (F_ISSET(frp, FR_TMPFILE)) {
714 CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
715 if (frp->name != NULL)
716 free(frp->name);
717 free(frp);
719 sp->frp = NULL;
723 * Clean up the EXF structure.
725 * Close the db structure.
727 if (ep->db->close != NULL) {
728 if ((sp->db_error = ep->db->close(ep->db, DB_NOSYNC)) != 0 &&
729 !force) {
730 msgq_str(sp, M_DBERR, frp->name, "241|%s: close");
731 ++ep->refcnt;
732 return (1);
734 ep->db = NULL;
737 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
739 /* Stop logging. */
740 (void)log_end(sp, ep);
742 /* Free up any marks. */
743 (void)mark_end(sp, ep);
746 * Delete recovery files, close the open descriptor, free recovery
747 * memory. See recover.c for a description of the protocol.
749 * XXX
750 * Unlink backup file first, we can detect that the recovery file
751 * doesn't reference anything when the user tries to recover it.
752 * There's a race, here, obviously, but it's fairly small.
754 if (!F_ISSET(ep, F_RCV_NORM)) {
755 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
756 msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
757 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
758 msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
760 CIRCLEQ_REMOVE(&sp->gp->exfq, ep, q);
761 if (ep->fd != -1)
762 (void)close(ep->fd);
763 if (ep->fcntl_fd != -1)
764 (void)close(ep->fcntl_fd);
765 if (ep->rcv_fd != -1)
766 (void)close(ep->rcv_fd);
767 if (ep->rcv_path != NULL)
768 free(ep->rcv_path);
769 if (ep->rcv_mpath != NULL)
770 free(ep->rcv_mpath);
772 free(ep);
773 return (0);
777 * file_write --
778 * Write the file to disk. Historic vi had fairly convoluted
779 * semantics for whether or not writes would happen. That's
780 * why all the flags.
782 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
785 file_write(sp, fm, tm, name, flags)
786 SCR *sp;
787 MARK *fm, *tm;
788 char *name;
789 int flags;
791 enum { NEWFILE, OLDFILE } mtype;
792 struct stat sb;
793 EXF *ep;
794 FILE *fp;
795 FREF *frp;
796 MARK from, to;
797 size_t len;
798 u_long nlno, nch;
799 int fd, nf, noname, oflags, rval;
800 char *p, *s, *t, buf[MAXPATHLEN + 64];
801 const char *msgstr;
803 ep = sp->ep;
804 frp = sp->frp;
807 * Writing '%', or naming the current file explicitly, has the
808 * same semantics as writing without a name.
810 if (name == NULL || !strcmp(name, frp->name)) {
811 noname = 1;
812 name = frp->name;
813 } else
814 noname = 0;
816 /* Can't write files marked read-only, unless forced. */
817 if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
818 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
819 "244|Read-only file, not written; use ! to override" :
820 "245|Read-only file, not written");
821 return (1);
824 /* If not forced, not appending, and "writeany" not set ... */
825 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
826 /* Don't overwrite anything but the original file. */
827 if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
828 !stat(name, &sb)) {
829 msgq_str(sp, M_ERR, name,
830 LF_ISSET(FS_POSSIBLE) ?
831 "246|%s exists, not written; use ! to override" :
832 "247|%s exists, not written");
833 return (1);
837 * Don't write part of any existing file. Only test for the
838 * original file, the previous test catches anything else.
840 if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
841 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
842 "248|Partial file, not written; use ! to override" :
843 "249|Partial file, not written");
844 return (1);
849 * Figure out if the file already exists -- if it doesn't, we display
850 * the "new file" message. The stat might not be necessary, but we
851 * just repeat it because it's easier than hacking the previous tests.
852 * The information is only used for the user message and modification
853 * time test, so we can ignore the obvious race condition.
855 * One final test. If we're not forcing or appending the current file,
856 * and we have a saved modification time, object if the file changed
857 * since we last edited or wrote it, and make them force it.
859 if (stat(name, &sb))
860 mtype = NEWFILE;
861 else {
862 if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
863 ((F_ISSET(ep, F_DEVSET) &&
864 (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
865 sb.st_mtime != ep->mtime)) {
866 msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
867 "250|%s: file modified more recently than this copy; use ! to override" :
868 "251|%s: file modified more recently than this copy");
869 return (1);
872 mtype = OLDFILE;
875 /* Set flags to create, write, and either append or truncate. */
876 oflags = O_CREAT | O_WRONLY |
877 (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
879 /* Backup the file if requested. */
880 if (!opts_empty(sp, O_BACKUP, 1) &&
881 file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
882 return (1);
884 /* Open the file. */
885 SIGBLOCK;
886 if ((fd = open(name, oflags,
887 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
888 msgq_str(sp, M_SYSERR, name, "%s");
889 SIGUNBLOCK;
890 return (1);
892 SIGUNBLOCK;
894 /* Try and get a lock. */
895 if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
896 msgq_str(sp, M_ERR, name,
897 "252|%s: write lock was unavailable");
899 #if __linux__
901 * XXX
902 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
903 * This bug is fixed in libc 4.6.x.
905 * This code works around this problem for libc 4.5.x users.
906 * Note that this code is harmless if you're using libc 4.6.x.
908 if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
909 msgq(sp, M_SYSERR, name);
910 return (1);
912 #endif
915 * Use stdio for buffering.
917 * XXX
918 * SVR4.2 requires the fdopen mode exactly match the original open
919 * mode, i.e. you have to open with "a" if appending.
921 if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
922 msgq_str(sp, M_SYSERR, name, "%s");
923 (void)close(fd);
924 return (1);
927 /* Build fake addresses, if necessary. */
928 if (fm == NULL) {
929 from.lno = 1;
930 from.cno = 0;
931 fm = &from;
932 if (db_last(sp, &to.lno))
933 return (1);
934 to.cno = 0;
935 tm = &to;
938 rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
941 * Save the new last modification time -- even if the write fails
942 * we re-init the time. That way the user can clean up the disk
943 * and rewrite without having to force it.
945 if (noname) {
946 if (stat(name, &sb))
947 time(&ep->mtime);
948 else {
949 F_SET(ep, F_DEVSET);
950 ep->mdev = sb.st_dev;
951 ep->minode = sb.st_ino;
953 ep->mtime = sb.st_mtime;
958 * If the write failed, complain loudly. ex_writefp() has already
959 * complained about the actual error, reinforce it if data was lost.
961 if (rval) {
962 if (!LF_ISSET(FS_APPEND))
963 msgq_str(sp, M_ERR, name,
964 "254|%s: WARNING: FILE TRUNCATED");
965 return (1);
969 * Once we've actually written the file, it doesn't matter that the
970 * file name was changed -- if it was, we've already whacked it.
972 F_CLR(frp, FR_NAMECHANGE);
975 * If wrote the entire file, and it wasn't by appending it to a file,
976 * clear the modified bit. If the file was written to the original
977 * file name and the file is a temporary, set the "no exit" bit. This
978 * permits the user to write the file and use it in the context of the
979 * filesystem, but still keeps them from discarding their changes by
980 * exiting.
982 if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
983 F_CLR(ep, F_MODIFIED);
984 if (F_ISSET(frp, FR_TMPFILE)) {
985 if (noname)
986 F_SET(frp, FR_TMPEXIT);
987 else
988 F_CLR(frp, FR_TMPEXIT);
992 p = msg_print(sp, name, &nf);
993 switch (mtype) {
994 case NEWFILE:
995 msgstr = msg_cat(sp,
996 "256|%s: new file: %lu lines, %lu characters", NULL);
997 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
998 break;
999 case OLDFILE:
1000 msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
1001 "315|%s: appended: %lu lines, %lu characters" :
1002 "257|%s: %lu lines, %lu characters", NULL);
1003 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
1004 break;
1005 default:
1006 abort();
1010 * There's a nasty problem with long path names. Cscope and tags files
1011 * can result in long paths and vi will request a continuation key from
1012 * the user. Unfortunately, the user has typed ahead, and chaos will
1013 * result. If we assume that the characters in the filenames only take
1014 * a single screen column each, we can trim the filename.
1016 s = buf;
1017 if (len >= sp->cols) {
1018 for (s = buf, t = buf + strlen(p); s < t &&
1019 (*s != '/' || len >= sp->cols - 3); ++s, --len);
1020 if (s == t)
1021 s = buf;
1022 else {
1023 *--s = '.'; /* Leading ellipses. */
1024 *--s = '.';
1025 *--s = '.';
1028 msgq(sp, M_INFO, s);
1029 if (nf)
1030 FREE_SPACE(sp, p, 0);
1031 return (0);
1035 * file_backup --
1036 * Backup the about-to-be-written file.
1038 * XXX
1039 * We do the backup by copying the entire file. It would be nice to do
1040 * a rename instead, but: (1) both files may not fit and we want to fail
1041 * before doing the rename; (2) the backup file may not be on the same
1042 * disk partition as the file being written; (3) there may be optional
1043 * file information (MACs, DACs, whatever) that we won't get right if we
1044 * recreate the file. So, let's not risk it.
1046 static int
1047 file_backup(sp, name, bname)
1048 SCR *sp;
1049 char *name, *bname;
1051 struct dirent *dp;
1052 struct stat sb;
1053 DIR *dirp;
1054 EXCMD cmd;
1055 off_t off;
1056 size_t blen;
1057 int flags, maxnum, nr, num, nw, rfd, wfd, version;
1058 char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];
1059 CHAR_T *wp;
1060 size_t wlen;
1061 size_t nlen;
1062 char *d = NULL;
1064 rfd = wfd = -1;
1065 bp = estr = wfname = NULL;
1068 * Open the current file for reading. Do this first, so that
1069 * we don't exec a shell before the most likely failure point.
1070 * If it doesn't exist, it's okay, there's just nothing to back
1071 * up.
1073 errno = 0;
1074 if ((rfd = open(name, O_RDONLY, 0)) < 0) {
1075 if (errno == ENOENT)
1076 return (0);
1077 estr = name;
1078 goto err;
1082 * If the name starts with an 'N' character, add a version number
1083 * to the name. Strip the leading N from the string passed to the
1084 * expansion routines, for no particular reason. It would be nice
1085 * to permit users to put the version number anywhere in the backup
1086 * name, but there isn't a special character that we can use in the
1087 * name, and giving a new character a special meaning leads to ugly
1088 * hacks both here and in the supporting ex routines.
1090 * Shell and file name expand the option's value.
1092 ex_cinit(sp, &cmd, 0, 0, 0, 0, 0);
1093 if (bname[0] == 'N') {
1094 version = 1;
1095 ++bname;
1096 } else
1097 version = 0;
1098 CHAR2INT(sp, bname, strlen(bname) + 1, wp, wlen);
1099 if (argv_exp2(sp, &cmd, wp, wlen - 1))
1100 return (1);
1103 * 0 args: impossible.
1104 * 1 args: use it.
1105 * >1 args: object, too many args.
1107 if (cmd.argc != 1) {
1108 msgq_str(sp, M_ERR, bname,
1109 "258|%s expanded into too many file names");
1110 (void)close(rfd);
1111 return (1);
1115 * If appending a version number, read through the directory, looking
1116 * for file names that match the name followed by a number. Make all
1117 * of the other % characters in name literal, so the user doesn't get
1118 * surprised and sscanf doesn't drop core indirecting through pointers
1119 * that don't exist. If any such files are found, increment its number
1120 * by one.
1122 if (version) {
1123 GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1124 INT2CHAR(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1125 p, nlen);
1126 d = strdup(p);
1127 p = d;
1128 for (t = bp, slash = NULL;
1129 p[0] != '\0'; *t++ = *p++)
1130 if (p[0] == '%') {
1131 if (p[1] != '%')
1132 *t++ = '%';
1133 } else if (p[0] == '/')
1134 slash = t;
1135 pct = t;
1136 *t++ = '%';
1137 *t++ = 'd';
1138 *t = '\0';
1140 if (slash == NULL) {
1141 dirp = opendir(".");
1142 p = bp;
1143 } else {
1144 *slash = '\0';
1145 dirp = opendir(bp);
1146 *slash = '/';
1147 p = slash + 1;
1149 if (dirp == NULL) {
1150 INT2CHAR(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1151 estr, nlen);
1152 goto err;
1155 for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1156 if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1157 maxnum = num;
1158 (void)closedir(dirp);
1160 /* Format the backup file name. */
1161 (void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1162 wfname = bp;
1163 } else {
1164 bp = NULL;
1165 INT2CHAR(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1166 wfname, nlen);
1169 /* Open the backup file, avoiding lurkers. */
1170 if (stat(wfname, &sb) == 0) {
1171 if (!S_ISREG(sb.st_mode)) {
1172 msgq_str(sp, M_ERR, bname,
1173 "259|%s: not a regular file");
1174 goto err;
1176 if (sb.st_uid != getuid()) {
1177 msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
1178 goto err;
1180 if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1181 msgq_str(sp, M_ERR, bname,
1182 "261|%s: accessible by a user other than the owner");
1183 goto err;
1185 flags = O_TRUNC;
1186 } else
1187 flags = O_CREAT | O_EXCL;
1188 if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
1189 estr = bname;
1190 goto err;
1193 /* Copy the file's current contents to its backup value. */
1194 while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1195 for (off = 0; nr != 0; nr -= nw, off += nw)
1196 if ((nw = write(wfd, buf + off, nr)) < 0) {
1197 estr = wfname;
1198 goto err;
1200 if (nr < 0) {
1201 estr = name;
1202 goto err;
1205 if (close(rfd)) {
1206 estr = name;
1207 goto err;
1209 if (close(wfd)) {
1210 estr = wfname;
1211 goto err;
1213 if (bp != NULL)
1214 FREE_SPACE(sp, bp, blen);
1215 return (0);
1217 alloc_err:
1218 err: if (rfd != -1)
1219 (void)close(rfd);
1220 if (wfd != -1) {
1221 (void)unlink(wfname);
1222 (void)close(wfd);
1224 if (estr)
1225 msgq_str(sp, M_SYSERR, estr, "%s");
1226 if (d != NULL)
1227 free(d);
1228 if (bp != NULL)
1229 FREE_SPACE(sp, bp, blen);
1230 return (1);
1234 * file_comment --
1235 * Skip the first comment.
1237 static void
1238 file_comment(sp)
1239 SCR *sp;
1241 db_recno_t lno;
1242 size_t len;
1243 CHAR_T *p;
1245 for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1246 if (p == NULL)
1247 return;
1248 if (p[0] == '#') {
1249 F_SET(sp, SC_SCR_TOP);
1250 while (!db_get(sp, ++lno, 0, &p, &len))
1251 if (len < 1 || p[0] != '#') {
1252 sp->lno = lno;
1253 return;
1255 } else if (len > 1 && p[0] == '/' && p[1] == '*') {
1256 F_SET(sp, SC_SCR_TOP);
1257 do {
1258 for (; len > 1; --len, ++p)
1259 if (p[0] == '*' && p[1] == '/') {
1260 sp->lno = lno;
1261 return;
1263 } while (!db_get(sp, ++lno, 0, &p, &len));
1264 } else if (len > 1 && p[0] == '/' && p[1] == '/') {
1265 F_SET(sp, SC_SCR_TOP);
1266 while (!db_get(sp, ++lno, 0, &p, &len))
1267 if (len < 1 || p[0] != '/' || p[1] != '/') {
1268 sp->lno = lno;
1269 return;
1275 * file_m1 --
1276 * First modification check routine. The :next, :prev, :rewind, :tag,
1277 * :tagpush, :tagpop, ^^ modifications check.
1279 * PUBLIC: int file_m1 __P((SCR *, int, int));
1282 file_m1(sp, force, flags)
1283 SCR *sp;
1284 int force, flags;
1286 EXF *ep;
1288 ep = sp->ep;
1290 /* If no file loaded, return no modifications. */
1291 if (ep == NULL)
1292 return (0);
1295 * If the file has been modified, we'll want to write it back or
1296 * fail. If autowrite is set, we'll write it back automatically,
1297 * unless force is also set. Otherwise, we fail unless forced or
1298 * there's another open screen on this file.
1300 if (F_ISSET(ep, F_MODIFIED)) {
1301 if (O_ISSET(sp, O_AUTOWRITE)) {
1302 if (!force && file_aw(sp, flags))
1303 return (1);
1304 } else if (ep->refcnt <= 1 && !force) {
1305 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1306 "262|File modified since last complete write; write or use ! to override" :
1307 "263|File modified since last complete write; write or use :edit! to override");
1308 return (1);
1312 return (file_m3(sp, force));
1316 * file_m2 --
1317 * Second modification check routine. The :edit, :quit, :recover
1318 * modifications check.
1320 * PUBLIC: int file_m2 __P((SCR *, int));
1323 file_m2(sp, force)
1324 SCR *sp;
1325 int force;
1327 EXF *ep;
1329 ep = sp->ep;
1331 /* If no file loaded, return no modifications. */
1332 if (ep == NULL)
1333 return (0);
1336 * If the file has been modified, we'll want to fail, unless forced
1337 * or there's another open screen on this file.
1339 if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1340 msgq(sp, M_ERR,
1341 "264|File modified since last complete write; write or use ! to override");
1342 return (1);
1345 return (file_m3(sp, force));
1349 * file_m3 --
1350 * Third modification check routine.
1352 * PUBLIC: int file_m3 __P((SCR *, int));
1355 file_m3(sp, force)
1356 SCR *sp;
1357 int force;
1359 EXF *ep;
1361 ep = sp->ep;
1363 /* If no file loaded, return no modifications. */
1364 if (ep == NULL)
1365 return (0);
1368 * Don't exit while in a temporary files if the file was ever modified.
1369 * The problem is that if the user does a ":wq", we write and quit,
1370 * unlinking the temporary file. Not what the user had in mind at all.
1371 * We permit writing to temporary files, so that user maps using file
1372 * system names work with temporary files.
1374 if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1375 msgq(sp, M_ERR,
1376 "265|File is a temporary; exit will discard modifications");
1377 return (1);
1379 return (0);
1383 * file_aw --
1384 * Autowrite routine. If modified, autowrite is set and the readonly bit
1385 * is not set, write the file. A routine so there's a place to put the
1386 * comment.
1388 * PUBLIC: int file_aw __P((SCR *, int));
1391 file_aw(sp, flags)
1392 SCR *sp;
1393 int flags;
1395 if (!F_ISSET(sp->ep, F_MODIFIED))
1396 return (0);
1397 if (!O_ISSET(sp, O_AUTOWRITE))
1398 return (0);
1401 * !!!
1402 * Historic 4BSD vi attempted to write the file if autowrite was set,
1403 * regardless of the writeability of the file (as defined by the file
1404 * readonly flag). System V changed this as some point, not attempting
1405 * autowrite if the file was readonly. This feels like a bug fix to
1406 * me (e.g. the principle of least surprise is violated if readonly is
1407 * set and vi writes the file), so I'm compatible with System V.
1409 if (O_ISSET(sp, O_READONLY)) {
1410 msgq(sp, M_INFO,
1411 "266|File readonly, modifications not auto-written");
1412 return (1);
1414 return (file_write(sp, NULL, NULL, NULL, flags));
1418 * set_alt_name --
1419 * Set the alternate pathname.
1421 * Set the alternate pathname. It's a routine because I wanted some place
1422 * to hang this comment. The alternate pathname (normally referenced using
1423 * the special character '#' during file expansion and in the vi ^^ command)
1424 * is set by almost all ex commands that take file names as arguments. The
1425 * rules go something like this:
1427 * 1: If any ex command takes a file name as an argument (except for the
1428 * :next command), the alternate pathname is set to that file name.
1429 * This excludes the command ":e" and ":w !command" as no file name
1430 * was specified. Note, historically, the :source command did not set
1431 * the alternate pathname. It does in nvi, for consistency.
1433 * 2: However, if any ex command sets the current pathname, e.g. the
1434 * ":e file" or ":rew" commands succeed, then the alternate pathname
1435 * is set to the previous file's current pathname, if it had one.
1436 * This includes the ":file" command and excludes the ":e" command.
1437 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1438 * pathname will be "foo", if it succeeds, the alternate pathname will
1439 * be the previous current pathname. The ":e" command will not set
1440 * the alternate or current pathnames regardless.
1442 * 3: However, if it's a read or write command with a file argument and
1443 * the current pathname has not yet been set, the file name becomes
1444 * the current pathname, and the alternate pathname is unchanged.
1446 * If the user edits a temporary file, there may be times when there is no
1447 * alternative file name. A name argument of NULL turns it off.
1449 * PUBLIC: void set_alt_name __P((SCR *, char *));
1451 void
1452 set_alt_name(sp, name)
1453 SCR *sp;
1454 char *name;
1456 if (sp->alt_name != NULL)
1457 free(sp->alt_name);
1458 if (name == NULL)
1459 sp->alt_name = NULL;
1460 else if ((sp->alt_name = strdup(name)) == NULL)
1461 msgq(sp, M_SYSERR, NULL);
1465 * file_lock --
1466 * Get an exclusive lock on a file.
1468 * XXX
1469 * The default locking is flock(2) style, not fcntl(2). The latter is
1470 * known to fail badly on some systems, and its only advantage is that
1471 * it occasionally works over NFS.
1473 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1474 * two-fold: you can't close any file descriptor associated with the file
1475 * without losing all of the locks, and you can't get an exclusive lock
1476 * unless you have the file open for writing. Someone ought to be shot,
1477 * but it's probably too late, they may already have reproduced. To get
1478 * around these problems, nvi opens the files for writing when it can and
1479 * acquires a second file descriptor when it can't. The recovery files
1480 * are examples of the former, they're always opened for writing. The DB
1481 * files can't be opened for writing because the semantics of DB are that
1482 * files opened for writing are flushed back to disk when the DB session
1483 * is ended. So, in that case we have to acquire an extra file descriptor.
1485 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1487 lockr_t
1488 file_lock(sp, name, fdp, fd, iswrite)
1489 SCR *sp;
1490 char *name;
1491 int *fdp, fd, iswrite;
1493 if (!O_ISSET(sp, O_LOCKFILES))
1494 return (LOCK_SUCCESS);
1496 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1498 * !!!
1499 * We need to distinguish a lock not being available for the file
1500 * from the file system not supporting locking. Flock is documented
1501 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1502 * they are the former. There's no portable way to do this.
1504 errno = 0;
1505 return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
1506 #ifdef EWOULDBLOCK
1507 || errno == EWOULDBLOCK
1508 #endif
1509 ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
1510 #endif
1511 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1513 struct flock arg;
1514 int didopen, sverrno;
1516 arg.l_type = F_WRLCK;
1517 arg.l_whence = 0; /* SEEK_SET */
1518 arg.l_start = arg.l_len = 0;
1519 arg.l_pid = 0;
1522 * If the file descriptor isn't opened for writing, it must fail.
1523 * If we fail because we can't get a read/write file descriptor,
1524 * we return LOCK_SUCCESS, believing that the file is readonly
1525 * and that will be sufficient to warn the user.
1527 if (!iswrite) {
1528 if (name == NULL || fdp == NULL)
1529 return (LOCK_FAILED);
1530 if ((fd = open(name, O_RDWR, 0)) == -1)
1531 return (LOCK_SUCCESS);
1532 *fdp = fd;
1533 didopen = 1;
1536 errno = 0;
1537 if (!fcntl(fd, F_SETLK, &arg))
1538 return (LOCK_SUCCESS);
1539 if (didopen) {
1540 sverrno = errno;
1541 (void)close(fd);
1542 errno = sverrno;
1546 * !!!
1547 * We need to distinguish a lock not being available for the file
1548 * from the file system not supporting locking. Fcntl is documented
1549 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1550 * and assume they are the former. There's no portable way to do this.
1552 return (errno == EACCES || errno == EAGAIN
1553 #ifdef EWOULDBLOCK
1554 || errno == EWOULDBLOCK
1555 #endif
1556 ? LOCK_UNAVAIL : LOCK_FAILED);
1558 #endif
1559 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1560 return (LOCK_SUCCESS);
1561 #endif