f4456ca153aac03218e94120ecf71f212e6ff689
[pspp] / src / data / make-file.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2004, 2010, 2015 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "data/make-file.h"
20 #include "libpspp/i18n.h"
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30
31 #include "data/file-name.h"
32 #include "data/file-handle-def.h"
33 #include "libpspp/ll.h"
34 #include "libpspp/message.h"
35
36 #include "gl/fatal-signal.h"
37 #include "gl/tempname.h"
38 #include "gl/xalloc.h"
39 #include "gl/xvasprintf.h"
40 #include "gl/localcharset.h"
41
42 #include "gettext.h"
43 #define _(msgid) gettext (msgid)
44
45
46 #if defined _WIN32 || defined __WIN32__
47 #define WIN32_LEAN_AND_MEAN  /* avoid including junk */
48 #include <windows.h>
49 #define TS_stat _stat
50 #define Tunlink _wunlink
51 #define Topen _wopen
52 #define Tstat _wstat
53
54 /* Shamelessly lifted and modified from the rpl_rename function in Gnulib */
55 static int
56 Trename (TCHAR const *src, TCHAR const *dst)
57 {
58   int error;
59
60   /* MoveFileExW works if SRC is a directory without any flags, but
61      fails with MOVEFILE_REPLACE_EXISTING, so try without flags first.
62      Thankfully, MoveFileExW handles hard links correctly, even though
63      rename() does not.  */
64   if (MoveFileExW (src, dst, 0))
65     return 0;
66
67   /* Retry with MOVEFILE_REPLACE_EXISTING if the move failed
68      due to the destination already existing.  */
69   error = GetLastError ();
70   if (error == ERROR_FILE_EXISTS || error == ERROR_ALREADY_EXISTS)
71     {
72       if (MoveFileExW (src, dst, MOVEFILE_REPLACE_EXISTING))
73         return 0;
74
75       error = GetLastError ();
76     }
77
78   switch (error)
79     {
80     case ERROR_FILE_NOT_FOUND:
81     case ERROR_PATH_NOT_FOUND:
82     case ERROR_BAD_PATHNAME:
83     case ERROR_DIRECTORY:
84       errno = ENOENT;
85       break;
86
87     case ERROR_ACCESS_DENIED:
88     case ERROR_SHARING_VIOLATION:
89       errno = EACCES;
90       break;
91
92     case ERROR_OUTOFMEMORY:
93       errno = ENOMEM;
94       break;
95
96     case ERROR_CURRENT_DIRECTORY:
97       errno = EBUSY;
98       break;
99
100     case ERROR_NOT_SAME_DEVICE:
101       errno = EXDEV;
102       break;
103
104     case ERROR_WRITE_PROTECT:
105       errno = EROFS;
106       break;
107
108     case ERROR_WRITE_FAULT:
109     case ERROR_READ_FAULT:
110     case ERROR_GEN_FAILURE:
111       errno = EIO;
112       break;
113
114     case ERROR_HANDLE_DISK_FULL:
115     case ERROR_DISK_FULL:
116     case ERROR_DISK_TOO_FRAGMENTED:
117       errno = ENOSPC;
118       break;
119
120     case ERROR_FILE_EXISTS:
121     case ERROR_ALREADY_EXISTS:
122       errno = EEXIST;
123       break;
124
125     case ERROR_BUFFER_OVERFLOW:
126     case ERROR_FILENAME_EXCED_RANGE:
127       errno = ENAMETOOLONG;
128       break;
129
130     case ERROR_INVALID_NAME:
131     case ERROR_DELETE_PENDING:
132       errno = EPERM;        /* ? */
133       break;
134
135 # ifndef ERROR_FILE_TOO_LARGE
136 /* This value is documented but not defined in all versions of windows.h.  */
137 #  define ERROR_FILE_TOO_LARGE 223
138 # endif
139     case ERROR_FILE_TOO_LARGE:
140       errno = EFBIG;
141       break;
142
143     default:
144       errno = EINVAL;
145       break;
146     }
147
148   return -1;
149 }
150
151 TCHAR * 
152 convert_to_filename_encoding (const char *s, size_t len, const char *current_encoding)
153 {
154   const char *enc = current_encoding;
155   if (NULL == enc || 0 == strcmp (enc, "Auto"))
156     enc = locale_charset ();
157
158   return (TCHAR *) recode_string ("UTF-16LE", enc, s, len);
159 }
160
161
162 #else
163 typedef char TCHAR;
164 #define TS_stat stat
165 #define Trename rename
166 #define Tunlink unlink
167 #define Topen open
168 #define Tstat stat
169
170 TCHAR * 
171 convert_to_filename_encoding (const char *s, size_t len UNUSED, const char *current_encoding UNUSED)
172 {
173   /* Non-windows systems don't care about the encoding.  
174      The string is copied here, to be consistent with the w32 case.  */
175   return xstrdup (s);
176 }
177
178 #endif
179
180
181 struct replace_file
182 {
183   struct ll ll;
184   TCHAR *file_name;
185   TCHAR *tmp_name;
186
187   char *tmp_name_verbatim;
188   const char *file_name_verbatim;
189 };
190  
191 static struct ll_list all_files = LL_INITIALIZER (all_files);
192
193 static void free_replace_file (struct replace_file *);
194 static void unlink_replace_files (void);
195
196 struct replace_file *
197 replace_file_start (const struct file_handle *fh, const char *mode,
198                     mode_t permissions, FILE **fp)
199 {
200   static bool registered;
201   struct TS_stat s;
202   struct replace_file *rf;
203   int fd;
204   int saved_errno = errno;
205
206   const char *file_name = fh_get_file_name (fh);
207
208   TCHAR * Tfile_name = convert_to_filename_encoding (file_name, strlen (file_name), fh_get_file_name_encoding (fh));
209
210   /* If FILE_NAME represents a special file, write to it directly
211      instead of trying to replace it. */
212   if (Tstat (Tfile_name, &s) == 0 && !S_ISREG (s.st_mode))
213     {
214       /* Open file descriptor. */
215       fd = Topen (Tfile_name, O_WRONLY);
216       if (fd < 0)
217         {
218           saved_errno = errno;     
219           msg (ME, _("Opening %s for writing: %s."),
220                file_name, strerror (saved_errno));
221           free (Tfile_name);
222           return NULL;
223         }
224
225       /* Open file as stream. */
226       *fp = fdopen (fd, mode);
227       if (*fp == NULL)
228         {
229           saved_errno = errno;     
230           msg (ME, _("Opening stream for %s: %s."),
231                file_name, strerror (saved_errno));
232           close (fd);
233           free (Tfile_name);
234           return NULL;
235         }
236
237       rf = xzalloc (sizeof *rf);
238       rf->file_name = NULL;
239       rf->tmp_name = Tfile_name;
240       return rf;
241     }
242
243   if (!registered)
244     {
245       at_fatal_signal (unlink_replace_files);
246       registered = true;
247     }
248   block_fatal_signals ();
249
250   rf = xzalloc (sizeof *rf);
251   rf->file_name = Tfile_name;
252   rf->file_name_verbatim = file_name;
253
254   for (;;)
255     {
256       /* Generate unique temporary file name. */
257       free (rf->tmp_name_verbatim);
258       rf->tmp_name_verbatim = xasprintf ("%stmpXXXXXX", file_name);
259       if (gen_tempname (rf->tmp_name_verbatim, 0, 0600, GT_NOCREATE) < 0)
260         {
261           saved_errno = errno;
262           msg (ME, _("Creating temporary file to replace %s: %s."),
263                file_name, strerror (saved_errno));
264           goto error;
265         }
266
267       rf->tmp_name = convert_to_filename_encoding (rf->tmp_name_verbatim, strlen (rf->tmp_name_verbatim), fh_get_file_name_encoding (fh));
268
269       /* Create file by that name. */
270       fd = Topen (rf->tmp_name, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, permissions);
271       if (fd >= 0)
272         break;
273       if (errno != EEXIST)
274         {
275           saved_errno = errno;
276           msg (ME, _("Creating temporary file %s: %s."),
277                rf->tmp_name_verbatim, strerror (saved_errno));
278           goto error;
279         }
280     }
281
282
283   /* Open file as stream. */
284   *fp = fdopen (fd, mode);
285   if (*fp == NULL)
286     {
287       saved_errno = errno;
288       msg (ME, _("Opening stream for temporary file %s: %s."),
289            rf->tmp_name_verbatim, strerror (saved_errno));
290       close (fd);
291       Tunlink (rf->tmp_name);
292       goto error;
293     }
294
295   /* Register file for deletion. */
296   ll_push_head (&all_files, &rf->ll);
297   unblock_fatal_signals ();
298
299   return rf;
300
301  error:
302   unblock_fatal_signals ();
303   free_replace_file (rf);
304   *fp = NULL;
305   errno = saved_errno;
306   return NULL;
307 }
308
309 bool
310 replace_file_commit (struct replace_file *rf)
311 {
312   bool ok = true;
313
314   if (rf->file_name != NULL)
315     {
316       int save_errno;
317
318       block_fatal_signals ();
319       ok = Trename (rf->tmp_name, rf->file_name) == 0;
320       save_errno = errno;
321       ll_remove (&rf->ll);
322       unblock_fatal_signals ();
323
324       if (!ok)
325         msg (ME, _("Replacing %s by %s: %s."),
326              rf->file_name_verbatim, rf->tmp_name_verbatim, strerror (save_errno));
327     }
328   else
329     {
330       /* Special file: no temporary file to rename. */
331     }
332   free_replace_file (rf);
333
334   return ok;
335 }
336
337 bool
338 replace_file_abort (struct replace_file *rf)
339 {
340   bool ok = true;
341
342   if (rf->file_name != NULL)
343     {
344       int save_errno;
345
346       block_fatal_signals ();
347       ok = Tunlink (rf->tmp_name) == 0;
348       save_errno = errno;
349       ll_remove (&rf->ll);
350       unblock_fatal_signals ();
351
352       if (!ok)
353         msg (ME, _("Removing %s: %s."), rf->tmp_name_verbatim, strerror (save_errno));
354     }
355   else
356     {
357       /* Special file: no temporary file to unlink. */
358     }
359   free_replace_file (rf);
360
361   return ok;
362 }
363
364 static void
365 free_replace_file (struct replace_file *rf)
366 {
367   free (rf->file_name);
368   free (rf->tmp_name);
369   free (rf->tmp_name_verbatim);
370   free (rf);
371 }
372
373 static void
374 unlink_replace_files (void)
375 {
376   struct replace_file *rf;
377
378   block_fatal_signals ();
379   ll_for_each (rf, struct replace_file, ll, &all_files)
380     {
381       /* We don't free_replace_file(RF) because calling free is unsafe
382          from an asynchronous signal handler. */
383       Tunlink (rf->tmp_name);
384     }
385   unblock_fatal_signals ();
386 }