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.
6 *
7 * See the LICENSE file for redistribution information.
8 */
9
10#include "config.h"
11
12#ifndef lint
13static const char sccsid[] = "$Id: ex_write.c,v 10.41 2011/12/02 01:07:06 zy Exp $";
14#endif /* not lint */
15
16#include <sys/types.h>
17#include <sys/queue.h>
18#include <sys/stat.h>
19
20#include <bitstring.h>
21#include <ctype.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <limits.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <strings.h>
29#include <unistd.h>
30
31#include "../common/common.h"
32
33enum which {WN, WQ, WRITE, XIT};
34static int exwr __P((SCR *, EXCMD *, enum which));
35
36/*
37 * ex_wn --	:wn[!] [>>] [file]
38 *	Write to a file and switch to the next one.
39 *
40 * PUBLIC: int ex_wn __P((SCR *, EXCMD *));
41 */
42int
43ex_wn(SCR *sp, EXCMD *cmdp)
44{
45	if (exwr(sp, cmdp, WN))
46		return (1);
47	if (file_m3(sp, 0))
48		return (1);
49
50	/* The file name isn't a new file to edit. */
51	cmdp->argc = 0;
52
53	return (ex_next(sp, cmdp));
54}
55
56/*
57 * ex_wq --	:wq[!] [>>] [file]
58 *	Write to a file and quit.
59 *
60 * PUBLIC: int ex_wq __P((SCR *, EXCMD *));
61 */
62int
63ex_wq(SCR *sp, EXCMD *cmdp)
64{
65	int force;
66
67	if (exwr(sp, cmdp, WQ))
68		return (1);
69	if (file_m3(sp, 0))
70		return (1);
71
72	force = FL_ISSET(cmdp->iflags, E_C_FORCE);
73
74	if (ex_ncheck(sp, force))
75		return (1);
76
77	F_SET(sp, force ? SC_EXIT_FORCE : SC_EXIT);
78	return (0);
79}
80
81/*
82 * ex_write --	:write[!] [>>] [file]
83 *		:write [!] [cmd]
84 *	Write to a file.
85 *
86 * PUBLIC: int ex_write __P((SCR *, EXCMD *));
87 */
88int
89ex_write(SCR *sp, EXCMD *cmdp)
90{
91	return (exwr(sp, cmdp, WRITE));
92}
93
94
95/*
96 * ex_xit -- :x[it]! [file]
97 *	Write out any modifications and quit.
98 *
99 * PUBLIC: int ex_xit __P((SCR *, EXCMD *));
100 */
101int
102ex_xit(SCR *sp, EXCMD *cmdp)
103{
104	int force;
105
106	NEEDFILE(sp, cmdp);
107
108	if (F_ISSET(sp->ep, F_MODIFIED) && exwr(sp, cmdp, XIT))
109		return (1);
110	if (file_m3(sp, 0))
111		return (1);
112
113	force = FL_ISSET(cmdp->iflags, E_C_FORCE);
114
115	if (ex_ncheck(sp, force))
116		return (1);
117
118	F_SET(sp, force ? SC_EXIT_FORCE : SC_EXIT);
119	return (0);
120}
121
122/*
123 * exwr --
124 *	The guts of the ex write commands.
125 */
126static int
127exwr(SCR *sp, EXCMD *cmdp, enum which cmd)
128{
129	MARK rm;
130	int flags;
131	char *name;
132	CHAR_T *p = NULL;
133	size_t nlen;
134	char *n;
135	int rc;
136	EX_PRIVATE *exp;
137
138	NEEDFILE(sp, cmdp);
139
140	/* All write commands can have an associated '!'. */
141	LF_INIT(FS_POSSIBLE);
142	if (FL_ISSET(cmdp->iflags, E_C_FORCE))
143		LF_SET(FS_FORCE);
144
145	/* Skip any leading whitespace. */
146	if (cmdp->argc != 0)
147		for (p = cmdp->argv[0]->bp; *p != '\0' && cmdskip(*p); ++p);
148
149	/* If "write !" it's a pipe to a utility. */
150	if (cmdp->argc != 0 && cmd == WRITE && *p == '!') {
151		/* Secure means no shell access. */
152		if (O_ISSET(sp, O_SECURE)) {
153			ex_wemsg(sp, cmdp->cmd->name, EXM_SECURE_F);
154			return (1);
155		}
156
157		/* Expand the argument. */
158		for (++p; *p && cmdskip(*p); ++p);
159		if (*p == '\0') {
160			ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE);
161			return (1);
162		}
163		if (argv_exp1(sp, cmdp, p, STRLEN(p), 1))
164			return (1);
165
166		/* Set the last bang command */
167		exp = EXP(sp);
168		free(exp->lastbcomm);
169		exp->lastbcomm = v_wstrdup(sp, cmdp->argv[1]->bp,
170		    cmdp->argv[1]->len);
171
172		/*
173		 * Historically, vi waited after a write filter even if there
174		 * wasn't any output from the command.  People complained when
175		 * nvi waited only if there was output, wanting the visual cue
176		 * that the program hadn't written anything.
177		 */
178		F_SET(sp, SC_EX_WAIT_YES);
179
180		/*
181		 * !!!
182		 * Ignore the return cursor position, the cursor doesn't
183		 * move.
184		 */
185		if (ex_filter(sp, cmdp, &cmdp->addr1,
186		    &cmdp->addr2, &rm, cmdp->argv[1]->bp, FILTER_WRITE))
187			return (1);
188
189		/* Ex terminates with a bang, even if the command fails. */
190		if (!F_ISSET(sp, SC_VI) && !F_ISSET(sp, SC_EX_SILENT))
191			(void)ex_puts(sp, "!\n");
192
193		return (0);
194	}
195
196	/* Set the FS_ALL flag if we're writing the entire file. */
197	if (cmdp->addr1.lno <= 1 && !db_exist(sp, cmdp->addr2.lno + 1))
198		LF_SET(FS_ALL);
199
200	/* If "write >>" it's an append to a file. */
201	if (cmdp->argc != 0 && cmd != XIT && p[0] == '>' && p[1] == '>') {
202		LF_SET(FS_APPEND);
203
204		/* Skip ">>" and whitespace. */
205		for (p += 2; *p && cmdskip(*p); ++p);
206	}
207
208	/* If no other arguments, just write the file back. */
209	if (cmdp->argc == 0 || *p == '\0')
210		return (file_write(sp,
211		    &cmdp->addr1, &cmdp->addr2, NULL, flags));
212
213	/* Build an argv so we get an argument count and file expansion. */
214	if (argv_exp2(sp, cmdp, p, STRLEN(p)))
215		return (1);
216
217	/*
218	 *  0 args: impossible.
219	 *  1 args: impossible (I hope).
220	 *  2 args: read it.
221	 * >2 args: object, too many args.
222	 *
223	 * The 1 args case depends on the argv_sexp() function refusing
224	 * to return success without at least one non-blank character.
225	 */
226	switch (cmdp->argc) {
227	case 0:
228	case 1:
229		abort();
230		/* NOTREACHED */
231	case 2:
232		INT2CHAR(sp, cmdp->argv[1]->bp, cmdp->argv[1]->len+1,
233			 n, nlen);
234		name = v_strdup(sp, n, nlen - 1);
235
236		/*
237		 * !!!
238		 * Historically, the read and write commands renamed
239		 * "unnamed" files, or, if the file had a name, set
240		 * the alternate file name.
241		 */
242		if (F_ISSET(sp->frp, FR_TMPFILE) &&
243		    !F_ISSET(sp->frp, FR_EXNAMED)) {
244			if ((n = v_strdup(sp, name, nlen - 1)) != NULL) {
245				free(sp->frp->name);
246				sp->frp->name = n;
247			}
248			/*
249			 * The file has a real name, it's no longer a
250			 * temporary, clear the temporary file flags.
251			 *
252			 * !!!
253			 * If we're writing the whole file, FR_NAMECHANGE
254			 * will be cleared by the write routine -- this is
255			 * historic practice.
256			 */
257			F_CLR(sp->frp, FR_TMPEXIT | FR_TMPFILE);
258			F_SET(sp->frp, FR_NAMECHANGE | FR_EXNAMED);
259
260			/* Notify the screen. */
261			(void)sp->gp->scr_rename(sp, sp->frp->name, 1);
262		} else
263			set_alt_name(sp, name);
264		break;
265	default:
266		INT2CHAR(sp, p, STRLEN(p) + 1, n, nlen);
267		ex_emsg(sp, n, EXM_FILECOUNT);
268		return (1);
269	}
270
271	rc = file_write(sp, &cmdp->addr1, &cmdp->addr2, name, flags);
272
273	free(name);
274
275	return rc;
276}
277
278/*
279 * ex_writefp --
280 *	Write a range of lines to a FILE *.
281 *
282 * PUBLIC: int ex_writefp __P((SCR *,
283 * PUBLIC:    char *, FILE *, MARK *, MARK *, u_long *, u_long *, int));
284 */
285int
286ex_writefp(SCR *sp, char *name, FILE *fp, MARK *fm, MARK *tm, u_long *nlno, u_long *nch, int silent)
287{
288	struct stat sb;
289	GS *gp;
290	u_long ccnt;			/* XXX: can't print off_t portably. */
291	recno_t fline, tline, lcnt;
292	size_t len;
293	int rval;
294	char *msg;
295	CHAR_T *p;
296	char *f;
297	size_t flen;
298	int isutf16;
299
300	gp = sp->gp;
301	fline = fm->lno;
302	tline = tm->lno;
303
304	if (nlno != NULL) {
305		*nch = 0;
306		*nlno = 0;
307	}
308
309	/*
310	 * The vi filter code has multiple processes running simultaneously,
311	 * and one of them calls ex_writefp().  The "unsafe" function calls
312	 * in this code are to db_get() and msgq().  Db_get() is safe, see
313	 * the comment in ex_filter.c:ex_filter() for details.  We don't call
314	 * msgq if the multiple process bit in the EXF is set.
315	 *
316	 * !!!
317	 * Historic vi permitted files of 0 length to be written.  However,
318	 * since the way vi got around dealing with "empty" files was to
319	 * always have a line in the file no matter what, it wrote them as
320	 * files of a single, empty line.  We write empty files.
321	 *
322	 * "Alex, I'll take vi trivia for $1000."
323	 */
324	ccnt = 0;
325	lcnt = 0;
326	msg = "253|Writing...";
327
328	if (O_ISSET(sp, O_FILEENCODING)) {
329		isutf16 = !strncasecmp(O_STR(sp, O_FILEENCODING), "utf-16", 6);
330		isutf16 += !strncasecmp(O_STR(sp, O_FILEENCODING), "utf-16le", 8);
331	} else isutf16 = 0;
332
333	if (tline != 0) {
334		if (isutf16 == 1 && fwrite("\xfe\xff", 1, 2, fp) != 2)
335			goto err;
336		if (isutf16 == 2 && fwrite("\xff\xfe", 1, 2, fp) != 2)
337			goto err;
338		for (; fline <= tline; ++fline, ++lcnt) {
339			/* Caller has to provide any interrupt message. */
340			if ((lcnt + 1) % INTERRUPT_CHECK == 0) {
341				if (INTERRUPTED(sp))
342					break;
343				if (!silent) {
344					gp->scr_busy(sp, msg, msg == NULL ?
345					    BUSY_UPDATE : BUSY_ON);
346					msg = NULL;
347				}
348			}
349			if (db_get(sp, fline, DBG_FATAL, &p, &len))
350				goto err;
351			INT2FILE(sp, p, len, f, flen);
352			if (fwrite(f, 1, flen, fp) != flen)
353				goto err;
354			ccnt += len;
355			/* UTF-16 w/o BOM is big-endian */
356			switch (isutf16) {
357			case 1:		/* UTF-16BE */
358				if (fwrite("\0\x0a", 1, 2, fp) != 2)
359					goto done;
360				break;
361			case 2:		/* UTF-16LE */
362				if (fwrite("\x0a\0", 1, 2, fp) != 2)
363					goto done;
364				break;
365			default:
366				if (putc('\n', fp) != '\n')
367					goto done;
368			}
369			++ccnt;
370		}
371	}
372
373done:	if (fflush(fp))
374		goto err;
375	/*
376	 * XXX
377	 * I don't trust NFS -- check to make sure that we're talking to
378	 * a regular file and sync so that NFS is forced to flush.
379	 */
380	if (!fstat(fileno(fp), &sb) &&
381	    S_ISREG(sb.st_mode) && fsync(fileno(fp)))
382		goto err;
383
384	if (fclose(fp))
385		goto err;
386
387	rval = 0;
388	if (0) {
389err:		if (!F_ISSET(sp->ep, F_MULTILOCK))
390			msgq_str(sp, M_SYSERR, name, "%s");
391		(void)fclose(fp);
392		rval = 1;
393	}
394
395	if (!silent)
396		gp->scr_busy(sp, NULL, BUSY_OFF);
397
398	/* Report the possibly partial transfer. */
399	if (nlno != NULL) {
400		*nch = ccnt;
401		*nlno = lcnt;
402	}
403	return (rval);
404}
405