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