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