static gboolean
g_local_file_output_stream_close (GOutputStream  *stream,
				  GCancellable   *cancellable,
				  GError        **error)
{
  GLocalFileOutputStream *file;
  GLocalFileStat final_stat;
  int res;

  file = G_LOCAL_FILE_OUTPUT_STREAM (stream);

#ifdef G_OS_WIN32

  /* Must close before renaming on Windows, so just do the close first
   * in all cases for now.
   */
  if (_fstati64 (file->priv->fd, &final_stat) == 0)
    file->priv->etag = _g_local_file_info_create_etag (&final_stat);

  res = close (file->priv->fd);
  if (res == -1)
    {
      int errsv = errno;
      
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error closing file: %s"),
		   g_strerror (errsv));
      return FALSE;
    }

#endif

  if (file->priv->tmp_filename)
    {
      /* We need to move the temp file to its final place,
       * and possibly create the backup file
       */

      if (file->priv->backup_filename)
	{
	  if (g_cancellable_set_error_if_cancelled (cancellable, error))
	    goto err_out;
	  
#ifdef HAVE_LINK
	  /* create original -> backup link, the original is then renamed over */
	  if (g_unlink (file->priv->backup_filename) != 0 &&
	      errno != ENOENT)
	    {
              int errsv = errno;

	      g_set_error (error, G_IO_ERROR,
			   G_IO_ERROR_CANT_CREATE_BACKUP,
			   _("Error removing old backup link: %s"),
			   g_strerror (errsv));
	      goto err_out;
	    }

	  if (link (file->priv->original_filename, file->priv->backup_filename) != 0)
	    {
	      /*  link failed or is not supported, try rename  */
	      if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
		{
                  int errsv = errno;

	    	  g_set_error (error, G_IO_ERROR,
		    	       G_IO_ERROR_CANT_CREATE_BACKUP,
			       _("Error creating backup copy: %s"),
			       g_strerror (errsv));
	          goto err_out;
		}
	    }
#else
	    /* If link not supported, just rename... */
	  if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
	    {
              int errsv = errno;

	      g_set_error (error, G_IO_ERROR,
			   G_IO_ERROR_CANT_CREATE_BACKUP,
			   _("Error creating backup copy: %s"),
			   g_strerror (errsv));
	      goto err_out;
	    }
#endif
	}
      

      if (g_cancellable_set_error_if_cancelled (cancellable, error))
	goto err_out;

      /* tmp -> original */
      if (g_rename (file->priv->tmp_filename, file->priv->original_filename) != 0)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errno),
		       _("Error renaming temporary file: %s"),
		       g_strerror (errsv));
	  goto err_out;
	}
    }
  
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
    goto err_out;
      
#ifndef G_OS_WIN32		/* Already did the fstat() and close() above on Win32 */

  if (fstat (file->priv->fd, &final_stat) == 0)
    file->priv->etag = _g_local_file_info_create_etag (&final_stat);

  while (1)
    {
      res = close (file->priv->fd);
      if (res == -1)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error closing file: %s"),
		       g_strerror (errsv));
	}
      break;
    }
  
  return res != -1;

#else

  return TRUE;

#endif

 err_out:

#ifndef G_OS_WIN32
  /* A simple try to close the fd in case we fail before the actual close */
  close (file->priv->fd);
#endif
  return FALSE;
}
static int
handle_overwrite_open (const char    *filename,
		       const char    *etag,
		       gboolean       create_backup,
		       char         **temp_filename,
		       GCancellable  *cancellable,
		       GError       **error)
{
  int fd = -1;
  GLocalFileStat original_stat;
  char *current_etag;
  gboolean is_symlink;
  int open_flags;
  int res;

  /* We only need read access to the original file if we are creating a backup.
   * We also add O_CREATE to avoid a race if the file was just removed */
  if (create_backup)
    open_flags = O_RDWR | O_CREAT | O_BINARY;
  else
    open_flags = O_WRONLY | O_CREAT | O_BINARY;
  
  /* Some systems have O_NOFOLLOW, which lets us avoid some races
   * when finding out if the file we opened was a symlink */
#ifdef O_NOFOLLOW
  is_symlink = FALSE;
  fd = g_open (filename, open_flags | O_NOFOLLOW, 0666);
  if (fd == -1 && errno == ELOOP)
    {
      /* Could be a symlink, or it could be a regular ELOOP error,
       * but then the next open will fail too. */
      is_symlink = TRUE;
      fd = g_open (filename, open_flags, 0666);
    }
#else
  fd = g_open (filename, open_flags, 0666);
  /* This is racy, but we do it as soon as possible to minimize the race */
  is_symlink = g_file_test (filename, G_FILE_TEST_IS_SYMLINK);
#endif
    
  if (fd == -1)
    {
      int errsv = errno;
      char *display_name = g_filename_display_name (filename);
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error opening file '%s': %s"),
		   display_name, g_strerror (errsv));
      g_free (display_name);
      return -1;
    }
  
#ifdef G_OS_WIN32
  res = _fstati64 (fd, &original_stat);
#else
  res = fstat (fd, &original_stat);
#endif

  if (res != 0) 
    {
      int errsv = errno;
      char *display_name = g_filename_display_name (filename);
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error stating file '%s': %s"),
		   display_name, g_strerror (errsv));
      g_free (display_name);
      goto err_out;
    }
  
  /* not a regular file */
  if (!S_ISREG (original_stat.st_mode))
    {
      if (S_ISDIR (original_stat.st_mode))
	g_set_error_literal (error,
                             G_IO_ERROR,
                             G_IO_ERROR_IS_DIRECTORY,
                             _("Target file is a directory"));
      else
	g_set_error_literal (error,
                             G_IO_ERROR,
                             G_IO_ERROR_NOT_REGULAR_FILE,
                             _("Target file is not a regular file"));
      goto err_out;
    }
  
  if (etag != NULL)
    {
      current_etag = _g_local_file_info_create_etag (&original_stat);
      if (strcmp (etag, current_etag) != 0)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_WRONG_ETAG,
                               _("The file was externally modified"));
	  g_free (current_etag);
	  goto err_out;
	}
      g_free (current_etag);
    }

  /* We use two backup strategies.
   * The first one (which is faster) consist in saving to a
   * tmp file then rename the original file to the backup and the
   * tmp file to the original name. This is fast but doesn't work
   * when the file is a link (hard or symbolic) or when we can't
   * write to the current dir or can't set the permissions on the
   * new file. 
   * The second strategy consist simply in copying the old file
   * to a backup file and rewrite the contents of the file.
   */
  
  if (!(original_stat.st_nlink > 1) && !is_symlink)
    {
      char *dirname, *tmp_filename;
      int tmpfd;
      
      dirname = g_path_get_dirname (filename);
      tmp_filename = g_build_filename (dirname, ".goutputstream-XXXXXX", NULL);
      g_free (dirname);

      tmpfd = g_mkstemp (tmp_filename);
      if (tmpfd == -1)
	{
	  g_free (tmp_filename);
	  goto fallback_strategy;
	}
      
      /* try to keep permissions */

      if (
#ifdef HAVE_FCHOWN
	  fchown (tmpfd, original_stat.st_uid, original_stat.st_gid) == -1 ||
#endif
#ifdef HAVE_FCHMOD
	  fchmod (tmpfd, original_stat.st_mode) == -1 ||
#endif
	  0
	  )
	{
	  struct stat tmp_statbuf;
	  
	  /* Check that we really needed to change something */
	  if (fstat (tmpfd, &tmp_statbuf) != 0 ||
	      original_stat.st_uid != tmp_statbuf.st_uid ||
	      original_stat.st_gid != tmp_statbuf.st_gid ||
	      original_stat.st_mode != tmp_statbuf.st_mode)
	    {
	      close (tmpfd);
	      g_unlink (tmp_filename);
	      g_free (tmp_filename);
	      goto fallback_strategy;
	    }
	}

      close (fd);
      *temp_filename = tmp_filename;
      return tmpfd;
    }

 fallback_strategy:

  if (create_backup)
    {
#if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
      struct stat tmp_statbuf;      
#endif
      char *backup_filename;
      int bfd;
      
      backup_filename = create_backup_filename (filename);

      if (g_unlink (backup_filename) == -1 && errno != ENOENT)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_free (backup_filename);
	  goto err_out;
	}

      bfd = g_open (backup_filename,
		    O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
		    original_stat.st_mode & 0777);

      if (bfd == -1)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_free (backup_filename);
	  goto err_out;
	}

      /* If needed, 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 defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
      if (fstat (bfd, &tmp_statbuf) != 0)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_unlink (backup_filename);
	  g_free (backup_filename);
	  goto err_out;
	}
      
      if ((original_stat.st_gid != tmp_statbuf.st_gid)  &&
	  fchown (bfd, (uid_t) -1, original_stat.st_gid) != 0)
	{
	  if (fchmod (bfd,
		      (original_stat.st_mode & 0707) |
		      ((original_stat.st_mode & 07) << 3)) != 0)
	    {
	      g_set_error_literal (error,
                                   G_IO_ERROR,
                                   G_IO_ERROR_CANT_CREATE_BACKUP,
                                   _("Backup file creation failed"));
	      g_unlink (backup_filename);
	      close (bfd);
	      g_free (backup_filename);
	      goto err_out;
	    }
	}
#endif

      if (!copy_file_data (fd, bfd, NULL))
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_unlink (backup_filename);
	  close (bfd);
	  g_free (backup_filename);
	  
	  goto err_out;
	}
      
      close (bfd);
      g_free (backup_filename);

      /* Seek back to the start of the file after the backup copy */
      if (lseek (fd, 0, SEEK_SET) == -1)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error seeking in file: %s"),
		       g_strerror (errsv));
	  goto err_out;
	}
    }

  /* Truncate the file at the start */
#ifdef G_OS_WIN32
  if (g_win32_ftruncate (fd, 0) == -1)
#else
  if (ftruncate (fd, 0) == -1)
#endif
    {
      int errsv = errno;

      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error truncating file: %s"),
		   g_strerror (errsv));
      goto err_out;
    }
    
  return fd;

 err_out:
  close (fd);
  return -1;
}
gboolean
_g_local_file_output_stream_really_close (GLocalFileOutputStream *file,
					  GCancellable   *cancellable,
					  GError        **error)
{
  GLocalFileStat final_stat;

#ifdef HAVE_FSYNC
  if (file->priv->sync_on_close &&
      fsync (file->priv->fd) != 0)
    {
      int errsv = errno;
      
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error writing to file: %s"),
		   g_strerror (errsv));
      goto err_out;
    }
#endif
 
#ifdef G_OS_WIN32

  /* Must close before renaming on Windows, so just do the close first
   * in all cases for now.
   */
  if (_fstati64 (file->priv->fd, &final_stat) == 0)
    file->priv->etag = _g_local_file_info_create_etag (&final_stat);

  if (!g_close (file->priv->fd, NULL))
    {
      int errsv = errno;
      
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error closing file: %s"),
		   g_strerror (errsv));
      return FALSE;
    }

#endif

  if (file->priv->tmp_filename)
    {
      /* We need to move the temp file to its final place,
       * and possibly create the backup file
       */

      if (file->priv->backup_filename)
	{
	  if (g_cancellable_set_error_if_cancelled (cancellable, error))
	    goto err_out;
	  
#ifdef G_OS_UNIX
	  /* create original -> backup link, the original is then renamed over */
	  if (g_unlink (file->priv->backup_filename) != 0 &&
	      errno != ENOENT)
	    {
              int errsv = errno;

	      g_set_error (error, G_IO_ERROR,
			   G_IO_ERROR_CANT_CREATE_BACKUP,
			   _("Error removing old backup link: %s"),
			   g_strerror (errsv));
	      goto err_out;
	    }

	  if (link (file->priv->original_filename, file->priv->backup_filename) != 0)
	    {
	      /*  link failed or is not supported, try rename  */
	      if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
		{
                  int errsv = errno;

	    	  g_set_error (error, G_IO_ERROR,
		    	       G_IO_ERROR_CANT_CREATE_BACKUP,
			       _("Error creating backup copy: %s"),
			       g_strerror (errsv));
	          goto err_out;
		}
	    }
#else
	    /* If link not supported, just rename... */
	  if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
	    {
              int errsv = errno;

	      g_set_error (error, G_IO_ERROR,
			   G_IO_ERROR_CANT_CREATE_BACKUP,
			   _("Error creating backup copy: %s"),
			   g_strerror (errsv));
	      goto err_out;
	    }
#endif
	}
      

      if (g_cancellable_set_error_if_cancelled (cancellable, error))
	goto err_out;

      /* tmp -> original */
      if (g_rename (file->priv->tmp_filename, file->priv->original_filename) != 0)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error renaming temporary file: %s"),
		       g_strerror (errsv));
	  goto err_out;
	}

      g_clear_pointer (&file->priv->tmp_filename, g_free);
    }
  
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
    goto err_out;
      
#ifndef G_OS_WIN32		/* Already did the fstat() and close() above on Win32 */

  if (fstat (file->priv->fd, &final_stat) == 0)
    file->priv->etag = _g_local_file_info_create_etag (&final_stat);

  if (!g_close (file->priv->fd, NULL))
    {
      int errsv = errno;
      
      g_set_error (error, G_IO_ERROR,
                   g_io_error_from_errno (errsv),
                   _("Error closing file: %s"),
                   g_strerror (errsv));
      goto err_out;
    }

#endif
  
  return TRUE;
 err_out:

#ifndef G_OS_WIN32
  /* A simple try to close the fd in case we fail before the actual close */
  g_close (file->priv->fd, NULL);
#endif
  if (file->priv->tmp_filename)
    g_unlink (file->priv->tmp_filename);

  return FALSE;
}