diff options
author | Bram Moolenaar <Bram@vim.org> | 2019-09-28 16:30:04 +0200 |
---|---|---|
committer | Bram Moolenaar <Bram@vim.org> | 2019-09-28 16:30:04 +0200 |
commit | 473952e85286eb9c6098801f1819981ba61ad153 (patch) | |
tree | 853c22efb3c9b723e336b560e756da38db610021 /src/fileio.c | |
parent | 9be0e0b9d31e42d0074527a7789836087475142a (diff) |
patch 8.1.2094: the fileio.c file is too bigv8.1.2094
Problem: The fileio.c file is too big.
Solution: Move buf_write() to bufwrite.c. (Yegappan Lakshmanan,
closes #4990)
Diffstat (limited to 'src/fileio.c')
-rw-r--r-- | src/fileio.c | 2780 |
1 files changed, 20 insertions, 2760 deletions
diff --git a/src/fileio.c b/src/fileio.c index e0226f8c8c..0c2238be6b 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -17,13 +17,6 @@ # include <limits.h> /* for SSIZE_MAX */ #endif -#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H) -# include <utime.h> /* for struct utimbuf */ -#endif - -#define BUFSIZE 8192 /* size of normal write buffer */ -#define SMBUFSIZE 256 /* size of emergency write buffer */ - /* Is there any system that doesn't have access()? */ #define USE_MCH_ACCESS @@ -34,84 +27,11 @@ static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp); #ifdef FEAT_CRYPT static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask); #endif -static int set_rw_fname(char_u *fname, char_u *sfname); -static int msg_add_fileformat(int eol_type); -static void msg_add_eol(void); -static int check_mtime(buf_T *buf, stat_T *s); -static int time_differs(long t1, long t2); - -#define HAS_BW_FLAGS -#define FIO_LATIN1 0x01 /* convert Latin1 */ -#define FIO_UTF8 0x02 /* convert UTF-8 */ -#define FIO_UCS2 0x04 /* convert UCS-2 */ -#define FIO_UCS4 0x08 /* convert UCS-4 */ -#define FIO_UTF16 0x10 /* convert UTF-16 */ -#ifdef MSWIN -# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */ -# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */ -# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */ -#endif -#ifdef MACOS_CONVERT -# define FIO_MACROMAN 0x20 /* convert MacRoman */ -#endif -#define FIO_ENDIAN_L 0x80 /* little endian */ -#define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */ -#define FIO_NOCONVERT 0x2000 /* skip encoding conversion */ -#define FIO_UCSBOM 0x4000 /* check for BOM at start of file */ -#define FIO_ALL -1 /* allow all formats */ - -/* When converting, a read() or write() may leave some bytes to be converted - * for the next call. The value is guessed... */ -#define CONV_RESTLEN 30 - -/* We have to guess how much a sequence of bytes may expand when converting - * with iconv() to be able to allocate a buffer. */ -#define ICONV_MULT 8 - -/* - * Structure to pass arguments from buf_write() to buf_write_bytes(). - */ -struct bw_info -{ - int bw_fd; /* file descriptor */ - char_u *bw_buf; /* buffer with data to be written */ - int bw_len; /* length of data */ -#ifdef HAS_BW_FLAGS - int bw_flags; /* FIO_ flags */ -#endif -#ifdef FEAT_CRYPT - buf_T *bw_buffer; /* buffer being written */ -#endif - char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */ - int bw_restlen; /* nr of bytes in bw_rest[] */ - int bw_first; /* first write call */ - char_u *bw_conv_buf; /* buffer for writing converted chars */ - size_t bw_conv_buflen; /* size of bw_conv_buf */ - int bw_conv_error; /* set for conversion error */ - linenr_T bw_conv_error_lnum; /* first line with error or zero */ - linenr_T bw_start_lnum; /* line number at start of buffer */ -#ifdef USE_ICONV - iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */ -#endif -}; - -static int buf_write_bytes(struct bw_info *ip); - static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp); -static int ucs2bytes(unsigned c, char_u **pp, int flags); -static int need_conversion(char_u *fenc); -static int get_fio_flags(char_u *ptr); static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags); -static int make_bom(char_u *buf, char_u *name); -#ifdef MSWIN -static int get_win_fio_flags(char_u *ptr); -#endif -#ifdef MACOS_CONVERT -static int get_mac_fio_flags(char_u *ptr); -#endif static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name"); - static void + void filemess( buf_T *buf, char_u *name, @@ -119,6 +39,7 @@ filemess( int attr) { int msg_scroll_save; + int prev_msg_col = msg_col; if (msg_silent != 0) return; @@ -138,6 +59,8 @@ filemess( if (!msg_scroll) /* wait a bit when overwriting an error msg */ check_for_delay(FALSE); msg_start(); + if (prev_msg_col != 0 && msg_col == 0) + msg_putchar('\r'); // overwrite any previous message. msg_scroll = msg_scroll_save; msg_scrolled_ign = TRUE; /* may truncate the message to avoid a hit-return prompt */ @@ -2512,7 +2435,11 @@ failed: p = msg_may_trunc(FALSE, IObuff); else #endif + { + if (msg_col > 0) + msg_putchar('\r'); // overwrite previous message p = (char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0); + } if (read_stdin || read_buffer || restart_edit != 0 || (msg_scrolled != 0 && !need_wait_return)) /* Need to repeat the message after redrawing when: @@ -2939,37 +2866,6 @@ check_for_cryptkey( } #endif /* FEAT_CRYPT */ -#ifdef UNIX - static void -set_file_time( - char_u *fname, - time_t atime, /* access time */ - time_t mtime) /* modification time */ -{ -# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H) - struct utimbuf buf; - - buf.actime = atime; - buf.modtime = mtime; - (void)utime((char *)fname, &buf); -# else -# if defined(HAVE_UTIMES) - struct timeval tvp[2]; - - tvp[0].tv_sec = atime; - tvp[0].tv_usec = 0; - tvp[1].tv_sec = mtime; - tvp[1].tv_usec = 0; -# ifdef NeXT - (void)utimes((char *)fname, tvp); -# else - (void)utimes((char *)fname, (const struct timeval *)&tvp); -# endif -# endif -# endif -} -#endif /* UNIX */ - #if defined(VMS) && !defined(MIN) /* Older DECC compiler for VAX doesn't define MIN() */ # define MIN(a, b) ((a) < (b) ? (a) : (b)) @@ -3000,2104 +2896,6 @@ check_file_readonly( ); } - -/* - * buf_write() - write to file "fname" lines "start" through "end" - * - * We do our own buffering here because fwrite() is so slow. - * - * If "forceit" is true, we don't care for errors when attempting backups. - * In case of an error everything possible is done to restore the original - * file. But when "forceit" is TRUE, we risk losing it. - * - * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and - * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed. - * - * This function must NOT use NameBuff (because it's called by autowrite()). - * - * return FAIL for failure, OK otherwise - */ - int -buf_write( - buf_T *buf, - char_u *fname, - char_u *sfname, - linenr_T start, - linenr_T end, - exarg_T *eap, /* for forced 'ff' and 'fenc', can be - NULL! */ - int append, /* append to the file */ - int forceit, - int reset_changed, - int filtering) -{ - int fd; - char_u *backup = NULL; - int backup_copy = FALSE; /* copy the original file? */ - int dobackup; - char_u *ffname; - char_u *wfname = NULL; /* name of file to write to */ - char_u *s; - char_u *ptr; - char_u c; - int len; - linenr_T lnum; - long nchars; - char_u *errmsg = NULL; - int errmsg_allocated = FALSE; - char_u *errnum = NULL; - char_u *buffer; - char_u smallbuf[SMBUFSIZE]; - char_u *backup_ext; - int bufsize; - long perm; /* file permissions */ - int retval = OK; - int newfile = FALSE; /* TRUE if file doesn't exist yet */ - int msg_save = msg_scroll; - int overwriting; /* TRUE if writing over original */ - int no_eol = FALSE; /* no end-of-line written */ - int device = FALSE; /* writing to a device */ - stat_T st_old; - int prev_got_int = got_int; - int checking_conversion; - int file_readonly = FALSE; /* overwritten file is read-only */ - static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')"; -#if defined(UNIX) /*XXX fix me sometime? */ - int made_writable = FALSE; /* 'w' bit has been set */ -#endif - /* writing everything */ - int whole = (start == 1 && end == buf->b_ml.ml_line_count); - linenr_T old_line_count = buf->b_ml.ml_line_count; - int attr; - int fileformat; - int write_bin; - struct bw_info write_info; /* info for buf_write_bytes() */ - int converted = FALSE; - int notconverted = FALSE; - char_u *fenc; /* effective 'fileencoding' */ - char_u *fenc_tofree = NULL; /* allocated "fenc" */ -#ifdef HAS_BW_FLAGS - int wb_flags = 0; -#endif -#ifdef HAVE_ACL - vim_acl_T acl = NULL; /* ACL copied from original file to - backup or new file */ -#endif -#ifdef FEAT_PERSISTENT_UNDO - int write_undo_file = FALSE; - context_sha256_T sha_ctx; -#endif - unsigned int bkc = get_bkc_value(buf); - - if (fname == NULL || *fname == NUL) /* safety check */ - return FAIL; - if (buf->b_ml.ml_mfp == NULL) - { - /* This can happen during startup when there is a stray "w" in the - * vimrc file. */ - emsg(_(e_emptybuf)); - return FAIL; - } - - /* - * Disallow writing from .exrc and .vimrc in current directory for - * security reasons. - */ - if (check_secure()) - return FAIL; - - /* Avoid a crash for a long name. */ - if (STRLEN(fname) >= MAXPATHL) - { - emsg(_(e_longname)); - return FAIL; - } - - /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */ - write_info.bw_conv_buf = NULL; - write_info.bw_conv_error = FALSE; - write_info.bw_conv_error_lnum = 0; - write_info.bw_restlen = 0; -#ifdef USE_ICONV - write_info.bw_iconv_fd = (iconv_t)-1; -#endif -#ifdef FEAT_CRYPT - write_info.bw_buffer = buf; -#endif - - /* After writing a file changedtick changes but we don't want to display - * the line. */ - ex_no_reprint = TRUE; - - /* - * If there is no file name yet, use the one for the written file. - * BF_NOTEDITED is set to reflect this (in case the write fails). - * Don't do this when the write is for a filter command. - * Don't do this when appending. - * Only do this when 'cpoptions' contains the 'F' flag. - */ - if (buf->b_ffname == NULL - && reset_changed - && whole - && buf == curbuf -#ifdef FEAT_QUICKFIX - && !bt_nofilename(buf) -#endif - && !filtering - && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL) - && vim_strchr(p_cpo, CPO_FNAMEW) != NULL) - { - if (set_rw_fname(fname, sfname) == FAIL) - return FAIL; - buf = curbuf; /* just in case autocmds made "buf" invalid */ - } - - if (sfname == NULL) - sfname = fname; - /* - * For Unix: Use the short file name whenever possible. - * Avoids problems with networks and when directory names are changed. - * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to - * another directory, which we don't detect - */ - ffname = fname; /* remember full fname */ -#ifdef UNIX - fname = sfname; -#endif - - if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0) - overwriting = TRUE; - else - overwriting = FALSE; - - if (exiting) - settmode(TMODE_COOK); /* when exiting allow typeahead now */ - - ++no_wait_return; /* don't wait for return yet */ - - /* - * Set '[ and '] marks to the lines to be written. - */ - buf->b_op_start.lnum = start; - buf->b_op_start.col = 0; - buf->b_op_end.lnum = end; - buf->b_op_end.col = 0; - - { - aco_save_T aco; - int buf_ffname = FALSE; - int buf_sfname = FALSE; - int buf_fname_f = FALSE; - int buf_fname_s = FALSE; - int did_cmd = FALSE; - int nofile_err = FALSE; - int empty_memline = (buf->b_ml.ml_mfp == NULL); - bufref_T bufref; - - /* - * Apply PRE autocommands. - * Set curbuf to the buffer to be written. - * Careful: The autocommands may call buf_write() recursively! - */ - if (ffname == buf->b_ffname) - buf_ffname = TRUE; - if (sfname == buf->b_sfname) - buf_sfname = TRUE; - if (fname == buf->b_ffname) - buf_fname_f = TRUE; - if (fname == buf->b_sfname) - buf_fname_s = TRUE; - - /* set curwin/curbuf to buf and save a few things */ - aucmd_prepbuf(&aco, buf); - set_bufref(&bufref, buf); - - if (append) - { - if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD, - sfname, sfname, FALSE, curbuf, eap))) - { -#ifdef FEAT_QUICKFIX - if (overwriting && bt_nofilename(curbuf)) - nofile_err = TRUE; - else -#endif - apply_autocmds_exarg(EVENT_FILEAPPENDPRE, - sfname, sfname, FALSE, curbuf, eap); - } - } - else if (filtering) - { - apply_autocmds_exarg(EVENT_FILTERWRITEPRE, - NULL, sfname, FALSE, curbuf, eap); - } - else if (reset_changed && whole) - { - int was_changed = curbufIsChanged(); - - did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD, - sfname, sfname, FALSE, curbuf, eap); - if (did_cmd) - { - if (was_changed && !curbufIsChanged()) - { - /* Written everything correctly and BufWriteCmd has reset - * 'modified': Correct the undo information so that an - * undo now sets 'modified'. */ - u_unchanged(curbuf); - u_update_save_nr(curbuf); - } - } - else - { -#ifdef FEAT_QUICKFIX - if (overwriting && bt_nofilename(curbuf)) - nofile_err = TRUE; - else -#endif - apply_autocmds_exarg(EVENT_BUFWRITEPRE, - sfname, sfname, FALSE, curbuf, eap); - } - } - else - { - if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD, - sfname, sfname, FALSE, curbuf, eap))) - { -#ifdef FEAT_QUICKFIX - if (overwriting && bt_nofilename(curbuf)) - nofile_err = TRUE; - else -#endif - apply_autocmds_exarg(EVENT_FILEWRITEPRE, - sfname, sfname, FALSE, curbuf, eap); - } - } - - /* restore curwin/curbuf and a few other things */ - aucmd_restbuf(&aco); - - /* - * In three situations we return here and don't write the file: - * 1. the autocommands deleted or unloaded the buffer. - * 2. The autocommands abort script processing. - * 3. If one of the "Cmd" autocommands was executed. - */ - if (!bufref_valid(&bufref)) - buf = NULL; - if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline) - || did_cmd || nofile_err -#ifdef FEAT_EVAL - || aborting() -#endif - ) - { - --no_wait_return; - msg_scroll = msg_save; - if (nofile_err) - emsg(_("E676: No matching autocommands for acwrite buffer")); - - if (nofile_err -#ifdef FEAT_EVAL - || aborting() -#endif - ) - /* An aborting error, interrupt or exception in the - * autocommands. */ - return FAIL; - if (did_cmd) - { - if (buf == NULL) - /* The buffer was deleted. We assume it was written - * (can't retry anyway). */ - return OK; - if (overwriting) - { - /* Assume the buffer was written, update the timestamp. */ - ml_timestamp(buf); - if (append) - buf->b_flags &= ~BF_NEW; - else - buf->b_flags &= ~BF_WRITE_MASK; - } - if (reset_changed && buf->b_changed && !append - && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) - /* Buffer still changed, the autocommands didn't work - * properly. */ - return FAIL; - return OK; - } -#ifdef FEAT_EVAL - if (!aborting()) -#endif - emsg(_("E203: Autocommands deleted or unloaded buffer to be written")); - return FAIL; - } - - /* - * The autocommands may have changed the number of lines in the file. - * When writing the whole file, adjust the end. - * When writing part of the file, assume that the autocommands only - * changed the number of lines that are to be written (tricky!). - */ - if (buf->b_ml.ml_line_count != old_line_count) - { - if (whole) /* write all */ - end = buf->b_ml.ml_line_count; - else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */ - end += buf->b_ml.ml_line_count - old_line_count; - else /* less lines */ - { - end -= old_line_count - buf->b_ml.ml_line_count; - if (end < start) - { - --no_wait_return; - msg_scroll = msg_save; - emsg(_("E204: Autocommand changed number of lines in unexpected way")); - return FAIL; - } - } - } - - /* - * The autocommands may have changed the name of the buffer, which may - * be kept in fname, ffname and sfname. - */ - if (buf_ffname) - ffname = buf->b_ffname; - if (buf_sfname) - sfname = buf->b_sfname; - if (buf_fname_f) - fname = buf->b_ffname; - if (buf_fname_s) - fname = buf->b_sfname; - } - -#ifdef FEAT_NETBEANS_INTG - if (netbeans_active() && isNetbeansBuffer(buf)) - { - if (whole) - { - /* - * b_changed can be 0 after an undo, but we still need to write - * the buffer to NetBeans. - */ - if (buf->b_changed || isNetbeansModified(buf)) - { - --no_wait_return; /* may wait for return now */ - msg_scroll = msg_save; - netbeans_save_buffer(buf); /* no error checking... */ - return retval; - } - else - { - errnum = (char_u *)"E656: "; - errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers"); - buffer = NULL; - goto fail; - } - } - else - { - errnum = (char_u *)"E657: "; - errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers"); - buffer = NULL; - goto fail; - } - } -#endif - - if (shortmess(SHM_OVER) && !exiting) - msg_scroll = FALSE; /* overwrite previous file message */ - else - msg_scroll = TRUE; /* don't overwrite previous file message */ - if (!filtering) - filemess(buf, -#ifndef UNIX - sfname, -#else - fname, -#endif - (char_u *)"", 0); /* show that we are busy */ - msg_scroll = FALSE; /* always overwrite the file message now */ - - buffer = alloc(BUFSIZE); - if (buffer == NULL) /* can't allocate big buffer, use small - * one (to be able to write when out of - * memory) */ - { - buffer = smallbuf; - bufsize = SMBUFSIZE; - } - else - bufsize = BUFSIZE; - - /* - * Get information about original file (if there is one). - */ -#if defined(UNIX) - st_old.st_dev = 0; - st_old.st_ino = 0; - perm = -1; - if (mch_stat((char *)fname, &st_old) < 0) - newfile = TRUE; - else - { - perm = st_old.st_mode; - if (!S_ISREG(st_old.st_mode)) /* not a file */ - { - if (S_ISDIR(st_old.st_mode)) - { - errnum = (char_u *)"E502: "; - errmsg = (char_u *)_("is a directory"); - goto fail; - } - if (mch_nodetype(fname) != NODE_WRITABLE) - { - errnum = (char_u *)"E503: "; - errmsg = (char_u *)_("is not a file or writable device"); - goto fail; - } - /* It's a device of some kind (or a fifo) which we can write to - * but for which we can't make a backup. */ - device = TRUE; - newfile = TRUE; - perm = -1; - } - } -#else /* !UNIX */ - /* - * Check for a writable device name. - */ - c = mch_nodetype(fname); - if (c == NODE_OTHER) - { - errnum = (char_u *)"E503: "; - errmsg = (char_u *)_("is not a file or writable device"); - goto fail; - } - if (c == NODE_WRITABLE) - { -# if defined(MSWIN) - /* MS-Windows allows opening a device, but we will probably get stuck - * trying to write to it. */ - if (!p_odev) - { - errnum = (char_u *)"E796: "; - errmsg = (char_u *)_("writing to device disabled with 'opendevice' option"); - goto fail; - } -# endif - device = TRUE; - newfile = TRUE; - perm = -1; - } - else - { - perm = mch_getperm(fname); - if (perm < 0) - newfile = TRUE; - else if (mch_isdir(fname)) - { - errnum = (char_u *)"E502: "; - errmsg = (char_u *)_("is a directory"); - goto fail; - } - if (overwriting) - (void)mch_stat((char *)fname, &st_old); - } -#endif /* !UNIX */ - - if (!device && !newfile) - { - /* - * Check if the file is really writable (when renaming the file to - * make a backup we won't discover it later). - */ - file_readonly = check_file_readonly(fname, (int)perm); - - if (!forceit && file_readonly) - { - if (vim_strchr(p_cpo, CPO_FWRITE) != NULL) - { - errnum = (char_u *)"E504: "; - errmsg = (char_u *)_(err_readonly); - } - else - { - errnum = (char_u *)"E505: "; - errmsg = (char_u *)_("is read-only (add ! to override)"); - } - goto fail; - } - - /* - * Check if the timestamp hasn't changed since reading the file. - */ - if (overwriting) - { - retval = check_mtime(buf, &st_old); - if (retval == FAIL) - goto fail; - } - } - -#ifdef HAVE_ACL - /* - * For systems that support ACL: get the ACL from the original file. - */ - if (!newfile) - acl = mch_get_acl(fname); -#endif - - /* - * If 'backupskip' is not empty, don't make a backup for some files. - */ - dobackup = (p_wb || p_bk || *p_pm != NUL); -#ifdef FEAT_WILDIGN - if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) - dobackup = FALSE; -#endif - - /* - * Save the value of got_int and reset it. We don't want a previous - * interruption cancel writing, only hitting CTRL-C while writing should - * abort it. - */ - prev_got_int = got_int; - got_int = FALSE; - - /* Mark the buffer as 'being saved' to prevent changed buffer warnings */ - buf->b_saving = TRUE; - - /* - * If we are not appending or filtering, the file exists, and the - * 'writebackup', 'backup' or 'patchmode' option is set, need a backup. - * When 'patchmode' is set also make a backup when appending. - * - * Do not make any backup, if 'writebackup' and 'backup' are both switched - * off. This helps when editing large files on almost-full disks. - */ - if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup) - { -#if defined(UNIX) || defined(MSWIN) - stat_T st; -#endif - - if ((bkc & BKC_YES) || append) /* "yes" */ - backup_copy = TRUE; -#if defined(UNIX) || defined(MSWIN) - else if ((bkc & BKC_AUTO)) /* "auto" */ - { - int i; - -# ifdef UNIX - /* - * Don't rename the file when: - * - it's a hard link - * - it's a symbolic link - * - we don't have write permission in the directory - * - we can't set the owner/group of the new file - */ - if (st_old.st_nlink > 1 - || mch_lstat((char *)fname, &st) < 0 - || st.st_dev != st_old.st_dev - || st.st_ino != st_old.st_ino -# ifndef HAVE_FCHOWN - || st.st_uid != st_old.st_uid - || st.st_gid != st_old.st_gid -# endif - ) - backup_copy = TRUE; - else -# else -# ifdef MSWIN - /* On NTFS file systems hard links are possible. */ - if (mch_is_linked(fname)) - backup_copy = TRUE; - else -# endif -# endif - { - /* - * Check if we can create a file and set the owner/group to - * the ones from the original file. - * First find a file name that doesn't exist yet (use some - * arbitrary numbers). - */ - STRCPY(IObuff, fname); - for (i = 4913; ; i += 123) - { - sprintf((char *)gettail(IObuff), "%d", i); - if (mch_lstat((char *)IObuff, &st) < 0) - break; - } - fd = mch_open((char *)IObuff, - O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); - if (fd < 0) /* can't write in directory */ - backup_copy = TRUE; - else - { -# ifdef UNIX -# ifdef HAVE_FCHOWN - vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid); -# endif - if (mch_stat((char *)IObuff, &st) < 0 - || st.st_uid != st_old.st_uid - || st.st_gid != st_old.st_gid - || (long)st.st_mode != perm) - backup_copy = TRUE; -# endif - /* Close the file before removing it, on MS-Windows we - * can't delete an open file. */ - close(fd); - mch_remove(IObuff); -# ifdef MSWIN - /* MS-Windows may trigger a virus scanner to open the - * file, we can't delete it then. Keep trying for half a - * second. */ - { - int try; - - for (try = 0; try < 10; ++try) - { - if (mch_lstat((char *)IObuff, &st) < 0) - break; - ui_delay(50L, TRUE); /* wait 50 msec */ - mch_remove(IObuff); - } - } -# endif - } - } - } - - /* - * Break symlinks and/or hardlinks if we've been asked to. - */ - if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK)) - { -# ifdef UNIX - int lstat_res; - - lstat_res = mch_lstat((char *)fname, &st); - - /* Symlinks. */ - if ((bkc & BKC_BREAKSYMLINK) - && lstat_res == 0 - && st.st_ino != st_old.st_ino) - backup_copy = FALSE; - - /* Hardlinks. */ - if ((bkc & BKC_BREAKHARDLINK) - && st_old.st_nlink > 1 - && (lstat_res != 0 || st.st_ino == st_old.st_ino)) - backup_copy = FALSE; -# else -# if defined(MSWIN) - /* Symlinks. */ - if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname)) - backup_copy = FALSE; - - /* Hardlinks. */ - if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname)) - backup_copy = FALSE; -# endif -# endif - } - -#endif - - /* make sure we have a valid backup extension to use */ - if (*p_bex == NUL) - backup_ext = (char_u *)".bak"; - else - backup_ext = p_bex; - - if (backup_copy - && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0) - { - int bfd; - char_u *copybuf, *wp; - int some_error = FALSE; - stat_T st_new; - char_u *dirp; - char_u *rootname; -#if defined(UNIX) || defined(MSWIN) - char_u *p; -#endif -#if defined(UNIX) - int did_set_shortname; - mode_t umask_save; -#endif - - copybuf = alloc(BUFSIZE + 1); - if (copybuf == NULL) - { - some_error = TRUE; /* out of memory */ - goto nobackup; - } - - /* - * Try to make the backup in each directory in the 'bdir' option. - * - * Unix semantics has it, that we may have a writable file, - * that cannot be recreated with a simple open(..., O_CREAT, ) e.g: - * - the directory is not writable, - * - the file may be a symbolic link, - * - the file may belong to another user/group, etc. - * - * For these reasons, the existing writable file must be truncated - * and reused. Creation of a backup COPY will be attempted. - */ - dirp = p_bdir; - while (*dirp) - { -#ifdef UNIX - st_new.st_ino = 0; - st_new.st_dev = 0; - st_new.st_gid = 0; -#endif - - /* - * Isolate one directory name, using an entry in 'bdir'. - */ - (void)copy_option_part(&dirp, copybuf, BUFSIZE, ","); - -#if defined(UNIX) || defined(MSWIN) - p = copybuf + STRLEN(copybuf); - if (after_pathsep(copybuf, p) && p[-1] == p[-2]) - // Ends with '//', use full path - if ((p = make_percent_swname(copybuf, fname)) != NULL) - { - backup = modname(p, backup_ext, FALSE); - vim_free(p); - } -#endif - rootname = get_file_in_dir(fname, copybuf); - if (rootname == NULL) - { - some_error = TRUE; /* out of memory */ - goto nobackup; - } - -#if defined(UNIX) - did_set_shortname = FALSE; -#endif - - /* - * May try twice if 'shortname' not set. - */ - for (;;) - { - /* - * Make the backup file name. - */ - if (backup == NULL) - backup = buf_modname((buf->b_p_sn || buf->b_shortname), - rootname, backup_ext, FALSE); - if (backup == NULL) - { - vim_free(rootname); - some_error = TRUE; /* out of memory */ - goto nobackup; - } - - /* - * Check if backup file already exists. - */ - if (mch_stat((char *)backup, &st_new) >= 0) - { -#ifdef UNIX - /* - * Check if backup file is same as original file. - * May happen when modname() gave the same file back. - * E.g. silly link, or file name-length reached. - * If we don't check here, we either ruin the file - * when copying or erase it after writing. jw. - */ - if (st_new.st_dev == st_old.st_dev - && st_new.st_ino == st_old.st_ino) - { - VIM_CLEAR(backup); /* no backup file to delete */ - /* - * may try again with 'shortname' set - */ - if (!(buf->b_shortname || buf->b_p_sn)) - { - buf->b_shortname = TRUE; - did_set_shortname = TRUE; - continue; - } - /* setting shortname didn't help */ - if (did_set_shortname) - buf->b_shortname = FALSE; - break; - } -#endif - - /* - * If we are not going to keep the backup file, don't - * delete an existing one, try to use another name. - * Change one character, just before the extension. - */ - if (!p_bk) - { - wp = backup + STRLEN(backup) - 1 - - STRLEN(backup_ext); - if (wp < backup) /* empty file name ??? */ - wp = backup; - *wp = 'z'; - while (*wp > 'a' - && mch_stat((char *)backup, &st_new) >= 0) - --*wp; - /* They all exist??? Must be something wrong. */ - if (*wp == 'a') - VIM_CLEAR(backup); - } - } - break; - } - vim_free(rootname); - - /* - * Try to create the backup file - */ - if (backup != NULL) - { - /* remove old backup, if present */ - mch_remove(backup); - /* Open with O_EXCL to avoid the file being created while - * we were sleeping (symlink hacker attack?). Reset umask - * if possible to avoid mch_setperm() below. */ -#ifdef UNIX - umask_save = umask(0); -#endif - bfd = mch_open((char *)backup, - O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW, - perm & 0777); -#ifdef UNIX - (void)umask(umask_save); -#endif - if (bfd < 0) - VIM_CLEAR(backup); - else - { - /* Set file protection same as original file, but - * strip s-bit. Only needed if umask() wasn't used - * above. */ -#ifndef UNIX - (void)mch_setperm(backup, perm & 0777); -#else - /* - * Try to set the group of the backup same as the - * original file. If this fails, set the protection - * bits for the group same as the protection bits for - * others. - */ - if (st_new.st_gid != st_old.st_gid -# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */ - && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0 -# endif - ) - mch_setperm(backup, - (perm & 0707) | ((perm & 07) << 3)); -# if defined(HAVE_SELINUX) || defined(HAVE_SMACK) - mch_copy_sec(fname, backup); -# endif -#endif - - /* - * copy the file. - */ - write_info.bw_fd = bfd; - write_info.bw_buf = copybuf; -#ifdef HAS_BW_FLAGS - write_info.bw_flags = FIO_NOCONVERT; -#endif - while ((write_info.bw_len = read_eintr(fd, copybuf, - BUFSIZE)) > 0) - { - if (buf_write_bytes(&write_info) == FAIL) - { - errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)"); - break; - } - ui_breakcheck(); - if (got_int) - { - errmsg = (char_u *)_(e_interr); - break; - } - } - - if (close(bfd) < 0 && errmsg == NULL) - errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)"); - if (write_info.bw_len < 0) - errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)"); -#ifdef UNIX - set_file_time(backup, st_old.st_atime, st_old.st_mtime); -#endif -#ifdef HAVE_ACL - mch_set_acl(backup, acl); -#endif -#if defined(HAVE_SELINUX) || defined(HAVE_SMACK) - mch_copy_sec(fname, backup); -#endif - break; - } - } - } - nobackup: - close(fd); /* ignore errors for closing read file */ - vim_free(copybuf); - - if (backup == NULL && errmsg == NULL) - errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)"); - /* ignore errors when forceit is TRUE */ - if ((some_error || errmsg != NULL) && !forceit) - { - retval = FAIL; - goto fail; - } - errmsg = NULL; - } - else - { - char_u *dirp; - char_u *p; - char_u *rootname; - - /* - * Make a backup by renaming the original file. - */ - /* - * If 'cpoptions' includes the "W" flag, we don't want to - * overwrite a read-only file. But rename may be possible - * anyway, thus we need an extra check here. - */ - if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL) - { - errnum = (char_u *)"E504: "; - errmsg = (char_u *)_(err_readonly); - goto fail; - } - - /* - * - * Form the backup file name - change path/fo.o.h to - * path/fo.o.h.bak Try all directories in 'backupdir', first one - * tha |