Local file implementation of GFileIOStream and ops
[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 (errno),
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 mode;
530   int fd;
531   int open_flags;
532
533   if (g_cancellable_set_error_if_cancelled (cancellable, error))
534     return NULL;
535
536   open_flags = O_BINARY;
537   if (readable)
538     open_flags |= O_RDWR;
539   else
540     open_flags |= O_WRONLY;
541
542   fd = g_open (filename, open_flags, 0666);
543   if (fd == -1)
544     {
545       int errsv = errno;
546
547       if (errsv == EINVAL)
548         /* This must be an invalid filename, on e.g. FAT */
549         g_set_error_literal (error, G_IO_ERROR,
550                              G_IO_ERROR_INVALID_FILENAME,
551                              _("Invalid filename"));
552       else
553         {
554           char *display_name = g_filename_display_name (filename);
555           g_set_error (error, G_IO_ERROR,
556                        g_io_error_from_errno (errsv),
557                        _("Error opening file '%s': %s"),
558                        display_name, g_strerror (errsv));
559           g_free (display_name);
560         }
561       return NULL;
562     }
563   
564   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
565   stream->priv->fd = fd;
566   return G_FILE_OUTPUT_STREAM (stream);
567 }
568
569 GFileOutputStream *
570 _g_local_file_output_stream_create  (const char        *filename,
571                                      gboolean          readable,
572                                      GFileCreateFlags   flags,
573                                      GCancellable      *cancellable,
574                                      GError           **error)
575 {
576   GLocalFileOutputStream *stream;
577   int mode;
578   int fd;
579   int open_flags;
580
581   if (g_cancellable_set_error_if_cancelled (cancellable, error))
582     return NULL;
583
584   if (flags & G_FILE_CREATE_PRIVATE)
585     mode = 0600;
586   else
587     mode = 0666;
588
589   open_flags = O_CREAT | O_EXCL | O_BINARY;
590   if (readable)
591     open_flags |= O_RDWR;
592   else
593     open_flags |= O_WRONLY;
594
595   fd = g_open (filename, open_flags, mode);
596   if (fd == -1)
597     {
598       int errsv = errno;
599
600       if (errsv == EINVAL)
601         /* This must be an invalid filename, on e.g. FAT */
602         g_set_error_literal (error, G_IO_ERROR,
603                              G_IO_ERROR_INVALID_FILENAME,
604                              _("Invalid filename"));
605       else
606         {
607           char *display_name = g_filename_display_name (filename);
608           g_set_error (error, G_IO_ERROR,
609                        g_io_error_from_errno (errsv),
610                        _("Error opening file '%s': %s"),
611                        display_name, g_strerror (errsv));
612           g_free (display_name);
613         }
614       return NULL;
615     }
616   
617   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
618   stream->priv->fd = fd;
619   return G_FILE_OUTPUT_STREAM (stream);
620 }
621
622 GFileOutputStream *
623 _g_local_file_output_stream_append  (const char        *filename,
624                                      GFileCreateFlags   flags,
625                                      GCancellable      *cancellable,
626                                      GError           **error)
627 {
628   GLocalFileOutputStream *stream;
629   int mode;
630   int fd;
631
632   if (g_cancellable_set_error_if_cancelled (cancellable, error))
633     return NULL;
634
635   if (flags & G_FILE_CREATE_PRIVATE)
636     mode = 0600;
637   else
638     mode = 0666;
639
640   fd = g_open (filename, O_CREAT | O_APPEND | O_WRONLY | O_BINARY, mode);
641   if (fd == -1)
642     {
643       int errsv = errno;
644
645       if (errsv == EINVAL)
646         /* This must be an invalid filename, on e.g. FAT */
647         g_set_error_literal (error, G_IO_ERROR,
648                              G_IO_ERROR_INVALID_FILENAME,
649                              _("Invalid filename"));
650       else
651         {
652           char *display_name = g_filename_display_name (filename);
653           g_set_error (error, G_IO_ERROR,
654                        g_io_error_from_errno (errsv),
655                        _("Error opening file '%s': %s"),
656                        display_name, g_strerror (errsv));
657           g_free (display_name);
658         }
659       return NULL;
660     }
661   
662   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
663   stream->priv->fd = fd;
664   
665   return G_FILE_OUTPUT_STREAM (stream);
666 }
667
668 static char *
669 create_backup_filename (const char *filename)
670 {
671   return g_strconcat (filename, BACKUP_EXTENSION, NULL);
672 }
673
674 #define BUFSIZE 8192 /* size of normal write buffer */
675
676 static gboolean
677 copy_file_data (gint     sfd,
678                 gint     dfd,
679                 GError **error)
680 {
681   gboolean ret = TRUE;
682   gpointer buffer;
683   const gchar *write_buffer;
684   gssize bytes_read;
685   gssize bytes_to_write;
686   gssize bytes_written;
687   
688   buffer = g_malloc (BUFSIZE);
689   
690   do
691     {
692       bytes_read = read (sfd, buffer, BUFSIZE);
693       if (bytes_read == -1)
694         {
695           int errsv = errno;
696
697           if (errsv == EINTR)
698             continue;
699           
700           g_set_error (error, G_IO_ERROR,
701                        g_io_error_from_errno (errsv),
702                        _("Error reading from file: %s"),
703                        g_strerror (errsv));
704           ret = FALSE;
705           break;
706         }
707       
708       bytes_to_write = bytes_read;
709       write_buffer = buffer;
710       
711       do
712         {
713           bytes_written = write (dfd, write_buffer, bytes_to_write);
714           if (bytes_written == -1)
715             {
716               int errsv = errno;
717
718               if (errsv == EINTR)
719                 continue;
720               
721               g_set_error (error, G_IO_ERROR,
722                            g_io_error_from_errno (errsv),
723                            _("Error writing to file: %s"),
724                            g_strerror (errsv));
725               ret = FALSE;
726               break;
727             }
728           
729           bytes_to_write -= bytes_written;
730           write_buffer += bytes_written;
731         }
732       while (bytes_to_write > 0);
733       
734     } while ((bytes_read != 0) && (ret == TRUE));
735
736   g_free (buffer);
737   
738   return ret;
739 }
740
741 static int
742 handle_overwrite_open (const char    *filename,
743                        gboolean       readable,
744                        const char    *etag,
745                        gboolean       create_backup,
746                        char         **temp_filename,
747                        GFileCreateFlags flags,
748                        GCancellable  *cancellable,
749                        GError       **error)
750 {
751   int fd = -1;
752   GLocalFileStat original_stat;
753   char *current_etag;
754   gboolean is_symlink;
755   int open_flags;
756   int res;
757   int mode;
758
759   if (flags & G_FILE_CREATE_PRIVATE)
760     mode = 0600;
761   else
762     mode = 0666;
763
764   /* We only need read access to the original file if we are creating a backup.
765    * We also add O_CREATE to avoid a race if the file was just removed */
766   if (create_backup || readable)
767     open_flags = O_RDWR | O_CREAT | O_BINARY;
768   else
769     open_flags = O_WRONLY | O_CREAT | O_BINARY;
770   
771   /* Some systems have O_NOFOLLOW, which lets us avoid some races
772    * when finding out if the file we opened was a symlink */
773 #ifdef O_NOFOLLOW
774   is_symlink = FALSE;
775   fd = g_open (filename, open_flags | O_NOFOLLOW, mode);
776   if (fd == -1 && errno == ELOOP)
777     {
778       /* Could be a symlink, or it could be a regular ELOOP error,
779        * but then the next open will fail too. */
780       is_symlink = TRUE;
781       fd = g_open (filename, open_flags, mode);
782     }
783 #else
784   fd = g_open (filename, open_flags, mode);
785   /* This is racy, but we do it as soon as possible to minimize the race */
786   is_symlink = g_file_test (filename, G_FILE_TEST_IS_SYMLINK);
787 #endif
788     
789   if (fd == -1)
790     {
791       int errsv = errno;
792       char *display_name = g_filename_display_name (filename);
793       g_set_error (error, G_IO_ERROR,
794                    g_io_error_from_errno (errsv),
795                    _("Error opening file '%s': %s"),
796                    display_name, g_strerror (errsv));
797       g_free (display_name);
798       return -1;
799     }
800   
801 #ifdef G_OS_WIN32
802   res = _fstati64 (fd, &original_stat);
803 #else
804   res = fstat (fd, &original_stat);
805 #endif
806
807   if (res != 0) 
808     {
809       int errsv = errno;
810       char *display_name = g_filename_display_name (filename);
811       g_set_error (error, G_IO_ERROR,
812                    g_io_error_from_errno (errsv),
813                    _("Error stating file '%s': %s"),
814                    display_name, g_strerror (errsv));
815       g_free (display_name);
816       goto err_out;
817     }
818   
819   /* not a regular file */
820   if (!S_ISREG (original_stat.st_mode))
821     {
822       if (S_ISDIR (original_stat.st_mode))
823         g_set_error_literal (error,
824                              G_IO_ERROR,
825                              G_IO_ERROR_IS_DIRECTORY,
826                              _("Target file is a directory"));
827       else
828         g_set_error_literal (error,
829                              G_IO_ERROR,
830                              G_IO_ERROR_NOT_REGULAR_FILE,
831                              _("Target file is not a regular file"));
832       goto err_out;
833     }
834   
835   if (etag != NULL)
836     {
837       current_etag = _g_local_file_info_create_etag (&original_stat);
838       if (strcmp (etag, current_etag) != 0)
839         {
840           g_set_error_literal (error,
841                                G_IO_ERROR,
842                                G_IO_ERROR_WRONG_ETAG,
843                                _("The file was externally modified"));
844           g_free (current_etag);
845           goto err_out;
846         }
847       g_free (current_etag);
848     }
849
850   /* We use two backup strategies.
851    * The first one (which is faster) consist in saving to a
852    * tmp file then rename the original file to the backup and the
853    * tmp file to the original name. This is fast but doesn't work
854    * when the file is a link (hard or symbolic) or when we can't
855    * write to the current dir or can't set the permissions on the
856    * new file. 
857    * The second strategy consist simply in copying the old file
858    * to a backup file and rewrite the contents of the file.
859    */
860   
861   if ((flags & G_FILE_CREATE_REPLACE_DESTINATION) ||
862       (!(original_stat.st_nlink > 1) && !is_symlink))
863     {
864       char *dirname, *tmp_filename;
865       int tmpfd;
866       
867       dirname = g_path_get_dirname (filename);
868       tmp_filename = g_build_filename (dirname, ".goutputstream-XXXXXX", NULL);
869       g_free (dirname);
870
871       tmpfd = g_mkstemp (tmp_filename);
872       if (tmpfd == -1)
873         {
874           g_free (tmp_filename);
875           goto fallback_strategy;
876         }
877       
878       /* try to keep permissions (unless replacing) */
879
880       if ( ! (flags & G_FILE_CREATE_REPLACE_DESTINATION) &&
881            (
882 #ifdef HAVE_FCHOWN
883             fchown (tmpfd, original_stat.st_uid, original_stat.st_gid) == -1 ||
884 #endif
885 #ifdef HAVE_FCHMOD
886             fchmod (tmpfd, original_stat.st_mode) == -1 ||
887 #endif
888             0
889             )
890           )
891         {
892           struct stat tmp_statbuf;
893           
894           /* Check that we really needed to change something */
895           if (fstat (tmpfd, &tmp_statbuf) != 0 ||
896               original_stat.st_uid != tmp_statbuf.st_uid ||
897               original_stat.st_gid != tmp_statbuf.st_gid ||
898               original_stat.st_mode != tmp_statbuf.st_mode)
899             {
900               close (tmpfd);
901               g_unlink (tmp_filename);
902               g_free (tmp_filename);
903               goto fallback_strategy;
904             }
905         }
906
907       close (fd);
908       *temp_filename = tmp_filename;
909       return tmpfd;
910     }
911
912  fallback_strategy:
913
914   if (create_backup)
915     {
916 #if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
917       struct stat tmp_statbuf;      
918 #endif
919       char *backup_filename;
920       int bfd;
921       
922       backup_filename = create_backup_filename (filename);
923
924       if (g_unlink (backup_filename) == -1 && errno != ENOENT)
925         {
926           g_set_error_literal (error,
927                                G_IO_ERROR,
928                                G_IO_ERROR_CANT_CREATE_BACKUP,
929                                _("Backup file creation failed"));
930           g_free (backup_filename);
931           goto err_out;
932         }
933
934       bfd = g_open (backup_filename,
935                     O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
936                     original_stat.st_mode & 0777);
937
938       if (bfd == -1)
939         {
940           g_set_error_literal (error,
941                                G_IO_ERROR,
942                                G_IO_ERROR_CANT_CREATE_BACKUP,
943                                _("Backup file creation failed"));
944           g_free (backup_filename);
945           goto err_out;
946         }
947
948       /* If needed, Try to set the group of the backup same as the
949        * original file. If this fails, set the protection
950        * bits for the group same as the protection bits for
951        * others. */
952 #if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
953       if (fstat (bfd, &tmp_statbuf) != 0)
954         {
955           g_set_error_literal (error,
956                                G_IO_ERROR,
957                                G_IO_ERROR_CANT_CREATE_BACKUP,
958                                _("Backup file creation failed"));
959           g_unlink (backup_filename);
960           g_free (backup_filename);
961           goto err_out;
962         }
963       
964       if ((original_stat.st_gid != tmp_statbuf.st_gid)  &&
965           fchown (bfd, (uid_t) -1, original_stat.st_gid) != 0)
966         {
967           if (fchmod (bfd,
968                       (original_stat.st_mode & 0707) |
969                       ((original_stat.st_mode & 07) << 3)) != 0)
970             {
971               g_set_error_literal (error,
972                                    G_IO_ERROR,
973                                    G_IO_ERROR_CANT_CREATE_BACKUP,
974                                    _("Backup file creation failed"));
975               g_unlink (backup_filename);
976               close (bfd);
977               g_free (backup_filename);
978               goto err_out;
979             }
980         }
981 #endif
982
983       if (!copy_file_data (fd, bfd, NULL))
984         {
985           g_set_error_literal (error,
986                                G_IO_ERROR,
987                                G_IO_ERROR_CANT_CREATE_BACKUP,
988                                _("Backup file creation failed"));
989           g_unlink (backup_filename);
990           close (bfd);
991           g_free (backup_filename);
992           
993           goto err_out;
994         }
995       
996       close (bfd);
997       g_free (backup_filename);
998
999       /* Seek back to the start of the file after the backup copy */
1000       if (lseek (fd, 0, SEEK_SET) == -1)
1001         {
1002           int errsv = errno;
1003
1004           g_set_error (error, G_IO_ERROR,
1005                        g_io_error_from_errno (errsv),
1006                        _("Error seeking in file: %s"),
1007                        g_strerror (errsv));
1008           goto err_out;
1009         }
1010     }
1011
1012   if (flags & G_FILE_CREATE_REPLACE_DESTINATION)
1013     {
1014       close (fd);
1015       
1016       if (g_unlink (filename) != 0)
1017         {
1018           int errsv = errno;
1019           
1020           g_set_error (error, G_IO_ERROR,
1021                        g_io_error_from_errno (errsv),
1022                        _("Error removing old file: %s"),
1023                        g_strerror (errsv));
1024           goto err_out2;
1025         }
1026
1027       if (readable)
1028         open_flags = O_RDWR | O_CREAT | O_BINARY;
1029       else
1030         open_flags = O_WRONLY | O_CREAT | O_BINARY;
1031       fd = g_open (filename, open_flags, mode);
1032       if (fd == -1)
1033         {
1034           int errsv = errno;
1035           char *display_name = g_filename_display_name (filename);
1036           g_set_error (error, G_IO_ERROR,
1037                        g_io_error_from_errno (errsv),
1038                        _("Error opening file '%s': %s"),
1039                        display_name, g_strerror (errsv));
1040           g_free (display_name);
1041           goto err_out2;
1042         }
1043     }
1044   else
1045     {
1046       /* Truncate the file at the start */
1047 #ifdef G_OS_WIN32
1048       if (g_win32_ftruncate (fd, 0) == -1)
1049 #else
1050         if (ftruncate (fd, 0) == -1)
1051 #endif
1052           {
1053             int errsv = errno;
1054             
1055             g_set_error (error, G_IO_ERROR,
1056                          g_io_error_from_errno (errsv),
1057                          _("Error truncating file: %s"),
1058                          g_strerror (errsv));
1059             goto err_out;
1060           }
1061     }
1062     
1063   return fd;
1064
1065  err_out:
1066   close (fd);
1067  err_out2:
1068   return -1;
1069 }
1070
1071 GFileOutputStream *
1072 _g_local_file_output_stream_replace (const char        *filename,
1073                                      gboolean          readable,
1074                                      const char        *etag,
1075                                      gboolean           create_backup,
1076                                      GFileCreateFlags   flags,
1077                                      GCancellable      *cancellable,
1078                                      GError           **error)
1079 {
1080   GLocalFileOutputStream *stream;
1081   int mode;
1082   int fd;
1083   char *temp_file;
1084   gboolean sync_on_close;
1085   int open_flags;
1086
1087   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1088     return NULL;
1089
1090   temp_file = NULL;
1091
1092   if (flags & G_FILE_CREATE_PRIVATE)
1093     mode = 0600;
1094   else
1095     mode = 0666;
1096   sync_on_close = FALSE;
1097
1098   /* If the file doesn't exist, create it */
1099   open_flags = O_CREAT | O_EXCL | O_BINARY;
1100   if (readable)
1101     open_flags |= O_RDWR;
1102   else
1103     open_flags |= O_WRONLY;
1104   fd = g_open (filename, open_flags, mode);
1105
1106   if (fd == -1 && errno == EEXIST)
1107     {
1108       /* The file already exists */
1109       fd = handle_overwrite_open (filename, readable, etag,
1110                                   create_backup, &temp_file,
1111                                   flags, cancellable, error);
1112       if (fd == -1)
1113         return NULL;
1114
1115       /* If the final destination exists, we want to sync the newly written
1116        * file to ensure the data is on disk when we rename over the destination.
1117        * otherwise if we get a system crash we can lose both the new and the
1118        * old file on some filesystems. (I.E. those that don't guarantee the
1119        * data is written to the disk before the metadata.)
1120        */
1121       sync_on_close = TRUE;
1122     }
1123   else if (fd == -1)
1124     {
1125       int errsv = errno;
1126
1127       if (errsv == EINVAL)
1128         /* This must be an invalid filename, on e.g. FAT */
1129         g_set_error_literal (error, G_IO_ERROR,
1130                              G_IO_ERROR_INVALID_FILENAME,
1131                              _("Invalid filename"));
1132       else
1133         {
1134           char *display_name = g_filename_display_name (filename);
1135           g_set_error (error, G_IO_ERROR,
1136                        g_io_error_from_errno (errsv),
1137                        _("Error opening file '%s': %s"),
1138                        display_name, g_strerror (errsv));
1139           g_free (display_name);
1140         }
1141       return NULL;
1142     }
1143   
1144  
1145   stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
1146   stream->priv->fd = fd;
1147   stream->priv->sync_on_close = sync_on_close;
1148   stream->priv->tmp_filename = temp_file;
1149   if (create_backup)
1150     stream->priv->backup_filename = create_backup_filename (filename);
1151   stream->priv->original_filename =  g_strdup (filename);
1152   
1153   return G_FILE_OUTPUT_STREAM (stream);
1154 }