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