78875746f24ea2ff99860c5af75825da78e60fe4
[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 #define TS_stat stat
164 #define Trename rename
165 #define Tunlink unlink
166 #define Topen open
167 #define Tstat stat
168
169 TCHAR *
170 convert_to_filename_encoding (const char *s, size_t len UNUSED, const char *current_encoding UNUSED)
171 {
172   /* Non-windows systems don't care about the encoding.
173      The string is copied here, to be consistent with the w32 case.  */
174   return xstrdup (s);
175 }
176
177 #endif
178
179
180 struct replace_file
181 {
182   struct ll ll;
183   TCHAR *file_name;
184   TCHAR *tmp_name;
185
186   char *tmp_name_verbatim;
187   const char *file_name_verbatim;
188 };
189
190 static struct ll_list all_files = LL_INITIALIZER (all_files);
191
192 static void free_replace_file (struct replace_file *);
193 static void unlink_replace_files (void);
194
195 struct replace_file *
196 replace_file_start (const struct file_handle *fh, const char *mode,
197                     mode_t permissions, FILE **fp)
198 {
199   static bool registered;
200   struct TS_stat s;
201   struct replace_file *rf;
202   int fd;
203   int saved_errno = errno;
204
205   const char *file_name = fh_get_file_name (fh);
206
207   TCHAR * Tfile_name = convert_to_filename_encoding (file_name, strlen (file_name), fh_get_file_name_encoding (fh));
208
209   /* If FILE_NAME represents a special file, write to it directly
210      instead of trying to replace it. */
211   if (Tstat (Tfile_name, &s) == 0 && !S_ISREG (s.st_mode))
212     {
213       /* Open file descriptor. */
214       fd = Topen (Tfile_name, O_WRONLY);
215       if (fd < 0)
216         {
217           saved_errno = errno;
218           msg (ME, _("Opening %s for writing: %s."),
219                file_name, strerror (saved_errno));
220           free (Tfile_name);
221           return NULL;
222         }
223
224       /* Open file as stream. */
225       *fp = fdopen (fd, mode);
226       if (*fp == NULL)
227         {
228           saved_errno = errno;
229           msg (ME, _("Opening stream for %s: %s."),
230                file_name, strerror (saved_errno));
231           close (fd);
232           free (Tfile_name);
233           return NULL;
234         }
235
236       rf = xzalloc (sizeof *rf);
237       rf->file_name = NULL;
238       rf->tmp_name = Tfile_name;
239       return rf;
240     }
241
242   if (!registered)
243     {
244       at_fatal_signal (unlink_replace_files);
245       registered = true;
246     }
247   block_fatal_signals ();
248
249   rf = xzalloc (sizeof *rf);
250   rf->file_name = Tfile_name;
251   rf->file_name_verbatim = file_name;
252
253   for (;;)
254     {
255       /* Generate unique temporary file name. */
256       free (rf->tmp_name_verbatim);
257       rf->tmp_name_verbatim = xasprintf ("%stmpXXXXXX", file_name);
258       if (gen_tempname (rf->tmp_name_verbatim, 0, 0600, GT_NOCREATE) < 0)
259         {
260           saved_errno = errno;
261           msg (ME, _("Creating temporary file to replace %s: %s."),
262                file_name, strerror (saved_errno));
263           goto error;
264         }
265
266       rf->tmp_name = convert_to_filename_encoding (rf->tmp_name_verbatim, strlen (rf->tmp_name_verbatim), fh_get_file_name_encoding (fh));
267
268       /* Create file by that name. */
269       fd = Topen (rf->tmp_name, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, permissions);
270       if (fd >= 0)
271         break;
272       if (errno != EEXIST)
273         {
274           saved_errno = errno;
275           msg (ME, _("Creating temporary file %s: %s."),
276                rf->tmp_name_verbatim, strerror (saved_errno));
277           goto error;
278         }
279     }
280
281
282   /* Open file as stream. */
283   *fp = fdopen (fd, mode);
284   if (*fp == NULL)
285     {
286       saved_errno = errno;
287       msg (ME, _("Opening stream for temporary file %s: %s."),
288            rf->tmp_name_verbatim, strerror (saved_errno));
289       close (fd);
290       Tunlink (rf->tmp_name);
291       goto error;
292     }
293
294   /* Register file for deletion. */
295   ll_push_head (&all_files, &rf->ll);
296   unblock_fatal_signals ();
297
298   return rf;
299
300  error:
301   unblock_fatal_signals ();
302   free_replace_file (rf);
303   *fp = NULL;
304   errno = saved_errno;
305   return NULL;
306 }
307
308 bool
309 replace_file_commit (struct replace_file *rf)
310 {
311   bool ok = true;
312
313   if (rf->file_name != NULL)
314     {
315       int save_errno;
316
317       block_fatal_signals ();
318       ok = Trename (rf->tmp_name, rf->file_name) == 0;
319       save_errno = errno;
320       ll_remove (&rf->ll);
321       unblock_fatal_signals ();
322
323       if (!ok)
324         msg (ME, _("Replacing %s by %s: %s."),
325              rf->file_name_verbatim, rf->tmp_name_verbatim, strerror (save_errno));
326     }
327   else
328     {
329       /* Special file: no temporary file to rename. */
330     }
331   free_replace_file (rf);
332
333   return ok;
334 }
335
336 bool
337 replace_file_abort (struct replace_file *rf)
338 {
339   bool ok = true;
340
341   if (rf->file_name != NULL)
342     {
343       int save_errno;
344
345       block_fatal_signals ();
346       ok = Tunlink (rf->tmp_name) == 0;
347       save_errno = errno;
348       ll_remove (&rf->ll);
349       unblock_fatal_signals ();
350
351       if (!ok)
352         msg (ME, _("Removing %s: %s."), rf->tmp_name_verbatim, strerror (save_errno));
353     }
354   else
355     {
356       /* Special file: no temporary file to unlink. */
357     }
358   free_replace_file (rf);
359
360   return ok;
361 }
362
363 static void
364 free_replace_file (struct replace_file *rf)
365 {
366   free (rf->file_name);
367   free (rf->tmp_name);
368   free (rf->tmp_name_verbatim);
369   free (rf);
370 }
371
372 static void
373 unlink_replace_files (void)
374 {
375   struct replace_file *rf;
376
377   block_fatal_signals ();
378   ll_for_each (rf, struct replace_file, ll, &all_files)
379     {
380       /* We don't free_replace_file(RF) because calling free is unsafe
381          from an asynchronous signal handler. */
382       Tunlink (rf->tmp_name);
383     }
384   unblock_fatal_signals ();
385 }