Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * Copyright (c) 2022, Kenneth Myhra <kennethmyhra@serenityos.org>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#include <AK/Vector.h>
9#include <LibCore/ArgsParser.h>
10#include <LibCore/System.h>
11#include <LibMain/Main.h>
12#include <fcntl.h>
13#include <signal.h>
14#include <sys/stat.h>
15#include <unistd.h>
16
17static ErrorOr<Vector<int>> collect_fds(Vector<StringView> paths, bool append)
18{
19 int oflag;
20 mode_t mode;
21 if (append) {
22 oflag = O_APPEND;
23 mode = 0;
24 } else {
25 oflag = O_CREAT | O_WRONLY | O_TRUNC;
26 mode = S_IROTH | S_IWOTH | S_IRGRP | S_IWGRP | S_IRUSR | S_IWUSR;
27 }
28
29 Vector<int> fds;
30 TRY(fds.try_ensure_capacity(paths.size() + 1));
31 for (auto path : paths) {
32 int fd = TRY(Core::System::open(path, oflag, mode));
33 fds.unchecked_append(fd);
34 }
35 fds.unchecked_append(STDOUT_FILENO);
36 return fds;
37}
38
39static ErrorOr<void> copy_stdin(Vector<int>& fds, bool* err)
40{
41 for (;;) {
42 Array<u8, 4096> buffer;
43 auto buffer_span = buffer.span();
44 auto nread = TRY(Core::System::read(STDIN_FILENO, buffer_span));
45 buffer_span = buffer_span.trim(nread);
46 if (nread == 0)
47 break;
48
49 Vector<int> broken_fds;
50 for (size_t i = 0; i < fds.size(); ++i) {
51 auto fd = fds.at(i);
52 auto nwrite_or_error = Core::System::write(fd, buffer_span);
53 if (nwrite_or_error.is_error()) {
54 if (nwrite_or_error.error().code() == EINTR) {
55 continue;
56 } else {
57 warnln("{}", nwrite_or_error.release_error());
58 *err = true;
59 broken_fds.append(fd);
60 // write failures to a successfully opened fd shall
61 // prevent further writes, but shall not block writes
62 // to the other open fds
63 break;
64 }
65 }
66 }
67
68 // remove any fds which we can no longer write to for subsequent copies
69 for (auto to_remove : broken_fds)
70 fds.remove_first_matching([&](int fd) { return to_remove == fd; });
71 }
72
73 return {};
74}
75
76static ErrorOr<void> close_fds(Vector<int>& fds)
77{
78 for (int fd : fds)
79 TRY(Core::System::close(fd));
80
81 return {};
82}
83
84static void int_handler(int)
85{
86 // pass
87}
88
89ErrorOr<int> serenity_main(Main::Arguments arguments)
90{
91 bool append = false;
92 bool ignore_interrupts = false;
93 Vector<StringView> paths;
94
95 Core::ArgsParser args_parser;
96 args_parser.add_option(append, "Append, don't overwrite", "append", 'a');
97 args_parser.add_option(ignore_interrupts, "Ignore SIGINT", "ignore-interrupts", 'i');
98 args_parser.add_positional_argument(paths, "Files to copy stdin to", "file", Core::ArgsParser::Required::No);
99 args_parser.parse(arguments);
100
101 if (ignore_interrupts)
102 TRY(Core::System::signal(SIGINT, int_handler));
103
104 auto fds = TRY(collect_fds(paths, append));
105 bool err_write = false;
106 TRY(copy_stdin(fds, &err_write));
107 TRY(close_fds(fds));
108
109 return err_write ? 1 : 0;
110}