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