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