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