summaryrefslogtreecommitdiff
path: root/usr.bin/vi/common/exf.c
blob: 1e7e1d608a4d99e607f1898b858ead7e6fab0e28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
/*	$OpenBSD: exf.c,v 1.17 2002/02/19 00:06:34 ericj Exp $	*/

/*-
 * Copyright (c) 1992, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 * Copyright (c) 1992, 1993, 1994, 1995, 1996
 *	Keith Bostic.  All rights reserved.
 *
 * See the LICENSE file for redistribution information.
 */

#include "config.h"

#ifndef lint
static const char sccsid[] = "@(#)exf.c	10.49 (Berkeley) 10/10/96";
#endif /* not lint */

#include <sys/param.h>
#include <sys/types.h>		/* XXX: param.h may not have included types.h */
#include <sys/queue.h>
#include <sys/stat.h>

/*
 * We include <sys/file.h>, because the flock(2) and open(2) #defines
 * were found there on historical systems.  We also include <fcntl.h>
 * because the open(2) #defines are found there on newer systems.
 */
#include <sys/file.h>

#include <bitstring.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "common.h"

static int	file_backup(SCR *, char *, char *);
static void	file_cinit(SCR *);
static void	file_comment(SCR *);
static int	file_spath(SCR *, FREF *, struct stat *, int *);

/*
 * file_add --
 *	Insert a file name into the FREF list, if it doesn't already
 *	appear in it.
 *
 * !!!
 * The "if it doesn't already appear" changes vi's semantics slightly.  If
 * you do a "vi foo bar", and then execute "next bar baz", the edit of bar
 * will reflect the line/column of the previous edit session.  Historic nvi
 * did not do this.  The change is a logical extension of the change where
 * vi now remembers the last location in any file that it has ever edited,
 * not just the previously edited file.
 *
 * PUBLIC: FREF *file_add(SCR *, CHAR_T *);
 */
FREF *
file_add(sp, name)
	SCR *sp;
	CHAR_T *name;
{
	GS *gp;
	FREF *frp, *tfrp;

	/*
	 * Return it if it already exists.  Note that we test against the
	 * user's name, whatever that happens to be, including if it's a
	 * temporary file.
	 *
	 * If the user added a file but was unable to initialize it, there
	 * can be file list entries where the name field is NULL.  Discard
	 * them the next time we see them.
	 */
	gp = sp->gp;
	if (name != NULL)
		for (frp = gp->frefq.cqh_first;
		    frp != (FREF *)&gp->frefq; frp = frp->q.cqe_next) {
			if (frp->name == NULL) {
				tfrp = frp->q.cqe_next;
				CIRCLEQ_REMOVE(&gp->frefq, frp, q);
				if (frp->name != NULL)
					free(frp->name);
				free(frp);
				frp = tfrp;
				continue;
			}
			if (!strcmp(frp->name, name))
				return (frp);
		}

	/* Allocate and initialize the FREF structure. */
	CALLOC(sp, frp, FREF *, 1, sizeof(FREF));
	if (frp == NULL)
		return (NULL);

	/*
	 * If no file name specified, or if the file name is a request
	 * for something temporary, file_init() will allocate the file
	 * name.  Temporary files are always ignored.
	 */
	if (name != NULL && strcmp(name, TEMPORARY_FILE_STRING) &&
	    (frp->name = strdup(name)) == NULL) {
		free(frp);
		msgq(sp, M_SYSERR, NULL);
		return (NULL);
	}

	/* Append into the chain of file names. */
	CIRCLEQ_INSERT_TAIL(&gp->frefq, frp, q);

	return (frp);
}

/*
 * file_init --
 *	Start editing a file, based on the FREF structure.  If successsful,
 *	let go of any previous file.  Don't release the previous file until
 *	absolutely sure we have the new one.
 *
 * PUBLIC: int file_init(SCR *, FREF *, char *, int);
 */
int
file_init(sp, frp, rcv_name, flags)
	SCR *sp;
	FREF *frp;
	char *rcv_name;
	int flags;
{
	EXF *ep;
	RECNOINFO oinfo;
	struct stat sb;
	size_t psize;
	int fd, exists, open_err, readonly;
	char *oname, tname[MAXPATHLEN];

	open_err = readonly = 0;

	/*
	 * If the file is a recovery file, let the recovery code handle it.
	 * Clear the FR_RECOVER flag first -- the recovery code does set up,
	 * and then calls us!  If the recovery call fails, it's probably
	 * because the named file doesn't exist.  So, move boldly forward,
	 * presuming that there's an error message the user will get to see.
	 */
	if (F_ISSET(frp, FR_RECOVER)) {
		F_CLR(frp, FR_RECOVER);
		return (rcv_read(sp, frp));
	}

	/*
	 * Required FRP initialization; the only flag we keep is the
	 * cursor information.
	 */
	F_CLR(frp, ~FR_CURSORSET);

	/*
	 * Required EXF initialization:
	 *	Flush the line caches.
	 *	Default recover mail file fd to -1.
	 *	Set initial EXF flag bits.
	 */
	CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF));
	ep->c_lno = ep->c_nlines = OOBLNO;
	ep->rcv_fd = ep->fcntl_fd = -1;
	F_SET(ep, F_FIRSTMODIFY);

	/*
	 * Scan the user's path to find the file that we're going to
	 * try and open.
	 */
	if (file_spath(sp, frp, &sb, &exists))
		return (1);

	/*
	 * If no name or backing file, for whatever reason, create a backing
	 * temporary file, saving the temp file name so we can later unlink
	 * it.  If the user never named this file, copy the temporary file name
	 * to the real name (we display that until the user renames it).
	 */
	oname = frp->name;
	if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) {
		/*
		 * Don't try to create a temporary support file twice.
		 */
		if (frp->tname != NULL)
			goto err;
		if (opts_empty(sp, O_DIRECTORY, 0))
			goto err;
		(void)snprintf(tname, sizeof(tname),
		    "%s/vi.XXXXXX", O_STR(sp, O_DIRECTORY));
		fd = mkstemp(tname);
		if (fd == -1 || fchmod(fd, S_IRUSR | S_IWUSR) == -1) {
			msgq(sp, M_SYSERR,
			    "237|Unable to create temporary file");
			if (fd != -1) {
				close(fd);
				(void)unlink(tname);
			}
			goto err;
		}
		(void)close(fd);

		if (frp->name == NULL)
			F_SET(frp, FR_TMPFILE);
		if ((frp->tname = strdup(tname)) == NULL ||
		    frp->name == NULL && (frp->name = strdup(tname)) == NULL) {
			if (frp->tname != NULL)
				free(frp->tname);
			msgq(sp, M_SYSERR, NULL);
			(void)unlink(tname);
			goto err;
		}
		oname = frp->tname;
		psize = 1024;
		if (!LF_ISSET(FS_OPENERR))
			F_SET(frp, FR_NEWFILE);

		time(&ep->mtime);
	} else {
		/*
		 * XXX
		 * A seat of the pants calculation: try to keep the file in
		 * 15 pages or less.  Don't use a page size larger than 10K
		 * (vi should have good locality) or smaller than 1K.
		 */
		psize = ((sb.st_size / 15) + 1023) / 1024;
		if (psize > 10)
			psize = 10;
		if (psize == 0)
			psize = 1;
		psize *= 1024;

		F_SET(ep, F_DEVSET);
		ep->mdev = sb.st_dev;
		ep->minode = sb.st_ino;

		ep->mtime = sb.st_mtime;

		if (!S_ISREG(sb.st_mode))
			msgq_str(sp, M_ERR, oname,
			    "238|Warning: %s is not a regular file");
	}

	/* Set up recovery. */
	memset(&oinfo, 0, sizeof(RECNOINFO));
	oinfo.bval = '\n';			/* Always set. */
	oinfo.psize = psize;
	oinfo.flags = F_ISSET(sp->gp, G_SNAPSHOT) ? R_SNAPSHOT : 0;
	if (rcv_name == NULL) {
		if (!rcv_tmp(sp, ep, frp->name))
			oinfo.bfname = ep->rcv_path;
	} else {
		if ((ep->rcv_path = strdup(rcv_name)) == NULL) {
			msgq(sp, M_SYSERR, NULL);
			goto err;
		}
		oinfo.bfname = ep->rcv_path;
		F_SET(ep, F_MODIFIED);
	}

	/* Open a db structure. */
	if ((ep->db = dbopen(rcv_name == NULL ? oname : NULL,
	    O_NONBLOCK | O_RDONLY,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH,
	    DB_RECNO, &oinfo)) == NULL) {
		msgq_str(sp,
		    M_SYSERR, rcv_name == NULL ? oname : rcv_name, "%s");
		/*
		 * !!!
		 * Historically, vi permitted users to edit files that couldn't
		 * be read.  This isn't useful for single files from a command
		 * line, but it's quite useful for "vi *.c", since you can skip
		 * past files that you can't read.
		 */ 
		open_err = 1;
		goto oerr;
	}

	/*
	 * Do the remaining things that can cause failure of the new file,
	 * mark and logging initialization.
	 */
	if (mark_init(sp, ep) || log_init(sp, ep))
		goto err;

	/*
	 * Set the alternate file name to be the file we're discarding.
	 *
	 * !!!
	 * Temporary files can't become alternate files, so there's no file
	 * name.  This matches historical practice, although it could only
	 * happen in historical vi as the result of the initial command, i.e.
	 * if vi was executed without a file name.
	 */
	if (LF_ISSET(FS_SETALT))
		set_alt_name(sp, sp->frp == NULL ||
		    F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name);

	/*
	 * Close the previous file; if that fails, close the new one and run
	 * for the border.
	 *
	 * !!!
	 * There's a nasty special case.  If the user edits a temporary file,
	 * and then does an ":e! %", we need to re-initialize the backing
	 * file, but we can't change the name.  (It's worse -- we're dealing
	 * with *names* here, we can't even detect that it happened.)  Set a
	 * flag so that the file_end routine ignores the backing information
	 * of the old file if it happens to be the same as the new one.
	 *
	 * !!!
	 * Side-effect: after the call to file_end(), sp->frp may be NULL.
	 */
	if (sp->ep != NULL) {
		F_SET(frp, FR_DONTDELETE);
		if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) {
			(void)file_end(sp, ep, 1);
			goto err;
		}
		F_CLR(frp, FR_DONTDELETE);
	}

	/*
	 * Lock the file; if it's a recovery file, it should already be
	 * locked.  Note, we acquire the lock after the previous file
	 * has been ended, so that we don't get an "already locked" error
	 * for ":edit!".
	 *
	 * XXX
	 * While the user can't interrupt us between the open and here,
	 * there's a race between the dbopen() and the lock.  Not much
	 * we can do about it.
	 *
	 * XXX
	 * We don't make a big deal of not being able to lock the file.  As
	 * locking rarely works over NFS, and often fails if the file was
	 * mmap(2)'d, it's far too common to do anything like print an error
	 * message, let alone make the file readonly.  At some future time,
	 * when locking is a little more reliable, this should change to be
	 * an error.
	 */
	if (rcv_name == NULL)
		switch (file_lock(sp, oname,
		    &ep->fcntl_fd, ep->db->fd(ep->db), 0)) {
		case LOCK_FAILED:
			F_SET(frp, FR_UNLOCKED);
			break;
		case LOCK_UNAVAIL:
			readonly = 1;
			msgq_str(sp, M_INFO, oname,
			    "239|%s already locked, session is read-only");
			break;
		case LOCK_SUCCESS:
			break;
		}

	/*
         * Historically, the readonly edit option was set per edit buffer in
         * vi, unless the -R command-line option was specified or the program
         * was executed as "view".  (Well, to be truthful, if the letter 'w'
         * occurred anywhere in the program name, but let's not get into that.)
	 * So, the persistant readonly state has to be stored in the screen
	 * structure, and the edit option value toggles with the contents of
	 * the edit buffer.  If the persistant readonly flag is set, set the
	 * readonly edit option.
	 *
	 * Otherwise, try and figure out if a file is readonly.  This is a
	 * dangerous thing to do.  The kernel is the only arbiter of whether
	 * or not a file is writeable, and the best that a user program can
	 * do is guess.  Obvious loopholes are files that are on a file system
	 * mounted readonly (access catches this one on a few systems), or
	 * alternate protection mechanisms, ACL's for example, that we can't
	 * portably check.  Lots of fun, and only here because users whined.
	 *
	 * !!!
	 * Historic vi displayed the readonly message if none of the file
	 * write bits were set, or if an an access(2) call on the path
	 * failed.  This seems reasonable.  If the file is mode 444, root
	 * users may want to know that the owner of the file did not expect
	 * it to be written.
	 *
	 * Historic vi set the readonly bit if no write bits were set for
	 * a file, even if the access call would have succeeded.  This makes
	 * the superuser force the write even when vi expects that it will
	 * succeed.  I'm less supportive of this semantic, but it's historic
	 * practice and the conservative approach to vi'ing files as root.
	 *
	 * It would be nice if there was some way to update this when the user
	 * does a "^Z; chmod ...".  The problem is that we'd first have to
	 * distinguish between readonly bits set because of file permissions
	 * and those set for other reasons.  That's not too hard, but deciding
	 * when to reevaluate the permissions is trickier.  An alternative
	 * might be to turn off the readonly bit if the user forces a write
	 * and it succeeds.
	 *
	 * XXX
	 * Access(2) doesn't consider the effective uid/gid values.  This
	 * probably isn't a problem for vi when it's running standalone.
	 */
	if (readonly || F_ISSET(sp, SC_READONLY) ||
	    !F_ISSET(frp, FR_NEWFILE) &&
	    (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) ||
	    access(frp->name, W_OK)))
		O_SET(sp, O_READONLY);
	else
		O_CLR(sp, O_READONLY);

	/* Switch... */
	++ep->refcnt;
	sp->ep = ep;
	sp->frp = frp;

	/* Set the initial cursor position, queue initial command. */
	file_cinit(sp);

	/* Redraw the screen from scratch, schedule a welcome message. */
	F_SET(sp, SC_SCR_REFORMAT | SC_STATUS);

	return (0);

err:	if (frp->name != NULL) {
		free(frp->name);
		frp->name = NULL;
	}
	if (frp->tname != NULL) {
		(void)unlink(frp->tname);
		free(frp->tname);
		frp->tname = NULL;
	}

oerr:	if (F_ISSET(ep, F_RCV_ON))
		(void)unlink(ep->rcv_path);
	if (ep->rcv_path != NULL) {
		free(ep->rcv_path);
		ep->rcv_path = NULL;
	}
	if (ep->db != NULL)
		(void)ep->db->close(ep->db);
	free(ep);

	return (open_err ?
	    file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1);
}

/*
 * file_spath --
 *	Scan the user's path to find the file that we're going to
 *	try and open.
 */
static int
file_spath(sp, frp, sbp, existsp)
	SCR *sp;
	FREF *frp;
	struct stat *sbp;
	int *existsp;
{
	CHAR_T savech;
	size_t len;
	int found;
	char *name, *p, *t, path[MAXPATHLEN];

	/*
	 * If the name is NULL or an explicit reference (i.e., the first
	 * component is . or ..) ignore the O_PATH option.
	 */
	name = frp->name;
	if (name == NULL) {
		*existsp = 0;
		return (0);
	}
	if (name[0] == '/' || name[0] == '.' &&
	    (name[1] == '/' || name[1] == '.' && name[2] == '/')) {
		*existsp = !stat(name, sbp);
		return (0);
	}

	/* Try . */
	if (!stat(name, sbp)) {
		*existsp = 1;
		return (0);
	}

	/* Try the O_PATH option values. */
	for (found = 0, p = t = O_STR(sp, O_PATH);; ++p)
		if (*p == ':' || *p == '\0') {
			if (t < p - 1) {
				savech = *p;
				*p = '\0';
				len = snprintf(path,
				    sizeof(path), "%s/%s", t, name);
				if (len >= sizeof(path))
					len = sizeof(path) - 1;
				*p = savech;
				if (!stat(path, sbp)) {
					found = 1;
					break;
				}
			}
			t = p + 1;
			if (*p == '\0')
				break;
		}

	/* If we found it, build a new pathname and discard the old one. */
	if (found) {
		MALLOC_RET(sp, p, char *, len + 1);
		memcpy(p, path, len + 1);
		free(frp->name);
		frp->name = p;
	}
	*existsp = found;
	return (0);
}

/*
 * file_cinit --
 *	Set up the initial cursor position.
 */
static void
file_cinit(sp)
	SCR *sp;
{
	GS *gp;
	MARK m;
	size_t len;
	int nb;

	/* Set some basic defaults. */
	sp->lno = 1;
	sp->cno = 0;

	/*
	 * Historically, initial commands (the -c option) weren't executed
	 * until a file was loaded, e.g. "vi +10 nofile", followed by an
	 * :edit or :tag command, would execute the +10 on the file loaded
	 * by the subsequent command, (assuming that it existed).  This
	 * applied as well to files loaded using the tag commands, and we
	 * follow that historic practice.  Also, all initial commands were
	 * ex commands and were always executed on the last line of the file.
	 *
	 * Otherwise, if no initial command for this file:
	 *    If in ex mode, move to the last line, first nonblank character.
	 *    If the file has previously been edited, move to the last known
	 *	  position, and check it for validity.
	 *    Otherwise, move to the first line, first nonblank.
	 *
	 * This gets called by the file init code, because we may be in a
	 * file of ex commands and we want to execute them from the right
	 * location in the file.
	 */
	nb = 0;
	gp = sp->gp;
	if (gp->c_option != NULL && !F_ISSET(sp->frp, FR_NEWFILE)) {
		if (db_last(sp, &sp->lno))
			return;
		if (sp->lno == 0) {
			sp->lno = 1;
			sp->cno = 0;
		}
		if (ex_run_str(sp,
		    "-c option", gp->c_option, strlen(gp->c_option), 1, 1))
			return;
		gp->c_option = NULL;
	} else if (F_ISSET(sp, SC_EX)) {
		if (db_last(sp, &sp->lno))
			return;
		if (sp->lno == 0) {
			sp->lno = 1;
			sp->cno = 0;
			return;
		}
		nb = 1;
	} else {
		if (F_ISSET(sp->frp, FR_CURSORSET)) {
			sp->lno = sp->frp->lno;
			sp->cno = sp->frp->cno;

			/* If returning to a file in vi, center the line. */
			 F_SET(sp, SC_SCR_CENTER);
		} else {
			if (O_ISSET(sp, O_COMMENT))
				file_comment(sp);
			else
				sp->lno = 1;
			nb = 1;
		}
		if (db_get(sp, sp->lno, 0, NULL, &len)) {
			sp->lno = 1;
			sp->cno = 0;
			return;
		}
		if (!nb && sp->cno > len)
			nb = 1;
	}
	if (nb) {
		sp->cno = 0;
		(void)nonblank(sp, sp->lno, &sp->cno);
	}

	/*
	 * !!!
	 * The initial column is also the most attractive column.
	 */
	sp->rcm = sp->cno;

	/*
	 * !!!
	 * Historically, vi initialized the absolute mark, but ex did not.
	 * Which meant, that if the first command in ex mode was "visual",
	 * or if an ex command was executed first (e.g. vi +10 file) vi was
	 * entered without the mark being initialized.  For consistency, if
	 * the file isn't empty, we initialize it for everyone, believing
	 * that it can't hurt, and is generally useful.  Not initializing it
	 * if the file is empty is historic practice, although it has always
	 * been possible to set (and use) marks in empty vi files.
	 */
	m.lno = sp->lno;
	m.cno = sp->cno;
	(void)mark_set(sp, ABSMARK1, &m, 0);
}

/*
 * file_end --
 *	Stop editing a file.
 *
 * PUBLIC: int file_end(SCR *, EXF *, int);
 */
int
file_end(sp, ep, force)
	SCR *sp;
	EXF *ep;
	int force;
{
	FREF *frp;

	/*
	 * !!!
	 * ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
	 * (If argument ep is NULL, use sp->ep.)
	 *
	 * If multiply referenced, just decrement the count and return.
	 */
	if (ep == NULL)
		ep = sp->ep;
	if (--ep->refcnt != 0)
		return (0);

	/*
	 *
	 * Clean up the FREF structure.
	 *
	 * Save the cursor location.
	 *
	 * XXX
	 * It would be cleaner to do this somewhere else, but by the time
	 * ex or vi knows that we're changing files it's already happened.
	 */
	frp = sp->frp;
	frp->lno = sp->lno;
	frp->cno = sp->cno;
	F_SET(frp, FR_CURSORSET);

	/*
	 * We may no longer need the temporary backing file, so clean it
	 * up.  We don't need the FREF structure either, if the file was
	 * never named, so lose it.
	 *
	 * !!!
	 * Re: FR_DONTDELETE, see the comment above in file_init().
	 */
	if (!F_ISSET(frp, FR_DONTDELETE) && frp->tname != NULL) {
		if (unlink(frp->tname))
			msgq_str(sp, M_SYSERR, frp->tname, "240|%s: remove");
		free(frp->tname);
		frp->tname = NULL;
		if (F_ISSET(frp, FR_TMPFILE)) {
			CIRCLEQ_REMOVE(&sp->gp->frefq, frp, q);
			if (frp->name != NULL)
				free(frp->name);
			free(frp);
		}
		sp->frp = NULL;
	}

	/*
	 * Clean up the EXF structure.
	 *
	 * Close the db structure.
	 */
	if (ep->db->close != NULL && ep->db->close(ep->db) && !force) {
		msgq_str(sp, M_SYSERR, frp->name, "241|%s: close");
		++ep->refcnt;
		return (1);
	}

	/* COMMITTED TO THE CLOSE.  THERE'S NO GOING BACK... */

	/* Stop logging. */
	(void)log_end(sp, ep);

	/* Free up any marks. */
	(void)mark_end(sp, ep);

	/*
	 * Delete recovery files, close the open descriptor, free recovery
	 * memory.  See recover.c for a description of the protocol.
	 *
	 * XXX
	 * Unlink backup file first, we can detect that the recovery file
	 * doesn't reference anything when the user tries to recover it.
	 * There's a race, here, obviously, but it's fairly small.
	 */
	if (!F_ISSET(ep, F_RCV_NORM)) {
		if (ep->rcv_path != NULL && unlink(ep->rcv_path))
			msgq_str(sp, M_SYSERR, ep->rcv_path, "242|%s: remove");
		if (ep->rcv_mpath != NULL && unlink(ep->rcv_mpath))
			msgq_str(sp, M_SYSERR, ep->rcv_mpath, "243|%s: remove");
	}
	if (ep->fcntl_fd != -1)
		(void)close(ep->fcntl_fd);
	if (ep->rcv_fd != -1)
		(void)close(ep->rcv_fd);
	if (ep->rcv_path != NULL)
		free(ep->rcv_path);
	if (ep->rcv_mpath != NULL)
		free(ep->rcv_mpath);

	free(ep);
	return (0);
}

/*
 * file_write --
 *	Write the file to disk.  Historic vi had fairly convoluted
 *	semantics for whether or not writes would happen.  That's
 *	why all the flags.
 *
 * PUBLIC: int file_write(SCR *, MARK *, MARK *, char *, int);
 */
int
file_write(sp, fm, tm, name, flags)
	SCR *sp;
	MARK *fm, *tm;
	char *name;
	int flags;
{
	enum { NEWFILE, OLDFILE } mtype;
	struct stat sb;
	EXF *ep;
	FILE *fp;
	FREF *frp;
	MARK from, to;
	size_t len;
	u_long nlno, nch;
	int fd, nf, noname, oflags, rval;
	char *p, *s, *t, buf[MAXPATHLEN + 64];
	const char *msgstr;

	ep = sp->ep;
	frp = sp->frp;

	/*
	 * Writing '%', or naming the current file explicitly, has the
	 * same semantics as writing without a name.
	 */
	if (name == NULL || !strcmp(name, frp->name)) {
		noname = 1;
		name = frp->name;
	} else
		noname = 0;

	/* Can't write files marked read-only, unless forced. */
	if (!LF_ISSET(FS_FORCE) && noname && O_ISSET(sp, O_READONLY)) {
		msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
		    "244|Read-only file, not written; use ! to override" :
		    "245|Read-only file, not written");
		return (1);
	}

	/* If not forced, not appending, and "writeany" not set ... */
	if (!LF_ISSET(FS_FORCE | FS_APPEND) && !O_ISSET(sp, O_WRITEANY)) {
		/* Don't overwrite anything but the original file. */
		if ((!noname || F_ISSET(frp, FR_NAMECHANGE)) &&
		    !stat(name, &sb)) {
			msgq_str(sp, M_ERR, name,
			    LF_ISSET(FS_POSSIBLE) ?
			    "246|%s exists, not written; use ! to override" :
			    "247|%s exists, not written");
			return (1);
		}

		/*
		 * Don't write part of any existing file.  Only test for the
		 * original file, the previous test catches anything else.
		 */
		if (!LF_ISSET(FS_ALL) && noname && !stat(name, &sb)) {
			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
			    "248|Partial file, not written; use ! to override" :
			    "249|Partial file, not written");
			return (1);
		}
	}

	/*
	 * Figure out if the file already exists -- if it doesn't, we display
	 * the "new file" message.  The stat might not be necessary, but we
	 * just repeat it because it's easier than hacking the previous tests.
	 * The information is only used for the user message and modification
	 * time test, so we can ignore the obvious race condition.
	 *
	 * One final test.  If we're not forcing or appending the current file,
	 * and we have a saved modification time, object if the file changed
	 * since we last edited or wrote it, and make them force it.
	 */
	if (stat(name, &sb))
		mtype = NEWFILE;
	else {
		if (noname && !LF_ISSET(FS_FORCE | FS_APPEND) &&
		    (F_ISSET(ep, F_DEVSET) &&
		    (sb.st_dev != ep->mdev || sb.st_ino != ep->minode) ||
		    sb.st_mtime != ep->mtime)) {
			msgq_str(sp, M_ERR, name, LF_ISSET(FS_POSSIBLE) ?
"250|%s: file modified more recently than this copy; use ! to override" :
"251|%s: file modified more recently than this copy");
			return (1);
		}

		mtype = OLDFILE;
	}

	/* Set flags to create, write, and either append or truncate. */
	oflags = O_CREAT | O_WRONLY |
	    (LF_ISSET(FS_APPEND) ? O_APPEND : O_TRUNC);

	/* Backup the file if requested. */
	if (!opts_empty(sp, O_BACKUP, 1) &&
	    file_backup(sp, name, O_STR(sp, O_BACKUP)) && !LF_ISSET(FS_FORCE))
		return (1);

	/* Open the file. */
	SIGBLOCK;
	if ((fd = open(name, oflags,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
		msgq_str(sp, M_SYSERR, name, "%s");
		SIGUNBLOCK;
		return (1);
	}
	SIGUNBLOCK;

	/* Try and get a lock. */
	if (!noname && file_lock(sp, NULL, NULL, fd, 0) == LOCK_UNAVAIL)
		msgq_str(sp, M_ERR, name,
		    "252|%s: write lock was unavailable");

#if __linux__
	/*
	 * XXX
	 * In libc 4.5.x, fdopen(fd, "w") clears the O_APPEND flag (if set).
	 * This bug is fixed in libc 4.6.x.
	 *
	 * This code works around this problem for libc 4.5.x users.
	 * Note that this code is harmless if you're using libc 4.6.x.
	 */
	if (LF_ISSET(FS_APPEND) && lseek(fd, (off_t)0, SEEK_END) < 0) {
		msgq(sp, M_SYSERR, "%s", name);
		return (1);
	}
#endif

	/*
	 * Use stdio for buffering.
	 *
	 * XXX
	 * SVR4.2 requires the fdopen mode exactly match the original open
	 * mode, i.e. you have to open with "a" if appending.
	 */
	if ((fp = fdopen(fd, LF_ISSET(FS_APPEND) ? "a" : "w")) == NULL) {
		msgq_str(sp, M_SYSERR, name, "%s");
		(void)close(fd);
		return (1);
	}

	/* Build fake addresses, if necessary. */
	if (fm == NULL) {
		from.lno = 1;
		from.cno = 0;
		fm = &from;
		if (db_last(sp, &to.lno))
			return (1);
		to.cno = 0;
		tm = &to;
	}

	rval = ex_writefp(sp, name, fp, fm, tm, &nlno, &nch, 0);

	/*
	 * Save the new last modification time -- even if the write fails
	 * we re-init the time.  That way the user can clean up the disk
	 * and rewrite without having to force it.
	 */
	if (noname)
		if (stat(name, &sb))
			time(&ep->mtime);
		else {
			F_SET(ep, F_DEVSET);
			ep->mdev = sb.st_dev;
			ep->minode = sb.st_ino;

			ep->mtime = sb.st_mtime;
		}

	/*
	 * If the write failed, complain loudly.  ex_writefp() has already
	 * complained about the actual error, reinforce it if data was lost.
	 */
	if (rval) {
		if (!LF_ISSET(FS_APPEND))
			msgq_str(sp, M_ERR, name,
			    "254|%s: WARNING: FILE TRUNCATED");
		return (1);
	}

	/*
	 * Once we've actually written the file, it doesn't matter that the
	 * file name was changed -- if it was, we've already whacked it.
	 */
	F_CLR(frp, FR_NAMECHANGE);

	/*
	 * If wrote the entire file, and it wasn't by appending it to a file,
	 * clear the modified bit.  If the file was written to the original
	 * file name and the file is a temporary, set the "no exit" bit.  This
	 * permits the user to write the file and use it in the context of the
	 * filesystem, but still keeps them from discarding their changes by
	 * exiting.
	 */
	if (LF_ISSET(FS_ALL) && !LF_ISSET(FS_APPEND)) {
		F_CLR(ep, F_MODIFIED);
		if (F_ISSET(frp, FR_TMPFILE))
			if (noname)
				F_SET(frp, FR_TMPEXIT);
			else
				F_CLR(frp, FR_TMPEXIT);
	}

	p = msg_print(sp, name, &nf);
	switch (mtype) {
	case NEWFILE:
		msgstr = msg_cat(sp,
		    "256|%s: new file: %lu lines, %lu characters", NULL);
		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
		if (len >= sizeof(buf))
			len = sizeof(buf) - 1;
		break;
	case OLDFILE:
		msgstr = msg_cat(sp, LF_ISSET(FS_APPEND) ?
		    "315|%s: appended: %lu lines, %lu characters" :
		    "257|%s: %lu lines, %lu characters", NULL);
		len = snprintf(buf, sizeof(buf), msgstr, p, nlno, nch);
		if (len >= sizeof(buf))
			len = sizeof(buf) - 1;
		break;
	default:
		abort();
	}

	/*
	 * There's a nasty problem with long path names.  Cscope and tags files
	 * can result in long paths and vi will request a continuation key from
	 * the user.  Unfortunately, the user has typed ahead, and chaos will
	 * result.  If we assume that the characters in the filenames only take
	 * a single screen column each, we can trim the filename.
	 */
	s = buf;
	if (len >= sp->cols) {
		for (s = buf, t = buf + strlen(p); s < t &&
		    (*s != '/' || len >= sp->cols - 3); ++s, --len);
		if (s == t)
			s = buf;
		else {
			*--s = '.';		/* Leading ellipses. */
			*--s = '.';
			*--s = '.';
		}
	}
	msgq(sp, M_INFO, "%s", s);
	if (nf)
		FREE_SPACE(sp, p, 0);
	return (0);
}

/*
 * file_backup --
 *	Backup the about-to-be-written file.
 *
 * XXX
 * We do the backup by copying the entire file.  It would be nice to do
 * a rename instead, but: (1) both files may not fit and we want to fail
 * before doing the rename; (2) the backup file may not be on the same
 * disk partition as the file being written; (3) there may be optional
 * file information (MACs, DACs, whatever) that we won't get right if we
 * recreate the file.  So, let's not risk it.
 */
static int
file_backup(sp, name, bname)
	SCR *sp;
	char *name, *bname;
{
	struct dirent *dp;
	struct stat sb;
	DIR *dirp;
	EXCMD cmd;
	off_t off;
	size_t blen;
	int flags, maxnum, nr, num, nw, rfd, wfd, version;
	char *bp, *estr, *p, *pct, *slash, *t, *wfname, buf[8192];

	rfd = wfd = -1;
	bp = estr = wfname = NULL;

	/*
	 * Open the current file for reading.  Do this first, so that
	 * we don't exec a shell before the most likely failure point.
	 * If it doesn't exist, it's okay, there's just nothing to back
	 * up.
	 */
	errno = 0;
	if ((rfd = open(name, O_RDONLY, 0)) < 0) {
		if (errno == ENOENT)
			return (0);
		estr = name;
		goto err;
	}

	/*
	 * If the name starts with an 'N' character, add a version number
	 * to the name.  Strip the leading N from the string passed to the
	 * expansion routines, for no particular reason.  It would be nice
	 * to permit users to put the version number anywhere in the backup
	 * name, but there isn't a special character that we can use in the
	 * name, and giving a new character a special meaning leads to ugly
	 * hacks both here and in the supporting ex routines.
	 *
	 * Shell and file name expand the option's value.
	 */
	argv_init(sp, &cmd);
	ex_cinit(&cmd, 0, 0, 0, 0, 0, NULL);
	if (bname[0] == 'N') {
		version = 1;
		++bname;
	} else
		version = 0;
	if (argv_exp2(sp, &cmd, bname, strlen(bname)))
		return (1);

	/*
	 *  0 args: impossible.
	 *  1 args: use it.
	 * >1 args: object, too many args.
	 */
	if (cmd.argc != 1) {
		msgq_str(sp, M_ERR, bname,
		    "258|%s expanded into too many file names");
		(void)close(rfd);
		return (1);
	}

	/*
	 * If appending a version number, read through the directory, looking
	 * for file names that match the name followed by a number.  Make all
	 * of the other % characters in name literal, so the user doesn't get
	 * surprised and sscanf doesn't drop core indirecting through pointers
	 * that don't exist.  If any such files are found, increment its number
	 * by one.
	 */
	if (version) {
		GET_SPACE_GOTO(sp, bp, blen, cmd.argv[0]->len * 2 + 50);
		for (t = bp, slash = NULL,
		    p = cmd.argv[0]->bp; p[0] != '\0'; *t++ = *p++)
			if (p[0] == '%') {
				if (p[1] != '%')
					*t++ = '%';
			} else if (p[0] == '/')
				slash = t;
		pct = t;
		*t++ = '%';
		*t++ = 'd';
		*t = '\0';

		if (slash == NULL) {
			dirp = opendir(".");
			p = bp;
		} else {
			*slash = '\0';
			dirp = opendir(bp);
			*slash = '/';
			p = slash + 1;
		}
		if (dirp == NULL) {
			estr = cmd.argv[0]->bp;
			goto err;
		}

		for (maxnum = 0; (dp = readdir(dirp)) != NULL;)
			if (sscanf(dp->d_name, p, &num) == 1 && num > maxnum)
				maxnum = num;
		(void)closedir(dirp);

		/* Format the backup file name. */
		(void)snprintf(pct, blen - (pct - bp), "%d", maxnum + 1);
		wfname = bp;
	} else {
		bp = NULL;
		wfname = cmd.argv[0]->bp;
	}
	
	/* Open the backup file, avoiding lurkers. */
	if (stat(wfname, &sb) == 0) {
		if (!S_ISREG(sb.st_mode)) {
			msgq_str(sp, M_ERR, bname,
			    "259|%s: not a regular file");
			goto err;
		}
		if (sb.st_uid != getuid()) {
			msgq_str(sp, M_ERR, bname, "260|%s: not owned by you");
			goto err;
		}
		if (sb.st_mode & (S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
			msgq_str(sp, M_ERR, bname,
			   "261|%s: accessible by a user other than the owner");
			goto err;
		}
		flags = O_TRUNC;
	} else
		flags = O_CREAT | O_EXCL;
	if ((wfd = open(wfname, flags | O_WRONLY, S_IRUSR | S_IWUSR)) < 0 ||
	    fchmod(wfd, S_IRUSR | S_IWUSR) < 0) {
		if (wfd != -1) {
			close(wfd);
			(void)unlink(wfname);
		}
		estr = bname;
		goto err;
	}

	/* Copy the file's current contents to its backup value. */
	while ((nr = read(rfd, buf, sizeof(buf))) > 0)
		for (off = 0; nr != 0; nr -= nw, off += nw)
			if ((nw = write(wfd, buf + off, nr)) < 0) {
				estr = wfname;
				goto err;
			}
	if (nr < 0) {
		estr = name;
		goto err;
	}

	if (close(rfd)) {
		estr = name;
		goto err;
	}
	if (close(wfd)) {
		estr = wfname;
		goto err;
	}
	if (bp != NULL)
		FREE_SPACE(sp, bp, blen);
	return (0);

alloc_err:
err:	if (rfd != -1)
		(void)close(rfd);
	if (wfd != -1) {
		(void)unlink(wfname);
		(void)close(wfd);
	}
	if (estr)
		msgq_str(sp, M_SYSERR, estr, "%s");
	if (bp != NULL)
		FREE_SPACE(sp, bp, blen);
	return (1);
}

/*
 * file_comment --
 *	Skip the first comment.
 */
static void
file_comment(sp)
	SCR *sp;
{
	recno_t lno;
	size_t len;
	char *p;

	for (lno = 1; !db_get(sp, lno, 0, &p, &len) && len == 0; ++lno);
	if (p == NULL)
		return;
	if (p[0] == '#') {
		F_SET(sp, SC_SCR_TOP);
		while (!db_get(sp, ++lno, 0, &p, &len))
			if (len < 1 || p[0] != '#') {
				sp->lno = lno;
				return;
			}
	} else if (len > 1 && p[0] == '/' && p[1] == '*') {
		F_SET(sp, SC_SCR_TOP);
		do {
			for (; len > 1; --len, ++p)
				if (p[0] == '*' && p[1] == '/') {
					sp->lno = lno;
					return;
				}
		} while (!db_get(sp, ++lno, 0, &p, &len));
	} else if (len > 1 && p[0] == '/' && p[1] == '/') {
		F_SET(sp, SC_SCR_TOP);
		p += 2;
		len -= 2;
		do {
			for (; len > 1; --len, ++p)
				if (p[0] == '/' && p[1] == '/') {
					sp->lno = lno;
					return;
				}
		} while (!db_get(sp, ++lno, 0, &p, &len));
	}
}

/*
 * file_m1 --
 * 	First modification check routine.  The :next, :prev, :rewind, :tag,
 *	:tagpush, :tagpop, ^^ modifications check.
 *
 * PUBLIC: int file_m1(SCR *, int, int);
 */
int
file_m1(sp, force, flags)
	SCR *sp;
	int force, flags;
{
	EXF *ep;

	ep = sp->ep;

	/* If no file loaded, return no modifications. */
	if (ep == NULL)
		return (0);

	/*
	 * If the file has been modified, we'll want to write it back or
	 * fail.  If autowrite is set, we'll write it back automatically,
	 * unless force is also set.  Otherwise, we fail unless forced or
	 * there's another open screen on this file.
	 */
	if (F_ISSET(ep, F_MODIFIED))
		if (O_ISSET(sp, O_AUTOWRITE)) {
			if (!force && file_aw(sp, flags))
				return (1);
		} else if (ep->refcnt <= 1 && !force) {
			msgq(sp, M_ERR, LF_ISSET(FS_POSSIBLE) ?
"262|File modified since last complete write; write or use ! to override" :
"263|File modified since last complete write; write or use :edit! to override");
			return (1);
		}

	return (file_m3(sp, force));
}

/*
 * file_m2 --
 * 	Second modification check routine.  The :edit, :quit, :recover
 *	modifications check.
 *
 * PUBLIC: int file_m2(SCR *, int);
 */
int
file_m2(sp, force)
	SCR *sp;
	int force;
{
	EXF *ep;

	ep = sp->ep;

	/* If no file loaded, return no modifications. */
	if (ep == NULL)
		return (0);

	/*
	 * If the file has been modified, we'll want to fail, unless forced
	 * or there's another open screen on this file.
	 */
	if (F_ISSET(ep, F_MODIFIED) && ep->refcnt <= 1 && !force) {
		msgq(sp, M_ERR,
"264|File modified since last complete write; write or use ! to override");
		return (1);
	}

	return (file_m3(sp, force));
}

/*
 * file_m3 --
 * 	Third modification check routine.
 *
 * PUBLIC: int file_m3(SCR *, int);
 */
int
file_m3(sp, force)
	SCR *sp;
	int force;
{
	EXF *ep;

	ep = sp->ep;

	/* If no file loaded, return no modifications. */
	if (ep == NULL)
		return (0);

	/*
	 * Don't exit while in a temporary files if the file was ever modified.
	 * The problem is that if the user does a ":wq", we write and quit,
	 * unlinking the temporary file.  Not what the user had in mind at all.
	 * We permit writing to temporary files, so that user maps using file
	 * system names work with temporary files.
	 */
	if (F_ISSET(sp->frp, FR_TMPEXIT) && ep->refcnt <= 1 && !force) {
		msgq(sp, M_ERR,
		    "265|File is a temporary; exit will discard modifications");
		return (1);
	}
	return (0);
}

/*
 * file_aw --
 *	Autowrite routine.  If modified, autowrite is set and the readonly bit
 *	is not set, write the file.  A routine so there's a place to put the
 *	comment.
 *
 * PUBLIC: int file_aw(SCR *, int);
 */
int
file_aw(sp, flags)
	SCR *sp;
	int flags;
{
	if (!F_ISSET(sp->ep, F_MODIFIED))
		return (0);
	if (!O_ISSET(sp, O_AUTOWRITE))
		return (0);

	/*
	 * !!!
	 * Historic 4BSD vi attempted to write the file if autowrite was set,
	 * regardless of the writeability of the file (as defined by the file
	 * readonly flag).  System V changed this as some point, not attempting
	 * autowrite if the file was readonly.  This feels like a bug fix to
	 * me (e.g. the principle of least surprise is violated if readonly is
	 * set and vi writes the file), so I'm compatible with System V.
	 */
	if (O_ISSET(sp, O_READONLY)) {
		msgq(sp, M_INFO,
		    "266|File readonly, modifications not auto-written");
		return (1);
	}
	return (file_write(sp, NULL, NULL, NULL, flags));
}

/*
 * set_alt_name --
 *	Set the alternate pathname.
 *
 * Set the alternate pathname.  It's a routine because I wanted some place
 * to hang this comment.  The alternate pathname (normally referenced using
 * the special character '#' during file expansion and in the vi ^^ command)
 * is set by almost all ex commands that take file names as arguments.  The
 * rules go something like this:
 *
 *    1: If any ex command takes a file name as an argument (except for the
 *	 :next command), the alternate pathname is set to that file name.
 *	 This excludes the command ":e" and ":w !command" as no file name
 *       was specified.  Note, historically, the :source command did not set
 *	 the alternate pathname.  It does in nvi, for consistency.
 *
 *    2: However, if any ex command sets the current pathname, e.g. the
 *	 ":e file" or ":rew" commands succeed, then the alternate pathname
 *	 is set to the previous file's current pathname, if it had one.
 *	 This includes the ":file" command and excludes the ":e" command.
 *	 So, by rule #1 and rule #2, if ":edit foo" fails, the alternate
 *	 pathname will be "foo", if it succeeds, the alternate pathname will
 *	 be the previous current pathname.  The ":e" command will not set
 *       the alternate or current pathnames regardless.
 *
 *    3: However, if it's a read or write command with a file argument and
 *	 the current pathname has not yet been set, the file name becomes
 *	 the current pathname, and the alternate pathname is unchanged.
 *
 * If the user edits a temporary file, there may be times when there is no
 * alternative file name.  A name argument of NULL turns it off.
 *
 * PUBLIC: void set_alt_name(SCR *, char *);
 */
void
set_alt_name(sp, name)
	SCR *sp;
	char *name;
{
	if (sp->alt_name != NULL)
		free(sp->alt_name);
	if (name == NULL)
		sp->alt_name = NULL;
	else if ((sp->alt_name = strdup(name)) == NULL)
		msgq(sp, M_SYSERR, NULL);
}

/*
 * file_lock --
 *	Get an exclusive lock on a file.
 *
 * XXX
 * The default locking is flock(2) style, not fcntl(2).  The latter is
 * known to fail badly on some systems, and its only advantage is that
 * it occasionally works over NFS.
 *
 * Furthermore, the semantics of fcntl(2) are wrong.  The problems are
 * two-fold: you can't close any file descriptor associated with the file
 * without losing all of the locks, and you can't get an exclusive lock
 * unless you have the file open for writing.  Someone ought to be shot,
 * but it's probably too late, they may already have reproduced.  To get
 * around these problems, nvi opens the files for writing when it can and
 * acquires a second file descriptor when it can't.  The recovery files
 * are examples of the former, they're always opened for writing.  The DB
 * files can't be opened for writing because the semantics of DB are that
 * files opened for writing are flushed back to disk when the DB session
 * is ended. So, in that case we have to acquire an extra file descriptor.
 *
 * PUBLIC: lockr_t file_lock(SCR *, char *, int *, int, int);
 */
lockr_t
file_lock(sp, name, fdp, fd, iswrite)
	SCR *sp;
	char *name;
	int *fdp, fd, iswrite;
{
	if (!O_ISSET(sp, O_LOCKFILES))
		return (LOCK_SUCCESS);
	
	/* Set close-on-exec flag so locks are not inherited by shell cmd. */
	if (fcntl(fd, F_SETFD, 1) == -1)
		msgq_str(sp, M_SYSERR, name, "%s");

#ifdef HAVE_LOCK_FLOCK			/* Hurrah!  We've got flock(2). */
	/*
	 * !!!
	 * We need to distinguish a lock not being available for the file
	 * from the file system not supporting locking.  Flock is documented
	 * as returning EWOULDBLOCK; add EAGAIN for good measure, and assume
	 * they are the former.  There's no portable way to do this.
	 */
	errno = 0;
	return (flock(fd, LOCK_EX | LOCK_NB) ? errno == EAGAIN
#ifdef EWOULDBLOCK
	    || errno == EWOULDBLOCK
#endif
	    ? LOCK_UNAVAIL : LOCK_FAILED : LOCK_SUCCESS);
#endif
#ifdef HAVE_LOCK_FCNTL			/* Gag me.  We've got fcntl(2). */
{
	struct flock arg;
	int didopen, sverrno;

	arg.l_type = F_WRLCK;
	arg.l_whence = 0;		/* SEEK_SET */
	arg.l_start = arg.l_len = 0;
	arg.l_pid = 0;

	/*
	 * If the file descriptor isn't opened for writing, it must fail.
	 * If we fail because we can't get a read/write file descriptor,
	 * we return LOCK_SUCCESS, believing that the file is readonly
	 * and that will be sufficient to warn the user.
	 */
	if (!iswrite) {
		if (name == NULL || fdp == NULL)
			return (LOCK_FAILED);
		if ((fd = open(name, O_RDWR, 0)) == -1)
			return (LOCK_SUCCESS);
		*fdp = fd;
		didopen = 1;
	}

	errno = 0;
	if (!fcntl(fd, F_SETLK, &arg))
		return (LOCK_SUCCESS);
	if (didopen) {
		sverrno = errno;
		(void)close(fd);
		errno = sverrno;
	}

	/*
	 * !!!
	 * We need to distinguish a lock not being available for the file
	 * from the file system not supporting locking.  Fcntl is documented
	 * as returning EACCESS and EAGAIN; add EWOULDBLOCK for good measure,
	 * and assume they are the former.  There's no portable way to do this.
	 */
	return (errno == EACCES || errno == EAGAIN
#ifdef EWOULDBLOCK
	|| errno == EWOULDBLOCK
#endif
	?  LOCK_UNAVAIL : LOCK_FAILED);
}
#endif
#if !defined(HAVE_LOCK_FLOCK) && !defined(HAVE_LOCK_FCNTL)
	return (LOCK_SUCCESS);
#endif
}