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