Use perl's setenv in case an interpreter has been started.
[nvi.git] / common / exf.c
blob4fd057e868179734d0635f9324e85659b67742c3
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.64 2001/06/25 15:19:09 skimo Exp $ (Berkeley) $Date: 2001/06/25 15:19:09 $";
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 ep->c_lno = ep->c_nlines = OOBLNO;
185 ep->rcv_fd = ep->fcntl_fd = -1;
186 F_SET(ep, F_FIRSTMODIFY);
189 * If no name or backing file, for whatever reason, create a backing
190 * temporary file, saving the temp file name so we can later unlink
191 * it. If the user never named this file, copy the temporary file name
192 * to the real name (we display that until the user renames it).
194 oname = frp->name;
195 if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
196 if (opts_empty(sp, O_DIRECTORY, 0))
197 goto err;
198 (void)snprintf(tname, sizeof(tname),
199 "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
200 if ((fd = mkstemp(tname)) == -1) {
201 msgq(sp, M_SYSERR,
202 "237|Unable to create temporary file");
203 goto err;
205 (void)close(fd);
207 if (frp->name == NULL)
208 F_SET(frp, FR_TMPFILE);
209 if ((frp->tname = strdup(tname)) == NULL ||
210 (frp->name == NULL &&
211 (frp->name = strdup(tname)) == NULL)) {
212 if (frp->tname != NULL) {
213 free(frp->tname);
215 msgq(sp, M_SYSERR, NULL);
216 (void)unlink(tname);
217 goto err;
219 oname = frp->tname;
220 psize = 1024;
221 if (!LF_ISSET(FS_OPENERR))
222 F_SET(frp, FR_NEWFILE);
224 time(&ep->mtime);
225 } else {
227 * XXX
228 * A seat of the pants calculation: try to keep the file in
229 * 15 pages or less. Don't use a page size larger than 10K
230 * (vi should have good locality) or smaller than 1K.
232 psize = ((sb.st_size / 15) + 1023) / 1024;
233 if (psize > 10)
234 psize = 10;
235 if (psize == 0)
236 psize = 1;
237 psize *= 1024;
239 F_SET(ep, F_DEVSET);
240 ep->mdev = sb.st_dev;
241 ep->minode = sb.st_ino;
243 ep->mtime = sb.st_mtime;
245 if (!S_ISREG(sb.st_mode))
246 msgq_str(sp, M_ERR, oname,
247 "238|Warning: %s is not a regular file");
250 /* Set up recovery. */
251 if (rcv_name == NULL) {
252 /* ep->rcv_path NULL if rcv_tmp fails */
253 rcv_tmp(sp, ep, frp->name);
254 } else {
255 if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
256 msgq(sp, M_SYSERR, NULL);
257 goto err;
259 F_SET(ep, F_MODIFIED);
262 /* Open a db structure. */
263 if ((sp->db_error = db_create(&ep->db, sp->gp->env, 0)) != 0) {
264 /* XXXX */
265 fprintf(stderr, "db_create %d\n", sp->db_error);
266 goto err;
269 ep->db->set_re_delim(ep->db, '\n'); /* Always set. */
270 ep->db->set_pagesize(ep->db, psize);
271 ep->db->set_flags(ep->db, DB_RENUMBER |
272 (F_ISSET(sp->gp, G_SNAPSHOT) ? DB_SNAPSHOT : 0));
273 if (rcv_name == NULL)
274 ep->db->set_re_source(ep->db, oname);
277 * Don't let db use mmap when using fcntl for locking
279 #ifdef HAVE_LOCK_FCNTL
280 #define NOMMAPIFFCNTL DB_NOMMAP
281 #else
282 #define NOMMAPIFFCNTL 0
283 #endif
285 if ((sp->db_error = ep->db->open(ep->db, ep->rcv_path, NULL, DB_RECNO,
286 ((rcv_name == 0) ? DB_TRUNCATE : 0) | VI_DB_THREAD | NOMMAPIFFCNTL,
287 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) != 0) {
288 msgq_str(sp,
289 M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s");
291 * !!!
292 * Historically, vi permitted users to edit files that couldn't
293 * be read. This isn't useful for single files from a command
294 * line, but it's quite useful for "vi *.c", since you can skip
295 * past files that you can't read.
297 ep->db = NULL; /* Don't close it; it wasn't opened */
299 if (LF_ISSET(FS_OPENERR))
300 goto err;
302 open_err = 1;
303 goto oerr;
307 * Do the remaining things that can cause failure of the new file,
308 * mark and logging initialization.
310 if (mark_init(sp, ep) || log_init(sp, ep))
311 goto err;
313 postinit:
315 * Set the alternate file name to be the file we're discarding.
317 * !!!
318 * Temporary files can't become alternate files, so there's no file
319 * name. This matches historical practice, although it could only
320 * happen in historical vi as the result of the initial command, i.e.
321 * if vi was executed without a file name.
323 if (LF_ISSET(FS_SETALT))
324 set_alt_name(sp, sp->frp == NULL ||
325 F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);
328 * Close the previous file; if that fails, close the new one and run
329 * for the border.
331 * !!!
332 * There's a nasty special case. If the user edits a temporary file,
333 * and then does an ":e! %", we need to re-initialize the backing
334 * file, but we can't change the name. (It's worse -- we're dealing
335 * with *names* here, we can't even detect that it happened.) Set a
336 * flag so that the file_end routine ignores the backing information
337 * of the old file if it happens to be the same as the new one.
339 * !!!
340 * Side-effect: after the call to file_end(), sp->frp may be NULL.
342 if (sp->ep != NULL) {
343 F_SET(frp, FR_DONTDELETE);
344 if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
345 (void)file_end(sp, ep, 1);
346 goto err;
348 sp->ep = NULL;
349 F_CLR(frp, FR_DONTDELETE);
353 * Lock the file; if it's a recovery file, it should already be
354 * locked. Note, we acquire the lock after the previous file
355 * has been ended, so that we don't get an "already locked" error
356 * for ":edit!".
358 * XXX
359 * While the user can't interrupt us between the open and here,
360 * there's a race between the dbopen() and the lock. Not much
361 * we can do about it.
363 * XXX
364 * We don't make a big deal of not being able to lock the file. As
365 * locking rarely works over NFS, and often fails if the file was
366 * mmap(2)'d, it's far too common to do anything like print an error
367 * message, let alone make the file readonly. At some future time,
368 * when locking is a little more reliable, this should change to be
369 * an error.
371 if (rcv_name == NULL && ep->refcnt == 0) {
372 if ((ep->fd = open(oname, O_RDWR)) == -1)
373 goto no_lock;
375 switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 1)) {
376 case LOCK_FAILED:
377 no_lock:
378 F_SET(frp, FR_UNLOCKED);
379 break;
380 case LOCK_UNAVAIL:
381 readonly = 1;
382 msgq_str(sp, M_INFO, oname,
383 "239|%s already locked, session is read-only");
384 break;
385 case LOCK_SUCCESS:
386 break;
391 * Historically, the readonly edit option was set per edit buffer in
392 * vi, unless the -R command-line option was specified or the program
393 * was executed as "view". (Well, to be truthful, if the letter 'w'
394 * occurred anywhere in the program name, but let's not get into that.)
395 * So, the persistant readonly state has to be stored in the screen
396 * structure, and the edit option value toggles with the contents of
397 * the edit buffer. If the persistant readonly flag is set, set the
398 * readonly edit option.
400 * Otherwise, try and figure out if a file is readonly. This is a
401 * dangerous thing to do. The kernel is the only arbiter of whether
402 * or not a file is writeable, and the best that a user program can
403 * do is guess. Obvious loopholes are files that are on a file system
404 * mounted readonly (access catches this one on a few systems), or
405 * alternate protection mechanisms, ACL's for example, that we can't
406 * portably check. Lots of fun, and only here because users whined.
408 * !!!
409 * Historic vi displayed the readonly message if none of the file
410 * write bits were set, or if an an access(2) call on the path
411 * failed. This seems reasonable. If the file is mode 444, root
412 * users may want to know that the owner of the file did not expect
413 * it to be written.
415 * Historic vi set the readonly bit if no write bits were set for
416 * a file, even if the access call would have succeeded. This makes
417 * the superuser force the write even when vi expects that it will
418 * succeed. I'm less supportive of this semantic, but it's historic
419 * practice and the conservative approach to vi'ing files as root.
421 * It would be nice if there was some way to update this when the user
422 * does a "^Z; chmod ...". The problem is that we'd first have to
423 * distinguish between readonly bits set because of file permissions
424 * and those set for other reasons. That's not too hard, but deciding
425 * when to reevaluate the permissions is trickier. An alternative
426 * might be to turn off the readonly bit if the user forces a write
427 * and it succeeds.
429 * XXX
430 * Access(2) doesn't consider the effective uid/gid values. This
431 * probably isn't a problem for vi when it's running standalone.
433 if (readonly || F_ISSET(sp, SC_READONLY) ||
434 (!F_ISSET(frp, FR_NEWFILE) &&
435 (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
436 access(frp->name, W_OK))))
437 O_SET(sp, O_READONLY);
438 else
439 O_CLR(sp, O_READONLY);
441 /* Switch... */
442 ++ep->refcnt;
443 sp->ep = ep;
444 sp->frp = frp;
446 /* Set the initial cursor position, queue initial command. */
447 file_cinit(sp);
449 /* Report conversion errors again. */
450 F_CLR(sp, SC_CONV_ERROR);
452 /* Redraw the screen from scratch, schedule a welcome message. */
453 F_SET(sp, SC_SCR_REFORMAT | SC_SCR_TOP | SC_STATUS);
455 /* Append into the chain of file structures. */
456 if (ep->refcnt == 1)
457 CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q);
459 return (0);
461 err: if (frp->name != NULL) {
462 free(frp->name);
463 frp->name = NULL;
465 if (frp->tname != NULL) {
466 (void)unlink(frp->tname);
467 free(frp->tname);
468 frp->tname = NULL;
471 oerr: if (F_ISSET(ep, F_RCV_ON))
472 (void)unlink(ep->rcv_path);
473 if (ep->rcv_path != NULL) {
474 free(ep->rcv_path);
475 ep->rcv_path = NULL;
477 if (ep->db != NULL) {
478 (void)ep->db->close(ep->db, DB_NOSYNC);
479 ep->db = NULL;
481 free(ep);
483 return (open_err && !LF_ISSET(FS_OPENERR) ?
484 file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
488 * file_spath --
489 * Scan the user's path to find the file that we're going to
490 * try and open.
492 static int
493 file_spath(SCR *sp, FREF *frp, struct stat *sbp, int *existsp)
495 CHAR_T savech;
496 size_t len;
497 int found;
498 char *name, *p, *t, path[MAXPATHLEN];
501 * If the name is NULL or an explicit reference (i.e., the first
502 * component is . or ..) ignore the O_PATH option.
504 name = frp->name;
505 if (name == NULL) {
506 *existsp = 0;
507 return (0);
509 if (name[0] == '/' || (name[0] == '.' &&
510 (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) {
511 *existsp = !stat(name, sbp);
512 return (0);
515 /* Try . */
516 if (!stat(name, sbp)) {
517 *existsp = 1;
518 return (0);
521 /* Try the O_PATH option values. */
522 for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
523 if (*p == ':' || *p == '\0') {
524 if (t < p - 1) {
525 savech = *p;
526 *p = '\0';
527 len = snprintf(path,
528 sizeof(path), "%s/%s", t, name);
529 *p = savech;
530 if (!stat(path, sbp)) {
531 found = 1;
532 break;
535 t = p + 1;
536 if (*p == '\0')
537 break;
540 /* If we found it, build a new pathname and discard the old one. */
541 if (found) {
542 MALLOC_RET(sp, p, char *, len + 1);
543 memcpy(p, path, len + 1);
544 free(frp->name);
545 frp->name = p;
547 *existsp = found;
548 return (0);
552 * file_cinit --
553 * Set up the initial cursor position.
555 static void
556 file_cinit(SCR *sp)
558 GS *gp;
559 MARK m;
560 size_t len;
561 int nb;
562 CHAR_T *wp;
563 size_t wlen;
565 /* Set some basic defaults. */
566 sp->lno = 1;
567 sp->cno = 0;
570 * Historically, initial commands (the -c option) weren't executed
571 * until a file was loaded, e.g. "vi +10 nofile", followed by an
572 * :edit or :tag command, would execute the +10 on the file loaded
573 * by the subsequent command, (assuming that it existed). This
574 * applied as well to files loaded using the tag commands, and we
575 * follow that historic practice. Also, all initial commands were
576 * ex commands and were always executed on the last line of the file.
578 * Otherwise, if no initial command for this file:
579 * If in ex mode, move to the last line, first nonblank character.
580 * If the file has previously been edited, move to the last known
581 * position, and check it for validity.
582 * Otherwise, move to the first line, first nonblank.
584 * This gets called by the file init code, because we may be in a
585 * file of ex commands and we want to execute them from the right
586 * location in the file.
588 nb = 0;
589 gp = sp->gp;
590 if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
591 if (db_last(sp, &sp->lno))
592 return;
593 if (sp->lno == 0) {
594 sp->lno = 1;
595 sp->cno = 0;
597 CHAR2INT(sp, gp->c_option, strlen(gp->c_option) + 1,
598 wp, wlen);
599 if (ex_run_str(sp, "-c option", wp, wlen - 1, 1, 1))
600 return;
601 gp->c_option = NULL;
602 } else if (F_ISSET(sp, SC_EX)) {
603 if (db_last(sp, &sp->lno))
604 return;
605 if (sp->lno == 0) {
606 sp->lno = 1;
607 sp->cno = 0;
608 return;
610 nb = 1;
611 } else {
612 if (F_ISSET(sp->frp, FR_CURSORSET)) {
613 sp->lno = sp->frp->lno;
614 sp->cno = sp->frp->cno;
616 /* If returning to a file in vi, center the line. */
617 F_SET(sp, SC_SCR_CENTER);
618 } else {
619 if (O_ISSET(sp, O_COMMENT))
620 file_comment(sp);
621 else
622 sp->lno = 1;
623 nb = 1;
625 if (db_get(sp, sp->lno, 0, NULL, &len)) {
626 sp->lno = 1;
627 sp->cno = 0;
628 return;
630 if (!nb && sp->cno > len)
631 nb = 1;
633 if (nb) {
634 sp->cno = 0;
635 (void)nonblank(sp, sp->lno, &sp->cno);
639 * !!!
640 * The initial column is also the most attractive column.
642 sp->rcm = sp->cno;
645 * !!!
646 * Historically, vi initialized the absolute mark, but ex did not.
647 * Which meant, that if the first command in ex mode was "visual",
648 * or if an ex command was executed first (e.g. vi +10 file) vi was
649 * entered without the mark being initialized. For consistency, if
650 * the file isn't empty, we initialize it for everyone, believing
651 * that it can't hurt, and is generally useful. Not initializing it
652 * if the file is empty is historic practice, although it has always
653 * been possible to set (and use) marks in empty vi files.
655 m.lno = sp->lno;
656 m.cno = sp->cno;
657 (void)mark_set(sp, ABSMARK1, &m, 0);
661 * file_end --
662 * Stop editing a file.
664 * PUBLIC: int file_end __P((SCR *, EXF *, int));
667 file_end(SCR *sp, EXF *ep, int force)
669 FREF *frp;
672 * !!!
673 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
674 * (If argument ep is NULL, use sp->ep.)
676 * If multiply referenced, just decrement the count and return.
678 if (ep == NULL)
679 ep = sp->ep;
680 if (--ep->refcnt != 0)
681 return (0);
685 * Clean up the FREF structure.
687 * Save the cursor location.
689 * XXX
690 * It would be cleaner to do this somewhere else, but by the time
691 * ex or vi knows that we're changing files it's already happened.
693 frp = sp->frp;
694 frp->lno = sp->lno;
695 frp->cno = sp->cno;
696 F_SET(frp, FR_CURSORSET);
699 * We may no longer need the temporary backing file, so clean it
700 * up. We don't need the FREF structure either, if the file was
701 * never named, so lose it.
703 * !!!
704 * Re: FR_DONTDELETE, see the comment above in file_init().
706 if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
707 if (unlink(frp->tname))
708 msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
709 free(frp->tname);
710 frp->tname = NULL;
711 if (F_ISSET(frp, FR_TMPFILE)) {
712 CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
713 if (frp->name != NULL)
714 free(frp->name);
715 free(frp);
717 sp->frp = NULL;
721 * Clean up the EXF structure.
723 * Close the db structure.
725 if (ep->db->close != NULL) {
726 if ((sp->db_error = ep->db->close(ep->db, DB_NOSYNC)) != 0 &&
727 !force) {
728 msgq_str(sp, M_DBERR, frp->name, "241|%s: close");
729 ++ep->refcnt;
730 return (1);
732 ep->db = NULL;
735 /* COMMITTED TO THE CLOSE. THERE'S NO GOING BACK... */
737 /* Stop logging. */
738 (void)log_end(sp, ep);
740 /* Free up any marks. */
741 (void)mark_end(sp, ep);
744 * Delete recovery files, close the open descriptor, free recovery
745 * memory. See recover.c for a description of the protocol.
747 * XXX
748 * Unlink backup file first, we can detect that the recovery file
749 * doesn't reference anything when the user tries to recover it.
750 * There's a race, here, obviously, but it's fairly small.
752 if (!F_ISSET(ep, F_RCV_NORM)) {
753 if (ep->rcv_path != NULL && unlink(ep->rcv_path))
754 msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
755 if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
756 msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
758 CIRCLEQ_REMOVE(&sp->gp->exfq, ep, q);
759 if (ep->fd != -1)
760 (void)close(ep->fd);
761 if (ep->fcntl_fd != -1)
762 (void)close(ep->fcntl_fd);
763 if (ep->rcv_fd != -1)
764 (void)close(ep->rcv_fd);
765 if (ep->rcv_path != NULL)
766 free(ep->rcv_path);
767 if (ep->rcv_mpath != NULL)
768 free(ep->rcv_mpath);
770 free(ep);
771 return (0);
775 * file_write --
776 * Write the file to disk. Historic vi had fairly convoluted
777 * semantics for whether or not writes would happen. That's
778 * why all the flags.
780 * PUBLIC: int file_write __P((SCR *, MARK *, MARK *, char *, int));
783 file_write(SCR *sp, MARK *fm, MARK *tm, char *name, int flags)
785 enum { NEWFILE, OLDFILE } mtype;
786 struct stat sb;
787 EXF *ep;
788 FILE *fp;
789 FREF *frp;
790 MARK from, to;
791 size_t len;
792 u_long nlno, nch;
793 int fd, nf, noname, oflags, rval;
794 char *p, *s, *t, buf[MAXPATHLEN + 64];
795 const char *msgstr;
797 ep = sp->ep;
798 frp = sp->frp;
801 * Writing '%', or naming the current file explicitly, has the
802 * same semantics as writing without a name.
804 if (name == NULL || !strcmp(name, frp->name)) {
805 noname = 1;
806 name = frp->name;
807 } else
808 noname = 0;
810 /* Can't write files marked read-only, unless forced. */
811 if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
812 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
813 "244|Read-only file, not written; use ! to override" :
814 "245|Read-only file, not written");
815 return (1);
818 /* If not forced, not appending, and "writeany" not set ... */
819 if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
820 /* Don't overwrite anything but the original file. */
821 if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
822 !stat(name, &sb)) {
823 msgq_str(sp, M_ERR, name,
824 LF_ISSET(FS_POSSIBLE) ?
825 "246|%s exists, not written; use ! to override" :
826 "247|%s exists, not written");
827 return (1);
831 * Don't write part of any existing file. Only test for the
832 * original file, the previous test catches anything else.
834 if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
835 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
836 "248|Partial file, not written; use ! to override" :
837 "249|Partial file, not written");
838 return (1);
843 * Figure out if the file already exists -- if it doesn't, we display
844 * the "new file" message. The stat might not be necessary, but we
845 * just repeat it because it's easier than hacking the previous tests.
846 * The information is only used for the user message and modification
847 * time test, so we can ignore the obvious race condition.
849 * One final test. If we're not forcing or appending the current file,
850 * and we have a saved modification time, object if the file changed
851 * since we last edited or wrote it, and make them force it.
853 if (stat(name, &sb))
854 mtype = NEWFILE;
855 else {
856 if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
857 ((F_ISSET(ep, F_DEVSET) &&
858 (sb.st_dev != ep->mdev || sb.st_ino != ep->minode)) ||
859 sb.st_mtime != ep->mtime)) {
860 msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
861 "250|%s: file modified more recently than this copy; use ! to override" :
862 "251|%s: file modified more recently than this copy");
863 return (1);
866 mtype = OLDFILE;
869 /* Set flags to create, write, and either append or truncate. */
870 oflags = O_CREAT | O_WRONLY |
871 (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);
873 /* Backup the file if requested. */
874 if (!opts_empty(sp, O_BACKUP, 1) &&
875 file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
876 return (1);
878 /* Open the file. */
879 SIGBLOCK;
880 if ((fd = open(name, oflags,
881 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
882 msgq_str(sp, M_SYSERR, name, "%s");
883 SIGUNBLOCK;
884 return (1);
886 SIGUNBLOCK;
888 /* Try and get a lock. */
889 if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
890 msgq_str(sp, M_ERR, name,
891 "252|%s: write lock was unavailable");
893 #if __linux__
895 * XXX
896 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
897 * This bug is fixed in libc 4.6.x.
899 * This code works around this problem for libc 4.5.x users.
900 * Note that this code is harmless if you're using libc 4.6.x.
902 if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
903 msgq(sp, M_SYSERR, name);
904 return (1);
906 #endif
909 * Use stdio for buffering.
911 * XXX
912 * SVR4.2 requires the fdopen mode exactly match the original open
913 * mode, i.e. you have to open with "a" if appending.
915 if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
916 msgq_str(sp, M_SYSERR, name, "%s");
917 (void)close(fd);
918 return (1);
921 /* Build fake addresses, if necessary. */
922 if (fm == NULL) {
923 from.lno = 1;
924 from.cno = 0;
925 fm = &from;
926 if (db_last(sp, &to.lno))
927 return (1);
928 to.cno = 0;
929 tm = &to;
932 rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);
935 * Save the new last modification time -- even if the write fails
936 * we re-init the time. That way the user can clean up the disk
937 * and rewrite without having to force it.
939 if (noname) {
940 if (stat(name, &sb))
941 time(&ep->mtime);
942 else {
943 F_SET(ep, F_DEVSET);
944 ep->mdev = sb.st_dev;
945 ep->minode = sb.st_ino;
947 ep->mtime = sb.st_mtime;
952 * If the write failed, complain loudly. ex_writefp() has already
953 * complained about the actual error, reinforce it if data was lost.
955 if (rval) {
956 if (!LF_ISSET(FS_APPEND))
957 msgq_str(sp, M_ERR, name,
958 "254|%s: WARNING: FILE TRUNCATED");
959 return (1);
963 * Once we've actually written the file, it doesn't matter that the
964 * file name was changed -- if it was, we've already whacked it.
966 F_CLR(frp, FR_NAMECHANGE);
969 * If wrote the entire file, and it wasn't by appending it to a file,
970 * clear the modified bit. If the file was written to the original
971 * file name and the file is a temporary, set the "no exit" bit. This
972 * permits the user to write the file and use it in the context of the
973 * filesystem, but still keeps them from discarding their changes by
974 * exiting.
976 if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
977 F_CLR(ep, F_MODIFIED);
978 if (F_ISSET(frp, FR_TMPFILE)) {
979 if (noname)
980 F_SET(frp, FR_TMPEXIT);
981 else
982 F_CLR(frp, FR_TMPEXIT);
986 p = msg_print(sp, name, &nf);
987 switch (mtype) {
988 case NEWFILE:
989 msgstr = msg_cat(sp,
990 "256|%s: new file: %lu lines, %lu characters", NULL);
991 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
992 break;
993 case OLDFILE:
994 msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
995 "315|%s: appended: %lu lines, %lu characters" :
996 "257|%s: %lu lines, %lu characters", NULL);
997 len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
998 break;
999 default:
1000 abort();
1004 * There's a nasty problem with long path names. Cscope and tags files
1005 * can result in long paths and vi will request a continuation key from
1006 * the user. Unfortunately, the user has typed ahead, and chaos will
1007 * result. If we assume that the characters in the filenames only take
1008 * a single screen column each, we can trim the filename.
1010 s = buf;
1011 if (len >= sp->cols) {
1012 for (s = buf, t = buf + strlen(p); s < t &&
1013 (*s != '/' || len >= sp->cols - 3); ++s, --len);
1014 if (s == t)
1015 s = buf;
1016 else {
1017 *--s = '.'; /* Leading ellipses. */
1018 *--s = '.';
1019 *--s = '.';
1022 msgq(sp, M_INFO, s);
1023 if (nf)
1024 FREE_SPACE(sp, p, 0);
1025 return (0);
1029 * file_backup --
1030 * Backup the about-to-be-written file.
1032 * XXX
1033 * We do the backup by copying the entire file. It would be nice to do
1034 * a rename instead, but: (1) both files may not fit and we want to fail
1035 * before doing the rename; (2) the backup file may not be on the same
1036 * disk partition as the file being written; (3) there may be optional
1037 * file information (MACs, DACs, whatever) that we won't get right if we
1038 * recreate the file. So, let's not risk it.
1040 static int
1041 file_backup(SCR *sp, char *name, char *bname)
1043 struct dirent *dp;
1044 struct stat sb;
1045 DIR *dirp;
1046 EXCMD cmd;
1047 off_t off;
1048 size_t blen;
1049 int flags, maxnum, nr, num, nw, rfd, wfd, version;
1050 char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];
1051 CHAR_T *wp;
1052 size_t wlen;
1053 size_t nlen;
1054 char *d = NULL;
1056 rfd = wfd = -1;
1057 bp = estr = wfname = NULL;
1060 * Open the current file for reading. Do this first, so that
1061 * we don't exec a shell before the most likely failure point.
1062 * If it doesn't exist, it's okay, there's just nothing to back
1063 * up.
1065 errno = 0;
1066 if ((rfd = open(name, O_RDONLY, 0)) < 0) {
1067 if (errno == ENOENT)
1068 return (0);
1069 estr = name;
1070 goto err;
1074 * If the name starts with an 'N' character, add a version number
1075 * to the name. Strip the leading N from the string passed to the
1076 * expansion routines, for no particular reason. It would be nice
1077 * to permit users to put the version number anywhere in the backup
1078 * name, but there isn't a special character that we can use in the
1079 * name, and giving a new character a special meaning leads to ugly
1080 * hacks both here and in the supporting ex routines.
1082 * Shell and file name expand the option's value.
1084 ex_cinit(sp, &cmd, 0, 0, 0, 0, 0);
1085 if (bname[0] == 'N') {
1086 version = 1;
1087 ++bname;
1088 } else
1089 version = 0;
1090 CHAR2INT(sp, bname, strlen(bname) + 1, wp, wlen);
1091 if (argv_exp2(sp, &cmd, wp, wlen - 1))
1092 return (1);
1095 * 0 args: impossible.
1096 * 1 args: use it.
1097 * >1 args: object, too many args.
1099 if (cmd.argc != 1) {
1100 msgq_str(sp, M_ERR, bname,
1101 "258|%s expanded into too many file names");
1102 (void)close(rfd);
1103 return (1);
1107 * If appending a version number, read through the directory, looking
1108 * for file names that match the name followed by a number. Make all
1109 * of the other % characters in name literal, so the user doesn't get
1110 * surprised and sscanf doesn't drop core indirecting through pointers
1111 * that don't exist. If any such files are found, increment its number
1112 * by one.
1114 if (version) {
1115 GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
1116 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1117 p, nlen);
1118 d = strdup(p);
1119 p = d;
1120 for (t = bp, slash = NULL;
1121 p[0] != '\0'; *t++ = *p++)
1122 if (p[0] == '%') {
1123 if (p[1] != '%')
1124 *t++ = '%';
1125 } else if (p[0] == '/')
1126 slash = t;
1127 pct = t;
1128 *t++ = '%';
1129 *t++ = 'd';
1130 *t = '\0';
1132 if (slash == NULL) {
1133 dirp = opendir(".");
1134 p = bp;
1135 } else {
1136 *slash = '\0';
1137 dirp = opendir(bp);
1138 *slash = '/';
1139 p = slash + 1;
1141 if (dirp == NULL) {
1142 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1143 estr, nlen);
1144 goto err;
1147 for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
1148 if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
1149 maxnum = num;
1150 (void)closedir(dirp);
1152 /* Format the backup file name. */
1153 (void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
1154 wfname = bp;
1155 } else {
1156 bp = NULL;
1157 INT2SYS(sp, cmd.argv[0]->bp, cmd.argv[0]->len + 1,
1158 wfname, nlen);
1161 /* Open the backup file, avoiding lurkers. */
1162 if (stat(wfname, &sb) == 0) {
1163 if (!S_ISREG(sb.st_mode)) {
1164 msgq_str(sp, M_ERR, bname,
1165 "259|%s: not a regular file");
1166 goto err;
1168 if (sb.st_uid != getuid()) {
1169 msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
1170 goto err;
1172 if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
1173 msgq_str(sp, M_ERR, bname,
1174 "261|%s: accessible by a user other than the owner");
1175 goto err;
1177 flags = O_TRUNC;
1178 } else
1179 flags = O_CREAT | O_EXCL;
1180 if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0) {
1181 estr = bname;
1182 goto err;
1185 /* Copy the file's current contents to its backup value. */
1186 while ((nr = read(rfd, buf, sizeof(buf))) > 0)
1187 for (off = 0; nr != 0; nr -= nw, off += nw)
1188 if ((nw = write(wfd, buf + off, nr)) < 0) {
1189 estr = wfname;
1190 goto err;
1192 if (nr < 0) {
1193 estr = name;
1194 goto err;
1197 if (close(rfd)) {
1198 estr = name;
1199 goto err;
1201 if (close(wfd)) {
1202 estr = wfname;
1203 goto err;
1205 if (bp != NULL)
1206 FREE_SPACE(sp, bp, blen);
1207 return (0);
1209 alloc_err:
1210 err: if (rfd != -1)
1211 (void)close(rfd);
1212 if (wfd != -1) {
1213 (void)unlink(wfname);
1214 (void)close(wfd);
1216 if (estr)
1217 msgq_str(sp, M_SYSERR, estr, "%s");
1218 if (d != NULL)
1219 free(d);
1220 if (bp != NULL)
1221 FREE_SPACE(sp, bp, blen);
1222 return (1);
1226 * file_comment --
1227 * Skip the first comment.
1229 static void
1230 file_comment(SCR *sp)
1232 db_recno_t lno;
1233 size_t len;
1234 CHAR_T *p;
1236 for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
1237 if (p == NULL)
1238 return;
1239 if (p[0] == '#') {
1240 F_SET(sp, SC_SCR_TOP);
1241 while (!db_get(sp, ++lno, 0, &p, &len))
1242 if (len < 1 || p[0] != '#') {
1243 sp->lno = lno;
1244 return;
1246 } else if (len > 1 && p[0] == '/' && p[1] == '*') {
1247 F_SET(sp, SC_SCR_TOP);
1248 do {
1249 for (; len > 1; --len, ++p)
1250 if (p[0] == '*' && p[1] == '/') {
1251 sp->lno = lno;
1252 return;
1254 } while (!db_get(sp, ++lno, 0, &p, &len));
1255 } else if (len > 1 && p[0] == '/' && p[1] == '/') {
1256 F_SET(sp, SC_SCR_TOP);
1257 while (!db_get(sp, ++lno, 0, &p, &len))
1258 if (len < 1 || p[0] != '/' || p[1] != '/') {
1259 sp->lno = lno;
1260 return;
1266 * file_m1 --
1267 * First modification check routine. The :next, :prev, :rewind, :tag,
1268 * :tagpush, :tagpop, ^^ modifications check.
1270 * PUBLIC: int file_m1 __P((SCR *, int, int));
1273 file_m1(SCR *sp, int force, int flags)
1275 EXF *ep;
1277 ep = sp->ep;
1279 /* If no file loaded, return no modifications. */
1280 if (ep == NULL)
1281 return (0);
1284 * If the file has been modified, we'll want to write it back or
1285 * fail. If autowrite is set, we'll write it back automatically,
1286 * unless force is also set. Otherwise, we fail unless forced or
1287 * there's another open screen on this file.
1289 if (F_ISSET(ep, F_MODIFIED)) {
1290 if (O_ISSET(sp, O_AUTOWRITE)) {
1291 if (!force && file_aw(sp, flags))
1292 return (1);
1293 } else if (ep->refcnt <= 1 && !force) {
1294 msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
1295 "262|File modified since last complete write; write or use ! to override" :
1296 "263|File modified since last complete write; write or use :edit! to override");
1297 return (1);
1301 return (file_m3(sp, force));
1305 * file_m2 --
1306 * Second modification check routine. The :edit, :quit, :recover
1307 * modifications check.
1309 * PUBLIC: int file_m2 __P((SCR *, int));
1312 file_m2(SCR *sp, int force)
1314 EXF *ep;
1316 ep = sp->ep;
1318 /* If no file loaded, return no modifications. */
1319 if (ep == NULL)
1320 return (0);
1323 * If the file has been modified, we'll want to fail, unless forced
1324 * or there's another open screen on this file.
1326 if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
1327 msgq(sp, M_ERR,
1328 "264|File modified since last complete write; write or use ! to override");
1329 return (1);
1332 return (file_m3(sp, force));
1336 * file_m3 --
1337 * Third modification check routine.
1339 * PUBLIC: int file_m3 __P((SCR *, int));
1342 file_m3(SCR *sp, int force)
1344 EXF *ep;
1346 ep = sp->ep;
1348 /* If no file loaded, return no modifications. */
1349 if (ep == NULL)
1350 return (0);
1353 * Don't exit while in a temporary files if the file was ever modified.
1354 * The problem is that if the user does a ":wq", we write and quit,
1355 * unlinking the temporary file. Not what the user had in mind at all.
1356 * We permit writing to temporary files, so that user maps using file
1357 * system names work with temporary files.
1359 if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
1360 msgq(sp, M_ERR,
1361 "265|File is a temporary; exit will discard modifications");
1362 return (1);
1364 return (0);
1368 * file_aw --
1369 * Autowrite routine. If modified, autowrite is set and the readonly bit
1370 * is not set, write the file. A routine so there's a place to put the
1371 * comment.
1373 * PUBLIC: int file_aw __P((SCR *, int));
1376 file_aw(SCR *sp, int flags)
1378 if (!F_ISSET(sp->ep, F_MODIFIED))
1379 return (0);
1380 if (!O_ISSET(sp, O_AUTOWRITE))
1381 return (0);
1384 * !!!
1385 * Historic 4BSD vi attempted to write the file if autowrite was set,
1386 * regardless of the writeability of the file (as defined by the file
1387 * readonly flag). System V changed this as some point, not attempting
1388 * autowrite if the file was readonly. This feels like a bug fix to
1389 * me (e.g. the principle of least surprise is violated if readonly is
1390 * set and vi writes the file), so I'm compatible with System V.
1392 if (O_ISSET(sp, O_READONLY)) {
1393 msgq(sp, M_INFO,
1394 "266|File readonly, modifications not auto-written");
1395 return (1);
1397 return (file_write(sp, NULL, NULL, NULL, flags));
1401 * set_alt_name --
1402 * Set the alternate pathname.
1404 * Set the alternate pathname. It's a routine because I wanted some place
1405 * to hang this comment. The alternate pathname (normally referenced using
1406 * the special character '#' during file expansion and in the vi ^^ command)
1407 * is set by almost all ex commands that take file names as arguments. The
1408 * rules go something like this:
1410 * 1: If any ex command takes a file name as an argument (except for the
1411 * :next command), the alternate pathname is set to that file name.
1412 * This excludes the command ":e" and ":w !command" as no file name
1413 * was specified. Note, historically, the :source command did not set
1414 * the alternate pathname. It does in nvi, for consistency.
1416 * 2: However, if any ex command sets the current pathname, e.g. the
1417 * ":e file" or ":rew" commands succeed, then the alternate pathname
1418 * is set to the previous file's current pathname, if it had one.
1419 * This includes the ":file" command and excludes the ":e" command.
1420 * So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
1421 * pathname will be "foo", if it succeeds, the alternate pathname will
1422 * be the previous current pathname. The ":e" command will not set
1423 * the alternate or current pathnames regardless.
1425 * 3: However, if it's a read or write command with a file argument and
1426 * the current pathname has not yet been set, the file name becomes
1427 * the current pathname, and the alternate pathname is unchanged.
1429 * If the user edits a temporary file, there may be times when there is no
1430 * alternative file name. A name argument of NULL turns it off.
1432 * PUBLIC: void set_alt_name __P((SCR *, char *));
1434 void
1435 set_alt_name(SCR *sp, char *name)
1437 if (sp->alt_name != NULL)
1438 free(sp->alt_name);
1439 if (name == NULL)
1440 sp->alt_name = NULL;
1441 else if ((sp->alt_name = strdup(name)) == NULL)
1442 msgq(sp, M_SYSERR, NULL);
1446 * file_lock --
1447 * Get an exclusive lock on a file.
1449 * XXX
1450 * The default locking is flock(2) style, not fcntl(2). The latter is
1451 * known to fail badly on some systems, and its only advantage is that
1452 * it occasionally works over NFS.
1454 * Furthermore, the semantics of fcntl(2) are wrong. The problems are
1455 * two-fold: you can't close any file descriptor associated with the file
1456 * without losing all of the locks, and you can't get an exclusive lock
1457 * unless you have the file open for writing. Someone ought to be shot,
1458 * but it's probably too late, they may already have reproduced. To get
1459 * around these problems, nvi opens the files for writing when it can and
1460 * acquires a second file descriptor when it can't. The recovery files
1461 * are examples of the former, they're always opened for writing. The DB
1462 * files can't be opened for writing because the semantics of DB are that
1463 * files opened for writing are flushed back to disk when the DB session
1464 * is ended. So, in that case we have to acquire an extra file descriptor.
1466 * PUBLIC: lockr_t file_lock __P((SCR *, char *, int *, int, int));
1468 lockr_t
1469 file_lock(SCR *sp, char *name, int *fdp, int fd, int iswrite)
1471 if (!O_ISSET(sp, O_LOCKFILES))
1472 return (LOCK_SUCCESS);
1474 #ifdef HAVE_LOCK_FLOCK /* Hurrah! We've got flock(2). */
1476 * !!!
1477 * We need to distinguish a lock not being available for the file
1478 * from the file system not supporting locking. Flock is documented
1479 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
1480 * they are the former. There's no portable way to do this.
1482 errno = 0;
1483 return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
1484 #ifdef EWOULDBLOCK
1485 || errno == EWOULDBLOCK
1486 #endif
1487 ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
1488 #endif
1489 #ifdef HAVE_LOCK_FCNTL /* Gag me. We've got fcntl(2). */
1491 struct flock arg;
1492 int didopen, sverrno;
1494 arg.l_type = F_WRLCK;
1495 arg.l_whence = 0; /* SEEK_SET */
1496 arg.l_start = arg.l_len = 0;
1497 arg.l_pid = 0;
1500 * If the file descriptor isn't opened for writing, it must fail.
1501 * If we fail because we can't get a read/write file descriptor,
1502 * we return LOCK_SUCCESS, believing that the file is readonly
1503 * and that will be sufficient to warn the user.
1505 if (!iswrite) {
1506 if (name == NULL || fdp == NULL)
1507 return (LOCK_FAILED);
1508 if ((fd = open(name, O_RDWR, 0)) == -1)
1509 return (LOCK_SUCCESS);
1510 *fdp = fd;
1511 didopen = 1;
1514 errno = 0;
1515 if (!fcntl(fd, F_SETLK, &arg))
1516 return (LOCK_SUCCESS);
1517 if (didopen) {
1518 sverrno = errno;
1519 (void)close(fd);
1520 errno = sverrno;
1524 * !!!
1525 * We need to distinguish a lock not being available for the file
1526 * from the file system not supporting locking. Fcntl is documented
1527 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
1528 * and assume they are the former. There's no portable way to do this.
1530 return (errno == EACCES || errno == EAGAIN
1531 #ifdef EWOULDBLOCK
1532 || errno == EWOULDBLOCK
1533 #endif
1534 ? LOCK_UNAVAIL : LOCK_FAILED);
1536 #endif
1537 #if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
1538 return (LOCK_SUCCESS);
1539 #endif