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