[kdbus] Do not set body message if signature field is empty
[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, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: Alexander Larsson <alexl@redhat.com>
19  */
20
21 #include "config.h"
22
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <string.h>
28
29 #include <glib.h>
30 #include <glib/gstdio.h>
31 #include "glibintl.h"
32 #include "gioerror.h"
33 #include "gcancellable.h"
34 #include "glocalfileoutputstream.h"
35 #include "gfileinfo.h"
36 #include "glocalfileinfo.h"
37
38 #ifdef G_OS_UNIX
39 #include <unistd.h>
40 #include "gfiledescriptorbased.h"
41 #endif
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 struct _GLocalFileOutputStreamPrivate {
58   char *tmp_filename;
59   char *original_filename;
60   char *backup_filename;
61   char *etag;
62   guint sync_on_close : 1;
63   guint do_close : 1;
64   int fd;
65 };
66
67 #ifdef G_OS_UNIX
68 static void       g_file_descriptor_based_iface_init   (GFileDescriptorBasedIface *iface);
69 #endif
70
71 #define g_local_file_output_stream_get_type _g_local_file_output_stream_get_type
72 #ifdef G_OS_UNIX
73 G_DEFINE_TYPE_WITH_CODE (GLocalFileOutputStream, g_local_file_output_stream, G_TYPE_FILE_OUTPUT_STREAM,
74                          G_ADD_PRIVATE (GLocalFileOutputStream)
75                          G_IMPLEMENT_INTERFACE (G_TYPE_FILE_DESCRIPTOR_BASED,
76                                                 g_file_descriptor_based_iface_init))
77 #else
78 G_DEFINE_TYPE_WITH_CODE (GLocalFileOutputStream, g_local_file_output_stream, G_TYPE_FILE_OUTPUT_STREAM,
79                          G_ADD_PRIVATE (GLocalFileOutputStream))
80 #endif
81
82
83 /* Some of the file replacement code was based on the code from gedit,
84  * relicenced to LGPL with permissions from the authors.
85  */
86
87 #define BACKUP_EXTENSION "~"
88
89 static gssize     g_local_file_output_stream_write        (GOutputStream      *stream,
90                                                            const void         *buffer,
91                                                            gsize               count,
92                                                            GCancellable       *cancellable,
93                                                            GError            **error);
94 static gboolean   g_local_file_output_stream_close        (GOutputStream      *stream,
95                                                            GCancellable       *cancellable,
96                                                            GError            **error);
97 static GFileInfo *g_local_file_output_stream_query_info   (GFileOutputStream  *stream,
98                                                            const char         *attributes,
99                                                            GCancellable       *cancellable,
100                                                            GError            **error);
101 static char *     g_local_file_output_stream_get_etag     (GFileOutputStream  *stream);
102 static goffset    g_local_file_output_stream_tell         (GFileOutputStream  *stream);
103 static gboolean   g_local_file_output_stream_can_seek     (GFileOutputStream  *stream);
104 static gboolean   g_local_file_output_stream_seek         (GFileOutputStream  *stream,
105                                                            goffset             offset,
106                                                            GSeekType           type,
107                                                            GCancellable       *cancellable,
108                                                            GError            **error);
109 static gboolean   g_local_file_output_stream_can_truncate (GFileOutputStream  *stream);
110 static gboolean   g_local_file_output_stream_truncate     (GFileOutputStream  *stream,
111                                                            goffset             size,
112                                                            GCancellable       *cancellable,
113                                                            GError            **error);
114 #ifdef G_OS_UNIX
115 static int        g_local_file_output_stream_get_fd       (GFileDescriptorBased *stream);
116 #endif
117
118 static void
119 g_local_file_output_stream_finalize (GObject *object)
120 {
121   GLocalFileOutputStream *file;
122   
123   file = G_LOCAL_FILE_OUTPUT_STREAM (object);
124   
125   g_free (file->priv->tmp_filename);
126   g_free (file->priv->original_filename);
127   g_free (file->priv->backup_filename);
128   g_free (file->priv->etag);
129
130   G_OBJECT_CLASS (g_local_file_output_stream_parent_class)->finalize (object);
131 }
132
133 static void
134 g_local_file_output_stream_class_init (GLocalFileOutputStreamClass *klass)
135 {
136   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
137   GOutputStreamClass *stream_class = G_OUTPUT_STREAM_CLASS (klass);
138   GFileOutputStreamClass *file_stream_class = G_FILE_OUTPUT_STREAM_CLASS (klass);
139
140   gobject_class->finalize = g_local_file_output_stream_finalize;
141
142   stream_class->write_fn = g_local_file_output_stream_write;
143   stream_class->close_fn = g_local_file_output_stream_close;
144   file_stream_class->query_info = g_local_file_output_stream_query_info;
145   file_stream_class->get_etag = g_local_file_output_stream_get_etag;
146   file_stream_class->tell = g_local_file_output_stream_tell;
147   file_stream_class->can_seek = g_local_file_output_stream_can_seek;
148   file_stream_class->seek = g_local_file_output_stream_seek;
149   file_stream_class->can_truncate = g_local_file_output_stream_can_truncate;
150   file_stream_class->truncate_fn = g_local_file_output_stream_truncate;
151 }
152
153 #ifdef G_OS_UNIX
154 static void
155 g_file_descriptor_based_iface_init (GFileDescriptorBasedIface *iface)
156 {
157   iface->get_fd = g_local_file_output_stream_get_fd;
158 }
159 #endif
160
161 static void
162 g_local_file_output_stream_init (GLocalFileOutputStream *stream)
163 {
164   stream->priv = g_local_file_output_stream_get_instance_private (stream);
165   stream->priv->do_close = TRUE;
166 }
167
168 static gssize
169 g_local_file_output_stream_write (GOutputStream  *stream,
170                                   const void     *buffer,
171                                   gsize           count,
172                                   GCancellable   *cancellable,
173                                   GError        **error)
174 {
175   GLocalFileOutputStream *file;
176   gssize res;
177
178   file = G_LOCAL_FILE_OUTPUT_STREAM (stream);
179
180   while (1)
181     {
182       if (g_cancellable_set_error_if_cancelled (cancellable, error))
183         return -1;
184       res = write (file->priv->fd, buffer, count);
185       if (res == -1)
186         {
187           int errsv = errno;
188
189           if (errsv == EINTR)
190             continue;
191           
192           g_set_error (error, G_IO_ERROR,
193                        g_io_error_from_errno (errsv),
194                        _("Error writing to file: %s"),
195                        g_strerror (errsv));
196         }
197       
198       break;
199     }
200   
201   return res;
202 }
203
204 void
205 _g_local_file_output_stream_set_do_close (GLocalFileOutputStream *out,
206                                           gboolean do_close)
207 {
208   out->priv->do_close = do_close;
209 }
210
211 gboolean
212 _g_local_file_output_stream_really_close (GLocalFileOutputStream *file,
213                                           GCancellable   *cancellable,
214                                           GError        **error)
215 {
216   GLocalFileStat final_stat;
217
218 #ifdef HAVE_FSYNC
219   if (file->priv->sync_on_close &&
220       fsync (file->priv->fd) != 0)
221     {
222       int errsv = errno;
223       
224       g_set_error (error, G_IO_ERROR,
225                    g_io_error_from_errno (errsv),
226                    _("Error writing to file: %s"),
227                    g_strerror (errsv));
228       goto err_out;
229     }
230 #endif
231  
232 #ifdef G_OS_WIN32
233
234   /* Must close before renaming on Windows, so just do the close first
235    * in all cases for now.
236    */
237   if (_fstati64 (file->priv->fd, &final_stat) == 0)
238     file->priv->etag = _g_local_file_info_create_etag (&final_stat);
239
240   if (!g_close (file->priv->fd, NULL))
241     {
242       int errsv = errno;
243       
244       g_set_error (error, G_IO_ERROR,
245                    g_io_error_from_errno (errsv),
246                    _("Error closing file: %s"),
247                    g_strerror (errsv));
248       return FALSE;
249     }
250
251 #endif
252
253   if (file->priv->tmp_filename)
254     {
255       /* We need to move the temp file to its final place,
256        * and possibly create the backup file
257        */
258
259       if (file->priv->backup_filename)
260         {
261           if (g_cancellable_set_error_if_cancelled (cancellable, error))
262             goto err_out;
263           
264 #ifdef G_OS_UNIX
265           /* create original -> backup link, the original is then renamed over */
266           if (g_unlink (file->priv->backup_filename) != 0 &&
267               errno != ENOENT)
268             {
269               int errsv = errno;
270
271               g_set_error (error, G_IO_ERROR,
272                            G_IO_ERROR_CANT_CREATE_BACKUP,
273                            _("Error removing old backup link: %s"),
274                            g_strerror (errsv));
275               goto err_out;
276             }
277
278           if (link (file->priv->original_filename, file->priv->backup_filename) != 0)
279             {
280               /*  link failed or is not supported, try rename  */
281               if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
282                 {
283                   int errsv = errno;
284
285                   g_set_error (error, G_IO_ERROR,
286                                G_IO_ERROR_CANT_CREATE_BACKUP,
287                                _("Error creating backup copy: %s"),
288                                g_strerror (errsv));
289                   goto err_out;
290                 }
291             }
292 #else
293             /* If link not supported, just rename... */
294           if (g_rename (file->priv->original_filename, file->priv->backup_filename) != 0)
295             {
296               int errsv = errno;
297
298               g_set_error (error, G_IO_ERROR,
299                            G_IO_ERROR_CANT_CREATE_BACKUP,
300                            _("Error creating backup copy: %s"),
301                            g_strerror (errsv));
302               goto err_out;
303             }
304 #endif
305         }
306       
307
308       if (g_cancellable_set_error_if_cancelled (cancellable, error))
309         goto err_out;
310
311       /* tmp -> original */
312       if (g_rename (file->priv->tmp_filename, file->priv->original_filename) != 0)
313         {
314           int errsv = errno;
315
316           g_set_error (error, G_IO_ERROR,
317                        g_io_error_from_errno (errsv),
318                        _("Error renaming temporary file: %s"),
319                        g_strerror (errsv));
320           goto err_out;
321         }
322
323       g_clear_pointer (&file->priv->tmp_filename, g_free);
324     }
325   
326   if (g_cancellable_set_error_if_cancelled (cancellable, error))
327     goto err_out;
328       
329 #ifndef G_OS_WIN32              /* Already did the fstat() and close() above on Win32 */
330
331   if (fstat (file->priv->fd, &final_stat) == 0)
332     file->priv->etag = _g_local_file_info_create_etag (&final_stat);
333
334   if (!g_close (file->priv->fd, NULL))
335     {
336       int errsv = errno;
337       
338       g_set_error (error, G_IO_ERROR,
339                    g_io_error_from_errno (errsv),
340                    _("Error closing file: %s"),
341                    g_strerror (errsv));
342       goto err_out;
343     }
344
345 #endif
346   
347   return TRUE;
348  err_out:
349
350 #ifndef G_OS_WIN32
351   /* A simple try to close the fd in case we fail before the actual close */
352   (void) g_close (file->priv->fd, NULL);
353 #endif
354   if (file->priv->tmp_filename)
355     g_unlink (file->priv->tmp_filename);
356
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_new (int fd)
531 {
532   GLocalFileOutputStream *stream;
533
534   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
535   stream->priv->fd = fd;
536   return G_FILE_OUTPUT_STREAM (stream);
537 }
538
539 static void
540 set_error_from_open_errno (const char *filename,
541                            GError    **error)
542 {
543   int errsv = errno;
544   
545   if (errsv == EINVAL)
546     /* This must be an invalid filename, on e.g. FAT */
547     g_set_error_literal (error, G_IO_ERROR,
548                          G_IO_ERROR_INVALID_FILENAME,
549                          _("Invalid filename"));
550   else
551     {
552       char *display_name = g_filename_display_name (filename);
553       g_set_error (error, G_IO_ERROR,
554                    g_io_error_from_errno (errsv),
555                    _("Error opening file '%s': %s"),
556                        display_name, g_strerror (errsv));
557       g_free (display_name);
558     }
559 }
560
561 static GFileOutputStream *
562 output_stream_open (const char    *filename,
563                     gint           open_flags,
564                     guint          mode,
565                     GCancellable  *cancellable,
566                     GError       **error)
567 {
568   GLocalFileOutputStream *stream;
569   gint fd;
570
571   fd = g_open (filename, open_flags, mode);
572   if (fd == -1)
573     {
574       set_error_from_open_errno (filename, error);
575       return NULL;
576     }
577   
578   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
579   stream->priv->fd = fd;
580   return G_FILE_OUTPUT_STREAM (stream);
581 }
582
583 GFileOutputStream *
584 _g_local_file_output_stream_open  (const char        *filename,
585                                    gboolean          readable,
586                                    GCancellable      *cancellable,
587                                    GError           **error)
588 {
589   int open_flags;
590
591   if (g_cancellable_set_error_if_cancelled (cancellable, error))
592     return NULL;
593
594   open_flags = O_BINARY;
595   if (readable)
596     open_flags |= O_RDWR;
597   else
598     open_flags |= O_WRONLY;
599
600   return output_stream_open (filename, open_flags, 0666, cancellable, error);
601 }
602
603 static gint
604 mode_from_flags_or_info (GFileCreateFlags   flags,
605                          GFileInfo         *reference_info)
606 {
607   if (flags & G_FILE_CREATE_PRIVATE)
608     return 0600;
609   else if (reference_info && g_file_info_has_attribute (reference_info, "unix::mode"))
610     return g_file_info_get_attribute_uint32 (reference_info, "unix::mode") & (~S_IFMT);
611   else
612     return 0666;
613 }
614
615 GFileOutputStream *
616 _g_local_file_output_stream_create  (const char        *filename,
617                                      gboolean          readable,
618                                      GFileCreateFlags   flags,
619                                      GFileInfo         *reference_info,
620                                      GCancellable      *cancellable,
621                                      GError           **error)
622 {
623   int mode;
624   int open_flags;
625
626   if (g_cancellable_set_error_if_cancelled (cancellable, error))
627     return NULL;
628
629   mode = mode_from_flags_or_info (flags, reference_info);
630
631   open_flags = O_CREAT | O_EXCL | O_BINARY;
632   if (readable)
633     open_flags |= O_RDWR;
634   else
635     open_flags |= O_WRONLY;
636
637   return output_stream_open (filename, open_flags, mode, cancellable, error);
638 }
639
640 GFileOutputStream *
641 _g_local_file_output_stream_append  (const char        *filename,
642                                      GFileCreateFlags   flags,
643                                      GCancellable      *cancellable,
644                                      GError           **error)
645 {
646   int mode;
647
648   if (g_cancellable_set_error_if_cancelled (cancellable, error))
649     return NULL;
650
651   if (flags & G_FILE_CREATE_PRIVATE)
652     mode = 0600;
653   else
654     mode = 0666;
655
656   return output_stream_open (filename, O_CREAT | O_APPEND | O_WRONLY | O_BINARY, mode,
657                              cancellable, error);
658 }
659
660 static char *
661 create_backup_filename (const char *filename)
662 {
663   return g_strconcat (filename, BACKUP_EXTENSION, NULL);
664 }
665
666 #define BUFSIZE 8192 /* size of normal write buffer */
667
668 static gboolean
669 copy_file_data (gint     sfd,
670                 gint     dfd,
671                 GError **error)
672 {
673   gboolean ret = TRUE;
674   gpointer buffer;
675   const gchar *write_buffer;
676   gssize bytes_read;
677   gssize bytes_to_write;
678   gssize bytes_written;
679   
680   buffer = g_malloc (BUFSIZE);
681   
682   do
683     {
684       bytes_read = read (sfd, buffer, BUFSIZE);
685       if (bytes_read == -1)
686         {
687           int errsv = errno;
688
689           if (errsv == EINTR)
690             continue;
691           
692           g_set_error (error, G_IO_ERROR,
693                        g_io_error_from_errno (errsv),
694                        _("Error reading from file: %s"),
695                        g_strerror (errsv));
696           ret = FALSE;
697           break;
698         }
699       
700       bytes_to_write = bytes_read;
701       write_buffer = buffer;
702       
703       do
704         {
705           bytes_written = write (dfd, write_buffer, bytes_to_write);
706           if (bytes_written == -1)
707             {
708               int errsv = errno;
709
710               if (errsv == EINTR)
711                 continue;
712               
713               g_set_error (error, G_IO_ERROR,
714                            g_io_error_from_errno (errsv),
715                            _("Error writing to file: %s"),
716                            g_strerror (errsv));
717               ret = FALSE;
718               break;
719             }
720           
721           bytes_to_write -= bytes_written;
722           write_buffer += bytes_written;
723         }
724       while (bytes_to_write > 0);
725       
726     } while ((bytes_read != 0) && (ret == TRUE));
727
728   g_free (buffer);
729   
730   return ret;
731 }
732
733 static int
734 handle_overwrite_open (const char    *filename,
735                        gboolean       readable,
736                        const char    *etag,
737                        gboolean       create_backup,
738                        char         **temp_filename,
739                        GFileCreateFlags flags,
740                        GFileInfo       *reference_info,
741                        GCancellable  *cancellable,
742                        GError       **error)
743 {
744   int fd = -1;
745   GLocalFileStat original_stat;
746   char *current_etag;
747   gboolean is_symlink;
748   int open_flags;
749   int res;
750   int mode;
751
752   mode = mode_from_flags_or_info (flags, reference_info);
753
754   /* We only need read access to the original file if we are creating a backup.
755    * We also add O_CREATE to avoid a race if the file was just removed */
756   if (create_backup || readable)
757     open_flags = O_RDWR | O_CREAT | O_BINARY;
758   else
759     open_flags = O_WRONLY | O_CREAT | O_BINARY;
760   
761   /* Some systems have O_NOFOLLOW, which lets us avoid some races
762    * when finding out if the file we opened was a symlink */
763 #ifdef O_NOFOLLOW
764   is_symlink = FALSE;
765   fd = g_open (filename, open_flags | O_NOFOLLOW, mode);
766   if (fd == -1 && errno == ELOOP)
767     {
768       /* Could be a symlink, or it could be a regular ELOOP error,
769        * but then the next open will fail too. */
770       is_symlink = TRUE;
771       fd = g_open (filename, open_flags, mode);
772     }
773 #else
774   fd = g_open (filename, open_flags, mode);
775   /* This is racy, but we do it as soon as possible to minimize the race */
776   is_symlink = g_file_test (filename, G_FILE_TEST_IS_SYMLINK);
777 #endif
778     
779   if (fd == -1)
780     {
781       int errsv = errno;
782       char *display_name = g_filename_display_name (filename);
783       g_set_error (error, G_IO_ERROR,
784                    g_io_error_from_errno (errsv),
785                    _("Error opening file '%s': %s"),
786                    display_name, g_strerror (errsv));
787       g_free (display_name);
788       return -1;
789     }
790   
791 #ifdef G_OS_WIN32
792   res = _fstati64 (fd, &original_stat);
793 #else
794   res = fstat (fd, &original_stat);
795 #endif
796
797   if (res != 0) 
798     {
799       int errsv = errno;
800       char *display_name = g_filename_display_name (filename);
801       g_set_error (error, G_IO_ERROR,
802                    g_io_error_from_errno (errsv),
803                    _("Error when getting information for file '%s': %s"),
804                    display_name, g_strerror (errsv));
805       g_free (display_name);
806       goto err_out;
807     }
808   
809   /* not a regular file */
810   if (!S_ISREG (original_stat.st_mode))
811     {
812       if (S_ISDIR (original_stat.st_mode))
813         g_set_error_literal (error,
814                              G_IO_ERROR,
815                              G_IO_ERROR_IS_DIRECTORY,
816                              _("Target file is a directory"));
817       else
818         g_set_error_literal (error,
819                              G_IO_ERROR,
820                              G_IO_ERROR_NOT_REGULAR_FILE,
821                              _("Target file is not a regular file"));
822       goto err_out;
823     }
824   
825   if (etag != NULL)
826     {
827       current_etag = _g_local_file_info_create_etag (&original_stat);
828       if (strcmp (etag, current_etag) != 0)
829         {
830           g_set_error_literal (error,
831                                G_IO_ERROR,
832                                G_IO_ERROR_WRONG_ETAG,
833                                _("The file was externally modified"));
834           g_free (current_etag);
835           goto err_out;
836         }
837       g_free (current_etag);
838     }
839
840   /* We use two backup strategies.
841    * The first one (which is faster) consist in saving to a
842    * tmp file then rename the original file to the backup and the
843    * tmp file to the original name. This is fast but doesn't work
844    * when the file is a link (hard or symbolic) or when we can't
845    * write to the current dir or can't set the permissions on the
846    * new file. 
847    * The second strategy consist simply in copying the old file
848    * to a backup file and rewrite the contents of the file.
849    */
850   
851   if ((flags & G_FILE_CREATE_REPLACE_DESTINATION) ||
852       (!(original_stat.st_nlink > 1) && !is_symlink))
853     {
854       char *dirname, *tmp_filename;
855       int tmpfd;
856       
857       dirname = g_path_get_dirname (filename);
858       tmp_filename = g_build_filename (dirname, ".goutputstream-XXXXXX", NULL);
859       g_free (dirname);
860
861       tmpfd = g_mkstemp_full (tmp_filename, (readable ? O_RDWR : O_WRONLY) | O_BINARY, mode);
862       if (tmpfd == -1)
863         {
864           g_free (tmp_filename);
865           goto fallback_strategy;
866         }
867       
868       /* try to keep permissions (unless replacing) */
869
870       if ( ! (flags & G_FILE_CREATE_REPLACE_DESTINATION) &&
871            (
872 #ifdef HAVE_FCHOWN
873             fchown (tmpfd, original_stat.st_uid, original_stat.st_gid) == -1 ||
874 #endif
875 #ifdef HAVE_FCHMOD
876             fchmod (tmpfd, original_stat.st_mode) == -1 ||
877 #endif
878             0
879             )
880           )
881         {
882           GLocalFileStat tmp_statbuf;
883           int tres;
884
885 #ifdef G_OS_WIN32
886           tres = _fstati64 (tmpfd, &tmp_statbuf);
887 #else
888           tres = fstat (tmpfd, &tmp_statbuf);
889 #endif
890           /* Check that we really needed to change something */
891           if (tres != 0 ||
892               original_stat.st_uid != tmp_statbuf.st_uid ||
893               original_stat.st_gid != tmp_statbuf.st_gid ||
894               original_stat.st_mode != tmp_statbuf.st_mode)
895             {
896               (void) g_close (tmpfd, NULL);
897               g_unlink (tmp_filename);
898               g_free (tmp_filename);
899               goto fallback_strategy;
900             }
901         }
902
903       (void) g_close (fd, NULL);
904       *temp_filename = tmp_filename;
905       return tmpfd;
906     }
907
908  fallback_strategy:
909
910   if (create_backup)
911     {
912 #if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
913       struct stat tmp_statbuf;      
914 #endif
915       char *backup_filename;
916       int bfd;
917       
918       backup_filename = create_backup_filename (filename);
919
920       if (g_unlink (backup_filename) == -1 && errno != ENOENT)
921         {
922           g_set_error_literal (error,
923                                G_IO_ERROR,
924                                G_IO_ERROR_CANT_CREATE_BACKUP,
925                                _("Backup file creation failed"));
926           g_free (backup_filename);
927           goto err_out;
928         }
929
930       bfd = g_open (backup_filename,
931                     O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
932                     original_stat.st_mode & 0777);
933
934       if (bfd == -1)
935         {
936           g_set_error_literal (error,
937                                G_IO_ERROR,
938                                G_IO_ERROR_CANT_CREATE_BACKUP,
939                                _("Backup file creation failed"));
940           g_free (backup_filename);
941           goto err_out;
942         }
943
944       /* If needed, Try to set the group of the backup same as the
945        * original file. If this fails, set the protection
946        * bits for the group same as the protection bits for
947        * others. */
948 #if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
949       if (fstat (bfd, &tmp_statbuf) != 0)
950         {
951           g_set_error_literal (error,
952                                G_IO_ERROR,
953                                G_IO_ERROR_CANT_CREATE_BACKUP,
954                                _("Backup file creation failed"));
955           g_unlink (backup_filename);
956           g_free (backup_filename);
957           goto err_out;
958         }
959       
960       if ((original_stat.st_gid != tmp_statbuf.st_gid)  &&
961           fchown (bfd, (uid_t) -1, original_stat.st_gid) != 0)
962         {
963           if (fchmod (bfd,
964                       (original_stat.st_mode & 0707) |
965                       ((original_stat.st_mode & 07) << 3)) != 0)
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_unlink (backup_filename);
972               (void) g_close (bfd, NULL);
973               g_free (backup_filename);
974               goto err_out;
975             }
976         }
977 #endif
978
979       if (!copy_file_data (fd, bfd, NULL))
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_unlink (backup_filename);
986           (void) g_close (bfd, NULL);
987           g_free (backup_filename);
988           
989           goto err_out;
990         }
991       
992       (void) g_close (bfd, NULL);
993       g_free (backup_filename);
994
995       /* Seek back to the start of the file after the backup copy */
996       if (lseek (fd, 0, SEEK_SET) == -1)
997         {
998           int errsv = errno;
999
1000           g_set_error (error, G_IO_ERROR,
1001                        g_io_error_from_errno (errsv),
1002                        _("Error seeking in file: %s"),
1003                        g_strerror (errsv));
1004           goto err_out;
1005         }
1006     }
1007
1008   if (flags & G_FILE_CREATE_REPLACE_DESTINATION)
1009     {
1010       (void) g_close (fd, NULL);
1011       
1012       if (g_unlink (filename) != 0)
1013         {
1014           int errsv = errno;
1015           
1016           g_set_error (error, G_IO_ERROR,
1017                        g_io_error_from_errno (errsv),
1018                        _("Error removing old file: %s"),
1019                        g_strerror (errsv));
1020           goto err_out2;
1021         }
1022
1023       if (readable)
1024         open_flags = O_RDWR | O_CREAT | O_BINARY;
1025       else
1026         open_flags = O_WRONLY | O_CREAT | O_BINARY;
1027       fd = g_open (filename, open_flags, mode);
1028       if (fd == -1)
1029         {
1030           int errsv = errno;
1031           char *display_name = g_filename_display_name (filename);
1032           g_set_error (error, G_IO_ERROR,
1033                        g_io_error_from_errno (errsv),
1034                        _("Error opening file '%s': %s"),
1035                        display_name, g_strerror (errsv));
1036           g_free (display_name);
1037           goto err_out2;
1038         }
1039     }
1040   else
1041     {
1042       /* Truncate the file at the start */
1043 #ifdef G_OS_WIN32
1044       if (g_win32_ftruncate (fd, 0) == -1)
1045 #else
1046         if (ftruncate (fd, 0) == -1)
1047 #endif
1048           {
1049             int errsv = errno;
1050             
1051             g_set_error (error, G_IO_ERROR,
1052                          g_io_error_from_errno (errsv),
1053                          _("Error truncating file: %s"),
1054                          g_strerror (errsv));
1055             goto err_out;
1056           }
1057     }
1058     
1059   return fd;
1060
1061  err_out:
1062   (void) g_close (fd, NULL);
1063  err_out2:
1064   return -1;
1065 }
1066
1067 GFileOutputStream *
1068 _g_local_file_output_stream_replace (const char        *filename,
1069                                      gboolean          readable,
1070                                      const char        *etag,
1071                                      gboolean           create_backup,
1072                                      GFileCreateFlags   flags,
1073                                      GFileInfo         *reference_info,
1074                                      GCancellable      *cancellable,
1075                                      GError           **error)
1076 {
1077   GLocalFileOutputStream *stream;
1078   int mode;
1079   int fd;
1080   char *temp_file;
1081   gboolean sync_on_close;
1082   int open_flags;
1083
1084   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1085     return NULL;
1086
1087   temp_file = NULL;
1088
1089   mode = mode_from_flags_or_info (flags, reference_info);
1090   sync_on_close = FALSE;
1091
1092   /* If the file doesn't exist, create it */
1093   open_flags = O_CREAT | O_EXCL | O_BINARY;
1094   if (readable)
1095     open_flags |= O_RDWR;
1096   else
1097     open_flags |= O_WRONLY;
1098   fd = g_open (filename, open_flags, mode);
1099
1100   if (fd == -1 && errno == EEXIST)
1101     {
1102       /* The file already exists */
1103       fd = handle_overwrite_open (filename, readable, etag,
1104                                   create_backup, &temp_file,
1105                                   flags, reference_info,
1106                                   cancellable, error);
1107       if (fd == -1)
1108         return NULL;
1109
1110       /* If the final destination exists, we want to sync the newly written
1111        * file to ensure the data is on disk when we rename over the destination.
1112        * otherwise if we get a system crash we can lose both the new and the
1113        * old file on some filesystems. (I.E. those that don't guarantee the
1114        * data is written to the disk before the metadata.)
1115        */
1116       sync_on_close = TRUE;
1117     }
1118   else if (fd == -1)
1119     {
1120       set_error_from_open_errno (filename, error);
1121       return NULL;
1122     }
1123   
1124  
1125   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
1126   stream->priv->fd = fd;
1127   stream->priv->sync_on_close = sync_on_close;
1128   stream->priv->tmp_filename = temp_file;
1129   if (create_backup)
1130     stream->priv->backup_filename = create_backup_filename (filename);
1131   stream->priv->original_filename =  g_strdup (filename);
1132   
1133   return G_FILE_OUTPUT_STREAM (stream);
1134 }
1135
1136 gint
1137 _g_local_file_output_stream_get_fd (GLocalFileOutputStream *stream)
1138 {
1139   g_return_val_if_fail (G_IS_LOCAL_FILE_OUTPUT_STREAM (stream), -1);
1140   return stream->priv->fd;
1141 }
1142
1143 #ifdef G_OS_UNIX
1144 static int
1145 g_local_file_output_stream_get_fd (GFileDescriptorBased *fd_based)
1146 {
1147   GLocalFileOutputStream *stream = G_LOCAL_FILE_OUTPUT_STREAM (fd_based);
1148   return _g_local_file_output_stream_get_fd (stream);
1149 }
1150 #endif