]> icculus.org git repositories - icculus/xz.git/blob - src/xz/io.c
Support NetBSD's errno for O_NOFOLLOW.
[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 #       elif defined(__NetBSD__)
304                 // FIXME? As of 2008-11-20, NetBSD doesn't document what
305                 // errno is used with O_NOFOLLOW. It seems to be EFTYPE,
306                 // but since it isn't documented, it may be wrong to rely
307                 // on it here.
308                 if (errno == EFTYPE)
309                         was_symlink = true;
310
311 #       else
312                 if (errno == ELOOP && reg_files_only) {
313                         const int saved_errno = errno;
314                         struct stat st;
315                         if (lstat(pair->src_name, &st) == 0
316                                         && S_ISLNK(st.st_mode))
317                                 was_symlink = true;
318
319                         errno = saved_errno;
320                 }
321 #       endif
322
323                 if (was_symlink)
324                         message_warning(_("%s: Is a symbolic link, "
325                                         "skipping"), pair->src_name);
326                 else
327 #endif
328                         // Something else than O_NOFOLLOW failing
329                         // (assuming that the race conditions didn't
330                         // confuse us).
331                         message_error("%s: %s", pair->src_name,
332                                         strerror(errno));
333
334                 return true;
335         }
336
337         // Drop O_NONBLOCK, which is used only when we are accepting only
338         // regular files. After the open() call, we want things to block
339         // instead of giving EAGAIN.
340         if (reg_files_only) {
341                 flags = fcntl(pair->src_fd, F_GETFL);
342                 if (flags == -1)
343                         goto error_msg;
344
345                 flags &= ~O_NONBLOCK;
346
347                 if (fcntl(pair->src_fd, F_SETFL, flags))
348                         goto error_msg;
349         }
350
351         // Stat the source file. We need the result also when we copy
352         // the permissions, and when unlinking.
353         if (fstat(pair->src_fd, &pair->src_st))
354                 goto error_msg;
355
356         if (S_ISDIR(pair->src_st.st_mode)) {
357                 message_warning(_("%s: Is a directory, skipping"),
358                                 pair->src_name);
359                 goto error;
360         }
361
362         if (reg_files_only) {
363                 if (!S_ISREG(pair->src_st.st_mode)) {
364                         message_warning(_("%s: Not a regular file, "
365                                         "skipping"), pair->src_name);
366                         goto error;
367                 }
368
369                 if (pair->src_st.st_mode & (S_ISUID | S_ISGID)) {
370                         // gzip rejects setuid and setgid files even
371                         // when --force was used. bzip2 doesn't check
372                         // for them, but calls fchown() after fchmod(),
373                         // and many systems automatically drop setuid
374                         // and setgid bits there.
375                         //
376                         // We accept setuid and setgid files if
377                         // --force was used. We drop these bits
378                         // explicitly in io_copy_attr().
379                         message_warning(_("%s: File has setuid or "
380                                         "setgid bit set, skipping"),
381                                         pair->src_name);
382                         goto error;
383                 }
384
385                 if (pair->src_st.st_mode & S_ISVTX) {
386                         message_warning(_("%s: File has sticky bit "
387                                         "set, skipping"),
388                                         pair->src_name);
389                         goto error;
390                 }
391
392                 if (pair->src_st.st_nlink > 1) {
393                         message_warning(_("%s: Input file has more "
394                                         "than one hard link, "
395                                         "skipping"), pair->src_name);
396                         goto error;
397                 }
398         }
399
400         return false;
401
402 error_msg:
403         message_error("%s: %s", pair->src_name, strerror(errno));
404 error:
405         (void)close(pair->src_fd);
406         return true;
407 }
408
409
410 /// \brief      Closes source file of the file_pair structure
411 ///
412 /// \param      pair    File whose src_fd should be closed
413 /// \param      success If true, the file will be removed from the disk if
414 ///                     closing succeeds and --keep hasn't been used.
415 static void
416 io_close_src(file_pair *pair, bool success)
417 {
418         if (pair->src_fd != STDIN_FILENO && pair->src_fd != -1) {
419                 // If we are going to unlink(), do it before closing the file.
420                 // This way there's no risk that someone replaces the file and
421                 // happens to get same inode number, which would make us
422                 // unlink() wrong file.
423                 if (success && !opt_keep_original)
424                         io_unlink(pair->src_name, &pair->src_st);
425
426                 (void)close(pair->src_fd);
427         }
428
429         return;
430 }
431
432
433 static bool
434 io_open_dest(file_pair *pair)
435 {
436         if (opt_stdout || pair->src_fd == STDIN_FILENO) {
437                 // We don't modify or free() this.
438                 pair->dest_name = (char *)"(stdout)";
439                 pair->dest_fd = STDOUT_FILENO;
440                 return false;
441         }
442
443         pair->dest_name = suffix_get_dest_name(pair->src_name);
444         if (pair->dest_name == NULL)
445                 return true;
446
447         // If --force was used, unlink the target file first.
448         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
449                 message_error("%s: Cannot unlink: %s",
450                                 pair->dest_name, strerror(errno));
451                 free(pair->dest_name);
452                 return true;
453         }
454
455         if (opt_force && unlink(pair->dest_name) && errno != ENOENT) {
456                 message_error("%s: Cannot unlink: %s", pair->dest_name,
457                                 strerror(errno));
458                 free(pair->dest_name);
459                 return true;
460         }
461
462         // Open the file.
463         const int flags = O_WRONLY | O_NOCTTY | O_CREAT | O_EXCL;
464         const mode_t mode = S_IRUSR | S_IWUSR;
465         pair->dest_fd = open(pair->dest_name, flags, mode);
466
467         if (pair->dest_fd == -1) {
468                 // Don't bother with error message if user requested
469                 // us to exit anyway.
470                 if (!user_abort)
471                         message_error("%s: %s", pair->dest_name,
472                                         strerror(errno));
473
474                 free(pair->dest_name);
475                 return true;
476         }
477
478         // If this really fails... well, we have a safe fallback.
479         if (fstat(pair->dest_fd, &pair->dest_st)) {
480                 pair->dest_st.st_dev = 0;
481                 pair->dest_st.st_ino = 0;
482         }
483
484         return false;
485 }
486
487
488 /// \brief      Closes destination file of the file_pair structure
489 ///
490 /// \param      pair    File whose dest_fd should be closed
491 /// \param      success If false, the file will be removed from the disk.
492 ///
493 /// \return     Zero if closing succeeds. On error, -1 is returned and
494 ///             error message printed.
495 static int
496 io_close_dest(file_pair *pair, bool success)
497 {
498         if (pair->dest_fd == -1 || pair->dest_fd == STDOUT_FILENO)
499                 return 0;
500
501         if (close(pair->dest_fd)) {
502                 message_error(_("%s: Closing the file failed: %s"),
503                                 pair->dest_name, strerror(errno));
504
505                 // Closing destination file failed, so we cannot trust its
506                 // contents. Get rid of junk:
507                 io_unlink(pair->dest_name, &pair->dest_st);
508                 free(pair->dest_name);
509                 return -1;
510         }
511
512         // If the operation using this file wasn't successful, we git rid
513         // of the junk file.
514         if (!success)
515                 io_unlink(pair->dest_name, &pair->dest_st);
516
517         free(pair->dest_name);
518
519         return 0;
520 }
521
522
523 extern file_pair *
524 io_open(const char *src_name)
525 {
526         if (is_empty_filename(src_name))
527                 return NULL;
528
529         // Since we have only one file open at a time, we can use
530         // a statically allocated structure.
531         static file_pair pair;
532
533         pair = (file_pair){
534                 .src_name = src_name,
535                 .dest_name = NULL,
536                 .src_fd = -1,
537                 .dest_fd = -1,
538                 .src_eof = false,
539         };
540
541         // Block the signals, for which we have a custom signal handler, so
542         // that we don't need to worry about EINTR.
543         signals_block();
544
545         file_pair *ret = NULL;
546         if (!io_open_src(&pair)) {
547                 // io_open_src() may have unblocked the signals temporarily,
548                 // and thus user_abort may have got set even if open()
549                 // succeeded.
550                 if (user_abort || io_open_dest(&pair))
551                         io_close_src(&pair, false);
552                 else
553                         ret = &pair;
554         }
555
556         signals_unblock();
557
558         return ret;
559 }
560
561
562 extern void
563 io_close(file_pair *pair, bool success)
564 {
565         signals_block();
566
567         if (success && pair->dest_fd != STDOUT_FILENO)
568                 io_copy_attrs(pair);
569
570         // Close the destination first. If it fails, we must not remove
571         // the source file!
572         if (io_close_dest(pair, success))
573                 success = false;
574
575         // Close the source file, and unlink it if the operation using this
576         // file pair was successful and we haven't requested to keep the
577         // source file.
578         io_close_src(pair, success);
579
580         signals_unblock();
581
582         return;
583 }
584
585
586 extern size_t
587 io_read(file_pair *pair, uint8_t *buf, size_t size)
588 {
589         // We use small buffers here.
590         assert(size < SSIZE_MAX);
591
592         size_t left = size;
593
594         while (left > 0) {
595                 const ssize_t amount = read(pair->src_fd, buf, left);
596
597                 if (amount == 0) {
598                         pair->src_eof = true;
599                         break;
600                 }
601
602                 if (amount == -1) {
603                         if (errno == EINTR) {
604                                 if (user_abort)
605                                         return SIZE_MAX;
606
607                                 continue;
608                         }
609
610                         message_error(_("%s: Read error: %s"),
611                                         pair->src_name, strerror(errno));
612
613                         // FIXME Is this needed?
614                         pair->src_eof = true;
615
616                         return SIZE_MAX;
617                 }
618
619                 buf += (size_t)(amount);
620                 left -= (size_t)(amount);
621         }
622
623         return size - left;
624 }
625
626
627 extern bool
628 io_write(const file_pair *pair, const uint8_t *buf, size_t size)
629 {
630         assert(size < SSIZE_MAX);
631
632         while (size > 0) {
633                 const ssize_t amount = write(pair->dest_fd, buf, size);
634                 if (amount == -1) {
635                         if (errno == EINTR) {
636                                 if (user_abort)
637                                         return -1;
638
639                                 continue;
640                         }
641
642                         // Handle broken pipe specially. gzip and bzip2
643                         // don't print anything on SIGPIPE. In addition,
644                         // gzip --quiet uses exit status 2 (warning) on
645                         // broken pipe instead of whatever raise(SIGPIPE)
646                         // would make it return. It is there to hide "Broken
647                         // pipe" message on some old shells (probably old
648                         // GNU bash).
649                         //
650                         // We don't do anything special with --quiet, which
651                         // is what bzip2 does too. If we get SIGPIPE, we
652                         // will handle it like other signals by setting
653                         // user_abort, and get EPIPE here.
654                         if (errno != EPIPE)
655                                 message_error(_("%s: Write error: %s"),
656                                         pair->dest_name, strerror(errno));
657
658                         return true;
659                 }
660
661                 buf += (size_t)(amount);
662                 size -= (size_t)(amount);
663         }
664
665         return false;
666 }