]> icculus.org git repositories - icculus/xz.git/blob - src/xz/io.c
Renamed lzma to xz and lzmadec to xzdec. We create symlinks
[icculus/xz.git] / src / xz / io.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       io.c
4 /// \brief      File opening, unlinking, and closing
5 //
6 //  Copyright (C) 2007 Lasse Collin
7 //
8 //  This program is free software; you can redistribute it and/or
9 //  modify it under the terms of the GNU Lesser General Public
10 //  License as published by the Free Software Foundation; either
11 //  version 2.1 of the License, or (at your option) any later version.
12 //
13 //  This program is distributed in the hope that it will be useful,
14 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 //  Lesser General Public License for more details.
17 //
18 ///////////////////////////////////////////////////////////////////////////////
19
20 #include "private.h"
21
22 #include <fcntl.h>
23
24 #if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
25 #       include <sys/time.h>
26 #elif defined(HAVE_UTIME)
27 #       include <utime.h>
28 #endif
29
30
31 /// \brief      Unlinks a file
32 ///
33 /// This tries to verify that the file being unlinked really is the file that
34 /// we want to unlink by verifying device and inode numbers. There's still
35 /// a small unavoidable race, but this is much better than nothing (the file
36 /// could have been moved/replaced even hours earlier).
37 static void
38 io_unlink(const char *name, const struct stat *known_st)
39 {
40         struct stat new_st;
41
42         if (lstat(name, &new_st)
43                         || new_st.st_dev != known_st->st_dev
44                         || new_st.st_ino != known_st->st_ino) {
45                 message_error(_("%s: File seems to be moved, not removing"),
46                                 name);
47         } else {
48                 // There's a race condition between lstat() and unlink()
49                 // but at least we have tried to avoid removing wrong file.
50                 if (unlink(name))
51                         message_error(_("%s: Cannot remove: %s"),
52                                         name, strerror(errno));
53         }
54
55         return;
56 }
57
58
59 /// \brief      Copies owner/group and permissions
60 ///
61 /// \todo       ACL and EA support
62 ///
63 static void
64 io_copy_attrs(const file_pair *pair)
65 {
66         // This function is more tricky than you may think at first.
67         // Blindly copying permissions may permit users to access the
68         // destination file who didn't have permission to access the
69         // source file.
70
71         // Simple cache to avoid repeated calls to geteuid().
72         static enum {
73                 WARN_FCHOWN_UNKNOWN,
74                 WARN_FCHOWN_NO,
75                 WARN_FCHOWN_YES,
76         } warn_fchown = WARN_FCHOWN_UNKNOWN;
77
78         // Try changing the owner of the file. If we aren't root or the owner
79         // isn't already us, fchown() probably doesn't succeed. We warn
80         // about failing fchown() only if we are root.
81         if (fchown(pair->dest_fd, pair->src_st.st_uid, -1)
82                         && warn_fchown != WARN_FCHOWN_NO) {
83                 if (warn_fchown == WARN_FCHOWN_UNKNOWN)
84                         warn_fchown = geteuid() == 0
85                                         ? WARN_FCHOWN_YES : WARN_FCHOWN_NO;
86
87                 if (warn_fchown == WARN_FCHOWN_YES)
88                         message_warning(_("%s: Cannot set the file owner: %s"),
89                                         pair->dest_name, strerror(errno));
90         }
91
92         mode_t mode;
93
94         if (fchown(pair->dest_fd, -1, pair->src_st.st_gid)) {
95                 message_warning(_("%s: Cannot set the file group: %s"),
96                                 pair->dest_name, strerror(errno));
97                 // We can still safely copy some additional permissions:
98                 // `group' must be at least as strict as `other' and
99                 // also vice versa.
100                 //
101                 // NOTE: After this, the owner of the source file may
102                 // get additional permissions. This shouldn't be too bad,
103                 // because the owner would have had permission to chmod
104                 // the original file anyway.
105                 mode = ((pair->src_st.st_mode & 0070) >> 3)
106                                 & (pair->src_st.st_mode & 0007);
107                 mode = (pair->src_st.st_mode & 0700) | (mode << 3) | mode;
108         } else {
109                 // Drop the setuid, setgid, and sticky bits.
110                 mode = pair->src_st.st_mode & 0777;
111         }
112
113         if (fchmod(pair->dest_fd, mode))
114                 message_warning(_("%s: Cannot set the file permissions: %s"),
115                                 pair->dest_name, strerror(errno));
116
117         // Copy the timestamps. We have several possible ways to do this, of
118         // which some are better in both security and precision.
119         //
120         // First, get the nanosecond part of the timestamps. As of writing,
121         // it's not standardized by POSIX, and there are several names for
122         // the same thing in struct stat.
123         long atime_nsec;
124         long mtime_nsec;
125
126 #       if defined(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
127         // GNU and Solaris
128         atime_nsec = pair->src_st.st_atim.tv_nsec;
129         mtime_nsec = pair->src_st.st_mtim.tv_nsec;
130
131 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
132         // BSD
133         atime_nsec = pair->src_st.st_atimespec.tv_nsec;
134         mtime_nsec = pair->src_st.st_mtimespec.tv_nsec;
135
136 #       elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
137         // GNU and BSD without extensions
138         atime_nsec = pair->src_st.st_atimensec;
139         mtime_nsec = pair->src_st.st_mtimensec;
140
141 #       elif defined(HAVE_STRUCT_STAT_ST_UATIME)
142         // Tru64
143         atime_nsec = pair->src_st.st_uatime * 1000;
144         mtime_nsec = pair->src_st.st_umtime * 1000;
145
146 #       elif defined(HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC)
147         // UnixWare
148         atime_nsec = pair->src_st.st_atim.st__tim.tv_nsec;
149         mtime_nsec = pair->src_st.st_mtim.st__tim.tv_nsec;
150
151 #       else
152         // Safe fallback
153         atime_nsec = 0;
154         mtime_nsec = 0;
155 #       endif
156
157         // Construct a structure to hold the timestamps and call appropriate
158         // function to set the timestamps.
159 #if defined(HAVE_FUTIMENS)
160         // Use nanosecond precision.
161         struct timespec tv[2];
162         tv[0].tv_sec = pair->src_st.st_atime;
163         tv[0].tv_nsec = atime_nsec;
164         tv[1].tv_sec = pair->src_st.st_mtime;
165         tv[1].tv_nsec = mtime_nsec;
166
167         (void)futimens(pair->dest_fd, tv);
168
169 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMES)
170         // Use microsecond precision.
171         struct timeval tv[2];
172         tv[0].tv_sec = pair->src_st.st_atime;
173         tv[0].tv_usec = atime_nsec / 1000;
174         tv[1].tv_sec = pair->src_st.st_mtime;
175         tv[1].tv_usec = mtime_nsec / 1000;
176
177 #       if defined(HAVE_FUTIMES)
178         (void)futimes(pair->dest_fd, tv);
179 #       elif defined(HAVE_FUTIMESAT)
180         (void)futimesat(pair->dest_fd, NULL, tv);
181 #       else
182         // Argh, no function to use a file descriptor to set the timestamp.
183         (void)utimes(pair->src_name, tv);
184 #       endif
185
186 #elif defined(HAVE_UTIME)
187         // Use one-second precision. utime() doesn't support using file
188         // descriptor either.
189         const struct utimbuf buf = {
190                 .actime = pair->src_st.st_atime;
191                 .modtime = pair->src_st.st_mtime;
192         };
193
194         // Avoid warnings.
195         (void)atime_nsec;
196         (void)mtime_nsec;
197
198         (void)utime(pair->src_name, &buf);
199 #endif
200
201         return;
202 }
203
204
205 /// Opens the source file. Returns false on success, true on error.
206 static bool
207 io_open_src(file_pair *pair)
208 {
209         // There's nothing to open when reading from stdin.
210         if (pair->src_name == stdin_filename) {
211                 pair->src_fd = STDIN_FILENO;
212                 return false;
213         }
214
215         // We accept only regular files if we are writing the output
216         // to disk too, and if --force was not given.
217         const bool reg_files_only = !opt_stdout && !opt_force;
218
219         // Flags for open()
220         int flags = O_RDONLY | O_NOCTTY;
221
222         // If we accept only regular files, we need to be careful to avoid
223         // problems with special files like devices and FIFOs. O_NONBLOCK
224         // prevents blocking when opening such files. When we want to accept
225         // special files, we must not use O_NONBLOCK, or otherwise we won't
226         // block waiting e.g. FIFOs to become readable.
227         if (reg_files_only)
228                 flags |= O_NONBLOCK;
229
230 #ifdef O_NOFOLLOW
231         if (reg_files_only)
232                 flags |= O_NOFOLLOW;
233 #else
234         // Some POSIX-like systems lack O_NOFOLLOW (it's not required
235         // by POSIX). Check for symlinks with a separate lstat() on
236         // these systems.
237         if (reg_files_only) {
238                 struct stat st;
239                 if (lstat(pair->src_name, &st)) {
240                         message_error("%s: %s", pair->src_name,
241                                         strerror(errno));
242                         return true;
243
244                 } else if (S_ISLNK(st.st_mode)) {
245                         message_warning(_("%s: Is a symbolic link, "
246                                         "skipping"), pair->src_name);
247                         return true;
248                 }
249         }
250 #endif
251
252         // Try to open the file. If we are accepting non-regular files,
253         // unblock the caught signals so that open() can be interrupted
254         // if it blocks e.g. due to a FIFO file.
255         if (!reg_files_only)
256                 signals_unblock();
257
258         // Maybe this wouldn't need a loop, since all the signal handlers for
259         // which we don't use SA_RESTART set user_abort to true. But it
260         // doesn't hurt to have it just in case.
261         do {
262                 pair->src_fd = open(pair->src_name, flags);
263         } while (pair->src_fd == -1 && errno == EINTR && !user_abort);
264
265         if (!reg_files_only)
266                 signals_block();
267
268         if (pair->src_fd == -1) {
269                 // If we were interrupted, don't display any error message.
270                 if (errno == EINTR) {
271                         // All the signals that don't have SA_RESTART
272                         // set user_abort.
273                         assert(user_abort);
274                         return true;
275                 }
276
277 #ifdef O_NOFOLLOW
278                 // Give an understandable error message in if reason
279                 // for failing was that the file was a symbolic link.
280                 //
281                 // Note that at least Linux, OpenBSD, Solaris, and Darwin
282                 // use ELOOP to indicate if O_NOFOLLOW was the reason
283                 // that open() failed. Because there may be
284                 // directories in the pathname, ELOOP may occur also
285                 // because of a symlink loop in the directory part.
286                 // So ELOOP doesn't tell us what actually went wrong.
287                 //
288                 // FreeBSD associates EMLINK with O_NOFOLLOW and
289                 // Tru64 uses ENOTSUP. We use these directly here
290                 // and skip the lstat() call and the associated race.
291                 // I want to hear if there are other kernels that
292                 // fail with something else than ELOOP with O_NOFOLLOW.
293                 bool was_symlink = false;
294
295 #       if defined(__FreeBSD__) || defined(__DragonFly__)
296                 if (errno == EMLINK)
297                         was_symlink = true;
298
299 #       elif defined(__digital__) && defined(__unix__)
300                 if (errno == ENOTSUP)
301                         was_symlink = true;
302
303 #       else
304                 if (errno == ELOOP && reg_files_only) {
305                         const int saved_errno = errno;
306                         struct stat st;
307                         if (lstat(pair->src_name, &st) == 0
308                                         && S_ISLNK(st.st_mode))
309                                 was_symlink = true;
310
311                         errno = saved_errno;
312                 }
313 #       endif
314
315                 if (was_symlink)
316                         message_warning(_("%s: Is a symbolic link, "
317                                         "skipping"), pair->src_name);
318                 else
319 #endif
320                         // Something else than O_NOFOLLOW failing
321                         // (assuming that the race conditions didn't
322                         // confuse us).
323                         message_error("%s: %s", pair->src_name,
324                                         strerror(errno));
325
326                 return true;
327         }
328
329         // Drop O_NONBLOCK, which is used only when we are accepting only
330         // regular files. After the open() call, we want things to block
331         // instead of giving EAGAIN.
332         if (reg_files_only) {
333                 flags = fcntl(pair->src_fd, F_GETFL);
334                 if (flags == -1)
335                         goto error_msg;
336
337                 flags &= ~O_NONBLOCK;
338
339                 if (fcntl(pair->src_fd, F_SETFL, flags))
340                         goto error_msg;
341         }
342
343         // Stat the source file. We need the result also when we copy
344         // the permissions, and when unlinking.
345         if (fstat(pair->src_fd, &pair->src_st))
346                 goto error_msg;
347
348         if (S_ISDIR(pair->src_st.st_mode)) {
349                 message_warning(_("%s: Is a directory, skipping"),
350                                 pair->src_name);
351                 goto error;
352         }
353
354         if (reg_files_only) {
355                 if (!S_ISREG(pair->src_st.st_mode)) {
356                         message_warning(_("%s: Not a regular file, "
357                                         "skipping"), pair->src_name);
358                         goto error;
359                 }
360
361                 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
362                         // gzip rejects setuid and setgid files even
363                         // when --force was used. bzip2 doesn't check
364                         // for them, but calls fchown() after fchmod(),
365                         // and many systems automatically drop setuid
366                         // and setgid bits there.
367                         //
368                         // We accept setuid and setgid files if
369                         // --force was used. We drop these bits
370                         // explicitly in io_copy_attr().
371                         message_warning(_("%s: File has setuid or "
372                                         "setgid bit set, skipping"),
373                                         pair->src_name);
374                         goto error;
375                 }
376
377                 if (pair->src_st.st_mode & S_ISVTX) {
378                         message_warning(_("%s: File has sticky bit "
379                                         "set, skipping"),
380                                         pair->src_name);
381                         goto error;
382                 }
383
384                 if (pair->src_st.st_nlink > 1) {
385                         message_warning(_("%s: Input file has more "
386                                         "than one hard link, "
387                                         "skipping"), pair->src_name);
388                         goto error;
389                 }
390         }
391
392         return false;
393
394 error_msg:
395         message_error("%s: %s", pair->src_name, strerror(errno));
396 error:
397         (void)close(pair->src_fd);
398         return true;
399 }
400
401
402 /// \brief      Closes source file of the file_pair structure
403 ///
404 /// \param      pair    File whose src_fd should be closed
405 /// \param      success If true, the file will be removed from the disk if
406 ///                     closing succeeds and --keep hasn't been used.
407 static void
408 io_close_src(file_pair *pair, bool success)
409 {
410         if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
411                 // If we are going to unlink(), do it before closing the file.
412                 // This way there's no risk that someone replaces the file and
413                 // happens to get same inode number, which would make us
414                 // unlink() wrong file.
415                 if (success && !opt_keep_original)
416                         io_unlink(pair->src_name, &pair->src_st);
417
418                 (void)close(pair->src_fd);
419         }
420
421         return;
422 }
423
424
425 static bool
426 io_open_dest(file_pair *pair)
427 {
428         if (opt_stdout || pair->src_fd == STDIN_FILENO) {
429                 // We don't modify or free() this.
430                 pair->dest_name = (char *)"(stdout)";
431                 pair->dest_fd = STDOUT_FILENO;
432                 return false;
433         }
434
435         pair->dest_name = suffix_get_dest_name(pair->src_name);
436         if (pair->dest_name == NULL)
437                 return true;
438
439         // If --force was used, unlink the target file first.
440         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
441                 message_error("%s: Cannot unlink: %s",
442                                 pair->dest_name, strerror(errno));
443                 free(pair->dest_name);
444                 return true;
445         }
446
447         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
448                 message_error("%s: Cannot unlink: %s", pair->dest_name,
449                                 strerror(errno));
450                 free(pair->dest_name);
451                 return true;
452         }
453
454         // Open the file.
455         const int flags = O_WRONLY | O_NOCTTY | O_CREAT | O_EXCL;
456         const mode_t mode = S_IRUSR | S_IWUSR;
457         pair->dest_fd = open(pair->dest_name, flags, mode);
458
459         if (pair->dest_fd == -1) {
460                 // Don't bother with error message if user requested
461                 // us to exit anyway.
462                 if (!user_abort)
463                         message_error("%s: %s", pair->dest_name,
464                                         strerror(errno));
465
466                 free(pair->dest_name);
467                 return true;
468         }
469
470         // If this really fails... well, we have a safe fallback.
471         if (fstat(pair->dest_fd, &pair->dest_st)) {
472                 pair->dest_st.st_dev = 0;
473                 pair->dest_st.st_ino = 0;
474         }
475
476         return false;
477 }
478
479
480 /// \brief      Closes destination file of the file_pair structure
481 ///
482 /// \param      pair    File whose dest_fd should be closed
483 /// \param      success If false, the file will be removed from the disk.
484 ///
485 /// \return     Zero if closing succeeds. On error, -1 is returned and
486 ///             error message printed.
487 static int
488 io_close_dest(file_pair *pair, bool success)
489 {
490         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
491                 return 0;
492
493         if (close(pair->dest_fd)) {
494                 message_error(_("%s: Closing the file failed: %s"),
495                                 pair->dest_name, strerror(errno));
496
497                 // Closing destination file failed, so we cannot trust its
498                 // contents. Get rid of junk:
499                 io_unlink(pair->dest_name, &pair->dest_st);
500                 free(pair->dest_name);
501                 return -1;
502         }
503
504         // If the operation using this file wasn't successful, we git rid
505         // of the junk file.
506         if (!success)
507                 io_unlink(pair->dest_name, &pair->dest_st);
508
509         free(pair->dest_name);
510
511         return 0;
512 }
513
514
515 extern file_pair *
516 io_open(const char *src_name)
517 {
518         if (is_empty_filename(src_name))
519                 return NULL;
520
521         // Since we have only one file open at a time, we can use
522         // a statically allocated structure.
523         static file_pair pair;
524
525         pair = (file_pair){
526                 .src_name = src_name,
527                 .dest_name = NULL,
528                 .src_fd = -1,
529                 .dest_fd = -1,
530                 .src_eof = false,
531         };
532
533         // Block the signals, for which we have a custom signal handler, so
534         // that we don't need to worry about EINTR.
535         signals_block();
536
537         file_pair *ret = NULL;
538         if (!io_open_src(&pair)) {
539                 // io_open_src() may have unblocked the signals temporarily,
540                 // and thus user_abort may have got set even if open()
541                 // succeeded.
542                 if (user_abort || io_open_dest(&pair))
543                         io_close_src(&pair, false);
544                 else
545                         ret = &pair;
546         }
547
548         signals_unblock();
549
550         return ret;
551 }
552
553
554 extern void
555 io_close(file_pair *pair, bool success)
556 {
557         signals_block();
558
559         if (success && pair->dest_fd != STDOUT_FILENO)
560                 io_copy_attrs(pair);
561
562         // Close the destination first. If it fails, we must not remove
563         // the source file!
564         if (io_close_dest(pair, success))
565                 success = false;
566
567         // Close the source file, and unlink it if the operation using this
568         // file pair was successful and we haven't requested to keep the
569         // source file.
570         io_close_src(pair, success);
571
572         signals_unblock();
573
574         return;
575 }
576
577
578 extern size_t
579 io_read(file_pair *pair, uint8_t *buf, size_t size)
580 {
581         // We use small buffers here.
582         assert(size < SSIZE_MAX);
583
584         size_t left = size;
585
586         while (left > 0) {
587                 const ssize_t amount = read(pair->src_fd, buf, left);
588
589                 if (amount == 0) {
590                         pair->src_eof = true;
591                         break;
592                 }
593
594                 if (amount == -1) {
595                         if (errno == EINTR) {
596                                 if (user_abort)
597                                         return SIZE_MAX;
598
599                                 continue;
600                         }
601
602                         message_error(_("%s: Read error: %s"),
603                                         pair->src_name, strerror(errno));
604
605                         // FIXME Is this needed?
606                         pair->src_eof = true;
607
608                         return SIZE_MAX;
609                 }
610
611                 buf += (size_t)(amount);
612                 left -= (size_t)(amount);
613         }
614
615         return size - left;
616 }
617
618
619 extern bool
620 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
621 {
622         assert(size < SSIZE_MAX);
623
624         while (size > 0) {
625                 const ssize_t amount = write(pair->dest_fd, buf, size);
626                 if (amount == -1) {
627                         if (errno == EINTR) {
628                                 if (user_abort)
629                                         return -1;
630
631                                 continue;
632                         }
633
634                         // Handle broken pipe specially. gzip and bzip2
635                         // don't print anything on SIGPIPE. In addition,
636                         // gzip --quiet uses exit status 2 (warning) on
637                         // broken pipe instead of whatever raise(SIGPIPE)
638                         // would make it return. It is there to hide "Broken
639                         // pipe" message on some old shells (probably old
640                         // GNU bash).
641                         //
642                         // We don't do anything special with --quiet, which
643                         // is what bzip2 does too. If we get SIGPIPE, we
644                         // will handle it like other signals by setting
645                         // user_abort, and get EPIPE here.
646                         if (errno != EPIPE)
647                                 message_error(_("%s: Write error: %s"),
648                                         pair->dest_name, strerror(errno));
649
650                         return true;
651                 }
652
653                 buf += (size_t)(amount);
654                 size -= (size_t)(amount);
655         }
656
657         return false;
658 }