blob: d7c74de35c315cbaeddaa88e42ef2db0478771fa [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
Bram Moolenaar722e5052020-06-12 22:31:00 +0200601 char *
602new_file_message(void)
603{
604 return shortmess(SHM_NEW) ? _("[New]") : _("[New File]");
605}
606
Bram Moolenaar473952e2019-09-28 16:30:04 +0200607/*
608 * buf_write() - write to file "fname" lines "start" through "end"
609 *
610 * We do our own buffering here because fwrite() is so slow.
611 *
612 * If "forceit" is true, we don't care for errors when attempting backups.
613 * In case of an error everything possible is done to restore the original
614 * file. But when "forceit" is TRUE, we risk losing it.
615 *
616 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
617 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
618 *
619 * This function must NOT use NameBuff (because it's called by autowrite()).
620 *
621 * return FAIL for failure, OK otherwise
622 */
623 int
624buf_write(
625 buf_T *buf,
626 char_u *fname,
627 char_u *sfname,
628 linenr_T start,
629 linenr_T end,
630 exarg_T *eap, // for forced 'ff' and 'fenc', can be
631 // NULL!
632 int append, // append to the file
633 int forceit,
634 int reset_changed,
635 int filtering)
636{
637 int fd;
638 char_u *backup = NULL;
639 int backup_copy = FALSE; // copy the original file?
640 int dobackup;
641 char_u *ffname;
642 char_u *wfname = NULL; // name of file to write to
643 char_u *s;
644 char_u *ptr;
645 char_u c;
646 int len;
647 linenr_T lnum;
648 long nchars;
649 char_u *errmsg = NULL;
650 int errmsg_allocated = FALSE;
651 char_u *errnum = NULL;
652 char_u *buffer;
653 char_u smallbuf[SMALLBUFSIZE];
654 char_u *backup_ext;
655 int bufsize;
656 long perm; // file permissions
657 int retval = OK;
658 int newfile = FALSE; // TRUE if file doesn't exist yet
659 int msg_save = msg_scroll;
660 int overwriting; // TRUE if writing over original
661 int no_eol = FALSE; // no end-of-line written
662 int device = FALSE; // writing to a device
663 stat_T st_old;
664 int prev_got_int = got_int;
665 int checking_conversion;
666 int file_readonly = FALSE; // overwritten file is read-only
667 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
668#if defined(UNIX) // XXX fix me sometime?
669 int made_writable = FALSE; // 'w' bit has been set
670#endif
671 // writing everything
672 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
673 linenr_T old_line_count = buf->b_ml.ml_line_count;
674 int attr;
675 int fileformat;
676 int write_bin;
677 struct bw_info write_info; // info for buf_write_bytes()
678 int converted = FALSE;
679 int notconverted = FALSE;
680 char_u *fenc; // effective 'fileencoding'
681 char_u *fenc_tofree = NULL; // allocated "fenc"
682 int wb_flags = 0;
683#ifdef HAVE_ACL
684 vim_acl_T acl = NULL; // ACL copied from original file to
685 // backup or new file
686#endif
687#ifdef FEAT_PERSISTENT_UNDO
688 int write_undo_file = FALSE;
689 context_sha256_T sha_ctx;
690#endif
691 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100692 pos_T orig_start = buf->b_op_start;
693 pos_T orig_end = buf->b_op_end;
Bram Moolenaar473952e2019-09-28 16:30:04 +0200694
695 if (fname == NULL || *fname == NUL) // safety check
696 return FAIL;
697 if (buf->b_ml.ml_mfp == NULL)
698 {
699 // This can happen during startup when there is a stray "w" in the
700 // vimrc file.
701 emsg(_(e_emptybuf));
702 return FAIL;
703 }
704
705 // Disallow writing from .exrc and .vimrc in current directory for
706 // security reasons.
707 if (check_secure())
708 return FAIL;
709
710 // Avoid a crash for a long name.
711 if (STRLEN(fname) >= MAXPATHL)
712 {
713 emsg(_(e_longname));
714 return FAIL;
715 }
716
717 // must init bw_conv_buf and bw_iconv_fd before jumping to "fail"
718 write_info.bw_conv_buf = NULL;
719 write_info.bw_conv_error = FALSE;
720 write_info.bw_conv_error_lnum = 0;
721 write_info.bw_restlen = 0;
722#ifdef USE_ICONV
723 write_info.bw_iconv_fd = (iconv_t)-1;
724#endif
725#ifdef FEAT_CRYPT
726 write_info.bw_buffer = buf;
727#endif
728
729 // After writing a file changedtick changes but we don't want to display
730 // the line.
731 ex_no_reprint = TRUE;
732
733 // If there is no file name yet, use the one for the written file.
734 // BF_NOTEDITED is set to reflect this (in case the write fails).
735 // Don't do this when the write is for a filter command.
736 // Don't do this when appending.
737 // Only do this when 'cpoptions' contains the 'F' flag.
738 if (buf->b_ffname == NULL
739 && reset_changed
740 && whole
741 && buf == curbuf
742#ifdef FEAT_QUICKFIX
743 && !bt_nofilename(buf)
744#endif
745 && !filtering
746 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
747 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
748 {
749 if (set_rw_fname(fname, sfname) == FAIL)
750 return FAIL;
751 buf = curbuf; // just in case autocmds made "buf" invalid
752 }
753
754 if (sfname == NULL)
755 sfname = fname;
756 // For Unix: Use the short file name whenever possible.
757 // Avoids problems with networks and when directory names are changed.
758 // Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
759 // another directory, which we don't detect
760 ffname = fname; // remember full fname
761#ifdef UNIX
762 fname = sfname;
763#endif
764
765 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
766 overwriting = TRUE;
767 else
768 overwriting = FALSE;
769
770 if (exiting)
771 settmode(TMODE_COOK); // when exiting allow typeahead now
772
773 ++no_wait_return; // don't wait for return yet
774
775 // Set '[ and '] marks to the lines to be written.
776 buf->b_op_start.lnum = start;
777 buf->b_op_start.col = 0;
778 buf->b_op_end.lnum = end;
779 buf->b_op_end.col = 0;
780
781 {
782 aco_save_T aco;
783 int buf_ffname = FALSE;
784 int buf_sfname = FALSE;
785 int buf_fname_f = FALSE;
786 int buf_fname_s = FALSE;
787 int did_cmd = FALSE;
788 int nofile_err = FALSE;
789 int empty_memline = (buf->b_ml.ml_mfp == NULL);
790 bufref_T bufref;
791
792 // Apply PRE autocommands.
793 // Set curbuf to the buffer to be written.
794 // Careful: The autocommands may call buf_write() recursively!
795 if (ffname == buf->b_ffname)
796 buf_ffname = TRUE;
797 if (sfname == buf->b_sfname)
798 buf_sfname = TRUE;
799 if (fname == buf->b_ffname)
800 buf_fname_f = TRUE;
801 if (fname == buf->b_sfname)
802 buf_fname_s = TRUE;
803
804 // set curwin/curbuf to buf and save a few things
805 aucmd_prepbuf(&aco, buf);
806 set_bufref(&bufref, buf);
807
808 if (append)
809 {
810 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
811 sfname, sfname, FALSE, curbuf, eap)))
812 {
813#ifdef FEAT_QUICKFIX
814 if (overwriting && bt_nofilename(curbuf))
815 nofile_err = TRUE;
816 else
817#endif
818 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
819 sfname, sfname, FALSE, curbuf, eap);
820 }
821 }
822 else if (filtering)
823 {
824 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
825 NULL, sfname, FALSE, curbuf, eap);
826 }
827 else if (reset_changed && whole)
828 {
829 int was_changed = curbufIsChanged();
830
831 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
832 sfname, sfname, FALSE, curbuf, eap);
833 if (did_cmd)
834 {
835 if (was_changed && !curbufIsChanged())
836 {
837 // Written everything correctly and BufWriteCmd has reset
838 // 'modified': Correct the undo information so that an
839 // undo now sets 'modified'.
840 u_unchanged(curbuf);
841 u_update_save_nr(curbuf);
842 }
843 }
844 else
845 {
846#ifdef FEAT_QUICKFIX
847 if (overwriting && bt_nofilename(curbuf))
848 nofile_err = TRUE;
849 else
850#endif
851 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
852 sfname, sfname, FALSE, curbuf, eap);
853 }
854 }
855 else
856 {
857 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
858 sfname, sfname, FALSE, curbuf, eap)))
859 {
860#ifdef FEAT_QUICKFIX
861 if (overwriting && bt_nofilename(curbuf))
862 nofile_err = TRUE;
863 else
864#endif
865 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
866 sfname, sfname, FALSE, curbuf, eap);
867 }
868 }
869
870 // restore curwin/curbuf and a few other things
871 aucmd_restbuf(&aco);
872
873 // In three situations we return here and don't write the file:
874 // 1. the autocommands deleted or unloaded the buffer.
875 // 2. The autocommands abort script processing.
876 // 3. If one of the "Cmd" autocommands was executed.
877 if (!bufref_valid(&bufref))
878 buf = NULL;
879 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
880 || did_cmd || nofile_err
881#ifdef FEAT_EVAL
882 || aborting()
883#endif
884 )
885 {
Bram Moolenaare1004402020-10-24 20:49:43 +0200886 if (buf != NULL && (cmdmod.cmod_flags & CMOD_LOCKMARKS))
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100887 {
888 // restore the original '[ and '] positions
889 buf->b_op_start = orig_start;
890 buf->b_op_end = orig_end;
891 }
892
Bram Moolenaar473952e2019-09-28 16:30:04 +0200893 --no_wait_return;
894 msg_scroll = msg_save;
895 if (nofile_err)
896 emsg(_("E676: No matching autocommands for acwrite buffer"));
897
898 if (nofile_err
899#ifdef FEAT_EVAL
900 || aborting()
901#endif
902 )
903 // An aborting error, interrupt or exception in the
904 // autocommands.
905 return FAIL;
906 if (did_cmd)
907 {
908 if (buf == NULL)
909 // The buffer was deleted. We assume it was written
910 // (can't retry anyway).
911 return OK;
912 if (overwriting)
913 {
914 // Assume the buffer was written, update the timestamp.
915 ml_timestamp(buf);
916 if (append)
917 buf->b_flags &= ~BF_NEW;
918 else
919 buf->b_flags &= ~BF_WRITE_MASK;
920 }
921 if (reset_changed && buf->b_changed && !append
922 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
923 // Buffer still changed, the autocommands didn't work
924 // properly.
925 return FAIL;
926 return OK;
927 }
928#ifdef FEAT_EVAL
929 if (!aborting())
930#endif
931 emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
932 return FAIL;
933 }
934
935 // The autocommands may have changed the number of lines in the file.
936 // When writing the whole file, adjust the end.
937 // When writing part of the file, assume that the autocommands only
938 // changed the number of lines that are to be written (tricky!).
939 if (buf->b_ml.ml_line_count != old_line_count)
940 {
941 if (whole) // write all
942 end = buf->b_ml.ml_line_count;
943 else if (buf->b_ml.ml_line_count > old_line_count) // more lines
944 end += buf->b_ml.ml_line_count - old_line_count;
945 else // less lines
946 {
947 end -= old_line_count - buf->b_ml.ml_line_count;
948 if (end < start)
949 {
950 --no_wait_return;
951 msg_scroll = msg_save;
952 emsg(_("E204: Autocommand changed number of lines in unexpected way"));
953 return FAIL;
954 }
955 }
956 }
957
958 // The autocommands may have changed the name of the buffer, which may
959 // be kept in fname, ffname and sfname.
960 if (buf_ffname)
961 ffname = buf->b_ffname;
962 if (buf_sfname)
963 sfname = buf->b_sfname;
964 if (buf_fname_f)
965 fname = buf->b_ffname;
966 if (buf_fname_s)
967 fname = buf->b_sfname;
968 }
969
Bram Moolenaare1004402020-10-24 20:49:43 +0200970 if (cmdmod.cmod_flags & CMOD_LOCKMARKS)
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100971 {
972 // restore the original '[ and '] positions
973 buf->b_op_start = orig_start;
974 buf->b_op_end = orig_end;
975 }
976
Bram Moolenaar473952e2019-09-28 16:30:04 +0200977#ifdef FEAT_NETBEANS_INTG
978 if (netbeans_active() && isNetbeansBuffer(buf))
979 {
980 if (whole)
981 {
982 // b_changed can be 0 after an undo, but we still need to write
983 // the buffer to NetBeans.
984 if (buf->b_changed || isNetbeansModified(buf))
985 {
986 --no_wait_return; // may wait for return now
987 msg_scroll = msg_save;
988 netbeans_save_buffer(buf); // no error checking...
989 return retval;
990 }
991 else
992 {
993 errnum = (char_u *)"E656: ";
994 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
995 buffer = NULL;
996 goto fail;
997 }
998 }
999 else
1000 {
1001 errnum = (char_u *)"E657: ";
1002 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
1003 buffer = NULL;
1004 goto fail;
1005 }
1006 }
1007#endif
1008
1009 if (shortmess(SHM_OVER) && !exiting)
1010 msg_scroll = FALSE; // overwrite previous file message
1011 else
1012 msg_scroll = TRUE; // don't overwrite previous file message
1013 if (!filtering)
1014 filemess(buf,
1015#ifndef UNIX
1016 sfname,
1017#else
1018 fname,
1019#endif
1020 (char_u *)"", 0); // show that we are busy
1021 msg_scroll = FALSE; // always overwrite the file message now
1022
1023 buffer = alloc(WRITEBUFSIZE);
1024 if (buffer == NULL) // can't allocate big buffer, use small
1025 // one (to be able to write when out of
1026 // memory)
1027 {
1028 buffer = smallbuf;
1029 bufsize = SMALLBUFSIZE;
1030 }
1031 else
1032 bufsize = WRITEBUFSIZE;
1033
1034 // Get information about original file (if there is one).
1035#if defined(UNIX)
1036 st_old.st_dev = 0;
1037 st_old.st_ino = 0;
1038 perm = -1;
1039 if (mch_stat((char *)fname, &st_old) < 0)
1040 newfile = TRUE;
1041 else
1042 {
1043 perm = st_old.st_mode;
1044 if (!S_ISREG(st_old.st_mode)) // not a file
1045 {
1046 if (S_ISDIR(st_old.st_mode))
1047 {
1048 errnum = (char_u *)"E502: ";
1049 errmsg = (char_u *)_("is a directory");
1050 goto fail;
1051 }
1052 if (mch_nodetype(fname) != NODE_WRITABLE)
1053 {
1054 errnum = (char_u *)"E503: ";
1055 errmsg = (char_u *)_("is not a file or writable device");
1056 goto fail;
1057 }
1058 // It's a device of some kind (or a fifo) which we can write to
1059 // but for which we can't make a backup.
1060 device = TRUE;
1061 newfile = TRUE;
1062 perm = -1;
1063 }
1064 }
1065#else // !UNIX
1066 // Check for a writable device name.
1067 c = mch_nodetype(fname);
1068 if (c == NODE_OTHER)
1069 {
1070 errnum = (char_u *)"E503: ";
1071 errmsg = (char_u *)_("is not a file or writable device");
1072 goto fail;
1073 }
1074 if (c == NODE_WRITABLE)
1075 {
1076# if defined(MSWIN)
1077 // MS-Windows allows opening a device, but we will probably get stuck
1078 // trying to write to it.
1079 if (!p_odev)
1080 {
1081 errnum = (char_u *)"E796: ";
1082 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
1083 goto fail;
1084 }
1085# endif
1086 device = TRUE;
1087 newfile = TRUE;
1088 perm = -1;
1089 }
1090 else
1091 {
1092 perm = mch_getperm(fname);
1093 if (perm < 0)
1094 newfile = TRUE;
1095 else if (mch_isdir(fname))
1096 {
1097 errnum = (char_u *)"E502: ";
1098 errmsg = (char_u *)_("is a directory");
1099 goto fail;
1100 }
1101 if (overwriting)
1102 (void)mch_stat((char *)fname, &st_old);
1103 }
1104#endif // !UNIX
1105
1106 if (!device && !newfile)
1107 {
1108 // Check if the file is really writable (when renaming the file to
1109 // make a backup we won't discover it later).
1110 file_readonly = check_file_readonly(fname, (int)perm);
1111
1112 if (!forceit && file_readonly)
1113 {
1114 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1115 {
1116 errnum = (char_u *)"E504: ";
1117 errmsg = (char_u *)_(err_readonly);
1118 }
1119 else
1120 {
1121 errnum = (char_u *)"E505: ";
1122 errmsg = (char_u *)_("is read-only (add ! to override)");
1123 }
1124 goto fail;
1125 }
1126
1127 // Check if the timestamp hasn't changed since reading the file.
1128 if (overwriting)
1129 {
1130 retval = check_mtime(buf, &st_old);
1131 if (retval == FAIL)
1132 goto fail;
1133 }
1134 }
1135
1136#ifdef HAVE_ACL
1137 // For systems that support ACL: get the ACL from the original file.
1138 if (!newfile)
1139 acl = mch_get_acl(fname);
1140#endif
1141
1142 // If 'backupskip' is not empty, don't make a backup for some files.
1143 dobackup = (p_wb || p_bk || *p_pm != NUL);
1144#ifdef FEAT_WILDIGN
1145 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
1146 dobackup = FALSE;
1147#endif
1148
1149 // Save the value of got_int and reset it. We don't want a previous
1150 // interruption cancel writing, only hitting CTRL-C while writing should
1151 // abort it.
1152 prev_got_int = got_int;
1153 got_int = FALSE;
1154
1155 // Mark the buffer as 'being saved' to prevent changed buffer warnings
1156 buf->b_saving = TRUE;
1157
1158 // If we are not appending or filtering, the file exists, and the
1159 // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
1160 // When 'patchmode' is set also make a backup when appending.
1161 //
1162 // Do not make any backup, if 'writebackup' and 'backup' are both switched
1163 // off. This helps when editing large files on almost-full disks.
1164 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
1165 {
1166#if defined(UNIX) || defined(MSWIN)
1167 stat_T st;
1168#endif
1169
1170 if ((bkc & BKC_YES) || append) // "yes"
1171 backup_copy = TRUE;
1172#if defined(UNIX) || defined(MSWIN)
1173 else if ((bkc & BKC_AUTO)) // "auto"
1174 {
1175 int i;
1176
1177# ifdef UNIX
1178 // Don't rename the file when:
1179 // - it's a hard link
1180 // - it's a symbolic link
1181 // - we don't have write permission in the directory
1182 // - we can't set the owner/group of the new file
1183 if (st_old.st_nlink > 1
1184 || mch_lstat((char *)fname, &st) < 0
1185 || st.st_dev != st_old.st_dev
1186 || st.st_ino != st_old.st_ino
1187# ifndef HAVE_FCHOWN
1188 || st.st_uid != st_old.st_uid
1189 || st.st_gid != st_old.st_gid
1190# endif
1191 )
1192 backup_copy = TRUE;
1193 else
1194# else
1195# ifdef MSWIN
1196 // On NTFS file systems hard links are possible.
1197 if (mch_is_linked(fname))
1198 backup_copy = TRUE;
1199 else
1200# endif
1201# endif
1202 {
1203 // Check if we can create a file and set the owner/group to
1204 // the ones from the original file.
1205 // First find a file name that doesn't exist yet (use some
1206 // arbitrary numbers).
1207 STRCPY(IObuff, fname);
1208 for (i = 4913; ; i += 123)
1209 {
1210 sprintf((char *)gettail(IObuff), "%d", i);
1211 if (mch_lstat((char *)IObuff, &st) < 0)
1212 break;
1213 }
1214 fd = mch_open((char *)IObuff,
1215 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
1216 if (fd < 0) // can't write in directory
1217 backup_copy = TRUE;
1218 else
1219 {
1220# ifdef UNIX
1221# ifdef HAVE_FCHOWN
1222 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
1223# endif
1224 if (mch_stat((char *)IObuff, &st) < 0
1225 || st.st_uid != st_old.st_uid
1226 || st.st_gid != st_old.st_gid
1227 || (long)st.st_mode != perm)
1228 backup_copy = TRUE;
1229# endif
1230 // Close the file before removing it, on MS-Windows we
1231 // can't delete an open file.
1232 close(fd);
1233 mch_remove(IObuff);
1234# ifdef MSWIN
1235 // MS-Windows may trigger a virus scanner to open the
1236 // file, we can't delete it then. Keep trying for half a
1237 // second.
1238 {
1239 int try;
1240
1241 for (try = 0; try < 10; ++try)
1242 {
1243 if (mch_lstat((char *)IObuff, &st) < 0)
1244 break;
1245 ui_delay(50L, TRUE); // wait 50 msec
1246 mch_remove(IObuff);
1247 }
1248 }
1249# endif
1250 }
1251 }
1252 }
1253
1254 // Break symlinks and/or hardlinks if we've been asked to.
1255 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
1256 {
1257# ifdef UNIX
1258 int lstat_res;
1259
1260 lstat_res = mch_lstat((char *)fname, &st);
1261
1262 // Symlinks.
1263 if ((bkc & BKC_BREAKSYMLINK)
1264 && lstat_res == 0
1265 && st.st_ino != st_old.st_ino)
1266 backup_copy = FALSE;
1267
1268 // Hardlinks.
1269 if ((bkc & BKC_BREAKHARDLINK)
1270 && st_old.st_nlink > 1
1271 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
1272 backup_copy = FALSE;
1273# else
1274# if defined(MSWIN)
1275 // Symlinks.
1276 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
1277 backup_copy = FALSE;
1278
1279 // Hardlinks.
1280 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
1281 backup_copy = FALSE;
1282# endif
1283# endif
1284 }
1285
1286#endif
1287
1288 // make sure we have a valid backup extension to use
1289 if (*p_bex == NUL)
1290 backup_ext = (char_u *)".bak";
1291 else
1292 backup_ext = p_bex;
1293
1294 if (backup_copy
1295 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
1296 {
1297 int bfd;
1298 char_u *copybuf, *wp;
1299 int some_error = FALSE;
1300 stat_T st_new;
1301 char_u *dirp;
1302 char_u *rootname;
1303#if defined(UNIX) || defined(MSWIN)
1304 char_u *p;
1305#endif
1306#if defined(UNIX)
1307 int did_set_shortname;
1308 mode_t umask_save;
1309#endif
1310
1311 copybuf = alloc(WRITEBUFSIZE + 1);
1312 if (copybuf == NULL)
1313 {
1314 some_error = TRUE; // out of memory
1315 goto nobackup;
1316 }
1317
1318 // Try to make the backup in each directory in the 'bdir' option.
1319 //
1320 // Unix semantics has it, that we may have a writable file,
1321 // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
1322 // - the directory is not writable,
1323 // - the file may be a symbolic link,
1324 // - the file may belong to another user/group, etc.
1325 //
1326 // For these reasons, the existing writable file must be truncated
1327 // and reused. Creation of a backup COPY will be attempted.
1328 dirp = p_bdir;
1329 while (*dirp)
1330 {
1331#ifdef UNIX
1332 st_new.st_ino = 0;
1333 st_new.st_dev = 0;
1334 st_new.st_gid = 0;
1335#endif
1336
1337 // Isolate one directory name, using an entry in 'bdir'.
1338 (void)copy_option_part(&dirp, copybuf, WRITEBUFSIZE, ",");
1339
1340#if defined(UNIX) || defined(MSWIN)
1341 p = copybuf + STRLEN(copybuf);
1342 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
1343 // Ends with '//', use full path
1344 if ((p = make_percent_swname(copybuf, fname)) != NULL)
1345 {
1346 backup = modname(p, backup_ext, FALSE);
1347 vim_free(p);
1348 }
1349#endif
1350 rootname = get_file_in_dir(fname, copybuf);
1351 if (rootname == NULL)
1352 {
1353 some_error = TRUE; // out of memory
1354 goto nobackup;
1355 }
1356
1357#if defined(UNIX)
1358 did_set_shortname = FALSE;
1359#endif
1360
1361 // May try twice if 'shortname' not set.
1362 for (;;)
1363 {
1364 // Make the backup file name.
1365 if (backup == NULL)
1366 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
1367 rootname, backup_ext, FALSE);
1368 if (backup == NULL)
1369 {
1370 vim_free(rootname);
1371 some_error = TRUE; // out of memory
1372 goto nobackup;
1373 }
1374
1375 // Check if backup file already exists.
1376 if (mch_stat((char *)backup, &st_new) >= 0)
1377 {
1378#ifdef UNIX
1379 // Check if backup file is same as original file.
1380 // May happen when modname() gave the same file back.
1381 // E.g. silly link, or file name-length reached.
1382 // If we don't check here, we either ruin the file
1383 // when copying or erase it after writing. jw.
1384 if (st_new.st_dev == st_old.st_dev
1385 && st_new.st_ino == st_old.st_ino)
1386 {
1387 VIM_CLEAR(backup); // no backup file to delete
1388 // may try again with 'shortname' set
1389 if (!(buf->b_shortname || buf->b_p_sn))
1390 {
1391 buf->b_shortname = TRUE;
1392 did_set_shortname = TRUE;
1393 continue;
1394 }
1395 // setting shortname didn't help
1396 if (did_set_shortname)
1397 buf->b_shortname = FALSE;
1398 break;
1399 }
1400#endif
1401
1402 // If we are not going to keep the backup file, don't
1403 // delete an existing one, try to use another name.
1404 // Change one character, just before the extension.
1405 if (!p_bk)
1406 {
1407 wp = backup + STRLEN(backup) - 1
1408 - STRLEN(backup_ext);
1409 if (wp < backup) // empty file name ???
1410 wp = backup;
1411 *wp = 'z';
1412 while (*wp > 'a'
1413 && mch_stat((char *)backup, &st_new) >= 0)
1414 --*wp;
1415 // They all exist??? Must be something wrong.
1416 if (*wp == 'a')
1417 VIM_CLEAR(backup);
1418 }
1419 }
1420 break;
1421 }
1422 vim_free(rootname);
1423
1424 // Try to create the backup file
1425 if (backup != NULL)
1426 {
1427 // remove old backup, if present
1428 mch_remove(backup);
1429 // Open with O_EXCL to avoid the file being created while
1430 // we were sleeping (symlink hacker attack?). Reset umask
1431 // if possible to avoid mch_setperm() below.
1432#ifdef UNIX
1433 umask_save = umask(0);
1434#endif
1435 bfd = mch_open((char *)backup,
1436 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
1437 perm & 0777);
1438#ifdef UNIX
1439 (void)umask(umask_save);
1440#endif
1441 if (bfd < 0)
1442 VIM_CLEAR(backup);
1443 else
1444 {
1445 // Set file protection same as original file, but
1446 // strip s-bit. Only needed if umask() wasn't used
1447 // above.
1448#ifndef UNIX
1449 (void)mch_setperm(backup, perm & 0777);
1450#else
1451 // Try to set the group of the backup same as the
1452 // original file. If this fails, set the protection
1453 // bits for the group same as the protection bits for
1454 // others.
1455 if (st_new.st_gid != st_old.st_gid
1456# ifdef HAVE_FCHOWN // sequent-ptx lacks fchown()
1457 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
1458# endif
1459 )
1460 mch_setperm(backup,
1461 (perm & 0707) | ((perm & 07) << 3));
1462# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1463 mch_copy_sec(fname, backup);
1464# endif
1465#endif
1466
1467 // copy the file.
1468 write_info.bw_fd = bfd;
1469 write_info.bw_buf = copybuf;
1470 write_info.bw_flags = FIO_NOCONVERT;
1471 while ((write_info.bw_len = read_eintr(fd, copybuf,
1472 WRITEBUFSIZE)) > 0)
1473 {
1474 if (buf_write_bytes(&write_info) == FAIL)
1475 {
1476 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
1477 break;
1478 }
1479 ui_breakcheck();
1480 if (got_int)
1481 {
1482 errmsg = (char_u *)_(e_interr);
1483 break;
1484 }
1485 }
1486
1487 if (close(bfd) < 0 && errmsg == NULL)
1488 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
1489 if (write_info.bw_len < 0)
1490 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
1491#ifdef UNIX
1492 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
1493#endif
1494#ifdef HAVE_ACL
1495 mch_set_acl(backup, acl);
1496#endif
1497#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1498 mch_copy_sec(fname, backup);
1499#endif
1500 break;
1501 }
1502 }
1503 }
1504 nobackup:
1505 close(fd); // ignore errors for closing read file
1506 vim_free(copybuf);
1507
1508 if (backup == NULL && errmsg == NULL)
1509 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
1510 // ignore errors when forceit is TRUE
1511 if ((some_error || errmsg != NULL) && !forceit)
1512 {
1513 retval = FAIL;
1514 goto fail;
1515 }
1516 errmsg = NULL;
1517 }
1518 else
1519 {
1520 char_u *dirp;
1521 char_u *p;
1522 char_u *rootname;
1523
1524 // Make a backup by renaming the original file.
1525
1526 // If 'cpoptions' includes the "W" flag, we don't want to
1527 // overwrite a read-only file. But rename may be possible
1528 // anyway, thus we need an extra check here.
1529 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1530 {
1531 errnum = (char_u *)"E504: ";
1532 errmsg = (char_u *)_(err_readonly);
1533 goto fail;
1534 }
1535
1536 // Form the backup file name - change path/fo.o.h to
1537 // path/fo.o.h.bak Try all directories in 'backupdir', first one
1538 // that works is used.
1539 dirp = p_bdir;
1540 while (*dirp)
1541 {
1542 // Isolate one directory name and make the backup file name.
1543 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
1544
1545#if defined(UNIX) || defined(MSWIN)
1546 p = IObuff + STRLEN(IObuff);
1547 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
1548 // path ends with '//', use full path
1549 if ((p = make_percent_swname(IObuff, fname)) != NULL)
1550 {
1551 backup = modname(p, backup_ext, FALSE);
1552 vim_free(p);
1553 }
1554#endif
1555 if (backup == NULL)
1556 {
1557 rootname = get_file_in_dir(fname, IObuff);
1558 if (rootname == NULL)
1559 backup = NULL;
1560 else
1561 {
1562 backup = buf_modname(
1563 (buf->b_p_sn || buf->b_shortname),
1564 rootname, backup_ext, FALSE);
1565 vim_free(rootname);
1566 }
1567 }
1568
1569 if (backup != NULL)
1570 {
1571 // If we are not going to keep the backup file, don't
1572 // delete an existing one, try to use another name.
1573 // Change one character, just before the extension.
1574 if (!p_bk && mch_getperm(backup) >= 0)
1575 {
1576 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
1577 if (p < backup) // empty file name ???
1578 p = backup;
1579 *p = 'z';
1580 while (*p > 'a' && mch_getperm(backup) >= 0)
1581 --*p;
1582 // They all exist??? Must be something wrong!
1583 if (*p == 'a')
1584 VIM_CLEAR(backup);
1585 }
1586 }
1587 if (backup != NULL)
1588 {
1589 // Delete any existing backup and move the current version
1590 // to the backup. For safety, we don't remove the backup
1591 // until the write has finished successfully. And if the
1592 // 'backup' option is set, leave it around.
1593
1594 // If the renaming of the original file to the backup file
1595 // works, quit here.
1596 if (vim_rename(fname, backup) == 0)
1597 break;
1598
1599 VIM_CLEAR(backup); // don't do the rename below
1600 }
1601 }
1602 if (backup == NULL && !forceit)
1603 {
1604 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
1605 goto fail;
1606 }
1607 }
1608 }
1609
1610#if defined(UNIX)
1611 // When using ":w!" and the file was read-only: make it writable
1612 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
1613 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
1614 {
1615 perm |= 0200;
1616 (void)mch_setperm(fname, perm);
1617 made_writable = TRUE;
1618 }
1619#endif
1620
1621 // When using ":w!" and writing to the current file, 'readonly' makes no
1622 // sense, reset it, unless 'Z' appears in 'cpoptions'.
1623 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
1624 {
1625 buf->b_p_ro = FALSE;
1626#ifdef FEAT_TITLE
1627 need_maketitle = TRUE; // set window title later
1628#endif
1629 status_redraw_all(); // redraw status lines later
1630 }
1631
1632 if (end > buf->b_ml.ml_line_count)
1633 end = buf->b_ml.ml_line_count;
1634 if (buf->b_ml.ml_flags & ML_EMPTY)
1635 start = end + 1;
1636
1637 // If the original file is being overwritten, there is a small chance that
1638 // we crash in the middle of writing. Therefore the file is preserved now.
1639 // This makes all block numbers positive so that recovery does not need
1640 // the original file.
1641 // Don't do this if there is a backup file and we are exiting.
1642 if (reset_changed && !newfile && overwriting
1643 && !(exiting && backup != NULL))
1644 {
1645 ml_preserve(buf, FALSE);
1646 if (got_int)
1647 {
1648 errmsg = (char_u *)_(e_interr);
1649 goto restore_backup;
1650 }
1651 }
1652
1653#ifdef VMS
1654 vms_remove_version(fname); // remove version
1655#endif
1656 // Default: write the file directly. May write to a temp file for
1657 // multi-byte conversion.
1658 wfname = fname;
1659
1660 // Check for forced 'fileencoding' from "++opt=val" argument.
1661 if (eap != NULL && eap->force_enc != 0)
1662 {
1663 fenc = eap->cmd + eap->force_enc;
1664 fenc = enc_canonize(fenc);
1665 fenc_tofree = fenc;
1666 }
1667 else
1668 fenc = buf->b_p_fenc;
1669
1670 // Check if the file needs to be converted.
1671 converted = need_conversion(fenc);
1672
1673 // Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
1674 // Latin1 to Unicode conversion. This is handled in buf_write_bytes().
1675 // Prepare the flags for it and allocate bw_conv_buf when needed.
1676 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
1677 {
1678 wb_flags = get_fio_flags(fenc);
1679 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
1680 {
1681 // Need to allocate a buffer to translate into.
1682 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
1683 write_info.bw_conv_buflen = bufsize * 2;
1684 else // FIO_UCS4
1685 write_info.bw_conv_buflen = bufsize * 4;
1686 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1687 if (write_info.bw_conv_buf == NULL)
1688 end = 0;
1689 }
1690 }
1691
1692#ifdef MSWIN
1693 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
1694 {
1695 // Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4:
1696 write_info.bw_conv_buflen = bufsize * 4;
1697 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1698 if (write_info.bw_conv_buf == NULL)
1699 end = 0;
1700 }
1701#endif
1702
1703#ifdef MACOS_CONVERT
1704 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
1705 {
1706 write_info.bw_conv_buflen = bufsize * 3;
1707 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1708 if (write_info.bw_conv_buf == NULL)
1709 end = 0;
1710 }
1711#endif
1712
1713#if defined(FEAT_EVAL) || defined(USE_ICONV)
1714 if (converted && wb_flags == 0)
1715 {
1716# ifdef USE_ICONV
1717 // Use iconv() conversion when conversion is needed and it's not done
1718 // internally.
1719 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
1720 enc_utf8 ? (char_u *)"utf-8" : p_enc);
1721 if (write_info.bw_iconv_fd != (iconv_t)-1)
1722 {
1723 // We're going to use iconv(), allocate a buffer to convert in.
1724 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
1725 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1726 if (write_info.bw_conv_buf == NULL)
1727 end = 0;
1728 write_info.bw_first = TRUE;
1729 }
1730# ifdef FEAT_EVAL
1731 else
1732# endif
1733# endif
1734
1735# ifdef FEAT_EVAL
1736 // When the file needs to be converted with 'charconvert' after
1737 // writing, write to a temp file instead and let the conversion
1738 // overwrite the original file.
1739 if (*p_ccv != NUL)
1740 {
1741 wfname = vim_tempname('w', FALSE);
1742 if (wfname == NULL) // Can't write without a tempfile!
1743 {
1744 errmsg = (char_u *)_("E214: Can't find temp file for writing");
1745 goto restore_backup;
1746 }
1747 }
1748# endif
1749 }
1750#endif
1751 if (converted && wb_flags == 0
1752#ifdef USE_ICONV
1753 && write_info.bw_iconv_fd == (iconv_t)-1
1754# endif
1755# ifdef FEAT_EVAL
1756 && wfname == fname
1757# endif
1758 )
1759 {
1760 if (!forceit)
1761 {
1762 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
1763 goto restore_backup;
1764 }
1765 notconverted = TRUE;
1766 }
1767
1768 // If conversion is taking place, we may first pretend to write and check
1769 // for conversion errors. Then loop again to write for real.
1770 // When not doing conversion this writes for real right away.
1771 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
1772 {
1773 // There is no need to check conversion when:
1774 // - there is no conversion
1775 // - we make a backup file, that can be restored in case of conversion
1776 // failure.
1777 if (!converted || dobackup)
1778 checking_conversion = FALSE;
1779
1780 if (checking_conversion)
1781 {
1782 // Make sure we don't write anything.
1783 fd = -1;
1784 write_info.bw_fd = fd;
1785 }
1786 else
1787 {
1788#ifdef HAVE_FTRUNCATE
1789# define TRUNC_ON_OPEN 0
1790#else
1791# define TRUNC_ON_OPEN O_TRUNC
1792#endif
1793 // Open the file "wfname" for writing.
1794 // We may try to open the file twice: If we can't write to the file
1795 // and forceit is TRUE we delete the existing file and try to
1796 // create a new one. If this still fails we may have lost the
1797 // original file! (this may happen when the user reached his
1798 // quotum for number of files).
1799 // Appending will fail if the file does not exist and forceit is
1800 // FALSE.
1801 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
1802 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
1803 : (O_CREAT | TRUNC_ON_OPEN))
1804 , perm < 0 ? 0666 : (perm & 0777))) < 0)
1805 {
1806 // A forced write will try to create a new file if the old one
1807 // is still readonly. This may also happen when the directory
1808 // is read-only. In that case the mch_remove() will fail.
1809 if (errmsg == NULL)
1810 {
1811#ifdef UNIX
1812 stat_T st;
1813
1814 // Don't delete the file when it's a hard or symbolic link.
1815 if ((!newfile && st_old.st_nlink > 1)
1816 || (mch_lstat((char *)fname, &st) == 0
1817 && (st.st_dev != st_old.st_dev
1818 || st.st_ino != st_old.st_ino)))
1819 errmsg = (char_u *)_("E166: Can't open linked file for writing");
1820 else
1821#endif
1822 {
1823 errmsg = (char_u *)_("E212: Can't open file for writing");
1824 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
1825 && perm >= 0)
1826 {
1827#ifdef UNIX
1828 // we write to the file, thus it should be marked
1829 // writable after all
1830 if (!(perm & 0200))
1831 made_writable = TRUE;
1832 perm |= 0200;
1833 if (st_old.st_uid != getuid()
1834 || st_old.st_gid != getgid())
1835 perm &= 0777;
1836#endif
1837 if (!append) // don't remove when appending
1838 mch_remove(wfname);
1839 continue;
1840 }
1841 }
1842 }
1843
1844restore_backup:
1845 {
1846 stat_T st;
1847
1848 // If we failed to open the file, we don't need a backup.
1849 // Throw it away. If we moved or removed the original file
1850 // try to put the backup in its place.
1851 if (backup != NULL && wfname == fname)
1852 {
1853 if (backup_copy)
1854 {
1855 // There is a small chance that we removed the
1856 // original, try to move the copy in its place.
1857 // This may not work if the vim_rename() fails.
1858 // In that case we leave the copy around.
1859
1860 // If file does not exist, put the copy in its
1861 // place
1862 if (mch_stat((char *)fname, &st) < 0)
1863 vim_rename(backup, fname);
1864 // if original file does exist throw away the copy
1865 if (mch_stat((char *)fname, &st) >= 0)
1866 mch_remove(backup);
1867 }
1868 else
1869 {
1870 // try to put the original file back
1871 vim_rename(backup, fname);
1872 }
1873 }
1874
1875 // if original file no longer exists give an extra warning
1876 if (!newfile && mch_stat((char *)fname, &st) < 0)
1877 end = 0;
1878 }
1879
1880 if (wfname != fname)
1881 vim_free(wfname);
1882 goto fail;
1883 }
1884 write_info.bw_fd = fd;
1885
1886#if defined(UNIX)
1887 {
1888 stat_T st;
1889
1890 // Double check we are writing the intended file before making
1891 // any changes.
1892 if (overwriting
1893 && (!dobackup || backup_copy)
1894 && fname == wfname
1895 && perm >= 0
1896 && mch_fstat(fd, &st) == 0
1897 && st.st_ino != st_old.st_ino)
1898 {
1899 close(fd);
1900 errmsg = (char_u *)_("E949: File changed while writing");
1901 goto fail;
1902 }
1903 }
1904#endif
1905#ifdef HAVE_FTRUNCATE
1906 if (!append)
1907 vim_ignored = ftruncate(fd, (off_t)0);
1908#endif
1909
1910#if defined(MSWIN)
1911 if (backup != NULL && overwriting && !append)
1912 {
1913 if (backup_copy)
1914 (void)mch_copy_file_attribute(wfname, backup);
1915 else
1916 (void)mch_copy_file_attribute(backup, wfname);
1917 }
1918
1919 if (!overwriting && !append)
1920 {
1921 if (buf->b_ffname != NULL)
1922 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
1923 // Should copy resource fork
1924 }
1925#endif
1926
1927#ifdef FEAT_CRYPT
1928 if (*buf->b_p_key != NUL && !filtering)
1929 {
1930 char_u *header;
1931 int header_len;
1932
1933 buf->b_cryptstate = crypt_create_for_writing(
1934 crypt_get_method_nr(buf),
1935 buf->b_p_key, &header, &header_len);
1936 if (buf->b_cryptstate == NULL || header == NULL)
1937 end = 0;
1938 else
1939 {
1940 // Write magic number, so that Vim knows how this file is
1941 // encrypted when reading it back.
1942 write_info.bw_buf = header;
1943 write_info.bw_len = header_len;
1944 write_info.bw_flags = FIO_NOCONVERT;
1945 if (buf_write_bytes(&write_info) == FAIL)
1946 end = 0;
1947 wb_flags |= FIO_ENCRYPTED;
1948 vim_free(header);
1949 }
1950 }
1951#endif
1952 }
1953 errmsg = NULL;
1954
1955 write_info.bw_buf = buffer;
1956 nchars = 0;
1957
1958 // use "++bin", "++nobin" or 'binary'
1959 if (eap != NULL && eap->force_bin != 0)
1960 write_bin = (eap->force_bin == FORCE_BIN);
1961 else
1962 write_bin = buf->b_p_bin;
1963
1964 // The BOM is written just after the encryption magic number.
1965 // Skip it when appending and the file already existed, the BOM only
1966 // makes sense at the start of the file.
1967 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
1968 {
1969 write_info.bw_len = make_bom(buffer, fenc);
1970 if (write_info.bw_len > 0)
1971 {
1972 // don't convert, do encryption
1973 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
1974 if (buf_write_bytes(&write_info) == FAIL)
1975 end = 0;
1976 else
1977 nchars += write_info.bw_len;
1978 }
1979 }
1980 write_info.bw_start_lnum = start;
1981
1982#ifdef FEAT_PERSISTENT_UNDO
1983 write_undo_file = (buf->b_p_udf
1984 && overwriting
1985 && !append
1986 && !filtering
1987 && reset_changed
1988 && !checking_conversion);
1989 if (write_undo_file)
1990 // Prepare for computing the hash value of the text.
1991 sha256_start(&sha_ctx);
1992#endif
1993
1994 write_info.bw_len = bufsize;
1995 write_info.bw_flags = wb_flags;
1996 fileformat = get_fileformat_force(buf, eap);
1997 s = buffer;
1998 len = 0;
1999 for (lnum = start; lnum <= end; ++lnum)
2000 {
2001 // The next while loop is done once for each character written.
2002 // Keep it fast!
2003 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
2004#ifdef FEAT_PERSISTENT_UNDO
2005 if (write_undo_file)
2006 sha256_update(&sha_ctx, ptr + 1,
2007 (UINT32_T)(STRLEN(ptr + 1) + 1));
2008#endif
2009 while ((c = *++ptr) != NUL)
2010 {
2011 if (c == NL)
2012 *s = NUL; // replace newlines with NULs
2013 else if (c == CAR && fileformat == EOL_MAC)
2014 *s = NL; // Mac: replace CRs with NLs
2015 else
2016 *s = c;
2017 ++s;
2018 if (++len != bufsize)
2019 continue;
2020 if (buf_write_bytes(&write_info) == FAIL)
2021 {
2022 end = 0; // write error: break loop
2023 break;
2024 }
2025 nchars += bufsize;
2026 s = buffer;
2027 len = 0;
2028 write_info.bw_start_lnum = lnum;
2029 }
2030 // write failed or last line has no EOL: stop here
2031 if (end == 0
2032 || (lnum == end
2033 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarb3c8b1d2020-12-23 18:54:57 +01002034 && ((write_bin && lnum == buf->b_no_eol_lnum)
Bram Moolenaar473952e2019-09-28 16:30:04 +02002035 || (lnum == buf->b_ml.ml_line_count
2036 && !buf->b_p_eol))))
2037 {
2038 ++lnum; // written the line, count it
2039 no_eol = TRUE;
2040 break;
2041 }
2042 if (fileformat == EOL_UNIX)
2043 *s++ = NL;
2044 else
2045 {
2046 *s++ = CAR; // EOL_MAC or EOL_DOS: write CR
2047 if (fileformat == EOL_DOS) // write CR-NL
2048 {
2049 if (++len == bufsize)
2050 {
2051 if (buf_write_bytes(&write_info) == FAIL)
2052 {
2053 end = 0; // write error: break loop
2054 break;
2055 }
2056 nchars += bufsize;
2057 s = buffer;
2058 len = 0;
2059 }
2060 *s++ = NL;
2061 }
2062 }
2063 if (++len == bufsize && end)
2064 {
2065 if (buf_write_bytes(&write_info) == FAIL)
2066 {
2067 end = 0; // write error: break loop
2068 break;
2069 }
2070 nchars += bufsize;
2071 s = buffer;
2072 len = 0;
2073
2074 ui_breakcheck();
2075 if (got_int)
2076 {
2077 end = 0; // Interrupted, break loop
2078 break;
2079 }
2080 }
2081#ifdef VMS
2082 // On VMS there is a problem: newlines get added when writing
2083 // blocks at a time. Fix it by writing a line at a time.
2084 // This is much slower!
2085 // Explanation: VAX/DECC RTL insists that records in some RMS
2086 // structures end with a newline (carriage return) character, and
2087 // if they don't it adds one.
2088 // With other RMS structures it works perfect without this fix.
Bram Moolenaar95f0b6e2019-12-15 12:54:18 +01002089# ifndef MIN
2090// Older DECC compiler for VAX doesn't define MIN()
2091# define MIN(a, b) ((a) < (b) ? (a) : (b))
2092# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002093 if (buf->b_fab_rfm == FAB$C_VFC
2094 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
2095 {
2096 int b2write;
2097
2098 buf->b_fab_mrs = (buf->b_fab_mrs == 0
2099 ? MIN(4096, bufsize)
2100 : MIN(buf->b_fab_mrs, bufsize));
2101
2102 b2write = len;
2103 while (b2write > 0)
2104 {
2105 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
2106 if (buf_write_bytes(&write_info) == FAIL)
2107 {
2108 end = 0;
2109 break;
2110 }
2111 b2write -= MIN(b2write, buf->b_fab_mrs);
2112 }
2113 write_info.bw_len = bufsize;
2114 nchars += len;
2115 s = buffer;
2116 len = 0;
2117 }
2118#endif
2119 }
2120 if (len > 0 && end > 0)
2121 {
2122 write_info.bw_len = len;
2123 if (buf_write_bytes(&write_info) == FAIL)
2124 end = 0; // write error
2125 nchars += len;
2126 }
2127
2128 // Stop when writing done or an error was encountered.
2129 if (!checking_conversion || end == 0)
2130 break;
2131
2132 // If no error happened until now, writing should be ok, so loop to
2133 // really write the buffer.
2134 }
2135
2136 // If we started writing, finish writing. Also when an error was
2137 // encountered.
2138 if (!checking_conversion)
2139 {
2140#if defined(UNIX) && defined(HAVE_FSYNC)
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002141 // On many journaling file systems there is a bug that causes both the
Bram Moolenaar473952e2019-09-28 16:30:04 +02002142 // original and the backup file to be lost when halting the system
2143 // right after writing the file. That's because only the meta-data is
2144 // journalled. Syncing the file slows down the system, but assures it
2145 // has been written to disk and we don't lose it.
2146 // For a device do try the fsync() but don't complain if it does not
2147 // work (could be a pipe).
2148 // If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
2149 if (p_fs && vim_fsync(fd) != 0 && !device)
2150 {
2151 errmsg = (char_u *)_(e_fsync);
2152 end = 0;
2153 }
2154#endif
2155
2156#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
2157 // Probably need to set the security context.
2158 if (!backup_copy)
2159 mch_copy_sec(backup, wfname);
2160#endif
2161
2162#ifdef UNIX
2163 // When creating a new file, set its owner/group to that of the
2164 // original file. Get the new device and inode number.
2165 if (backup != NULL && !backup_copy)
2166 {
2167# ifdef HAVE_FCHOWN
2168 stat_T st;
2169
2170 // Don't change the owner when it's already OK, some systems remove
2171 // permission or ACL stuff.
2172 if (mch_stat((char *)wfname, &st) < 0
2173 || st.st_uid != st_old.st_uid
2174 || st.st_gid != st_old.st_gid)
2175 {
2176 // changing owner might not be possible
2177 vim_ignored = fchown(fd, st_old.st_uid, -1);
2178 // if changing group fails clear the group permissions
2179 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
2180 perm &= ~070;
2181 }
2182# endif
2183 buf_setino(buf);
2184 }
2185 else if (!buf->b_dev_valid)
2186 // Set the inode when creating a new file.
2187 buf_setino(buf);
2188#endif
2189
2190#ifdef UNIX
2191 if (made_writable)
2192 perm &= ~0200; // reset 'w' bit for security reasons
2193#endif
2194#ifdef HAVE_FCHMOD
2195 // set permission of new file same as old file
2196 if (perm >= 0)
2197 (void)mch_fsetperm(fd, perm);
2198#endif
2199 if (close(fd) != 0)
2200 {
2201 errmsg = (char_u *)_("E512: Close failed");
2202 end = 0;
2203 }
2204
2205#ifndef HAVE_FCHMOD
2206 // set permission of new file same as old file
2207 if (perm >= 0)
2208 (void)mch_setperm(wfname, perm);
2209#endif
2210#ifdef HAVE_ACL
2211 // Probably need to set the ACL before changing the user (can't set the
2212 // ACL on a file the user doesn't own).
2213 // On Solaris, with ZFS and the aclmode property set to "discard" (the
2214 // default), chmod() discards all part of a file's ACL that don't
2215 // represent the mode of the file. It's non-trivial for us to discover
2216 // whether we're in that situation, so we simply always re-set the ACL.
2217# ifndef HAVE_SOLARIS_ZFS_ACL
2218 if (!backup_copy)
2219# endif
2220 mch_set_acl(wfname, acl);
2221#endif
2222#ifdef FEAT_CRYPT
2223 if (buf->b_cryptstate != NULL)
2224 {
2225 crypt_free_state(buf->b_cryptstate);
2226 buf->b_cryptstate = NULL;
2227 }
2228#endif
2229
2230#if defined(FEAT_EVAL)
2231 if (wfname != fname)
2232 {
2233 // The file was written to a temp file, now it needs to be
2234 // converted with 'charconvert' to (overwrite) the output file.
2235 if (end != 0)
2236 {
2237 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
2238 fenc, wfname, fname) == FAIL)
2239 {
2240 write_info.bw_conv_error = TRUE;
2241 end = 0;
2242 }
2243 }
2244 mch_remove(wfname);
2245 vim_free(wfname);
2246 }
2247#endif
2248 }
2249
2250 if (end == 0)
2251 {
2252 // Error encountered.
2253 if (errmsg == NULL)
2254 {
2255 if (write_info.bw_conv_error)
2256 {
2257 if (write_info.bw_conv_error_lnum == 0)
2258 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
2259 else
2260 {
2261 errmsg_allocated = TRUE;
2262 errmsg = alloc(300);
2263 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
2264 (long)write_info.bw_conv_error_lnum);
2265 }
2266 }
2267 else if (got_int)
2268 errmsg = (char_u *)_(e_interr);
2269 else
2270 errmsg = (char_u *)_("E514: write error (file system full?)");
2271 }
2272
2273 // If we have a backup file, try to put it in place of the new file,
2274 // because the new file is probably corrupt. This avoids losing the
2275 // original file when trying to make a backup when writing the file a
2276 // second time.
2277 // When "backup_copy" is set we need to copy the backup over the new
2278 // file. Otherwise rename the backup file.
2279 // If this is OK, don't give the extra warning message.
2280 if (backup != NULL)
2281 {
2282 if (backup_copy)
2283 {
2284 // This may take a while, if we were interrupted let the user
2285 // know we got the message.
2286 if (got_int)
2287 {
2288 msg(_(e_interr));
2289 out_flush();
2290 }
2291 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
2292 {
2293 if ((write_info.bw_fd = mch_open((char *)fname,
2294 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
2295 perm & 0777)) >= 0)
2296 {
2297 // copy the file.
2298 write_info.bw_buf = smallbuf;
2299 write_info.bw_flags = FIO_NOCONVERT;
2300 while ((write_info.bw_len = read_eintr(fd, smallbuf,
2301 SMALLBUFSIZE)) > 0)
2302 if (buf_write_bytes(&write_info) == FAIL)
2303 break;
2304
2305 if (close(write_info.bw_fd) >= 0
2306 && write_info.bw_len == 0)
2307 end = 1; // success
2308 }
2309 close(fd); // ignore errors for closing read file
2310 }
2311 }
2312 else
2313 {
2314 if (vim_rename(backup, fname) == 0)
2315 end = 1;
2316 }
2317 }
2318 goto fail;
2319 }
2320
2321 lnum -= start; // compute number of written lines
2322 --no_wait_return; // may wait for return now
2323
2324#if !(defined(UNIX) || defined(VMS))
2325 fname = sfname; // use shortname now, for the messages
2326#endif
2327 if (!filtering)
2328 {
2329 msg_add_fname(buf, fname); // put fname in IObuff with quotes
2330 c = FALSE;
2331 if (write_info.bw_conv_error)
2332 {
2333 STRCAT(IObuff, _(" CONVERSION ERROR"));
2334 c = TRUE;
2335 if (write_info.bw_conv_error_lnum != 0)
2336 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
2337 (long)write_info.bw_conv_error_lnum);
2338 }
2339 else if (notconverted)
2340 {
2341 STRCAT(IObuff, _("[NOT converted]"));
2342 c = TRUE;
2343 }
2344 else if (converted)
2345 {
2346 STRCAT(IObuff, _("[converted]"));
2347 c = TRUE;
2348 }
2349 if (device)
2350 {
2351 STRCAT(IObuff, _("[Device]"));
2352 c = TRUE;
2353 }
2354 else if (newfile)
2355 {
Bram Moolenaar722e5052020-06-12 22:31:00 +02002356 STRCAT(IObuff, new_file_message());
Bram Moolenaar473952e2019-09-28 16:30:04 +02002357 c = TRUE;
2358 }
2359 if (no_eol)
2360 {
2361 msg_add_eol();
2362 c = TRUE;
2363 }
2364 // may add [unix/dos/mac]
2365 if (msg_add_fileformat(fileformat))
2366 c = TRUE;
2367#ifdef FEAT_CRYPT
2368 if (wb_flags & FIO_ENCRYPTED)
2369 {
2370 crypt_append_msg(buf);
2371 c = TRUE;
2372 }
2373#endif
2374 msg_add_lines(c, (long)lnum, nchars); // add line/char count
2375 if (!shortmess(SHM_WRITE))
2376 {
2377 if (append)
2378 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
2379 else
2380 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
2381 }
2382
2383 set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0);
2384 }
2385
2386 // When written everything correctly: reset 'modified'. Unless not
2387 // writing to the original file and '+' is not in 'cpoptions'.
2388 if (reset_changed && whole && !append
2389 && !write_info.bw_conv_error
2390 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
2391 {
2392 unchanged(buf, TRUE, FALSE);
2393 // b:changedtick is may be incremented in unchanged() but that
2394 // should not trigger a TextChanged event.
2395 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
2396 buf->b_last_changedtick = CHANGEDTICK(buf);
2397 u_unchanged(buf);
2398 u_update_save_nr(buf);
2399 }
2400
2401 // If written to the current file, update the timestamp of the swap file
2402 // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
2403 if (overwriting)
2404 {
2405 ml_timestamp(buf);
2406 if (append)
2407 buf->b_flags &= ~BF_NEW;
2408 else
2409 buf->b_flags &= ~BF_WRITE_MASK;
2410 }
2411
2412 // If we kept a backup until now, and we are in patch mode, then we make
2413 // the backup file our 'original' file.
2414 if (*p_pm && dobackup)
2415 {
2416 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
2417 fname, p_pm, FALSE);
2418
2419 if (backup != NULL)
2420 {
2421 stat_T st;
2422
2423 // If the original file does not exist yet
2424 // the current backup file becomes the original file
2425 if (org == NULL)
2426 emsg(_("E205: Patchmode: can't save original file"));
2427 else if (mch_stat(org, &st) < 0)
2428 {
2429 vim_rename(backup, (char_u *)org);
2430 VIM_CLEAR(backup); // don't delete the file
2431#ifdef UNIX
2432 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
2433#endif
2434 }
2435 }
2436 // If there is no backup file, remember that a (new) file was
2437 // created.
2438 else
2439 {
2440 int empty_fd;
2441
2442 if (org == NULL
2443 || (empty_fd = mch_open(org,
2444 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
2445 perm < 0 ? 0666 : (perm & 0777))) < 0)
2446 emsg(_("E206: patchmode: can't touch empty original file"));
2447 else
2448 close(empty_fd);
2449 }
2450 if (org != NULL)
2451 {
2452 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
2453 vim_free(org);
2454 }
2455 }
2456
2457 // Remove the backup unless 'backup' option is set or there was a
2458 // conversion error.
2459 if (!p_bk && backup != NULL && !write_info.bw_conv_error
2460 && mch_remove(backup) != 0)
2461 emsg(_("E207: Can't delete backup file"));
2462
2463 goto nofail;
2464
2465 // Finish up. We get here either after failure or success.
2466fail:
2467 --no_wait_return; // may wait for return now
2468nofail:
2469
2470 // Done saving, we accept changed buffer warnings again
2471 buf->b_saving = FALSE;
2472
2473 vim_free(backup);
2474 if (buffer != smallbuf)
2475 vim_free(buffer);
2476 vim_free(fenc_tofree);
2477 vim_free(write_info.bw_conv_buf);
2478#ifdef USE_ICONV
2479 if (write_info.bw_iconv_fd != (iconv_t)-1)
2480 {
2481 iconv_close(write_info.bw_iconv_fd);
2482 write_info.bw_iconv_fd = (iconv_t)-1;
2483 }
2484#endif
2485#ifdef HAVE_ACL
2486 mch_free_acl(acl);
2487#endif
2488
2489 if (errmsg != NULL)
2490 {
2491 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
2492
2493 attr = HL_ATTR(HLF_E); // set highlight for error messages
2494 msg_add_fname(buf,
2495#ifndef UNIX
2496 sfname
2497#else
2498 fname
2499#endif
2500 ); // put file name in IObuff with quotes
2501 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
2502 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
2503 // If the error message has the form "is ...", put the error number in
2504 // front of the file name.
2505 if (errnum != NULL)
2506 {
2507 STRMOVE(IObuff + numlen, IObuff);
2508 mch_memmove(IObuff, errnum, (size_t)numlen);
2509 }
2510 STRCAT(IObuff, errmsg);
2511 emsg((char *)IObuff);
2512 if (errmsg_allocated)
2513 vim_free(errmsg);
2514
2515 retval = FAIL;
2516 if (end == 0)
2517 {
2518 msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
2519 attr | MSG_HIST);
2520 msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
2521 attr | MSG_HIST);
2522
2523 // Update the timestamp to avoid an "overwrite changed file"
2524 // prompt when writing again.
2525 if (mch_stat((char *)fname, &st_old) >= 0)
2526 {
2527 buf_store_time(buf, &st_old, fname);
2528 buf->b_mtime_read = buf->b_mtime;
2529 }
2530 }
2531 }
2532 msg_scroll = msg_save;
2533
2534#ifdef FEAT_PERSISTENT_UNDO
2535 // When writing the whole file and 'undofile' is set, also write the undo
2536 // file.
2537 if (retval == OK && write_undo_file)
2538 {
2539 char_u hash[UNDO_HASH_SIZE];
2540
2541 sha256_finish(&sha_ctx, hash);
2542 u_write_undo(NULL, FALSE, buf, hash);
2543 }
2544#endif
2545
2546#ifdef FEAT_EVAL
2547 if (!should_abort(retval))
2548#else
2549 if (!got_int)
2550#endif
2551 {
2552 aco_save_T aco;
2553
2554 curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
2555
2556 // Apply POST autocommands.
2557 // Careful: The autocommands may call buf_write() recursively!
2558 aucmd_prepbuf(&aco, buf);
2559
2560 if (append)
2561 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
2562 FALSE, curbuf, eap);
2563 else if (filtering)
2564 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
2565 FALSE, curbuf, eap);
2566 else if (reset_changed && whole)
2567 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
2568 FALSE, curbuf, eap);
2569 else
2570 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
2571 FALSE, curbuf, eap);
2572
2573 // restore curwin/curbuf and a few other things
2574 aucmd_restbuf(&aco);
2575
2576#ifdef FEAT_EVAL
2577 if (aborting()) // autocmds may abort script processing
2578 retval = FALSE;
2579#endif
2580 }
2581
Bram Moolenaar8e6be342020-11-23 22:01:26 +01002582#ifdef FEAT_VIMINFO
2583 // Make sure marks will be written out to the viminfo file later, even when
2584 // the file is new.
2585 curbuf->b_marks_read = TRUE;
2586#endif
2587
Bram Moolenaar473952e2019-09-28 16:30:04 +02002588 got_int |= prev_got_int;
2589
2590 return retval;
2591}