]> icculus.org git repositories - icculus/xz.git/blob - src/xz/file_io.c
Use past tense in error message in io_unlink().
[icculus/xz.git] / src / xz / file_io.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       file_io.c
4 /// \brief      File opening, unlinking, and closing
5 //
6 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #include "private.h"
14
15 #include <fcntl.h>
16
17 #ifdef TUKLIB_DOSLIKE
18 #       include <io.h>
19 #else
20 static bool warn_fchown;
21 #endif
22
23 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
24 #       include <sys/time.h>
25 #elif defined(HAVE_UTIME)
26 #       include <utime.h>
27 #endif
28
29 #include "tuklib_open_stdxxx.h"
30
31 #ifndef O_BINARY
32 #       define O_BINARY 0
33 #endif
34
35 #ifndef O_NOCTTY
36 #       define O_NOCTTY 0
37 #endif
38
39
40 /// If true, try to create sparse files when decompressing.
41 static bool try_sparse = true;
42
43 #ifndef TUKLIB_DOSLIKE
44 /// File status flags of standard output. This is used by io_open_dest()
45 /// and io_close_dest().
46 static int stdout_flags = 0;
47 #endif
48
49
50 static bool io_write_buf(file_pair *pair, const uint8_t *buf, size_t size);
51
52
53 extern void
54 io_init(void)
55 {
56         // Make sure that stdin, stdout, and and stderr are connected to
57         // a valid file descriptor. Exit immediatelly with exit code ERROR
58         // if we cannot make the file descriptors valid. Maybe we should
59         // print an error message, but our stderr could be screwed anyway.
60         tuklib_open_stdxxx(E_ERROR);
61
62 #ifndef TUKLIB_DOSLIKE
63         // If fchown() fails setting the owner, we warn about it only if
64         // we are root.
65         warn_fchown = geteuid() == 0;
66 #endif
67
68 #ifdef __DJGPP__
69         // Avoid doing useless things when statting files.
70         // This isn't important but doesn't hurt.
71         _djstat_flags = _STAT_INODE | _STAT_EXEC_EXT
72                         | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
73 #endif
74
75         return;
76 }
77
78
79 extern void
80 io_no_sparse(void)
81 {
82         try_sparse = false;
83         return;
84 }
85
86
87 /// \brief      Unlink a file
88 ///
89 /// This tries to verify that the file being unlinked really is the file that
90 /// we want to unlink by verifying device and inode numbers. There's still
91 /// a small unavoidable race, but this is much better than nothing (the file
92 /// could have been moved/replaced even hours earlier).
93 static void
94 io_unlink(const char *name, const struct stat *known_st)
95 {
96 #if defined(TUKLIB_DOSLIKE)
97         // On DOS-like systems, st_ino is meaningless, so don't bother
98         // testing it. Just silence a compiler warning.
99         (void)known_st;
100 #else
101         struct stat new_st;
102
103         if (lstat(name, &new_st)
104 #       ifdef __VMS
105                         // st_ino is an array, and we don't want to
106                         // compare st_dev at all.
107                         || memcmp(&new_st.st_ino, &known_st->st_ino,
108                                 sizeof(new_st.st_ino)) != 0
109 #       else
110                         // Typical POSIX-like system
111                         || new_st.st_dev != known_st->st_dev
112                         || new_st.st_ino != known_st->st_ino
113 #       endif
114                         )
115                 // TRANSLATORS: When compression or decompression finishes,
116                 // and xz is going to remove the source file, xz first checks
117                 // if the source file still exists, and if it does, does its
118                 // device and inode numbers match what xz saw when it opened
119                 // the source file. If these checks fail, this message is
120                 // shown, %s being the filename, and the file is not deleted.
121                 // The check for device and inode numbers is there, because
122                 // it is possible that the user has put a new file in place
123                 // of the original file, and in that case it obviously
124                 // shouldn't be removed.
125                 message_error(_("%s: File seems to have been moved, "
126                                 "not removing"), name);
127         else
128 #endif
129                 // There's a race condition between lstat() and unlink()
130                 // but at least we have tried to avoid removing wrong file.
131                 if (unlink(name))
132                         message_error(_("%s: Cannot remove: %s"),
133                                         name, strerror(errno));
134
135         return;
136 }
137
138
139 /// \brief      Copies owner/group and permissions
140 ///
141 /// \todo       ACL and EA support
142 ///
143 static void
144 io_copy_attrs(const file_pair *pair)
145 {
146         // Skip chown and chmod on Windows.
147 #ifndef TUKLIB_DOSLIKE
148         // This function is more tricky than you may think at first.
149         // Blindly copying permissions may permit users to access the
150         // destination file who didn't have permission to access the
151         // source file.
152
153         // Try changing the owner of the file. If we aren't root or the owner
154         // isn't already us, fchown() probably doesn't succeed. We warn
155         // about failing fchown() only if we are root.
156         if (fchown(pair->dest_fd, pair->src_st.st_uid, -1) && warn_fchown)
157                 message_warning(_("%s: Cannot set the file owner: %s"),
158                                 pair->dest_name, strerror(errno));
159
160         mode_t mode;
161
162         if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
163                 message_warning(_("%s: Cannot set the file group: %s"),
164                                 pair->dest_name, strerror(errno));
165                 // We can still safely copy some additional permissions:
166                 // `group' must be at least as strict as `other' and
167                 // also vice versa.
168                 //
169                 // NOTE: After this, the owner of the source file may
170                 // get additional permissions. This shouldn't be too bad,
171                 // because the owner would have had permission to chmod
172                 // the original file anyway.
173                 mode = ((pair->src_st.st_mode & 0070) >> 3)
174                                 & (pair->src_st.st_mode & 0007);
175                 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
176         } else {
177                 // Drop the setuid, setgid, and sticky bits.
178                 mode = pair->src_st.st_mode & 0777;
179         }
180
181         if (fchmod(pair->dest_fd, mode))
182                 message_warning(_("%s: Cannot set the file permissions: %s"),
183                                 pair->dest_name, strerror(errno));
184 #endif
185
186         // Copy the timestamps. We have several possible ways to do this, of
187         // which some are better in both security and precision.
188         //
189         // First, get the nanosecond part of the timestamps. As of writing,
190         // it's not standardized by POSIX, and there are several names for
191         // the same thing in struct stat.
192         long atime_nsec;
193         long mtime_nsec;
194
195 #       if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
196         // GNU and Solaris
197         atime_nsec = pair->src_st.st_atim.tv_nsec;
198         mtime_nsec = pair->src_st.st_mtim.tv_nsec;
199
200 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
201         // BSD
202         atime_nsec = pair->src_st.st_atimespec.tv_nsec;
203         mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
204
205 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
206         // GNU and BSD without extensions
207         atime_nsec = pair->src_st.st_atimensec;
208         mtime_nsec = pair->src_st.st_mtimensec;
209
210 #       elif defined(HAVE_STRUCT_STAT_ST_UATIME)
211         // Tru64
212         atime_nsec = pair->src_st.st_uatime * 1000;
213         mtime_nsec = pair->src_st.st_umtime * 1000;
214
215 #       elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
216         // UnixWare
217         atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
218         mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
219
220 #       else
221         // Safe fallback
222         atime_nsec = 0;
223         mtime_nsec = 0;
224 #       endif
225
226         // Construct a structure to hold the timestamps and call appropriate
227         // function to set the timestamps.
228 #if defined(HAVE_FUTIMENS)
229         // Use nanosecond precision.
230         struct timespec tv[2];
231         tv[0].tv_sec = pair->src_st.st_atime;
232         tv[0].tv_nsec = atime_nsec;
233         tv[1].tv_sec = pair->src_st.st_mtime;
234         tv[1].tv_nsec = mtime_nsec;
235
236         (void)futimens(pair->dest_fd, tv);
237
238 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
239         // Use microsecond precision.
240         struct timeval tv[2];
241         tv[0].tv_sec = pair->src_st.st_atime;
242         tv[0].tv_usec = atime_nsec / 1000;
243         tv[1].tv_sec = pair->src_st.st_mtime;
244         tv[1].tv_usec = mtime_nsec / 1000;
245
246 #       if defined(HAVE_FUTIMES)
247         (void)futimes(pair->dest_fd, tv);
248 #       elif defined(HAVE_FUTIMESAT)
249         (void)futimesat(pair->dest_fd, NULL, tv);
250 #       else
251         // Argh, no function to use a file descriptor to set the timestamp.
252         (void)utimes(pair->dest_name, tv);
253 #       endif
254
255 #elif defined(HAVE_UTIME)
256         // Use one-second precision. utime() doesn't support using file
257         // descriptor either. Some systems have broken utime() prototype
258         // so don't make this const.
259         struct utimbuf buf = {
260                 .actime = pair->src_st.st_atime,
261                 .modtime = pair->src_st.st_mtime,
262         };
263
264         // Avoid warnings.
265         (void)atime_nsec;
266         (void)mtime_nsec;
267
268         (void)utime(pair->dest_name, &buf);
269 #endif
270
271         return;
272 }
273
274
275 /// Opens the source file. Returns false on success, true on error.
276 static bool
277 io_open_src(file_pair *pair)
278 {
279         // There's nothing to open when reading from stdin.
280         if (pair->src_name == stdin_filename) {
281                 pair->src_fd = STDIN_FILENO;
282 #ifdef TUKLIB_DOSLIKE
283                 setmode(STDIN_FILENO, O_BINARY);
284 #endif
285                 return false;
286         }
287
288         // Symlinks are not followed unless writing to stdout or --force
289         // was used.
290         const bool follow_symlinks = opt_stdout || opt_force;
291
292         // We accept only regular files if we are writing the output
293         // to disk too. bzip2 allows overriding this with --force but
294         // gzip and xz don't.
295         const bool reg_files_only = !opt_stdout;
296
297         // Flags for open()
298         int flags = O_RDONLY | O_BINARY | O_NOCTTY;
299
300 #ifndef TUKLIB_DOSLIKE
301         // If we accept only regular files, we need to be careful to avoid
302         // problems with special files like devices and FIFOs. O_NONBLOCK
303         // prevents blocking when opening such files. When we want to accept
304         // special files, we must not use O_NONBLOCK, or otherwise we won't
305         // block waiting e.g. FIFOs to become readable.
306         if (reg_files_only)
307                 flags |= O_NONBLOCK;
308 #endif
309
310 #if defined(O_NOFOLLOW)
311         if (!follow_symlinks)
312                 flags |= O_NOFOLLOW;
313 #elif !defined(TUKLIB_DOSLIKE)
314         // Some POSIX-like systems lack O_NOFOLLOW (it's not required
315         // by POSIX). Check for symlinks with a separate lstat() on
316         // these systems.
317         if (!follow_symlinks) {
318                 struct stat st;
319                 if (lstat(pair->src_name, &st)) {
320                         message_error("%s: %s", pair->src_name,
321                                         strerror(errno));
322                         return true;
323
324                 } else if (S_ISLNK(st.st_mode)) {
325                         message_warning(_("%s: Is a symbolic link, "
326                                         "skipping"), pair->src_name);
327                         return true;
328                 }
329         }
330 #endif
331
332         // Try to open the file. If we are accepting non-regular files,
333         // unblock the caught signals so that open() can be interrupted
334         // if it blocks e.g. due to a FIFO file.
335         if (!reg_files_only)
336                 signals_unblock();
337
338         // Maybe this wouldn't need a loop, since all the signal handlers for
339         // which we don't use SA_RESTART set user_abort to true. But it
340         // doesn't hurt to have it just in case.
341         do {
342                 pair->src_fd = open(pair->src_name, flags);
343         } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
344
345         if (!reg_files_only)
346                 signals_block();
347
348         if (pair->src_fd == -1) {
349                 // If we were interrupted, don't display any error message.
350                 if (errno == EINTR) {
351                         // All the signals that don't have SA_RESTART
352                         // set user_abort.
353                         assert(user_abort);
354                         return true;
355                 }
356
357 #ifdef O_NOFOLLOW
358                 // Give an understandable error message in if reason
359                 // for failing was that the file was a symbolic link.
360                 //
361                 // Note that at least Linux, OpenBSD, Solaris, and Darwin
362                 // use ELOOP to indicate if O_NOFOLLOW was the reason
363                 // that open() failed. Because there may be
364                 // directories in the pathname, ELOOP may occur also
365                 // because of a symlink loop in the directory part.
366                 // So ELOOP doesn't tell us what actually went wrong.
367                 //
368                 // FreeBSD associates EMLINK with O_NOFOLLOW and
369                 // Tru64 uses ENOTSUP. We use these directly here
370                 // and skip the lstat() call and the associated race.
371                 // I want to hear if there are other kernels that
372                 // fail with something else than ELOOP with O_NOFOLLOW.
373                 bool was_symlink = false;
374
375 #       if defined(__FreeBSD__) || defined(__DragonFly__)
376                 if (errno == EMLINK)
377                         was_symlink = true;
378
379 #       elif defined(__digital__) && defined(__unix__)
380                 if (errno == ENOTSUP)
381                         was_symlink = true;
382
383 #       elif defined(__NetBSD__)
384                 // FIXME? As of 2008-11-20, NetBSD doesn't document what
385                 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
386                 // but since it isn't documented, it may be wrong to rely
387                 // on it here.
388                 if (errno == EFTYPE)
389                         was_symlink = true;
390
391 #       else
392                 if (errno == ELOOP && !follow_symlinks) {
393                         const int saved_errno = errno;
394                         struct stat st;
395                         if (lstat(pair->src_name, &st) == 0
396                                         && S_ISLNK(st.st_mode))
397                                 was_symlink = true;
398
399                         errno = saved_errno;
400                 }
401 #       endif
402
403                 if (was_symlink)
404                         message_warning(_("%s: Is a symbolic link, "
405                                         "skipping"), pair->src_name);
406                 else
407 #endif
408                         // Something else than O_NOFOLLOW failing
409                         // (assuming that the race conditions didn't
410                         // confuse us).
411                         message_error("%s: %s", pair->src_name,
412                                         strerror(errno));
413
414                 return true;
415         }
416
417 #ifndef TUKLIB_DOSLIKE
418         // Drop O_NONBLOCK, which is used only when we are accepting only
419         // regular files. After the open() call, we want things to block
420         // instead of giving EAGAIN.
421         if (reg_files_only) {
422                 flags = fcntl(pair->src_fd, F_GETFL);
423                 if (flags == -1)
424                         goto error_msg;
425
426                 flags &= ~O_NONBLOCK;
427
428                 if (fcntl(pair->src_fd, F_SETFL, flags))
429                         goto error_msg;
430         }
431 #endif
432
433         // Stat the source file. We need the result also when we copy
434         // the permissions, and when unlinking.
435         if (fstat(pair->src_fd, &pair->src_st))
436                 goto error_msg;
437
438         if (S_ISDIR(pair->src_st.st_mode)) {
439                 message_warning(_("%s: Is a directory, skipping"),
440                                 pair->src_name);
441                 goto error;
442         }
443
444         if (reg_files_only) {
445                 if (!S_ISREG(pair->src_st.st_mode)) {
446                         message_warning(_("%s: Not a regular file, "
447                                         "skipping"), pair->src_name);
448                         goto error;
449                 }
450
451                 // These are meaningless on Windows.
452 #ifndef TUKLIB_DOSLIKE
453                 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
454                         // gzip rejects setuid and setgid files even
455                         // when --force was used. bzip2 doesn't check
456                         // for them, but calls fchown() after fchmod(),
457                         // and many systems automatically drop setuid
458                         // and setgid bits there.
459                         //
460                         // We accept setuid and setgid files if
461                         // --force was used. We drop these bits
462                         // explicitly in io_copy_attr().
463                         message_warning(_("%s: File has setuid or "
464                                         "setgid bit set, skipping"),
465                                         pair->src_name);
466                         goto error;
467                 }
468
469                 if (pair->src_st.st_mode & S_ISVTX) {
470                         message_warning(_("%s: File has sticky bit "
471                                         "set, skipping"),
472                                         pair->src_name);
473                         goto error;
474                 }
475
476                 if (pair->src_st.st_nlink > 1) {
477                         message_warning(_("%s: Input file has more "
478                                         "than one hard link, "
479                                         "skipping"), pair->src_name);
480                         goto error;
481                 }
482 #endif
483         }
484
485         return false;
486
487 error_msg:
488         message_error("%s: %s", pair->src_name, strerror(errno));
489 error:
490         (void)close(pair->src_fd);
491         return true;
492 }
493
494
495 /// \brief      Closes source file of the file_pair structure
496 ///
497 /// \param      pair    File whose src_fd should be closed
498 /// \param      success If true, the file will be removed from the disk if
499 ///                     closing succeeds and --keep hasn't been used.
500 static void
501 io_close_src(file_pair *pair, bool success)
502 {
503         if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
504 #ifdef TUKLIB_DOSLIKE
505                 (void)close(pair->src_fd);
506 #endif
507
508                 // If we are going to unlink(), do it before closing the file.
509                 // This way there's no risk that someone replaces the file and
510                 // happens to get same inode number, which would make us
511                 // unlink() wrong file.
512                 //
513                 // NOTE: DOS-like systems are an exception to this, because
514                 // they don't allow unlinking files that are open. *sigh*
515                 if (success && !opt_keep_original)
516                         io_unlink(pair->src_name, &pair->src_st);
517
518 #ifndef TUKLIB_DOSLIKE
519                 (void)close(pair->src_fd);
520 #endif
521         }
522
523         return;
524 }
525
526
527 static bool
528 io_open_dest(file_pair *pair)
529 {
530         if (opt_stdout || pair->src_fd == STDIN_FILENO) {
531                 // We don't modify or free() this.
532                 pair->dest_name = (char *)"(stdout)";
533                 pair->dest_fd = STDOUT_FILENO;
534 #ifdef TUKLIB_DOSLIKE
535                 setmode(STDOUT_FILENO, O_BINARY);
536 #endif
537         } else {
538                 pair->dest_name = suffix_get_dest_name(pair->src_name);
539                 if (pair->dest_name == NULL)
540                         return true;
541
542                 // If --force was used, unlink the target file first.
543                 if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
544                         message_error(_("%s: Cannot remove: %s"),
545                                         pair->dest_name, strerror(errno));
546                         free(pair->dest_name);
547                         return true;
548                 }
549
550                 // Open the file.
551                 const int flags = O_WRONLY | O_BINARY | O_NOCTTY
552                                 | O_CREAT | O_EXCL;
553                 const mode_t mode = S_IRUSR | S_IWUSR;
554                 pair->dest_fd = open(pair->dest_name, flags, mode);
555
556                 if (pair->dest_fd == -1) {
557                         // Don't bother with error message if user requested
558                         // us to exit anyway.
559                         if (!user_abort)
560                                 message_error("%s: %s", pair->dest_name,
561                                                 strerror(errno));
562
563                         free(pair->dest_name);
564                         return true;
565                 }
566         }
567
568         // If this really fails... well, we have a safe fallback.
569         if (fstat(pair->dest_fd, &pair->dest_st)) {
570 #if defined(__VMS)
571                 pair->dest_st.st_ino[0] = 0;
572                 pair->dest_st.st_ino[1] = 0;
573                 pair->dest_st.st_ino[2] = 0;
574 #elif !defined(TUKLIB_DOSLIKE)
575                 pair->dest_st.st_dev = 0;
576                 pair->dest_st.st_ino = 0;
577 #endif
578 #ifndef TUKLIB_DOSLIKE
579         } else if (try_sparse && opt_mode == MODE_DECOMPRESS) {
580                 // When writing to standard output, we need to be extra
581                 // careful:
582                 //  - It may be connected to something else than
583                 //    a regular file.
584                 //  - We aren't necessarily writing to a new empty file
585                 //    or to the end of an existing file.
586                 //  - O_APPEND may be active.
587                 //
588                 // TODO: I'm keeping this disabled for DOS-like systems
589                 // for now. FAT doesn't support sparse files, but NTFS
590                 // does, so maybe this should be enabled on Windows after
591                 // some testing.
592                 if (pair->dest_fd == STDOUT_FILENO) {
593                         if (!S_ISREG(pair->dest_st.st_mode))
594                                 return false;
595
596                         const int flags = fcntl(STDOUT_FILENO, F_GETFL);
597                         if (flags == -1)
598                                 return false;
599
600                         if (flags & O_APPEND) {
601                                 // Creating a sparse file is not possible
602                                 // when O_APPEND is active (it's used by
603                                 // shell's >> redirection). As I understand
604                                 // it, it is safe to temporarily disable
605                                 // O_APPEND in xz, because if someone
606                                 // happened to write to the same file at the
607                                 // same time, results would be bad anyway
608                                 // (users shouldn't assume that xz uses any
609                                 // specific block size when writing data).
610                                 //
611                                 // The write position may be something else
612                                 // than the end of the file, so we must fix
613                                 // it to start writing at the end of the file
614                                 // to imitate O_APPEND.
615                                 if (lseek(STDOUT_FILENO, 0, SEEK_END) == -1)
616                                         return false;
617
618                                 if (fcntl(STDOUT_FILENO, F_SETFL,
619                                                 stdout_flags & ~O_APPEND))
620                                         return false;
621
622                                 // Remember the flags so that io_close_dest()
623                                 // can restore them.
624                                 stdout_flags = flags;
625
626                         } else if (lseek(STDOUT_FILENO, 0, SEEK_CUR)
627                                         != pair->dest_st.st_size) {
628                                 // Writing won't start exactly at the end
629                                 // of the file. We cannot use sparse output,
630                                 // because it would probably corrupt the file.
631                                 return false;
632                         }
633                 }
634
635                 pair->dest_try_sparse = true;
636 #endif
637         }
638
639         return false;
640 }
641
642
643 /// \brief      Closes destination file of the file_pair structure
644 ///
645 /// \param      pair    File whose dest_fd should be closed
646 /// \param      success If false, the file will be removed from the disk.
647 ///
648 /// \return     Zero if closing succeeds. On error, -1 is returned and
649 ///             error message printed.
650 static int
651 io_close_dest(file_pair *pair, bool success)
652 {
653 #ifndef TUKLIB_DOSLIKE
654         // If io_open_dest() has disabled O_APPEND, restore it here.
655         if (stdout_flags != 0) {
656                 assert(pair->dest_fd == STDOUT_FILENO);
657
658                 const int fail = fcntl(STDOUT_FILENO, F_SETFL, stdout_flags);
659                 stdout_flags = 0;
660
661                 if (fail) {
662                         message_error(_("Error restoring the O_APPEND flag "
663                                         "to standard output: %s"),
664                                         strerror(errno));
665                         return -1;
666                 }
667         }
668 #endif
669
670         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
671                 return 0;
672
673         if (close(pair->dest_fd)) {
674                 message_error(_("%s: Closing the file failed: %s"),
675                                 pair->dest_name, strerror(errno));
676
677                 // Closing destination file failed, so we cannot trust its
678                 // contents. Get rid of junk:
679                 io_unlink(pair->dest_name, &pair->dest_st);
680                 free(pair->dest_name);
681                 return -1;
682         }
683
684         // If the operation using this file wasn't successful, we git rid
685         // of the junk file.
686         if (!success)
687                 io_unlink(pair->dest_name, &pair->dest_st);
688
689         free(pair->dest_name);
690
691         return 0;
692 }
693
694
695 extern file_pair *
696 io_open(const char *src_name)
697 {
698         if (is_empty_filename(src_name))
699                 return NULL;
700
701         // Since we have only one file open at a time, we can use
702         // a statically allocated structure.
703         static file_pair pair;
704
705         pair = (file_pair){
706                 .src_name = src_name,
707                 .dest_name = NULL,
708                 .src_fd = -1,
709                 .dest_fd = -1,
710                 .src_eof = false,
711                 .dest_try_sparse = false,
712                 .dest_pending_sparse = 0,
713         };
714
715         // Block the signals, for which we have a custom signal handler, so
716         // that we don't need to worry about EINTR.
717         signals_block();
718
719         file_pair *ret = NULL;
720         if (!io_open_src(&pair)) {
721                 // io_open_src() may have unblocked the signals temporarily,
722                 // and thus user_abort may have got set even if open()
723                 // succeeded.
724                 if (user_abort || io_open_dest(&pair))
725                         io_close_src(&pair, false);
726                 else
727                         ret = &pair;
728         }
729
730         signals_unblock();
731
732         return ret;
733 }
734
735
736 extern void
737 io_close(file_pair *pair, bool success)
738 {
739         // Take care of sparseness at the end of the output file.
740         if (success && pair->dest_try_sparse
741                         && pair->dest_pending_sparse > 0) {
742                 // Seek forward one byte less than the size of the pending
743                 // hole, then write one zero-byte. This way the file grows
744                 // to its correct size. An alternative would be to use
745                 // ftruncate() but that isn't portable enough (e.g. it
746                 // doesn't work with FAT on Linux; FAT isn't that important
747                 // since it doesn't support sparse files anyway, but we don't
748                 // want to create corrupt files on it).
749                 if (lseek(pair->dest_fd, pair->dest_pending_sparse - 1,
750                                 SEEK_CUR) == -1) {
751                         message_error(_("%s: Seeking failed when trying "
752                                         "to create a sparse file: %s"),
753                                         pair->dest_name, strerror(errno));
754                         success = false;
755                 } else {
756                         const uint8_t zero[1] = { '\0' };
757                         if (io_write_buf(pair, zero, 1))
758                                 success = false;
759                 }
760         }
761
762         signals_block();
763
764         if (success && pair->dest_fd != STDOUT_FILENO)
765                 io_copy_attrs(pair);
766
767         // Close the destination first. If it fails, we must not remove
768         // the source file!
769         if (io_close_dest(pair, success))
770                 success = false;
771
772         // Close the source file, and unlink it if the operation using this
773         // file pair was successful and we haven't requested to keep the
774         // source file.
775         io_close_src(pair, success);
776
777         signals_unblock();
778
779         return;
780 }
781
782
783 extern size_t
784 io_read(file_pair *pair, io_buf *buf_union, size_t size)
785 {
786         // We use small buffers here.
787         assert(size < SSIZE_MAX);
788
789         uint8_t *buf = buf_union->u8;
790         size_t left = size;
791
792         while (left > 0) {
793                 const ssize_t amount = read(pair->src_fd, buf, left);
794
795                 if (amount == 0) {
796                         pair->src_eof = true;
797                         break;
798                 }
799
800                 if (amount == -1) {
801                         if (errno == EINTR) {
802                                 if (user_abort)
803                                         return SIZE_MAX;
804
805                                 continue;
806                         }
807
808                         message_error(_("%s: Read error: %s"),
809                                         pair->src_name, strerror(errno));
810
811                         // FIXME Is this needed?
812                         pair->src_eof = true;
813
814                         return SIZE_MAX;
815                 }
816
817                 buf += (size_t)(amount);
818                 left -= (size_t)(amount);
819         }
820
821         return size - left;
822 }
823
824
825 extern bool
826 io_pread(file_pair *pair, io_buf *buf, size_t size, off_t pos)
827 {
828         // Using lseek() and read() is more portable than pread() and
829         // for us it is as good as real pread().
830         if (lseek(pair->src_fd, pos, SEEK_SET) != pos) {
831                 message_error(_("%s: Error seeking the file: %s"),
832                                 pair->src_name, strerror(errno));
833                 return true;
834         }
835
836         const size_t amount = io_read(pair, buf, size);
837         if (amount == SIZE_MAX)
838                 return true;
839
840         if (amount != size) {
841                 message_error(_("%s: Unexpected end of file"),
842                                 pair->src_name);
843                 return true;
844         }
845
846         return false;
847 }
848
849
850 static bool
851 is_sparse(const io_buf *buf)
852 {
853         assert(IO_BUFFER_SIZE % sizeof(uint64_t) == 0);
854
855         for (size_t i = 0; i < ARRAY_SIZE(buf->u64); ++i)
856                 if (buf->u64[i] != 0)
857                         return false;
858
859         return true;
860 }
861
862
863 static bool
864 io_write_buf(file_pair *pair, const uint8_t *buf, size_t size)
865 {
866         assert(size < SSIZE_MAX);
867
868         while (size > 0) {
869                 const ssize_t amount = write(pair->dest_fd, buf, size);
870                 if (amount == -1) {
871                         if (errno == EINTR) {
872                                 if (user_abort)
873                                         return -1;
874
875                                 continue;
876                         }
877
878                         // Handle broken pipe specially. gzip and bzip2
879                         // don't print anything on SIGPIPE. In addition,
880                         // gzip --quiet uses exit status 2 (warning) on
881                         // broken pipe instead of whatever raise(SIGPIPE)
882                         // would make it return. It is there to hide "Broken
883                         // pipe" message on some old shells (probably old
884                         // GNU bash).
885                         //
886                         // We don't do anything special with --quiet, which
887                         // is what bzip2 does too. If we get SIGPIPE, we
888                         // will handle it like other signals by setting
889                         // user_abort, and get EPIPE here.
890                         if (errno != EPIPE)
891                                 message_error(_("%s: Write error: %s"),
892                                         pair->dest_name, strerror(errno));
893
894                         return true;
895                 }
896
897                 buf += (size_t)(amount);
898                 size -= (size_t)(amount);
899         }
900
901         return false;
902 }
903
904
905 extern bool
906 io_write(file_pair *pair, const io_buf *buf, size_t size)
907 {
908         assert(size <= IO_BUFFER_SIZE);
909
910         if (pair->dest_try_sparse) {
911                 // Check if the block is sparse (contains only zeros). If it
912                 // sparse, we just store the amount and return. We will take
913                 // care of actually skipping over the hole when we hit the
914                 // next data block or close the file.
915                 //
916                 // Since io_close() requires that dest_pending_sparse > 0
917                 // if the file ends with sparse block, we must also return
918                 // if size == 0 to avoid doing the lseek().
919                 if (size == IO_BUFFER_SIZE) {
920                         if (is_sparse(buf)) {
921                                 pair->dest_pending_sparse += size;
922                                 return false;
923                         }
924                 } else if (size == 0) {
925                         return false;
926                 }
927
928                 // This is not a sparse block. If we have a pending hole,
929                 // skip it now.
930                 if (pair->dest_pending_sparse > 0) {
931                         if (lseek(pair->dest_fd, pair->dest_pending_sparse,
932                                         SEEK_CUR) == -1) {
933                                 message_error(_("%s: Seeking failed when "
934                                                 "trying to create a sparse "
935                                                 "file: %s"), pair->dest_name,
936                                                 strerror(errno));
937                                 return true;
938                         }
939
940                         pair->dest_pending_sparse = 0;
941                 }
942         }
943
944         return io_write_buf(pair, buf->u8, size);
945 }