Require POSIX.1 (1990) compliance on unix
[platform/upstream/glib.git] / gio / glocalfileoutputstream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #include <errno.h>
32 #include <string.h>
33
34 #include <glib.h>
35 #include <glib/gstdio.h>
36 #include "glibintl.h"
37 #include "gioerror.h"
38 #include "gcancellable.h"
39 #include "glocalfileoutputstream.h"
40 #include "gfileinfo.h"
41 #include "glocalfileinfo.h"
42
43 #ifdef G_OS_UNIX
44 #include "gfiledescriptorbased.h"
45 #endif
46
47 #ifdef G_OS_WIN32
48 #include <io.h>
49 #ifndef S_ISDIR
50 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
51 #endif
52 #ifndef S_ISREG
53 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
54 #endif
55 #endif
56
57 #ifndef O_BINARY
58 #define O_BINARY 0
59 #endif
60
61 struct _GLocalFileOutputStreamPrivate {
62   char *tmp_filename;
63   char *original_filename;
64   char *backup_filename;
65   char *etag;
66   guint sync_on_close : 1;
67   guint do_close : 1;
68   int fd;
69 };
70
71 #ifdef G_OS_UNIX
72 static void       g_file_descriptor_based_iface_init   (GFileDescriptorBasedIface *iface);
73 #endif
74
75 #define g_local_file_output_stream_get_type _g_local_file_output_stream_get_type
76 #ifdef G_OS_UNIX
77 G_DEFINE_TYPE_WITH_CODE (GLocalFileOutputStream, g_local_file_output_stream, G_TYPE_FILE_OUTPUT_STREAM,
78                          G_ADD_PRIVATE (GLocalFileOutputStream)
79                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
80                                                 g_file_descriptor_based_iface_init))
81 #else
82 G_DEFINE_TYPE_WITH_CODE (GLocalFileOutputStream, g_local_file_output_stream, G_TYPE_FILE_OUTPUT_STREAM,
83                          G_ADD_PRIVATE (GLocalFileOutputStream))
84 #endif
85
86
87 /* Some of the file replacement code was based on the code from gedit,
88  * relicenced to LGPL with permissions from the authors.
89  */
90
91 #define BACKUP_EXTENSION "~"
92
93 static gssize     g_local_file_output_stream_write        (GOutputStream      *stream,
94                                                            const void         *buffer,
95                                                            gsize               count,
96                                                            GCancellable       *cancellable,
97                                                            GError            **error);
98 static gboolean   g_local_file_output_stream_close        (GOutputStream      *stream,
99                                                            GCancellable       *cancellable,
100                                                            GError            **error);
101 static GFileInfo *g_local_file_output_stream_query_info   (GFileOutputStream  *stream,
102                                                            const char         *attributes,
103                                                            GCancellable       *cancellable,
104                                                            GError            **error);
105 static char *     g_local_file_output_stream_get_etag     (GFileOutputStream  *stream);
106 static goffset    g_local_file_output_stream_tell         (GFileOutputStream  *stream);
107 static gboolean   g_local_file_output_stream_can_seek     (GFileOutputStream  *stream);
108 static gboolean   g_local_file_output_stream_seek         (GFileOutputStream  *stream,
109                                                            goffset             offset,
110                                                            GSeekType           type,
111                                                            GCancellable       *cancellable,
112                                                            GError            **error);
113 static gboolean   g_local_file_output_stream_can_truncate (GFileOutputStream  *stream);
114 static gboolean   g_local_file_output_stream_truncate     (GFileOutputStream  *stream,
115                                                            goffset             size,
116                                                            GCancellable       *cancellable,
117                                                            GError            **error);
118 #ifdef G_OS_UNIX
119 static int        g_local_file_output_stream_get_fd       (GFileDescriptorBased *stream);
120 #endif
121
122 static void
123 g_local_file_output_stream_finalize (GObject *object)
124 {
125   GLocalFileOutputStream *file;
126   
127   file = G_LOCAL_FILE_OUTPUT_STREAM (object);
128   
129   g_free (file->priv->tmp_filename);
130   g_free (file->priv->original_filename);
131   g_free (file->priv->backup_filename);
132   g_free (file->priv->etag);
133
134   G_OBJECT_CLASS (g_local_file_output_stream_parent_class)->finalize (object);
135 }
136
137 static void
138 g_local_file_output_stream_class_init (GLocalFileOutputStreamClass *klass)
139 {
140   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
141   GOutputStreamClass *stream_class = G_OUTPUT_STREAM_CLASS (klass);
142   GFileOutputStreamClass *file_stream_class = G_FILE_OUTPUT_STREAM_CLASS (klass);
143
144   gobject_class->finalize = g_local_file_output_stream_finalize;
145
146   stream_class->write_fn = g_local_file_output_stream_write;
147   stream_class->close_fn = g_local_file_output_stream_close;
148   file_stream_class->query_info = g_local_file_output_stream_query_info;
149   file_stream_class->get_etag = g_local_file_output_stream_get_etag;
150   file_stream_class->tell = g_local_file_output_stream_tell;
151   file_stream_class->can_seek = g_local_file_output_stream_can_seek;
152   file_stream_class->seek = g_local_file_output_stream_seek;
153   file_stream_class->can_truncate = g_local_file_output_stream_can_truncate;
154   file_stream_class->truncate_fn = g_local_file_output_stream_truncate;
155 }
156
157 #ifdef G_OS_UNIX
158 static void
159 g_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
160 {
161   iface->get_fd = g_local_file_output_stream_get_fd;
162 }
163 #endif
164
165 static void
166 g_local_file_output_stream_init (GLocalFileOutputStream *stream)
167 {
168   stream->priv = g_local_file_output_stream_get_instance_private (stream);
169   stream->priv->do_close = TRUE;
170 }
171
172 static gssize
173 g_local_file_output_stream_write (GOutputStream  *stream,
174                                   const void     *buffer,
175                                   gsize           count,
176                                   GCancellable   *cancellable,
177                                   GError        **error)
178 {
179   GLocalFileOutputStream *file;
180   gssize res;
181
182   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
183
184   while (1)
185     {
186       if (g_cancellable_set_error_if_cancelled (cancellable, error))
187         return -1;
188       res = write (file->priv->fd, buffer, count);
189       if (res == -1)
190         {
191           int errsv = errno;
192
193           if (errsv == EINTR)
194             continue;
195           
196           g_set_error (error, G_IO_ERROR,
197                        g_io_error_from_errno (errsv),
198                        _("Error writing to file: %s"),
199                        g_strerror (errsv));
200         }
201       
202       break;
203     }
204   
205   return res;
206 }
207
208 void
209 _g_local_file_output_stream_set_do_close (GLocalFileOutputStream *out,
210                                           gboolean do_close)
211 {
212   out->priv->do_close = do_close;
213 }
214
215 gboolean
216 _g_local_file_output_stream_really_close (GLocalFileOutputStream *file,
217                                           GCancellable   *cancellable,
218                                           GError        **error)
219 {
220   GLocalFileStat final_stat;
221
222 #ifdef HAVE_FSYNC
223   if (file->priv->sync_on_close &&
224       fsync (file->priv->fd) != 0)
225     {
226       int errsv = errno;
227       
228       g_set_error (error, G_IO_ERROR,
229                    g_io_error_from_errno (errsv),
230                    _("Error writing to file: %s"),
231                    g_strerror (errsv));
232       goto err_out;
233     }
234 #endif
235  
236 #ifdef G_OS_WIN32
237
238   /* Must close before renaming on Windows, so just do the close first
239    * in all cases for now.
240    */
241   if (_fstati64 (file->priv->fd, &final_stat) == 0)
242     file->priv->etag = _g_local_file_info_create_etag (&final_stat);
243
244   if (!g_close (file->priv->fd, NULL))
245     {
246       int errsv = errno;
247       
248       g_set_error (error, G_IO_ERROR,
249                    g_io_error_from_errno (errsv),
250                    _("Error closing file: %s"),
251                    g_strerror (errsv));
252       return FALSE;
253     }
254
255 #endif
256
257   if (file->priv->tmp_filename)
258     {
259       /* We need to move the temp file to its final place,
260        * and possibly create the backup file
261        */
262
263       if (file->priv->backup_filename)
264         {
265           if (g_cancellable_set_error_if_cancelled (cancellable, error))
266             goto err_out;
267           
268 #ifdef G_OS_UNIX
269           /* create original -> backup link, the original is then renamed over */
270           if (g_unlink (file->priv->backup_filename) != 0 &&
271               errno != ENOENT)
272             {
273               int errsv = errno;
274
275               g_set_error (error, G_IO_ERROR,
276                            G_IO_ERROR_CANT_CREATE_BACKUP,
277                            _("Error removing old backup link: %s"),
278                            g_strerror (errsv));
279               goto err_out;
280             }
281
282           if (link (file->priv->original_filename, file->priv->backup_filename) != 0)
283             {
284               /*  link failed or is not supported, try rename  */
285               if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
286                 {
287                   int errsv = errno;
288
289                   g_set_error (error, G_IO_ERROR,
290                                G_IO_ERROR_CANT_CREATE_BACKUP,
291                                _("Error creating backup copy: %s"),
292                                g_strerror (errsv));
293                   goto err_out;
294                 }
295             }
296 #else
297             /* If link not supported, just rename... */
298           if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
299             {
300               int errsv = errno;
301
302               g_set_error (error, G_IO_ERROR,
303                            G_IO_ERROR_CANT_CREATE_BACKUP,
304                            _("Error creating backup copy: %s"),
305                            g_strerror (errsv));
306               goto err_out;
307             }
308 #endif
309         }
310       
311
312       if (g_cancellable_set_error_if_cancelled (cancellable, error))
313         goto err_out;
314
315       /* tmp -> original */
316       if (g_rename (file->priv->tmp_filename, file->priv->original_filename) != 0)
317         {
318           int errsv = errno;
319
320           g_set_error (error, G_IO_ERROR,
321                        g_io_error_from_errno (errsv),
322                        _("Error renaming temporary file: %s"),
323                        g_strerror (errsv));
324           goto err_out;
325         }
326
327       g_clear_pointer (&file->priv->tmp_filename, g_free);
328     }
329   
330   if (g_cancellable_set_error_if_cancelled (cancellable, error))
331     goto err_out;
332       
333 #ifndef G_OS_WIN32              /* Already did the fstat() and close() above on Win32 */
334
335   if (fstat (file->priv->fd, &final_stat) == 0)
336     file->priv->etag = _g_local_file_info_create_etag (&final_stat);
337
338   if (!g_close (file->priv->fd, NULL))
339     {
340       int errsv = errno;
341       
342       g_set_error (error, G_IO_ERROR,
343                    g_io_error_from_errno (errsv),
344                    _("Error closing file: %s"),
345                    g_strerror (errsv));
346       goto err_out;
347     }
348
349 #endif
350   
351   return TRUE;
352  err_out:
353
354 #ifndef G_OS_WIN32
355   /* A simple try to close the fd in case we fail before the actual close */
356   (void) g_close (file->priv->fd, NULL);
357 #endif
358   if (file->priv->tmp_filename)
359     g_unlink (file->priv->tmp_filename);
360
361   return FALSE;
362 }
363
364
365 static gboolean
366 g_local_file_output_stream_close (GOutputStream  *stream,
367                                   GCancellable   *cancellable,
368                                   GError        **error)
369 {
370   GLocalFileOutputStream *file;
371
372   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
373
374   if (file->priv->do_close)
375     return _g_local_file_output_stream_really_close (file,
376                                                      cancellable,
377                                                      error);
378   return TRUE;
379 }
380
381 static char *
382 g_local_file_output_stream_get_etag (GFileOutputStream *stream)
383 {
384   GLocalFileOutputStream *file;
385
386   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
387   
388   return g_strdup (file->priv->etag);
389 }
390
391 static goffset
392 g_local_file_output_stream_tell (GFileOutputStream *stream)
393 {
394   GLocalFileOutputStream *file;
395   off_t pos;
396
397   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
398   
399   pos = lseek (file->priv->fd, 0, SEEK_CUR);
400
401   if (pos == (off_t)-1)
402     return 0;
403   
404   return pos;
405 }
406
407 static gboolean
408 g_local_file_output_stream_can_seek (GFileOutputStream *stream)
409 {
410   GLocalFileOutputStream *file;
411   off_t pos;
412
413   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
414   
415   pos = lseek (file->priv->fd, 0, SEEK_CUR);
416
417   if (pos == (off_t)-1 && errno == ESPIPE)
418     return FALSE;
419   
420   return TRUE;
421 }
422
423 static int
424 seek_type_to_lseek (GSeekType type)
425 {
426   switch (type)
427     {
428     default:
429     case G_SEEK_CUR:
430       return SEEK_CUR;
431       
432     case G_SEEK_SET:
433       return SEEK_SET;
434       
435     case G_SEEK_END:
436       return SEEK_END;
437     }
438 }
439
440 static gboolean
441 g_local_file_output_stream_seek (GFileOutputStream  *stream,
442                                  goffset             offset,
443                                  GSeekType           type,
444                                  GCancellable       *cancellable,
445                                  GError            **error)
446 {
447   GLocalFileOutputStream *file;
448   off_t pos;
449
450   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
451
452   pos = lseek (file->priv->fd, offset, seek_type_to_lseek (type));
453
454   if (pos == (off_t)-1)
455     {
456       int errsv = errno;
457
458       g_set_error (error, G_IO_ERROR,
459                    g_io_error_from_errno (errsv),
460                    _("Error seeking in file: %s"),
461                    g_strerror (errsv));
462       return FALSE;
463     }
464   
465   return TRUE;
466 }
467
468 static gboolean
469 g_local_file_output_stream_can_truncate (GFileOutputStream *stream)
470 {
471   /* We can't truncate pipes and stuff where we can't seek */
472   return g_local_file_output_stream_can_seek (stream);
473 }
474
475 static gboolean
476 g_local_file_output_stream_truncate (GFileOutputStream  *stream,
477                                      goffset             size,
478                                      GCancellable       *cancellable,
479                                      GError            **error)
480 {
481   GLocalFileOutputStream *file;
482   int res;
483
484   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
485
486  restart:
487 #ifdef G_OS_WIN32
488   res = g_win32_ftruncate (file->priv->fd, size);
489 #else
490   res = ftruncate (file->priv->fd, size);
491 #endif
492   
493   if (res == -1)
494     {
495       int errsv = errno;
496
497       if (errsv == EINTR)
498         {
499           if (g_cancellable_set_error_if_cancelled (cancellable, error))
500             return FALSE;
501           goto restart;
502         }
503
504       g_set_error (error, G_IO_ERROR,
505                    g_io_error_from_errno (errsv),
506                    _("Error truncating file: %s"),
507                    g_strerror (errsv));
508       return FALSE;
509     }
510   
511   return TRUE;
512 }
513
514
515 static GFileInfo *
516 g_local_file_output_stream_query_info (GFileOutputStream  *stream,
517                                        const char         *attributes,
518                                        GCancellable       *cancellable,
519                                        GError            **error)
520 {
521   GLocalFileOutputStream *file;
522
523   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
524
525   if (g_cancellable_set_error_if_cancelled (cancellable, error))
526     return NULL;
527   
528   return _g_local_file_info_get_from_fd (file->priv->fd,
529                                          attributes,
530                                          error);
531 }
532
533 GFileOutputStream *
534 _g_local_file_output_stream_new (int fd)
535 {
536   GLocalFileOutputStream *stream;
537
538   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
539   stream->priv->fd = fd;
540   return G_FILE_OUTPUT_STREAM (stream);
541 }
542
543 static void
544 set_error_from_open_errno (const char *filename,
545                            GError    **error)
546 {
547   int errsv = errno;
548   
549   if (errsv == EINVAL)
550     /* This must be an invalid filename, on e.g. FAT */
551     g_set_error_literal (error, G_IO_ERROR,
552                          G_IO_ERROR_INVALID_FILENAME,
553                          _("Invalid filename"));
554   else
555     {
556       char *display_name = g_filename_display_name (filename);
557       g_set_error (error, G_IO_ERROR,
558                    g_io_error_from_errno (errsv),
559                    _("Error opening file '%s': %s"),
560                        display_name, g_strerror (errsv));
561       g_free (display_name);
562     }
563 }
564
565 static GFileOutputStream *
566 output_stream_open (const char    *filename,
567                     gint           open_flags,
568                     guint          mode,
569                     GCancellable  *cancellable,
570                     GError       **error)
571 {
572   GLocalFileOutputStream *stream;
573   gint fd;
574
575   fd = g_open (filename, open_flags, mode);
576   if (fd == -1)
577     {
578       set_error_from_open_errno (filename, error);
579       return NULL;
580     }
581   
582   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
583   stream->priv->fd = fd;
584   return G_FILE_OUTPUT_STREAM (stream);
585 }
586
587 GFileOutputStream *
588 _g_local_file_output_stream_open  (const char        *filename,
589                                    gboolean          readable,
590                                    GCancellable      *cancellable,
591                                    GError           **error)
592 {
593   int open_flags;
594
595   if (g_cancellable_set_error_if_cancelled (cancellable, error))
596     return NULL;
597
598   open_flags = O_BINARY;
599   if (readable)
600     open_flags |= O_RDWR;
601   else
602     open_flags |= O_WRONLY;
603
604   return output_stream_open (filename, open_flags, 0666, cancellable, error);
605 }
606
607 static gint
608 mode_from_flags_or_info (GFileCreateFlags   flags,
609                          GFileInfo         *reference_info)
610 {
611   if (flags & G_FILE_CREATE_PRIVATE)
612     return 0600;
613   else if (reference_info && g_file_info_has_attribute (reference_info, "unix::mode"))
614     return g_file_info_get_attribute_uint32 (reference_info, "unix::mode") & (~S_IFMT);
615   else
616     return 0666;
617 }
618
619 GFileOutputStream *
620 _g_local_file_output_stream_create  (const char        *filename,
621                                      gboolean          readable,
622                                      GFileCreateFlags   flags,
623                                      GFileInfo         *reference_info,
624                                      GCancellable      *cancellable,
625                                      GError           **error)
626 {
627   int mode;
628   int open_flags;
629
630   if (g_cancellable_set_error_if_cancelled (cancellable, error))
631     return NULL;
632
633   mode = mode_from_flags_or_info (flags, reference_info);
634
635   open_flags = O_CREAT | O_EXCL | O_BINARY;
636   if (readable)
637     open_flags |= O_RDWR;
638   else
639     open_flags |= O_WRONLY;
640
641   return output_stream_open (filename, open_flags, mode, cancellable, error);
642 }
643
644 GFileOutputStream *
645 _g_local_file_output_stream_append  (const char        *filename,
646                                      GFileCreateFlags   flags,
647                                      GCancellable      *cancellable,
648                                      GError           **error)
649 {
650   int mode;
651
652   if (g_cancellable_set_error_if_cancelled (cancellable, error))
653     return NULL;
654
655   if (flags & G_FILE_CREATE_PRIVATE)
656     mode = 0600;
657   else
658     mode = 0666;
659
660   return output_stream_open (filename, O_CREAT | O_APPEND | O_WRONLY | O_BINARY, mode,
661                              cancellable, error);
662 }
663
664 static char *
665 create_backup_filename (const char *filename)
666 {
667   return g_strconcat (filename, BACKUP_EXTENSION, NULL);
668 }
669
670 #define BUFSIZE 8192 /* size of normal write buffer */
671
672 static gboolean
673 copy_file_data (gint     sfd,
674                 gint     dfd,
675                 GError **error)
676 {
677   gboolean ret = TRUE;
678   gpointer buffer;
679   const gchar *write_buffer;
680   gssize bytes_read;
681   gssize bytes_to_write;
682   gssize bytes_written;
683   
684   buffer = g_malloc (BUFSIZE);
685   
686   do
687     {
688       bytes_read = read (sfd, buffer, BUFSIZE);
689       if (bytes_read == -1)
690         {
691           int errsv = errno;
692
693           if (errsv == EINTR)
694             continue;
695           
696           g_set_error (error, G_IO_ERROR,
697                        g_io_error_from_errno (errsv),
698                        _("Error reading from file: %s"),
699                        g_strerror (errsv));
700           ret = FALSE;
701           break;
702         }
703       
704       bytes_to_write = bytes_read;
705       write_buffer = buffer;
706       
707       do
708         {
709           bytes_written = write (dfd, write_buffer, bytes_to_write);
710           if (bytes_written == -1)
711             {
712               int errsv = errno;
713
714               if (errsv == EINTR)
715                 continue;
716               
717               g_set_error (error, G_IO_ERROR,
718                            g_io_error_from_errno (errsv),
719                            _("Error writing to file: %s"),
720                            g_strerror (errsv));
721               ret = FALSE;
722               break;
723             }
724           
725           bytes_to_write -= bytes_written;
726           write_buffer += bytes_written;
727         }
728       while (bytes_to_write > 0);
729       
730     } while ((bytes_read != 0) && (ret == TRUE));
731
732   g_free (buffer);
733   
734   return ret;
735 }
736
737 static int
738 handle_overwrite_open (const char    *filename,
739                        gboolean       readable,
740                        const char    *etag,
741                        gboolean       create_backup,
742                        char         **temp_filename,
743                        GFileCreateFlags flags,
744                        GFileInfo       *reference_info,
745                        GCancellable  *cancellable,
746                        GError       **error)
747 {
748   int fd = -1;
749   GLocalFileStat original_stat;
750   char *current_etag;
751   gboolean is_symlink;
752   int open_flags;
753   int res;
754   int mode;
755
756   mode = mode_from_flags_or_info (flags, reference_info);
757
758   /* We only need read access to the original file if we are creating a backup.
759    * We also add O_CREATE to avoid a race if the file was just removed */
760   if (create_backup || readable)
761     open_flags = O_RDWR | O_CREAT | O_BINARY;
762   else
763     open_flags = O_WRONLY | O_CREAT | O_BINARY;
764   
765   /* Some systems have O_NOFOLLOW, which lets us avoid some races
766    * when finding out if the file we opened was a symlink */
767 #ifdef O_NOFOLLOW
768   is_symlink = FALSE;
769   fd = g_open (filename, open_flags | O_NOFOLLOW, mode);
770   if (fd == -1 && errno == ELOOP)
771     {
772       /* Could be a symlink, or it could be a regular ELOOP error,
773        * but then the next open will fail too. */
774       is_symlink = TRUE;
775       fd = g_open (filename, open_flags, mode);
776     }
777 #else
778   fd = g_open (filename, open_flags, mode);
779   /* This is racy, but we do it as soon as possible to minimize the race */
780   is_symlink = g_file_test (filename, G_FILE_TEST_IS_SYMLINK);
781 #endif
782     
783   if (fd == -1)
784     {
785       int errsv = errno;
786       char *display_name = g_filename_display_name (filename);
787       g_set_error (error, G_IO_ERROR,
788                    g_io_error_from_errno (errsv),
789                    _("Error opening file '%s': %s"),
790                    display_name, g_strerror (errsv));
791       g_free (display_name);
792       return -1;
793     }
794   
795 #ifdef G_OS_WIN32
796   res = _fstati64 (fd, &original_stat);
797 #else
798   res = fstat (fd, &original_stat);
799 #endif
800
801   if (res != 0) 
802     {
803       int errsv = errno;
804       char *display_name = g_filename_display_name (filename);
805       g_set_error (error, G_IO_ERROR,
806                    g_io_error_from_errno (errsv),
807                    _("Error when getting information for file '%s': %s"),
808                    display_name, g_strerror (errsv));
809       g_free (display_name);
810       goto err_out;
811     }
812   
813   /* not a regular file */
814   if (!S_ISREG (original_stat.st_mode))
815     {
816       if (S_ISDIR (original_stat.st_mode))
817         g_set_error_literal (error,
818                              G_IO_ERROR,
819                              G_IO_ERROR_IS_DIRECTORY,
820                              _("Target file is a directory"));
821       else
822         g_set_error_literal (error,
823                              G_IO_ERROR,
824                              G_IO_ERROR_NOT_REGULAR_FILE,
825                              _("Target file is not a regular file"));
826       goto err_out;
827     }
828   
829   if (etag != NULL)
830     {
831       current_etag = _g_local_file_info_create_etag (&original_stat);
832       if (strcmp (etag, current_etag) != 0)
833         {
834           g_set_error_literal (error,
835                                G_IO_ERROR,
836                                G_IO_ERROR_WRONG_ETAG,
837                                _("The file was externally modified"));
838           g_free (current_etag);
839           goto err_out;
840         }
841       g_free (current_etag);
842     }
843
844   /* We use two backup strategies.
845    * The first one (which is faster) consist in saving to a
846    * tmp file then rename the original file to the backup and the
847    * tmp file to the original name. This is fast but doesn't work
848    * when the file is a link (hard or symbolic) or when we can't
849    * write to the current dir or can't set the permissions on the
850    * new file. 
851    * The second strategy consist simply in copying the old file
852    * to a backup file and rewrite the contents of the file.
853    */
854   
855   if ((flags & G_FILE_CREATE_REPLACE_DESTINATION) ||
856       (!(original_stat.st_nlink > 1) && !is_symlink))
857     {
858       char *dirname, *tmp_filename;
859       int tmpfd;
860       
861       dirname = g_path_get_dirname (filename);
862       tmp_filename = g_build_filename (dirname, ".goutputstream-XXXXXX", NULL);
863       g_free (dirname);
864
865       tmpfd = g_mkstemp_full (tmp_filename, (readable ? O_RDWR : O_WRONLY) | O_BINARY, mode);
866       if (tmpfd == -1)
867         {
868           g_free (tmp_filename);
869           goto fallback_strategy;
870         }
871       
872       /* try to keep permissions (unless replacing) */
873
874       if ( ! (flags & G_FILE_CREATE_REPLACE_DESTINATION) &&
875            (
876 #ifdef HAVE_FCHOWN
877             fchown (tmpfd, original_stat.st_uid, original_stat.st_gid) == -1 ||
878 #endif
879 #ifdef HAVE_FCHMOD
880             fchmod (tmpfd, original_stat.st_mode) == -1 ||
881 #endif
882             0
883             )
884           )
885         {
886           GLocalFileStat tmp_statbuf;
887           int tres;
888
889 #ifdef G_OS_WIN32
890           tres = _fstati64 (tmpfd, &tmp_statbuf);
891 #else
892           tres = fstat (tmpfd, &tmp_statbuf);
893 #endif
894           /* Check that we really needed to change something */
895           if (tres != 0 ||
896               original_stat.st_uid != tmp_statbuf.st_uid ||
897               original_stat.st_gid != tmp_statbuf.st_gid ||
898               original_stat.st_mode != tmp_statbuf.st_mode)
899             {
900               (void) g_close (tmpfd, NULL);
901               g_unlink (tmp_filename);
902               g_free (tmp_filename);
903               goto fallback_strategy;
904             }
905         }
906
907       (void) g_close (fd, NULL);
908       *temp_filename = tmp_filename;
909       return tmpfd;
910     }
911
912  fallback_strategy:
913
914   if (create_backup)
915     {
916 #if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
917       struct stat tmp_statbuf;      
918 #endif
919       char *backup_filename;
920       int bfd;
921       
922       backup_filename = create_backup_filename (filename);
923
924       if (g_unlink (backup_filename) == -1 && errno != ENOENT)
925         {
926           g_set_error_literal (error,
927                                G_IO_ERROR,
928                                G_IO_ERROR_CANT_CREATE_BACKUP,
929                                _("Backup file creation failed"));
930           g_free (backup_filename);
931           goto err_out;
932         }
933
934       bfd = g_open (backup_filename,
935                     O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
936                     original_stat.st_mode & 0777);
937
938       if (bfd == -1)
939         {
940           g_set_error_literal (error,
941                                G_IO_ERROR,
942                                G_IO_ERROR_CANT_CREATE_BACKUP,
943                                _("Backup file creation failed"));
944           g_free (backup_filename);
945           goto err_out;
946         }
947
948       /* If needed, Try to set the group of the backup same as the
949        * original file. If this fails, set the protection
950        * bits for the group same as the protection bits for
951        * others. */
952 #if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
953       if (fstat (bfd, &tmp_statbuf) != 0)
954         {
955           g_set_error_literal (error,
956                                G_IO_ERROR,
957                                G_IO_ERROR_CANT_CREATE_BACKUP,
958                                _("Backup file creation failed"));
959           g_unlink (backup_filename);
960           g_free (backup_filename);
961           goto err_out;
962         }
963       
964       if ((original_stat.st_gid != tmp_statbuf.st_gid)  &&
965           fchown (bfd, (uid_t) -1, original_stat.st_gid) != 0)
966         {
967           if (fchmod (bfd,
968                       (original_stat.st_mode & 0707) |
969                       ((original_stat.st_mode & 07) << 3)) != 0)
970             {
971               g_set_error_literal (error,
972                                    G_IO_ERROR,
973                                    G_IO_ERROR_CANT_CREATE_BACKUP,
974                                    _("Backup file creation failed"));
975               g_unlink (backup_filename);
976               (void) g_close (bfd, NULL);
977               g_free (backup_filename);
978               goto err_out;
979             }
980         }
981 #endif
982
983       if (!copy_file_data (fd, bfd, NULL))
984         {
985           g_set_error_literal (error,
986                                G_IO_ERROR,
987                                G_IO_ERROR_CANT_CREATE_BACKUP,
988                                _("Backup file creation failed"));
989           g_unlink (backup_filename);
990           (void) g_close (bfd, NULL);
991           g_free (backup_filename);
992           
993           goto err_out;
994         }
995       
996       (void) g_close (bfd, NULL);
997       g_free (backup_filename);
998
999       /* Seek back to the start of the file after the backup copy */
1000       if (lseek (fd, 0, SEEK_SET) == -1)
1001         {
1002           int errsv = errno;
1003
1004           g_set_error (error, G_IO_ERROR,
1005                        g_io_error_from_errno (errsv),
1006                        _("Error seeking in file: %s"),
1007                        g_strerror (errsv));
1008           goto err_out;
1009         }
1010     }
1011
1012   if (flags & G_FILE_CREATE_REPLACE_DESTINATION)
1013     {
1014       (void) g_close (fd, NULL);
1015       
1016       if (g_unlink (filename) != 0)
1017         {
1018           int errsv = errno;
1019           
1020           g_set_error (error, G_IO_ERROR,
1021                        g_io_error_from_errno (errsv),
1022                        _("Error removing old file: %s"),
1023                        g_strerror (errsv));
1024           goto err_out2;
1025         }
1026
1027       if (readable)
1028         open_flags = O_RDWR | O_CREAT | O_BINARY;
1029       else
1030         open_flags = O_WRONLY | O_CREAT | O_BINARY;
1031       fd = g_open (filename, open_flags, mode);
1032       if (fd == -1)
1033         {
1034           int errsv = errno;
1035           char *display_name = g_filename_display_name (filename);
1036           g_set_error (error, G_IO_ERROR,
1037                        g_io_error_from_errno (errsv),
1038                        _("Error opening file '%s': %s"),
1039                        display_name, g_strerror (errsv));
1040           g_free (display_name);
1041           goto err_out2;
1042         }
1043     }
1044   else
1045     {
1046       /* Truncate the file at the start */
1047 #ifdef G_OS_WIN32
1048       if (g_win32_ftruncate (fd, 0) == -1)
1049 #else
1050         if (ftruncate (fd, 0) == -1)
1051 #endif
1052           {
1053             int errsv = errno;
1054             
1055             g_set_error (error, G_IO_ERROR,
1056                          g_io_error_from_errno (errsv),
1057                          _("Error truncating file: %s"),
1058                          g_strerror (errsv));
1059             goto err_out;
1060           }
1061     }
1062     
1063   return fd;
1064
1065  err_out:
1066   (void) g_close (fd, NULL);
1067  err_out2:
1068   return -1;
1069 }
1070
1071 GFileOutputStream *
1072 _g_local_file_output_stream_replace (const char        *filename,
1073                                      gboolean          readable,
1074                                      const char        *etag,
1075                                      gboolean           create_backup,
1076                                      GFileCreateFlags   flags,
1077                                      GFileInfo         *reference_info,
1078                                      GCancellable      *cancellable,
1079                                      GError           **error)
1080 {
1081   GLocalFileOutputStream *stream;
1082   int mode;
1083   int fd;
1084   char *temp_file;
1085   gboolean sync_on_close;
1086   int open_flags;
1087
1088   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1089     return NULL;
1090
1091   temp_file = NULL;
1092
1093   mode = mode_from_flags_or_info (flags, reference_info);
1094   sync_on_close = FALSE;
1095
1096   /* If the file doesn't exist, create it */
1097   open_flags = O_CREAT | O_EXCL | O_BINARY;
1098   if (readable)
1099     open_flags |= O_RDWR;
1100   else
1101     open_flags |= O_WRONLY;
1102   fd = g_open (filename, open_flags, mode);
1103
1104   if (fd == -1 && errno == EEXIST)
1105     {
1106       /* The file already exists */
1107       fd = handle_overwrite_open (filename, readable, etag,
1108                                   create_backup, &temp_file,
1109                                   flags, reference_info,
1110                                   cancellable, error);
1111       if (fd == -1)
1112         return NULL;
1113
1114       /* If the final destination exists, we want to sync the newly written
1115        * file to ensure the data is on disk when we rename over the destination.
1116        * otherwise if we get a system crash we can lose both the new and the
1117        * old file on some filesystems. (I.E. those that don't guarantee the
1118        * data is written to the disk before the metadata.)
1119        */
1120       sync_on_close = TRUE;
1121     }
1122   else if (fd == -1)
1123     {
1124       set_error_from_open_errno (filename, error);
1125       return NULL;
1126     }
1127   
1128  
1129   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
1130   stream->priv->fd = fd;
1131   stream->priv->sync_on_close = sync_on_close;
1132   stream->priv->tmp_filename = temp_file;
1133   if (create_backup)
1134     stream->priv->backup_filename = create_backup_filename (filename);
1135   stream->priv->original_filename =  g_strdup (filename);
1136   
1137   return G_FILE_OUTPUT_STREAM (stream);
1138 }
1139
1140 gint
1141 _g_local_file_output_stream_get_fd (GLocalFileOutputStream *stream)
1142 {
1143   g_return_val_if_fail (G_IS_LOCAL_FILE_OUTPUT_STREAM (stream), -1);
1144   return stream->priv->fd;
1145 }
1146
1147 #ifdef G_OS_UNIX
1148 static int
1149 g_local_file_output_stream_get_fd (GFileDescriptorBased *fd_based)
1150 {
1151   GLocalFileOutputStream *stream = G_LOCAL_FILE_OUTPUT_STREAM (fd_based);
1152   return _g_local_file_output_stream_get_fd (stream);
1153 }
1154 #endif