blob: f1895518b39f456f0c9917f804664d3864878f9c [file] [log] [blame]
Bram Moolenaar473952e2019-09-28 16:30:04 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * bufwrite.c: functions for writing a buffer
12 */
13
14#include "vim.h"
15
16#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
17# include <utime.h> // for struct utimbuf
18#endif
19
20#define SMALLBUFSIZE 256 // size of emergency write buffer
21
22/*
23 * Structure to pass arguments from buf_write() to buf_write_bytes().
24 */
25struct bw_info
26{
27 int bw_fd; // file descriptor
28 char_u *bw_buf; // buffer with data to be written
29 int bw_len; // length of data
30 int bw_flags; // FIO_ flags
31#ifdef FEAT_CRYPT
32 buf_T *bw_buffer; // buffer being written
33#endif
34 char_u bw_rest[CONV_RESTLEN]; // not converted bytes
35 int bw_restlen; // nr of bytes in bw_rest[]
36 int bw_first; // first write call
37 char_u *bw_conv_buf; // buffer for writing converted chars
38 size_t bw_conv_buflen; // size of bw_conv_buf
39 int bw_conv_error; // set for conversion error
40 linenr_T bw_conv_error_lnum; // first line with error or zero
41 linenr_T bw_start_lnum; // line number at start of buffer
42#ifdef USE_ICONV
43 iconv_t bw_iconv_fd; // descriptor for iconv() or -1
44#endif
45};
46
47/*
48 * Convert a Unicode character to bytes.
49 * Return TRUE for an error, FALSE when it's OK.
50 */
51 static int
52ucs2bytes(
53 unsigned c, // in: character
54 char_u **pp, // in/out: pointer to result
55 int flags) // FIO_ flags
56{
57 char_u *p = *pp;
58 int error = FALSE;
59 int cc;
60
61
62 if (flags & FIO_UCS4)
63 {
64 if (flags & FIO_ENDIAN_L)
65 {
66 *p++ = c;
67 *p++ = (c >> 8);
68 *p++ = (c >> 16);
69 *p++ = (c >> 24);
70 }
71 else
72 {
73 *p++ = (c >> 24);
74 *p++ = (c >> 16);
75 *p++ = (c >> 8);
76 *p++ = c;
77 }
78 }
79 else if (flags & (FIO_UCS2 | FIO_UTF16))
80 {
81 if (c >= 0x10000)
82 {
83 if (flags & FIO_UTF16)
84 {
85 // Make two words, ten bits of the character in each. First
86 // word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff
87 c -= 0x10000;
88 if (c >= 0x100000)
89 error = TRUE;
90 cc = ((c >> 10) & 0x3ff) + 0xd800;
91 if (flags & FIO_ENDIAN_L)
92 {
93 *p++ = cc;
94 *p++ = ((unsigned)cc >> 8);
95 }
96 else
97 {
98 *p++ = ((unsigned)cc >> 8);
99 *p++ = cc;
100 }
101 c = (c & 0x3ff) + 0xdc00;
102 }
103 else
104 error = TRUE;
105 }
106 if (flags & FIO_ENDIAN_L)
107 {
108 *p++ = c;
109 *p++ = (c >> 8);
110 }
111 else
112 {
113 *p++ = (c >> 8);
114 *p++ = c;
115 }
116 }
117 else // Latin1
118 {
119 if (c >= 0x100)
120 {
121 error = TRUE;
122 *p++ = 0xBF;
123 }
124 else
125 *p++ = c;
126 }
127
128 *pp = p;
129 return error;
130}
131
132/*
133 * Call write() to write a number of bytes to the file.
134 * Handles encryption and 'encoding' conversion.
135 *
136 * Return FAIL for failure, OK otherwise.
137 */
138 static int
139buf_write_bytes(struct bw_info *ip)
140{
141 int wlen;
142 char_u *buf = ip->bw_buf; // data to write
143 int len = ip->bw_len; // length of data
144 int flags = ip->bw_flags; // extra flags
145
146 // Skip conversion when writing the crypt magic number or the BOM.
147 if (!(flags & FIO_NOCONVERT))
148 {
149 char_u *p;
150 unsigned c;
151 int n;
152
153 if (flags & FIO_UTF8)
154 {
155 // Convert latin1 in the buffer to UTF-8 in the file.
156 p = ip->bw_conv_buf; // translate to buffer
157 for (wlen = 0; wlen < len; ++wlen)
158 p += utf_char2bytes(buf[wlen], p);
159 buf = ip->bw_conv_buf;
160 len = (int)(p - ip->bw_conv_buf);
161 }
162 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
163 {
164 // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
165 // Latin1 chars in the file.
166 if (flags & FIO_LATIN1)
167 p = buf; // translate in-place (can only get shorter)
168 else
169 p = ip->bw_conv_buf; // translate to buffer
170 for (wlen = 0; wlen < len; wlen += n)
171 {
172 if (wlen == 0 && ip->bw_restlen != 0)
173 {
174 int l;
175
176 // Use remainder of previous call. Append the start of
177 // buf[] to get a full sequence. Might still be too
178 // short!
179 l = CONV_RESTLEN - ip->bw_restlen;
180 if (l > len)
181 l = len;
182 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
183 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
184 if (n > ip->bw_restlen + len)
185 {
186 // We have an incomplete byte sequence at the end to
187 // be written. We can't convert it without the
188 // remaining bytes. Keep them for the next call.
189 if (ip->bw_restlen + len > CONV_RESTLEN)
190 return FAIL;
191 ip->bw_restlen += len;
192 break;
193 }
194 if (n > 1)
195 c = utf_ptr2char(ip->bw_rest);
196 else
197 c = ip->bw_rest[0];
198 if (n >= ip->bw_restlen)
199 {
200 n -= ip->bw_restlen;
201 ip->bw_restlen = 0;
202 }
203 else
204 {
205 ip->bw_restlen -= n;
206 mch_memmove(ip->bw_rest, ip->bw_rest + n,
207 (size_t)ip->bw_restlen);
208 n = 0;
209 }
210 }
211 else
212 {
213 n = utf_ptr2len_len(buf + wlen, len - wlen);
214 if (n > len - wlen)
215 {
216 // We have an incomplete byte sequence at the end to
217 // be written. We can't convert it without the
218 // remaining bytes. Keep them for the next call.
219 if (len - wlen > CONV_RESTLEN)
220 return FAIL;
221 ip->bw_restlen = len - wlen;
222 mch_memmove(ip->bw_rest, buf + wlen,
223 (size_t)ip->bw_restlen);
224 break;
225 }
226 if (n > 1)
227 c = utf_ptr2char(buf + wlen);
228 else
229 c = buf[wlen];
230 }
231
232 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
233 {
234 ip->bw_conv_error = TRUE;
235 ip->bw_conv_error_lnum = ip->bw_start_lnum;
236 }
237 if (c == NL)
238 ++ip->bw_start_lnum;
239 }
240 if (flags & FIO_LATIN1)
241 len = (int)(p - buf);
242 else
243 {
244 buf = ip->bw_conv_buf;
245 len = (int)(p - ip->bw_conv_buf);
246 }
247 }
248
249#ifdef MSWIN
250 else if (flags & FIO_CODEPAGE)
251 {
252 // Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
253 // codepage.
254 char_u *from;
255 size_t fromlen;
256 char_u *to;
257 int u8c;
258 BOOL bad = FALSE;
259 int needed;
260
261 if (ip->bw_restlen > 0)
262 {
263 // Need to concatenate the remainder of the previous call and
264 // the bytes of the current call. Use the end of the
265 // conversion buffer for this.
266 fromlen = len + ip->bw_restlen;
267 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
268 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
269 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
270 }
271 else
272 {
273 from = buf;
274 fromlen = len;
275 }
276
277 to = ip->bw_conv_buf;
278 if (enc_utf8)
279 {
280 // Convert from UTF-8 to UCS-2, to the start of the buffer.
281 // The buffer has been allocated to be big enough.
282 while (fromlen > 0)
283 {
284 n = (int)utf_ptr2len_len(from, (int)fromlen);
285 if (n > (int)fromlen) // incomplete byte sequence
286 break;
287 u8c = utf_ptr2char(from);
288 *to++ = (u8c & 0xff);
289 *to++ = (u8c >> 8);
290 fromlen -= n;
291 from += n;
292 }
293
294 // Copy remainder to ip->bw_rest[] to be used for the next
295 // call.
296 if (fromlen > CONV_RESTLEN)
297 {
298 // weird overlong sequence
299 ip->bw_conv_error = TRUE;
300 return FAIL;
301 }
302 mch_memmove(ip->bw_rest, from, fromlen);
303 ip->bw_restlen = (int)fromlen;
304 }
305 else
306 {
307 // Convert from enc_codepage to UCS-2, to the start of the
308 // buffer. The buffer has been allocated to be big enough.
309 ip->bw_restlen = 0;
310 needed = MultiByteToWideChar(enc_codepage,
311 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
312 NULL, 0);
313 if (needed == 0)
314 {
315 // When conversion fails there may be a trailing byte.
316 needed = MultiByteToWideChar(enc_codepage,
317 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
318 NULL, 0);
319 if (needed == 0)
320 {
321 // Conversion doesn't work.
322 ip->bw_conv_error = TRUE;
323 return FAIL;
324 }
325 // Save the trailing byte for the next call.
326 ip->bw_rest[0] = from[fromlen - 1];
327 ip->bw_restlen = 1;
328 }
329 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
330 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
331 (LPWSTR)to, needed);
332 if (needed == 0)
333 {
334 // Safety check: Conversion doesn't work.
335 ip->bw_conv_error = TRUE;
336 return FAIL;
337 }
338 to += needed * 2;
339 }
340
341 fromlen = to - ip->bw_conv_buf;
342 buf = to;
343# ifdef CP_UTF8 // VC 4.1 doesn't define CP_UTF8
344 if (FIO_GET_CP(flags) == CP_UTF8)
345 {
346 // Convert from UCS-2 to UTF-8, using the remainder of the
347 // conversion buffer. Fails when out of space.
348 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
349 {
350 u8c = *from++;
351 u8c += (*from++ << 8);
352 to += utf_char2bytes(u8c, to);
353 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
354 {
355 ip->bw_conv_error = TRUE;
356 return FAIL;
357 }
358 }
359 len = (int)(to - buf);
360 }
361 else
362# endif
363 {
364 // Convert from UCS-2 to the codepage, using the remainder of
365 // the conversion buffer. If the conversion uses the default
366 // character "0", the data doesn't fit in this encoding, so
367 // fail.
368 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
369 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
370 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
371 &bad);
372 if (bad)
373 {
374 ip->bw_conv_error = TRUE;
375 return FAIL;
376 }
377 }
378 }
379#endif
380
381#ifdef MACOS_CONVERT
382 else if (flags & FIO_MACROMAN)
383 {
384 // Convert UTF-8 or latin1 to Apple MacRoman.
385 char_u *from;
386 size_t fromlen;
387
388 if (ip->bw_restlen > 0)
389 {
390 // Need to concatenate the remainder of the previous call and
391 // the bytes of the current call. Use the end of the
392 // conversion buffer for this.
393 fromlen = len + ip->bw_restlen;
394 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
395 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
396 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
397 }
398 else
399 {
400 from = buf;
401 fromlen = len;
402 }
403
404 if (enc2macroman(from, fromlen,
405 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
406 ip->bw_rest, &ip->bw_restlen) == FAIL)
407 {
408 ip->bw_conv_error = TRUE;
409 return FAIL;
410 }
411 buf = ip->bw_conv_buf;
412 }
413#endif
414
415#ifdef USE_ICONV
416 if (ip->bw_iconv_fd != (iconv_t)-1)
417 {
418 const char *from;
419 size_t fromlen;
420 char *to;
421 size_t tolen;
422
423 // Convert with iconv().
424 if (ip->bw_restlen > 0)
425 {
426 char *fp;
427
428 // Need to concatenate the remainder of the previous call and
429 // the bytes of the current call. Use the end of the
430 // conversion buffer for this.
431 fromlen = len + ip->bw_restlen;
432 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
433 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
434 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
435 from = fp;
436 tolen = ip->bw_conv_buflen - fromlen;
437 }
438 else
439 {
440 from = (const char *)buf;
441 fromlen = len;
442 tolen = ip->bw_conv_buflen;
443 }
444 to = (char *)ip->bw_conv_buf;
445
446 if (ip->bw_first)
447 {
448 size_t save_len = tolen;
449
450 // output the initial shift state sequence
451 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
452
453 // There is a bug in iconv() on Linux (which appears to be
454 // wide-spread) which sets "to" to NULL and messes up "tolen".
455 if (to == NULL)
456 {
457 to = (char *)ip->bw_conv_buf;
458 tolen = save_len;
459 }
460 ip->bw_first = FALSE;
461 }
462
463 // If iconv() has an error or there is not enough room, fail.
464 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
465 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
466 || fromlen > CONV_RESTLEN)
467 {
468 ip->bw_conv_error = TRUE;
469 return FAIL;
470 }
471
472 // copy remainder to ip->bw_rest[] to be used for the next call.
473 if (fromlen > 0)
474 mch_memmove(ip->bw_rest, (void *)from, fromlen);
475 ip->bw_restlen = (int)fromlen;
476
477 buf = ip->bw_conv_buf;
478 len = (int)((char_u *)to - ip->bw_conv_buf);
479 }
480#endif
481 }
482
483 if (ip->bw_fd < 0)
484 // Only checking conversion, which is OK if we get here.
485 return OK;
486
487#ifdef FEAT_CRYPT
488 if (flags & FIO_ENCRYPTED)
489 {
490 // Encrypt the data. Do it in-place if possible, otherwise use an
491 // allocated buffer.
492# ifdef CRYPT_NOT_INPLACE
493 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
494 {
495# endif
496 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
497# ifdef CRYPT_NOT_INPLACE
498 }
499 else
500 {
501 char_u *outbuf;
502
503 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
504 if (len == 0)
505 return OK; // Crypt layer is buffering, will flush later.
506 wlen = write_eintr(ip->bw_fd, outbuf, len);
507 vim_free(outbuf);
508 return (wlen < len) ? FAIL : OK;
509 }
510# endif
511 }
512#endif
513
514 wlen = write_eintr(ip->bw_fd, buf, len);
515 return (wlen < len) ? FAIL : OK;
516}
517
518/*
519 * Check modification time of file, before writing to it.
520 * The size isn't checked, because using a tool like "gzip" takes care of
521 * using the same timestamp but can't set the size.
522 */
523 static int
524check_mtime(buf_T *buf, stat_T *st)
525{
526 if (buf->b_mtime_read != 0
527 && time_differs((long)st->st_mtime, buf->b_mtime_read))
528 {
529 msg_scroll = TRUE; // don't overwrite messages here
530 msg_silent = 0; // must give this prompt
531 // don't use emsg() here, don't want to flush the buffers
532 msg_attr(_("WARNING: The file has been changed since reading it!!!"),
533 HL_ATTR(HLF_E));
534 if (ask_yesno((char_u *)_("Do you really want to write to it"),
535 TRUE) == 'n')
536 return FAIL;
537 msg_scroll = FALSE; // always overwrite the file message now
538 }
539 return OK;
540}
541
542/*
543 * Generate a BOM in "buf[4]" for encoding "name".
544 * Return the length of the BOM (zero when no BOM).
545 */
546 static int
547make_bom(char_u *buf, char_u *name)
548{
549 int flags;
550 char_u *p;
551
552 flags = get_fio_flags(name);
553
554 // Can't put a BOM in a non-Unicode file.
555 if (flags == FIO_LATIN1 || flags == 0)
556 return 0;
557
558 if (flags == FIO_UTF8) // UTF-8
559 {
560 buf[0] = 0xef;
561 buf[1] = 0xbb;
562 buf[2] = 0xbf;
563 return 3;
564 }
565 p = buf;
566 (void)ucs2bytes(0xfeff, &p, flags);
567 return (int)(p - buf);
568}
569
570#ifdef UNIX
571 static void
572set_file_time(
573 char_u *fname,
574 time_t atime, // access time
575 time_t mtime) // modification time
576{
577# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
578 struct utimbuf buf;
579
580 buf.actime = atime;
581 buf.modtime = mtime;
582 (void)utime((char *)fname, &buf);
583# else
584# if defined(HAVE_UTIMES)
585 struct timeval tvp[2];
586
587 tvp[0].tv_sec = atime;
588 tvp[0].tv_usec = 0;
589 tvp[1].tv_sec = mtime;
590 tvp[1].tv_usec = 0;
591# ifdef NeXT
592 (void)utimes((char *)fname, tvp);
593# else
594 (void)utimes((char *)fname, (const struct timeval *)&tvp);
595# endif
596# endif
597# endif
598}
599#endif // UNIX
600
601/*
602 * buf_write() - write to file "fname" lines "start" through "end"
603 *
604 * We do our own buffering here because fwrite() is so slow.
605 *
606 * If "forceit" is true, we don't care for errors when attempting backups.
607 * In case of an error everything possible is done to restore the original
608 * file. But when "forceit" is TRUE, we risk losing it.
609 *
610 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
611 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
612 *
613 * This function must NOT use NameBuff (because it's called by autowrite()).
614 *
615 * return FAIL for failure, OK otherwise
616 */
617 int
618buf_write(
619 buf_T *buf,
620 char_u *fname,
621 char_u *sfname,
622 linenr_T start,
623 linenr_T end,
624 exarg_T *eap, // for forced 'ff' and 'fenc', can be
625 // NULL!
626 int append, // append to the file
627 int forceit,
628 int reset_changed,
629 int filtering)
630{
631 int fd;
632 char_u *backup = NULL;
633 int backup_copy = FALSE; // copy the original file?
634 int dobackup;
635 char_u *ffname;
636 char_u *wfname = NULL; // name of file to write to
637 char_u *s;
638 char_u *ptr;
639 char_u c;
640 int len;
641 linenr_T lnum;
642 long nchars;
643 char_u *errmsg = NULL;
644 int errmsg_allocated = FALSE;
645 char_u *errnum = NULL;
646 char_u *buffer;
647 char_u smallbuf[SMALLBUFSIZE];
648 char_u *backup_ext;
649 int bufsize;
650 long perm; // file permissions
651 int retval = OK;
652 int newfile = FALSE; // TRUE if file doesn't exist yet
653 int msg_save = msg_scroll;
654 int overwriting; // TRUE if writing over original
655 int no_eol = FALSE; // no end-of-line written
656 int device = FALSE; // writing to a device
657 stat_T st_old;
658 int prev_got_int = got_int;
659 int checking_conversion;
660 int file_readonly = FALSE; // overwritten file is read-only
661 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
662#if defined(UNIX) // XXX fix me sometime?
663 int made_writable = FALSE; // 'w' bit has been set
664#endif
665 // writing everything
666 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
667 linenr_T old_line_count = buf->b_ml.ml_line_count;
668 int attr;
669 int fileformat;
670 int write_bin;
671 struct bw_info write_info; // info for buf_write_bytes()
672 int converted = FALSE;
673 int notconverted = FALSE;
674 char_u *fenc; // effective 'fileencoding'
675 char_u *fenc_tofree = NULL; // allocated "fenc"
676 int wb_flags = 0;
677#ifdef HAVE_ACL
678 vim_acl_T acl = NULL; // ACL copied from original file to
679 // backup or new file
680#endif
681#ifdef FEAT_PERSISTENT_UNDO
682 int write_undo_file = FALSE;
683 context_sha256_T sha_ctx;
684#endif
685 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100686 pos_T orig_start = buf->b_op_start;
687 pos_T orig_end = buf->b_op_end;
Bram Moolenaar473952e2019-09-28 16:30:04 +0200688
689 if (fname == NULL || *fname == NUL) // safety check
690 return FAIL;
691 if (buf->b_ml.ml_mfp == NULL)
692 {
693 // This can happen during startup when there is a stray "w" in the
694 // vimrc file.
695 emsg(_(e_emptybuf));
696 return FAIL;
697 }
698
699 // Disallow writing from .exrc and .vimrc in current directory for
700 // security reasons.
701 if (check_secure())
702 return FAIL;
703
704 // Avoid a crash for a long name.
705 if (STRLEN(fname) >= MAXPATHL)
706 {
707 emsg(_(e_longname));
708 return FAIL;
709 }
710
711 // must init bw_conv_buf and bw_iconv_fd before jumping to "fail"
712 write_info.bw_conv_buf = NULL;
713 write_info.bw_conv_error = FALSE;
714 write_info.bw_conv_error_lnum = 0;
715 write_info.bw_restlen = 0;
716#ifdef USE_ICONV
717 write_info.bw_iconv_fd = (iconv_t)-1;
718#endif
719#ifdef FEAT_CRYPT
720 write_info.bw_buffer = buf;
721#endif
722
723 // After writing a file changedtick changes but we don't want to display
724 // the line.
725 ex_no_reprint = TRUE;
726
727 // If there is no file name yet, use the one for the written file.
728 // BF_NOTEDITED is set to reflect this (in case the write fails).
729 // Don't do this when the write is for a filter command.
730 // Don't do this when appending.
731 // Only do this when 'cpoptions' contains the 'F' flag.
732 if (buf->b_ffname == NULL
733 && reset_changed
734 && whole
735 && buf == curbuf
736#ifdef FEAT_QUICKFIX
737 && !bt_nofilename(buf)
738#endif
739 && !filtering
740 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
741 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
742 {
743 if (set_rw_fname(fname, sfname) == FAIL)
744 return FAIL;
745 buf = curbuf; // just in case autocmds made "buf" invalid
746 }
747
748 if (sfname == NULL)
749 sfname = fname;
750 // For Unix: Use the short file name whenever possible.
751 // Avoids problems with networks and when directory names are changed.
752 // Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
753 // another directory, which we don't detect
754 ffname = fname; // remember full fname
755#ifdef UNIX
756 fname = sfname;
757#endif
758
759 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
760 overwriting = TRUE;
761 else
762 overwriting = FALSE;
763
764 if (exiting)
765 settmode(TMODE_COOK); // when exiting allow typeahead now
766
767 ++no_wait_return; // don't wait for return yet
768
769 // Set '[ and '] marks to the lines to be written.
770 buf->b_op_start.lnum = start;
771 buf->b_op_start.col = 0;
772 buf->b_op_end.lnum = end;
773 buf->b_op_end.col = 0;
774
775 {
776 aco_save_T aco;
777 int buf_ffname = FALSE;
778 int buf_sfname = FALSE;
779 int buf_fname_f = FALSE;
780 int buf_fname_s = FALSE;
781 int did_cmd = FALSE;
782 int nofile_err = FALSE;
783 int empty_memline = (buf->b_ml.ml_mfp == NULL);
784 bufref_T bufref;
785
786 // Apply PRE autocommands.
787 // Set curbuf to the buffer to be written.
788 // Careful: The autocommands may call buf_write() recursively!
789 if (ffname == buf->b_ffname)
790 buf_ffname = TRUE;
791 if (sfname == buf->b_sfname)
792 buf_sfname = TRUE;
793 if (fname == buf->b_ffname)
794 buf_fname_f = TRUE;
795 if (fname == buf->b_sfname)
796 buf_fname_s = TRUE;
797
798 // set curwin/curbuf to buf and save a few things
799 aucmd_prepbuf(&aco, buf);
800 set_bufref(&bufref, buf);
801
802 if (append)
803 {
804 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
805 sfname, sfname, FALSE, curbuf, eap)))
806 {
807#ifdef FEAT_QUICKFIX
808 if (overwriting && bt_nofilename(curbuf))
809 nofile_err = TRUE;
810 else
811#endif
812 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
813 sfname, sfname, FALSE, curbuf, eap);
814 }
815 }
816 else if (filtering)
817 {
818 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
819 NULL, sfname, FALSE, curbuf, eap);
820 }
821 else if (reset_changed && whole)
822 {
823 int was_changed = curbufIsChanged();
824
825 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
826 sfname, sfname, FALSE, curbuf, eap);
827 if (did_cmd)
828 {
829 if (was_changed && !curbufIsChanged())
830 {
831 // Written everything correctly and BufWriteCmd has reset
832 // 'modified': Correct the undo information so that an
833 // undo now sets 'modified'.
834 u_unchanged(curbuf);
835 u_update_save_nr(curbuf);
836 }
837 }
838 else
839 {
840#ifdef FEAT_QUICKFIX
841 if (overwriting && bt_nofilename(curbuf))
842 nofile_err = TRUE;
843 else
844#endif
845 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
846 sfname, sfname, FALSE, curbuf, eap);
847 }
848 }
849 else
850 {
851 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
852 sfname, sfname, FALSE, curbuf, eap)))
853 {
854#ifdef FEAT_QUICKFIX
855 if (overwriting && bt_nofilename(curbuf))
856 nofile_err = TRUE;
857 else
858#endif
859 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
860 sfname, sfname, FALSE, curbuf, eap);
861 }
862 }
863
864 // restore curwin/curbuf and a few other things
865 aucmd_restbuf(&aco);
866
867 // In three situations we return here and don't write the file:
868 // 1. the autocommands deleted or unloaded the buffer.
869 // 2. The autocommands abort script processing.
870 // 3. If one of the "Cmd" autocommands was executed.
871 if (!bufref_valid(&bufref))
872 buf = NULL;
873 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
874 || did_cmd || nofile_err
875#ifdef FEAT_EVAL
876 || aborting()
877#endif
878 )
879 {
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100880 if (buf != NULL && cmdmod.lockmarks)
881 {
882 // restore the original '[ and '] positions
883 buf->b_op_start = orig_start;
884 buf->b_op_end = orig_end;
885 }
886
Bram Moolenaar473952e2019-09-28 16:30:04 +0200887 --no_wait_return;
888 msg_scroll = msg_save;
889 if (nofile_err)
890 emsg(_("E676: No matching autocommands for acwrite buffer"));
891
892 if (nofile_err
893#ifdef FEAT_EVAL
894 || aborting()
895#endif
896 )
897 // An aborting error, interrupt or exception in the
898 // autocommands.
899 return FAIL;
900 if (did_cmd)
901 {
902 if (buf == NULL)
903 // The buffer was deleted. We assume it was written
904 // (can't retry anyway).
905 return OK;
906 if (overwriting)
907 {
908 // Assume the buffer was written, update the timestamp.
909 ml_timestamp(buf);
910 if (append)
911 buf->b_flags &= ~BF_NEW;
912 else
913 buf->b_flags &= ~BF_WRITE_MASK;
914 }
915 if (reset_changed && buf->b_changed && !append
916 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
917 // Buffer still changed, the autocommands didn't work
918 // properly.
919 return FAIL;
920 return OK;
921 }
922#ifdef FEAT_EVAL
923 if (!aborting())
924#endif
925 emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
926 return FAIL;
927 }
928
929 // The autocommands may have changed the number of lines in the file.
930 // When writing the whole file, adjust the end.
931 // When writing part of the file, assume that the autocommands only
932 // changed the number of lines that are to be written (tricky!).
933 if (buf->b_ml.ml_line_count != old_line_count)
934 {
935 if (whole) // write all
936 end = buf->b_ml.ml_line_count;
937 else if (buf->b_ml.ml_line_count > old_line_count) // more lines
938 end += buf->b_ml.ml_line_count - old_line_count;
939 else // less lines
940 {
941 end -= old_line_count - buf->b_ml.ml_line_count;
942 if (end < start)
943 {
944 --no_wait_return;
945 msg_scroll = msg_save;
946 emsg(_("E204: Autocommand changed number of lines in unexpected way"));
947 return FAIL;
948 }
949 }
950 }
951
952 // The autocommands may have changed the name of the buffer, which may
953 // be kept in fname, ffname and sfname.
954 if (buf_ffname)
955 ffname = buf->b_ffname;
956 if (buf_sfname)
957 sfname = buf->b_sfname;
958 if (buf_fname_f)
959 fname = buf->b_ffname;
960 if (buf_fname_s)
961 fname = buf->b_sfname;
962 }
963
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100964 if (cmdmod.lockmarks)
965 {
966 // restore the original '[ and '] positions
967 buf->b_op_start = orig_start;
968 buf->b_op_end = orig_end;
969 }
970
Bram Moolenaar473952e2019-09-28 16:30:04 +0200971#ifdef FEAT_NETBEANS_INTG
972 if (netbeans_active() && isNetbeansBuffer(buf))
973 {
974 if (whole)
975 {
976 // b_changed can be 0 after an undo, but we still need to write
977 // the buffer to NetBeans.
978 if (buf->b_changed || isNetbeansModified(buf))
979 {
980 --no_wait_return; // may wait for return now
981 msg_scroll = msg_save;
982 netbeans_save_buffer(buf); // no error checking...
983 return retval;
984 }
985 else
986 {
987 errnum = (char_u *)"E656: ";
988 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
989 buffer = NULL;
990 goto fail;
991 }
992 }
993 else
994 {
995 errnum = (char_u *)"E657: ";
996 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
997 buffer = NULL;
998 goto fail;
999 }
1000 }
1001#endif
1002
1003 if (shortmess(SHM_OVER) && !exiting)
1004 msg_scroll = FALSE; // overwrite previous file message
1005 else
1006 msg_scroll = TRUE; // don't overwrite previous file message
1007 if (!filtering)
1008 filemess(buf,
1009#ifndef UNIX
1010 sfname,
1011#else
1012 fname,
1013#endif
1014 (char_u *)"", 0); // show that we are busy
1015 msg_scroll = FALSE; // always overwrite the file message now
1016
1017 buffer = alloc(WRITEBUFSIZE);
1018 if (buffer == NULL) // can't allocate big buffer, use small
1019 // one (to be able to write when out of
1020 // memory)
1021 {
1022 buffer = smallbuf;
1023 bufsize = SMALLBUFSIZE;
1024 }
1025 else
1026 bufsize = WRITEBUFSIZE;
1027
1028 // Get information about original file (if there is one).
1029#if defined(UNIX)
1030 st_old.st_dev = 0;
1031 st_old.st_ino = 0;
1032 perm = -1;
1033 if (mch_stat((char *)fname, &st_old) < 0)
1034 newfile = TRUE;
1035 else
1036 {
1037 perm = st_old.st_mode;
1038 if (!S_ISREG(st_old.st_mode)) // not a file
1039 {
1040 if (S_ISDIR(st_old.st_mode))
1041 {
1042 errnum = (char_u *)"E502: ";
1043 errmsg = (char_u *)_("is a directory");
1044 goto fail;
1045 }
1046 if (mch_nodetype(fname) != NODE_WRITABLE)
1047 {
1048 errnum = (char_u *)"E503: ";
1049 errmsg = (char_u *)_("is not a file or writable device");
1050 goto fail;
1051 }
1052 // It's a device of some kind (or a fifo) which we can write to
1053 // but for which we can't make a backup.
1054 device = TRUE;
1055 newfile = TRUE;
1056 perm = -1;
1057 }
1058 }
1059#else // !UNIX
1060 // Check for a writable device name.
1061 c = mch_nodetype(fname);
1062 if (c == NODE_OTHER)
1063 {
1064 errnum = (char_u *)"E503: ";
1065 errmsg = (char_u *)_("is not a file or writable device");
1066 goto fail;
1067 }
1068 if (c == NODE_WRITABLE)
1069 {
1070# if defined(MSWIN)
1071 // MS-Windows allows opening a device, but we will probably get stuck
1072 // trying to write to it.
1073 if (!p_odev)
1074 {
1075 errnum = (char_u *)"E796: ";
1076 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
1077 goto fail;
1078 }
1079# endif
1080 device = TRUE;
1081 newfile = TRUE;
1082 perm = -1;
1083 }
1084 else
1085 {
1086 perm = mch_getperm(fname);
1087 if (perm < 0)
1088 newfile = TRUE;
1089 else if (mch_isdir(fname))
1090 {
1091 errnum = (char_u *)"E502: ";
1092 errmsg = (char_u *)_("is a directory");
1093 goto fail;
1094 }
1095 if (overwriting)
1096 (void)mch_stat((char *)fname, &st_old);
1097 }
1098#endif // !UNIX
1099
1100 if (!device && !newfile)
1101 {
1102 // Check if the file is really writable (when renaming the file to
1103 // make a backup we won't discover it later).
1104 file_readonly = check_file_readonly(fname, (int)perm);
1105
1106 if (!forceit && file_readonly)
1107 {
1108 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1109 {
1110 errnum = (char_u *)"E504: ";
1111 errmsg = (char_u *)_(err_readonly);
1112 }
1113 else
1114 {
1115 errnum = (char_u *)"E505: ";
1116 errmsg = (char_u *)_("is read-only (add ! to override)");
1117 }
1118 goto fail;
1119 }
1120
1121 // Check if the timestamp hasn't changed since reading the file.
1122 if (overwriting)
1123 {
1124 retval = check_mtime(buf, &st_old);
1125 if (retval == FAIL)
1126 goto fail;
1127 }
1128 }
1129
1130#ifdef HAVE_ACL
1131 // For systems that support ACL: get the ACL from the original file.
1132 if (!newfile)
1133 acl = mch_get_acl(fname);
1134#endif
1135
1136 // If 'backupskip' is not empty, don't make a backup for some files.
1137 dobackup = (p_wb || p_bk || *p_pm != NUL);
1138#ifdef FEAT_WILDIGN
1139 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
1140 dobackup = FALSE;
1141#endif
1142
1143 // Save the value of got_int and reset it. We don't want a previous
1144 // interruption cancel writing, only hitting CTRL-C while writing should
1145 // abort it.
1146 prev_got_int = got_int;
1147 got_int = FALSE;
1148
1149 // Mark the buffer as 'being saved' to prevent changed buffer warnings
1150 buf->b_saving = TRUE;
1151
1152 // If we are not appending or filtering, the file exists, and the
1153 // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
1154 // When 'patchmode' is set also make a backup when appending.
1155 //
1156 // Do not make any backup, if 'writebackup' and 'backup' are both switched
1157 // off. This helps when editing large files on almost-full disks.
1158 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
1159 {
1160#if defined(UNIX) || defined(MSWIN)
1161 stat_T st;
1162#endif
1163
1164 if ((bkc & BKC_YES) || append) // "yes"
1165 backup_copy = TRUE;
1166#if defined(UNIX) || defined(MSWIN)
1167 else if ((bkc & BKC_AUTO)) // "auto"
1168 {
1169 int i;
1170
1171# ifdef UNIX
1172 // Don't rename the file when:
1173 // - it's a hard link
1174 // - it's a symbolic link
1175 // - we don't have write permission in the directory
1176 // - we can't set the owner/group of the new file
1177 if (st_old.st_nlink > 1
1178 || mch_lstat((char *)fname, &st) < 0
1179 || st.st_dev != st_old.st_dev
1180 || st.st_ino != st_old.st_ino
1181# ifndef HAVE_FCHOWN
1182 || st.st_uid != st_old.st_uid
1183 || st.st_gid != st_old.st_gid
1184# endif
1185 )
1186 backup_copy = TRUE;
1187 else
1188# else
1189# ifdef MSWIN
1190 // On NTFS file systems hard links are possible.
1191 if (mch_is_linked(fname))
1192 backup_copy = TRUE;
1193 else
1194# endif
1195# endif
1196 {
1197 // Check if we can create a file and set the owner/group to
1198 // the ones from the original file.
1199 // First find a file name that doesn't exist yet (use some
1200 // arbitrary numbers).
1201 STRCPY(IObuff, fname);
1202 for (i = 4913; ; i += 123)
1203 {
1204 sprintf((char *)gettail(IObuff), "%d", i);
1205 if (mch_lstat((char *)IObuff, &st) < 0)
1206 break;
1207 }
1208 fd = mch_open((char *)IObuff,
1209 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
1210 if (fd < 0) // can't write in directory
1211 backup_copy = TRUE;
1212 else
1213 {
1214# ifdef UNIX
1215# ifdef HAVE_FCHOWN
1216 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
1217# endif
1218 if (mch_stat((char *)IObuff, &st) < 0
1219 || st.st_uid != st_old.st_uid
1220 || st.st_gid != st_old.st_gid
1221 || (long)st.st_mode != perm)
1222 backup_copy = TRUE;
1223# endif
1224 // Close the file before removing it, on MS-Windows we
1225 // can't delete an open file.
1226 close(fd);
1227 mch_remove(IObuff);
1228# ifdef MSWIN
1229 // MS-Windows may trigger a virus scanner to open the
1230 // file, we can't delete it then. Keep trying for half a
1231 // second.
1232 {
1233 int try;
1234
1235 for (try = 0; try < 10; ++try)
1236 {
1237 if (mch_lstat((char *)IObuff, &st) < 0)
1238 break;
1239 ui_delay(50L, TRUE); // wait 50 msec
1240 mch_remove(IObuff);
1241 }
1242 }
1243# endif
1244 }
1245 }
1246 }
1247
1248 // Break symlinks and/or hardlinks if we've been asked to.
1249 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
1250 {
1251# ifdef UNIX
1252 int lstat_res;
1253
1254 lstat_res = mch_lstat((char *)fname, &st);
1255
1256 // Symlinks.
1257 if ((bkc & BKC_BREAKSYMLINK)
1258 && lstat_res == 0
1259 && st.st_ino != st_old.st_ino)
1260 backup_copy = FALSE;
1261
1262 // Hardlinks.
1263 if ((bkc & BKC_BREAKHARDLINK)
1264 && st_old.st_nlink > 1
1265 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
1266 backup_copy = FALSE;
1267# else
1268# if defined(MSWIN)
1269 // Symlinks.
1270 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
1271 backup_copy = FALSE;
1272
1273 // Hardlinks.
1274 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
1275 backup_copy = FALSE;
1276# endif
1277# endif
1278 }
1279
1280#endif
1281
1282 // make sure we have a valid backup extension to use
1283 if (*p_bex == NUL)
1284 backup_ext = (char_u *)".bak";
1285 else
1286 backup_ext = p_bex;
1287
1288 if (backup_copy
1289 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
1290 {
1291 int bfd;
1292 char_u *copybuf, *wp;
1293 int some_error = FALSE;
1294 stat_T st_new;
1295 char_u *dirp;
1296 char_u *rootname;
1297#if defined(UNIX) || defined(MSWIN)
1298 char_u *p;
1299#endif
1300#if defined(UNIX)
1301 int did_set_shortname;
1302 mode_t umask_save;
1303#endif
1304
1305 copybuf = alloc(WRITEBUFSIZE + 1);
1306 if (copybuf == NULL)
1307 {
1308 some_error = TRUE; // out of memory
1309 goto nobackup;
1310 }
1311
1312 // Try to make the backup in each directory in the 'bdir' option.
1313 //
1314 // Unix semantics has it, that we may have a writable file,
1315 // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
1316 // - the directory is not writable,
1317 // - the file may be a symbolic link,
1318 // - the file may belong to another user/group, etc.
1319 //
1320 // For these reasons, the existing writable file must be truncated
1321 // and reused. Creation of a backup COPY will be attempted.
1322 dirp = p_bdir;
1323 while (*dirp)
1324 {
1325#ifdef UNIX
1326 st_new.st_ino = 0;
1327 st_new.st_dev = 0;
1328 st_new.st_gid = 0;
1329#endif
1330
1331 // Isolate one directory name, using an entry in 'bdir'.
1332 (void)copy_option_part(&dirp, copybuf, WRITEBUFSIZE, ",");
1333
1334#if defined(UNIX) || defined(MSWIN)
1335 p = copybuf + STRLEN(copybuf);
1336 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
1337 // Ends with '//', use full path
1338 if ((p = make_percent_swname(copybuf, fname)) != NULL)
1339 {
1340 backup = modname(p, backup_ext, FALSE);
1341 vim_free(p);
1342 }
1343#endif
1344 rootname = get_file_in_dir(fname, copybuf);
1345 if (rootname == NULL)
1346 {
1347 some_error = TRUE; // out of memory
1348 goto nobackup;
1349 }
1350
1351#if defined(UNIX)
1352 did_set_shortname = FALSE;
1353#endif
1354
1355 // May try twice if 'shortname' not set.
1356 for (;;)
1357 {
1358 // Make the backup file name.
1359 if (backup == NULL)
1360 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
1361 rootname, backup_ext, FALSE);
1362 if (backup == NULL)
1363 {
1364 vim_free(rootname);
1365 some_error = TRUE; // out of memory
1366 goto nobackup;
1367 }
1368
1369 // Check if backup file already exists.
1370 if (mch_stat((char *)backup, &st_new) >= 0)
1371 {
1372#ifdef UNIX
1373 // Check if backup file is same as original file.
1374 // May happen when modname() gave the same file back.
1375 // E.g. silly link, or file name-length reached.
1376 // If we don't check here, we either ruin the file
1377 // when copying or erase it after writing. jw.
1378 if (st_new.st_dev == st_old.st_dev
1379 && st_new.st_ino == st_old.st_ino)
1380 {
1381 VIM_CLEAR(backup); // no backup file to delete
1382 // may try again with 'shortname' set
1383 if (!(buf->b_shortname || buf->b_p_sn))
1384 {
1385 buf->b_shortname = TRUE;
1386 did_set_shortname = TRUE;
1387 continue;
1388 }
1389 // setting shortname didn't help
1390 if (did_set_shortname)
1391 buf->b_shortname = FALSE;
1392 break;
1393 }
1394#endif
1395
1396 // If we are not going to keep the backup file, don't
1397 // delete an existing one, try to use another name.
1398 // Change one character, just before the extension.
1399 if (!p_bk)
1400 {
1401 wp = backup + STRLEN(backup) - 1
1402 - STRLEN(backup_ext);
1403 if (wp < backup) // empty file name ???
1404 wp = backup;
1405 *wp = 'z';
1406 while (*wp > 'a'
1407 && mch_stat((char *)backup, &st_new) >= 0)
1408 --*wp;
1409 // They all exist??? Must be something wrong.
1410 if (*wp == 'a')
1411 VIM_CLEAR(backup);
1412 }
1413 }
1414 break;
1415 }
1416 vim_free(rootname);
1417
1418 // Try to create the backup file
1419 if (backup != NULL)
1420 {
1421 // remove old backup, if present
1422 mch_remove(backup);
1423 // Open with O_EXCL to avoid the file being created while
1424 // we were sleeping (symlink hacker attack?). Reset umask
1425 // if possible to avoid mch_setperm() below.
1426#ifdef UNIX
1427 umask_save = umask(0);
1428#endif
1429 bfd = mch_open((char *)backup,
1430 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
1431 perm & 0777);
1432#ifdef UNIX
1433 (void)umask(umask_save);
1434#endif
1435 if (bfd < 0)
1436 VIM_CLEAR(backup);
1437 else
1438 {
1439 // Set file protection same as original file, but
1440 // strip s-bit. Only needed if umask() wasn't used
1441 // above.
1442#ifndef UNIX
1443 (void)mch_setperm(backup, perm & 0777);
1444#else
1445 // Try to set the group of the backup same as the
1446 // original file. If this fails, set the protection
1447 // bits for the group same as the protection bits for
1448 // others.
1449 if (st_new.st_gid != st_old.st_gid
1450# ifdef HAVE_FCHOWN // sequent-ptx lacks fchown()
1451 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
1452# endif
1453 )
1454 mch_setperm(backup,
1455 (perm & 0707) | ((perm & 07) << 3));
1456# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1457 mch_copy_sec(fname, backup);
1458# endif
1459#endif
1460
1461 // copy the file.
1462 write_info.bw_fd = bfd;
1463 write_info.bw_buf = copybuf;
1464 write_info.bw_flags = FIO_NOCONVERT;
1465 while ((write_info.bw_len = read_eintr(fd, copybuf,
1466 WRITEBUFSIZE)) > 0)
1467 {
1468 if (buf_write_bytes(&write_info) == FAIL)
1469 {
1470 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
1471 break;
1472 }
1473 ui_breakcheck();
1474 if (got_int)
1475 {
1476 errmsg = (char_u *)_(e_interr);
1477 break;
1478 }
1479 }
1480
1481 if (close(bfd) < 0 && errmsg == NULL)
1482 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
1483 if (write_info.bw_len < 0)
1484 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
1485#ifdef UNIX
1486 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
1487#endif
1488#ifdef HAVE_ACL
1489 mch_set_acl(backup, acl);
1490#endif
1491#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1492 mch_copy_sec(fname, backup);
1493#endif
1494 break;
1495 }
1496 }
1497 }
1498 nobackup:
1499 close(fd); // ignore errors for closing read file
1500 vim_free(copybuf);
1501
1502 if (backup == NULL && errmsg == NULL)
1503 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
1504 // ignore errors when forceit is TRUE
1505 if ((some_error || errmsg != NULL) && !forceit)
1506 {
1507 retval = FAIL;
1508 goto fail;
1509 }
1510 errmsg = NULL;
1511 }
1512 else
1513 {
1514 char_u *dirp;
1515 char_u *p;
1516 char_u *rootname;
1517
1518 // Make a backup by renaming the original file.
1519
1520 // If 'cpoptions' includes the "W" flag, we don't want to
1521 // overwrite a read-only file. But rename may be possible
1522 // anyway, thus we need an extra check here.
1523 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1524 {
1525 errnum = (char_u *)"E504: ";
1526 errmsg = (char_u *)_(err_readonly);
1527 goto fail;
1528 }
1529
1530 // Form the backup file name - change path/fo.o.h to
1531 // path/fo.o.h.bak Try all directories in 'backupdir', first one
1532 // that works is used.
1533 dirp = p_bdir;
1534 while (*dirp)
1535 {
1536 // Isolate one directory name and make the backup file name.
1537 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
1538
1539#if defined(UNIX) || defined(MSWIN)
1540 p = IObuff + STRLEN(IObuff);
1541 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
1542 // path ends with '//', use full path
1543 if ((p = make_percent_swname(IObuff, fname)) != NULL)
1544 {
1545 backup = modname(p, backup_ext, FALSE);
1546 vim_free(p);
1547 }
1548#endif
1549 if (backup == NULL)
1550 {
1551 rootname = get_file_in_dir(fname, IObuff);
1552 if (rootname == NULL)
1553 backup = NULL;
1554 else
1555 {
1556 backup = buf_modname(
1557 (buf->b_p_sn || buf->b_shortname),
1558 rootname, backup_ext, FALSE);
1559 vim_free(rootname);
1560 }
1561 }
1562
1563 if (backup != NULL)
1564 {
1565 // If we are not going to keep the backup file, don't
1566 // delete an existing one, try to use another name.
1567 // Change one character, just before the extension.
1568 if (!p_bk && mch_getperm(backup) >= 0)
1569 {
1570 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
1571 if (p < backup) // empty file name ???
1572 p = backup;
1573 *p = 'z';
1574 while (*p > 'a' && mch_getperm(backup) >= 0)
1575 --*p;
1576 // They all exist??? Must be something wrong!
1577 if (*p == 'a')
1578 VIM_CLEAR(backup);
1579 }
1580 }
1581 if (backup != NULL)
1582 {
1583 // Delete any existing backup and move the current version
1584 // to the backup. For safety, we don't remove the backup
1585 // until the write has finished successfully. And if the
1586 // 'backup' option is set, leave it around.
1587
1588 // If the renaming of the original file to the backup file
1589 // works, quit here.
1590 if (vim_rename(fname, backup) == 0)
1591 break;
1592
1593 VIM_CLEAR(backup); // don't do the rename below
1594 }
1595 }
1596 if (backup == NULL && !forceit)
1597 {
1598 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
1599 goto fail;
1600 }
1601 }
1602 }
1603
1604#if defined(UNIX)
1605 // When using ":w!" and the file was read-only: make it writable
1606 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
1607 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
1608 {
1609 perm |= 0200;
1610 (void)mch_setperm(fname, perm);
1611 made_writable = TRUE;
1612 }
1613#endif
1614
1615 // When using ":w!" and writing to the current file, 'readonly' makes no
1616 // sense, reset it, unless 'Z' appears in 'cpoptions'.
1617 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
1618 {
1619 buf->b_p_ro = FALSE;
1620#ifdef FEAT_TITLE
1621 need_maketitle = TRUE; // set window title later
1622#endif
1623 status_redraw_all(); // redraw status lines later
1624 }
1625
1626 if (end > buf->b_ml.ml_line_count)
1627 end = buf->b_ml.ml_line_count;
1628 if (buf->b_ml.ml_flags & ML_EMPTY)
1629 start = end + 1;
1630
1631 // If the original file is being overwritten, there is a small chance that
1632 // we crash in the middle of writing. Therefore the file is preserved now.
1633 // This makes all block numbers positive so that recovery does not need
1634 // the original file.
1635 // Don't do this if there is a backup file and we are exiting.
1636 if (reset_changed && !newfile && overwriting
1637 && !(exiting && backup != NULL))
1638 {
1639 ml_preserve(buf, FALSE);
1640 if (got_int)
1641 {
1642 errmsg = (char_u *)_(e_interr);
1643 goto restore_backup;
1644 }
1645 }
1646
1647#ifdef VMS
1648 vms_remove_version(fname); // remove version
1649#endif
1650 // Default: write the file directly. May write to a temp file for
1651 // multi-byte conversion.
1652 wfname = fname;
1653
1654 // Check for forced 'fileencoding' from "++opt=val" argument.
1655 if (eap != NULL && eap->force_enc != 0)
1656 {
1657 fenc = eap->cmd + eap->force_enc;
1658 fenc = enc_canonize(fenc);
1659 fenc_tofree = fenc;
1660 }
1661 else
1662 fenc = buf->b_p_fenc;
1663
1664 // Check if the file needs to be converted.
1665 converted = need_conversion(fenc);
1666
1667 // Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
1668 // Latin1 to Unicode conversion. This is handled in buf_write_bytes().
1669 // Prepare the flags for it and allocate bw_conv_buf when needed.
1670 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
1671 {
1672 wb_flags = get_fio_flags(fenc);
1673 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
1674 {
1675 // Need to allocate a buffer to translate into.
1676 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
1677 write_info.bw_conv_buflen = bufsize * 2;
1678 else // FIO_UCS4
1679 write_info.bw_conv_buflen = bufsize * 4;
1680 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1681 if (write_info.bw_conv_buf == NULL)
1682 end = 0;
1683 }
1684 }
1685
1686#ifdef MSWIN
1687 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
1688 {
1689 // Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4:
1690 write_info.bw_conv_buflen = bufsize * 4;
1691 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1692 if (write_info.bw_conv_buf == NULL)
1693 end = 0;
1694 }
1695#endif
1696
1697#ifdef MACOS_CONVERT
1698 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
1699 {
1700 write_info.bw_conv_buflen = bufsize * 3;
1701 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1702 if (write_info.bw_conv_buf == NULL)
1703 end = 0;
1704 }
1705#endif
1706
1707#if defined(FEAT_EVAL) || defined(USE_ICONV)
1708 if (converted && wb_flags == 0)
1709 {
1710# ifdef USE_ICONV
1711 // Use iconv() conversion when conversion is needed and it's not done
1712 // internally.
1713 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
1714 enc_utf8 ? (char_u *)"utf-8" : p_enc);
1715 if (write_info.bw_iconv_fd != (iconv_t)-1)
1716 {
1717 // We're going to use iconv(), allocate a buffer to convert in.
1718 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
1719 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1720 if (write_info.bw_conv_buf == NULL)
1721 end = 0;
1722 write_info.bw_first = TRUE;
1723 }
1724# ifdef FEAT_EVAL
1725 else
1726# endif
1727# endif
1728
1729# ifdef FEAT_EVAL
1730 // When the file needs to be converted with 'charconvert' after
1731 // writing, write to a temp file instead and let the conversion
1732 // overwrite the original file.
1733 if (*p_ccv != NUL)
1734 {
1735 wfname = vim_tempname('w', FALSE);
1736 if (wfname == NULL) // Can't write without a tempfile!
1737 {
1738 errmsg = (char_u *)_("E214: Can't find temp file for writing");
1739 goto restore_backup;
1740 }
1741 }
1742# endif
1743 }
1744#endif
1745 if (converted && wb_flags == 0
1746#ifdef USE_ICONV
1747 && write_info.bw_iconv_fd == (iconv_t)-1
1748# endif
1749# ifdef FEAT_EVAL
1750 && wfname == fname
1751# endif
1752 )
1753 {
1754 if (!forceit)
1755 {
1756 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
1757 goto restore_backup;
1758 }
1759 notconverted = TRUE;
1760 }
1761
1762 // If conversion is taking place, we may first pretend to write and check
1763 // for conversion errors. Then loop again to write for real.
1764 // When not doing conversion this writes for real right away.
1765 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
1766 {
1767 // There is no need to check conversion when:
1768 // - there is no conversion
1769 // - we make a backup file, that can be restored in case of conversion
1770 // failure.
1771 if (!converted || dobackup)
1772 checking_conversion = FALSE;
1773
1774 if (checking_conversion)
1775 {
1776 // Make sure we don't write anything.
1777 fd = -1;
1778 write_info.bw_fd = fd;
1779 }
1780 else
1781 {
1782#ifdef HAVE_FTRUNCATE
1783# define TRUNC_ON_OPEN 0
1784#else
1785# define TRUNC_ON_OPEN O_TRUNC
1786#endif
1787 // Open the file "wfname" for writing.
1788 // We may try to open the file twice: If we can't write to the file
1789 // and forceit is TRUE we delete the existing file and try to
1790 // create a new one. If this still fails we may have lost the
1791 // original file! (this may happen when the user reached his
1792 // quotum for number of files).
1793 // Appending will fail if the file does not exist and forceit is
1794 // FALSE.
1795 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
1796 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
1797 : (O_CREAT | TRUNC_ON_OPEN))
1798 , perm < 0 ? 0666 : (perm & 0777))) < 0)
1799 {
1800 // A forced write will try to create a new file if the old one
1801 // is still readonly. This may also happen when the directory
1802 // is read-only. In that case the mch_remove() will fail.
1803 if (errmsg == NULL)
1804 {
1805#ifdef UNIX
1806 stat_T st;
1807
1808 // Don't delete the file when it's a hard or symbolic link.
1809 if ((!newfile && st_old.st_nlink > 1)
1810 || (mch_lstat((char *)fname, &st) == 0
1811 && (st.st_dev != st_old.st_dev
1812 || st.st_ino != st_old.st_ino)))
1813 errmsg = (char_u *)_("E166: Can't open linked file for writing");
1814 else
1815#endif
1816 {
1817 errmsg = (char_u *)_("E212: Can't open file for writing");
1818 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
1819 && perm >= 0)
1820 {
1821#ifdef UNIX
1822 // we write to the file, thus it should be marked
1823 // writable after all
1824 if (!(perm & 0200))
1825 made_writable = TRUE;
1826 perm |= 0200;
1827 if (st_old.st_uid != getuid()
1828 || st_old.st_gid != getgid())
1829 perm &= 0777;
1830#endif
1831 if (!append) // don't remove when appending
1832 mch_remove(wfname);
1833 continue;
1834 }
1835 }
1836 }
1837
1838restore_backup:
1839 {
1840 stat_T st;
1841
1842 // If we failed to open the file, we don't need a backup.
1843 // Throw it away. If we moved or removed the original file
1844 // try to put the backup in its place.
1845 if (backup != NULL && wfname == fname)
1846 {
1847 if (backup_copy)
1848 {
1849 // There is a small chance that we removed the
1850 // original, try to move the copy in its place.
1851 // This may not work if the vim_rename() fails.
1852 // In that case we leave the copy around.
1853
1854 // If file does not exist, put the copy in its
1855 // place
1856 if (mch_stat((char *)fname, &st) < 0)
1857 vim_rename(backup, fname);
1858 // if original file does exist throw away the copy
1859 if (mch_stat((char *)fname, &st) >= 0)
1860 mch_remove(backup);
1861 }
1862 else
1863 {
1864 // try to put the original file back
1865 vim_rename(backup, fname);
1866 }
1867 }
1868
1869 // if original file no longer exists give an extra warning
1870 if (!newfile && mch_stat((char *)fname, &st) < 0)
1871 end = 0;
1872 }
1873
1874 if (wfname != fname)
1875 vim_free(wfname);
1876 goto fail;
1877 }
1878 write_info.bw_fd = fd;
1879
1880#if defined(UNIX)
1881 {
1882 stat_T st;
1883
1884 // Double check we are writing the intended file before making
1885 // any changes.
1886 if (overwriting
1887 && (!dobackup || backup_copy)
1888 && fname == wfname
1889 && perm >= 0
1890 && mch_fstat(fd, &st) == 0
1891 && st.st_ino != st_old.st_ino)
1892 {
1893 close(fd);
1894 errmsg = (char_u *)_("E949: File changed while writing");
1895 goto fail;
1896 }
1897 }
1898#endif
1899#ifdef HAVE_FTRUNCATE
1900 if (!append)
1901 vim_ignored = ftruncate(fd, (off_t)0);
1902#endif
1903
1904#if defined(MSWIN)
1905 if (backup != NULL && overwriting && !append)
1906 {
1907 if (backup_copy)
1908 (void)mch_copy_file_attribute(wfname, backup);
1909 else
1910 (void)mch_copy_file_attribute(backup, wfname);
1911 }
1912
1913 if (!overwriting && !append)
1914 {
1915 if (buf->b_ffname != NULL)
1916 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
1917 // Should copy resource fork
1918 }
1919#endif
1920
1921#ifdef FEAT_CRYPT
1922 if (*buf->b_p_key != NUL && !filtering)
1923 {
1924 char_u *header;
1925 int header_len;
1926
1927 buf->b_cryptstate = crypt_create_for_writing(
1928 crypt_get_method_nr(buf),
1929 buf->b_p_key, &header, &header_len);
1930 if (buf->b_cryptstate == NULL || header == NULL)
1931 end = 0;
1932 else
1933 {
1934 // Write magic number, so that Vim knows how this file is
1935 // encrypted when reading it back.
1936 write_info.bw_buf = header;
1937 write_info.bw_len = header_len;
1938 write_info.bw_flags = FIO_NOCONVERT;
1939 if (buf_write_bytes(&write_info) == FAIL)
1940 end = 0;
1941 wb_flags |= FIO_ENCRYPTED;
1942 vim_free(header);
1943 }
1944 }
1945#endif
1946 }
1947 errmsg = NULL;
1948
1949 write_info.bw_buf = buffer;
1950 nchars = 0;
1951
1952 // use "++bin", "++nobin" or 'binary'
1953 if (eap != NULL && eap->force_bin != 0)
1954 write_bin = (eap->force_bin == FORCE_BIN);
1955 else
1956 write_bin = buf->b_p_bin;
1957
1958 // The BOM is written just after the encryption magic number.
1959 // Skip it when appending and the file already existed, the BOM only
1960 // makes sense at the start of the file.
1961 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
1962 {
1963 write_info.bw_len = make_bom(buffer, fenc);
1964 if (write_info.bw_len > 0)
1965 {
1966 // don't convert, do encryption
1967 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
1968 if (buf_write_bytes(&write_info) == FAIL)
1969 end = 0;
1970 else
1971 nchars += write_info.bw_len;
1972 }
1973 }
1974 write_info.bw_start_lnum = start;
1975
1976#ifdef FEAT_PERSISTENT_UNDO
1977 write_undo_file = (buf->b_p_udf
1978 && overwriting
1979 && !append
1980 && !filtering
1981 && reset_changed
1982 && !checking_conversion);
1983 if (write_undo_file)
1984 // Prepare for computing the hash value of the text.
1985 sha256_start(&sha_ctx);
1986#endif
1987
1988 write_info.bw_len = bufsize;
1989 write_info.bw_flags = wb_flags;
1990 fileformat = get_fileformat_force(buf, eap);
1991 s = buffer;
1992 len = 0;
1993 for (lnum = start; lnum <= end; ++lnum)
1994 {
1995 // The next while loop is done once for each character written.
1996 // Keep it fast!
1997 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
1998#ifdef FEAT_PERSISTENT_UNDO
1999 if (write_undo_file)
2000 sha256_update(&sha_ctx, ptr + 1,
2001 (UINT32_T)(STRLEN(ptr + 1) + 1));
2002#endif
2003 while ((c = *++ptr) != NUL)
2004 {
2005 if (c == NL)
2006 *s = NUL; // replace newlines with NULs
2007 else if (c == CAR && fileformat == EOL_MAC)
2008 *s = NL; // Mac: replace CRs with NLs
2009 else
2010 *s = c;
2011 ++s;
2012 if (++len != bufsize)
2013 continue;
2014 if (buf_write_bytes(&write_info) == FAIL)
2015 {
2016 end = 0; // write error: break loop
2017 break;
2018 }
2019 nchars += bufsize;
2020 s = buffer;
2021 len = 0;
2022 write_info.bw_start_lnum = lnum;
2023 }
2024 // write failed or last line has no EOL: stop here
2025 if (end == 0
2026 || (lnum == end
2027 && (write_bin || !buf->b_p_fixeol)
2028 && (lnum == buf->b_no_eol_lnum
2029 || (lnum == buf->b_ml.ml_line_count
2030 && !buf->b_p_eol))))
2031 {
2032 ++lnum; // written the line, count it
2033 no_eol = TRUE;
2034 break;
2035 }
2036 if (fileformat == EOL_UNIX)
2037 *s++ = NL;
2038 else
2039 {
2040 *s++ = CAR; // EOL_MAC or EOL_DOS: write CR
2041 if (fileformat == EOL_DOS) // write CR-NL
2042 {
2043 if (++len == bufsize)
2044 {
2045 if (buf_write_bytes(&write_info) == FAIL)
2046 {
2047 end = 0; // write error: break loop
2048 break;
2049 }
2050 nchars += bufsize;
2051 s = buffer;
2052 len = 0;
2053 }
2054 *s++ = NL;
2055 }
2056 }
2057 if (++len == bufsize && end)
2058 {
2059 if (buf_write_bytes(&write_info) == FAIL)
2060 {
2061 end = 0; // write error: break loop
2062 break;
2063 }
2064 nchars += bufsize;
2065 s = buffer;
2066 len = 0;
2067
2068 ui_breakcheck();
2069 if (got_int)
2070 {
2071 end = 0; // Interrupted, break loop
2072 break;
2073 }
2074 }
2075#ifdef VMS
2076 // On VMS there is a problem: newlines get added when writing
2077 // blocks at a time. Fix it by writing a line at a time.
2078 // This is much slower!
2079 // Explanation: VAX/DECC RTL insists that records in some RMS
2080 // structures end with a newline (carriage return) character, and
2081 // if they don't it adds one.
2082 // With other RMS structures it works perfect without this fix.
Bram Moolenaar95f0b6e2019-12-15 12:54:18 +01002083# ifndef MIN
2084// Older DECC compiler for VAX doesn't define MIN()
2085# define MIN(a, b) ((a) < (b) ? (a) : (b))
2086# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002087 if (buf->b_fab_rfm == FAB$C_VFC
2088 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
2089 {
2090 int b2write;
2091
2092 buf->b_fab_mrs = (buf->b_fab_mrs == 0
2093 ? MIN(4096, bufsize)
2094 : MIN(buf->b_fab_mrs, bufsize));
2095
2096 b2write = len;
2097 while (b2write > 0)
2098 {
2099 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
2100 if (buf_write_bytes(&write_info) == FAIL)
2101 {
2102 end = 0;
2103 break;
2104 }
2105 b2write -= MIN(b2write, buf->b_fab_mrs);
2106 }
2107 write_info.bw_len = bufsize;
2108 nchars += len;
2109 s = buffer;
2110 len = 0;
2111 }
2112#endif
2113 }
2114 if (len > 0 && end > 0)
2115 {
2116 write_info.bw_len = len;
2117 if (buf_write_bytes(&write_info) == FAIL)
2118 end = 0; // write error
2119 nchars += len;
2120 }
2121
2122 // Stop when writing done or an error was encountered.
2123 if (!checking_conversion || end == 0)
2124 break;
2125
2126 // If no error happened until now, writing should be ok, so loop to
2127 // really write the buffer.
2128 }
2129
2130 // If we started writing, finish writing. Also when an error was
2131 // encountered.
2132 if (!checking_conversion)
2133 {
2134#if defined(UNIX) && defined(HAVE_FSYNC)
2135 // On many journalling file systems there is a bug that causes both the
2136 // original and the backup file to be lost when halting the system
2137 // right after writing the file. That's because only the meta-data is
2138 // journalled. Syncing the file slows down the system, but assures it
2139 // has been written to disk and we don't lose it.
2140 // For a device do try the fsync() but don't complain if it does not
2141 // work (could be a pipe).
2142 // If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
2143 if (p_fs && vim_fsync(fd) != 0 && !device)
2144 {
2145 errmsg = (char_u *)_(e_fsync);
2146 end = 0;
2147 }
2148#endif
2149
2150#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
2151 // Probably need to set the security context.
2152 if (!backup_copy)
2153 mch_copy_sec(backup, wfname);
2154#endif
2155
2156#ifdef UNIX
2157 // When creating a new file, set its owner/group to that of the
2158 // original file. Get the new device and inode number.
2159 if (backup != NULL && !backup_copy)
2160 {
2161# ifdef HAVE_FCHOWN
2162 stat_T st;
2163
2164 // Don't change the owner when it's already OK, some systems remove
2165 // permission or ACL stuff.
2166 if (mch_stat((char *)wfname, &st) < 0
2167 || st.st_uid != st_old.st_uid
2168 || st.st_gid != st_old.st_gid)
2169 {
2170 // changing owner might not be possible
2171 vim_ignored = fchown(fd, st_old.st_uid, -1);
2172 // if changing group fails clear the group permissions
2173 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
2174 perm &= ~070;
2175 }
2176# endif
2177 buf_setino(buf);
2178 }
2179 else if (!buf->b_dev_valid)
2180 // Set the inode when creating a new file.
2181 buf_setino(buf);
2182#endif
2183
2184#ifdef UNIX
2185 if (made_writable)
2186 perm &= ~0200; // reset 'w' bit for security reasons
2187#endif
2188#ifdef HAVE_FCHMOD
2189 // set permission of new file same as old file
2190 if (perm >= 0)
2191 (void)mch_fsetperm(fd, perm);
2192#endif
2193 if (close(fd) != 0)
2194 {
2195 errmsg = (char_u *)_("E512: Close failed");
2196 end = 0;
2197 }
2198
2199#ifndef HAVE_FCHMOD
2200 // set permission of new file same as old file
2201 if (perm >= 0)
2202 (void)mch_setperm(wfname, perm);
2203#endif
2204#ifdef HAVE_ACL
2205 // Probably need to set the ACL before changing the user (can't set the
2206 // ACL on a file the user doesn't own).
2207 // On Solaris, with ZFS and the aclmode property set to "discard" (the
2208 // default), chmod() discards all part of a file's ACL that don't
2209 // represent the mode of the file. It's non-trivial for us to discover
2210 // whether we're in that situation, so we simply always re-set the ACL.
2211# ifndef HAVE_SOLARIS_ZFS_ACL
2212 if (!backup_copy)
2213# endif
2214 mch_set_acl(wfname, acl);
2215#endif
2216#ifdef FEAT_CRYPT
2217 if (buf->b_cryptstate != NULL)
2218 {
2219 crypt_free_state(buf->b_cryptstate);
2220 buf->b_cryptstate = NULL;
2221 }
2222#endif
2223
2224#if defined(FEAT_EVAL)
2225 if (wfname != fname)
2226 {
2227 // The file was written to a temp file, now it needs to be
2228 // converted with 'charconvert' to (overwrite) the output file.
2229 if (end != 0)
2230 {
2231 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
2232 fenc, wfname, fname) == FAIL)
2233 {
2234 write_info.bw_conv_error = TRUE;
2235 end = 0;
2236 }
2237 }
2238 mch_remove(wfname);
2239 vim_free(wfname);
2240 }
2241#endif
2242 }
2243
2244 if (end == 0)
2245 {
2246 // Error encountered.
2247 if (errmsg == NULL)
2248 {
2249 if (write_info.bw_conv_error)
2250 {
2251 if (write_info.bw_conv_error_lnum == 0)
2252 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
2253 else
2254 {
2255 errmsg_allocated = TRUE;
2256 errmsg = alloc(300);
2257 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
2258 (long)write_info.bw_conv_error_lnum);
2259 }
2260 }
2261 else if (got_int)
2262 errmsg = (char_u *)_(e_interr);
2263 else
2264 errmsg = (char_u *)_("E514: write error (file system full?)");
2265 }
2266
2267 // If we have a backup file, try to put it in place of the new file,
2268 // because the new file is probably corrupt. This avoids losing the
2269 // original file when trying to make a backup when writing the file a
2270 // second time.
2271 // When "backup_copy" is set we need to copy the backup over the new
2272 // file. Otherwise rename the backup file.
2273 // If this is OK, don't give the extra warning message.
2274 if (backup != NULL)
2275 {
2276 if (backup_copy)
2277 {
2278 // This may take a while, if we were interrupted let the user
2279 // know we got the message.
2280 if (got_int)
2281 {
2282 msg(_(e_interr));
2283 out_flush();
2284 }
2285 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
2286 {
2287 if ((write_info.bw_fd = mch_open((char *)fname,
2288 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
2289 perm & 0777)) >= 0)
2290 {
2291 // copy the file.
2292 write_info.bw_buf = smallbuf;
2293 write_info.bw_flags = FIO_NOCONVERT;
2294 while ((write_info.bw_len = read_eintr(fd, smallbuf,
2295 SMALLBUFSIZE)) > 0)
2296 if (buf_write_bytes(&write_info) == FAIL)
2297 break;
2298
2299 if (close(write_info.bw_fd) >= 0
2300 && write_info.bw_len == 0)
2301 end = 1; // success
2302 }
2303 close(fd); // ignore errors for closing read file
2304 }
2305 }
2306 else
2307 {
2308 if (vim_rename(backup, fname) == 0)
2309 end = 1;
2310 }
2311 }
2312 goto fail;
2313 }
2314
2315 lnum -= start; // compute number of written lines
2316 --no_wait_return; // may wait for return now
2317
2318#if !(defined(UNIX) || defined(VMS))
2319 fname = sfname; // use shortname now, for the messages
2320#endif
2321 if (!filtering)
2322 {
2323 msg_add_fname(buf, fname); // put fname in IObuff with quotes
2324 c = FALSE;
2325 if (write_info.bw_conv_error)
2326 {
2327 STRCAT(IObuff, _(" CONVERSION ERROR"));
2328 c = TRUE;
2329 if (write_info.bw_conv_error_lnum != 0)
2330 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
2331 (long)write_info.bw_conv_error_lnum);
2332 }
2333 else if (notconverted)
2334 {
2335 STRCAT(IObuff, _("[NOT converted]"));
2336 c = TRUE;
2337 }
2338 else if (converted)
2339 {
2340 STRCAT(IObuff, _("[converted]"));
2341 c = TRUE;
2342 }
2343 if (device)
2344 {
2345 STRCAT(IObuff, _("[Device]"));
2346 c = TRUE;
2347 }
2348 else if (newfile)
2349 {
2350 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
2351 c = TRUE;
2352 }
2353 if (no_eol)
2354 {
2355 msg_add_eol();
2356 c = TRUE;
2357 }
2358 // may add [unix/dos/mac]
2359 if (msg_add_fileformat(fileformat))
2360 c = TRUE;
2361#ifdef FEAT_CRYPT
2362 if (wb_flags & FIO_ENCRYPTED)
2363 {
2364 crypt_append_msg(buf);
2365 c = TRUE;
2366 }
2367#endif
2368 msg_add_lines(c, (long)lnum, nchars); // add line/char count
2369 if (!shortmess(SHM_WRITE))
2370 {
2371 if (append)
2372 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
2373 else
2374 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
2375 }
2376
2377 set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0);
2378 }
2379
2380 // When written everything correctly: reset 'modified'. Unless not
2381 // writing to the original file and '+' is not in 'cpoptions'.
2382 if (reset_changed && whole && !append
2383 && !write_info.bw_conv_error
2384 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
2385 {
2386 unchanged(buf, TRUE, FALSE);
2387 // b:changedtick is may be incremented in unchanged() but that
2388 // should not trigger a TextChanged event.
2389 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
2390 buf->b_last_changedtick = CHANGEDTICK(buf);
2391 u_unchanged(buf);
2392 u_update_save_nr(buf);
2393 }
2394
2395 // If written to the current file, update the timestamp of the swap file
2396 // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
2397 if (overwriting)
2398 {
2399 ml_timestamp(buf);
2400 if (append)
2401 buf->b_flags &= ~BF_NEW;
2402 else
2403 buf->b_flags &= ~BF_WRITE_MASK;
2404 }
2405
2406 // If we kept a backup until now, and we are in patch mode, then we make
2407 // the backup file our 'original' file.
2408 if (*p_pm && dobackup)
2409 {
2410 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
2411 fname, p_pm, FALSE);
2412
2413 if (backup != NULL)
2414 {
2415 stat_T st;
2416
2417 // If the original file does not exist yet
2418 // the current backup file becomes the original file
2419 if (org == NULL)
2420 emsg(_("E205: Patchmode: can't save original file"));
2421 else if (mch_stat(org, &st) < 0)
2422 {
2423 vim_rename(backup, (char_u *)org);
2424 VIM_CLEAR(backup); // don't delete the file
2425#ifdef UNIX
2426 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
2427#endif
2428 }
2429 }
2430 // If there is no backup file, remember that a (new) file was
2431 // created.
2432 else
2433 {
2434 int empty_fd;
2435
2436 if (org == NULL
2437 || (empty_fd = mch_open(org,
2438 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
2439 perm < 0 ? 0666 : (perm & 0777))) < 0)
2440 emsg(_("E206: patchmode: can't touch empty original file"));
2441 else
2442 close(empty_fd);
2443 }
2444 if (org != NULL)
2445 {
2446 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
2447 vim_free(org);
2448 }
2449 }
2450
2451 // Remove the backup unless 'backup' option is set or there was a
2452 // conversion error.
2453 if (!p_bk && backup != NULL && !write_info.bw_conv_error
2454 && mch_remove(backup) != 0)
2455 emsg(_("E207: Can't delete backup file"));
2456
2457 goto nofail;
2458
2459 // Finish up. We get here either after failure or success.
2460fail:
2461 --no_wait_return; // may wait for return now
2462nofail:
2463
2464 // Done saving, we accept changed buffer warnings again
2465 buf->b_saving = FALSE;
2466
2467 vim_free(backup);
2468 if (buffer != smallbuf)
2469 vim_free(buffer);
2470 vim_free(fenc_tofree);
2471 vim_free(write_info.bw_conv_buf);
2472#ifdef USE_ICONV
2473 if (write_info.bw_iconv_fd != (iconv_t)-1)
2474 {
2475 iconv_close(write_info.bw_iconv_fd);
2476 write_info.bw_iconv_fd = (iconv_t)-1;
2477 }
2478#endif
2479#ifdef HAVE_ACL
2480 mch_free_acl(acl);
2481#endif
2482
2483 if (errmsg != NULL)
2484 {
2485 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
2486
2487 attr = HL_ATTR(HLF_E); // set highlight for error messages
2488 msg_add_fname(buf,
2489#ifndef UNIX
2490 sfname
2491#else
2492 fname
2493#endif
2494 ); // put file name in IObuff with quotes
2495 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
2496 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
2497 // If the error message has the form "is ...", put the error number in
2498 // front of the file name.
2499 if (errnum != NULL)
2500 {
2501 STRMOVE(IObuff + numlen, IObuff);
2502 mch_memmove(IObuff, errnum, (size_t)numlen);
2503 }
2504 STRCAT(IObuff, errmsg);
2505 emsg((char *)IObuff);
2506 if (errmsg_allocated)
2507 vim_free(errmsg);
2508
2509 retval = FAIL;
2510 if (end == 0)
2511 {
2512 msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
2513 attr | MSG_HIST);
2514 msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
2515 attr | MSG_HIST);
2516
2517 // Update the timestamp to avoid an "overwrite changed file"
2518 // prompt when writing again.
2519 if (mch_stat((char *)fname, &st_old) >= 0)
2520 {
2521 buf_store_time(buf, &st_old, fname);
2522 buf->b_mtime_read = buf->b_mtime;
2523 }
2524 }
2525 }
2526 msg_scroll = msg_save;
2527
2528#ifdef FEAT_PERSISTENT_UNDO
2529 // When writing the whole file and 'undofile' is set, also write the undo
2530 // file.
2531 if (retval == OK && write_undo_file)
2532 {
2533 char_u hash[UNDO_HASH_SIZE];
2534
2535 sha256_finish(&sha_ctx, hash);
2536 u_write_undo(NULL, FALSE, buf, hash);
2537 }
2538#endif
2539
2540#ifdef FEAT_EVAL
2541 if (!should_abort(retval))
2542#else
2543 if (!got_int)
2544#endif
2545 {
2546 aco_save_T aco;
2547
2548 curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
2549
2550 // Apply POST autocommands.
2551 // Careful: The autocommands may call buf_write() recursively!
2552 aucmd_prepbuf(&aco, buf);
2553
2554 if (append)
2555 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
2556 FALSE, curbuf, eap);
2557 else if (filtering)
2558 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
2559 FALSE, curbuf, eap);
2560 else if (reset_changed && whole)
2561 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
2562 FALSE, curbuf, eap);
2563 else
2564 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
2565 FALSE, curbuf, eap);
2566
2567 // restore curwin/curbuf and a few other things
2568 aucmd_restbuf(&aco);
2569
2570#ifdef FEAT_EVAL
2571 if (aborting()) // autocmds may abort script processing
2572 retval = FALSE;
2573#endif
2574 }
2575
2576 got_int |= prev_got_int;
2577
2578 return retval;
2579}