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