summaryrefslogtreecommitdiff
path: root/Userland/Services/TelnetServer/Client.cpp
blob: b8a412c18d6686e545524b7d0005d91221290ed9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "Client.h"

#include <AK/ByteBuffer.h>
#include <AK/MemoryStream.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <AK/Types.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Notifier.h>
#include <stdio.h>
#include <unistd.h>

Client::Client(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket, int ptm_fd)
    : m_id(id)
    , m_socket(move(socket))
    , m_ptm_fd(ptm_fd)
    , m_ptm_notifier(Core::Notifier::construct(ptm_fd, Core::Notifier::Read))
{
    m_socket->on_ready_to_read = [this] {
        auto result = drain_socket();
        if (result.is_error()) {
            dbgln("Failed to drain the socket: {}", result.error());
            Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
        }
    };

    m_ptm_notifier->on_ready_to_read = [this] {
        auto result = drain_pty();
        if (result.is_error()) {
            dbgln("Failed to drain the PTY: {}", result.error());
            Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
        }
    };

    m_parser.on_command = [this](Command const& command) {
        auto result = handle_command(command);
        if (result.is_error()) {
            dbgln("Failed to handle the command: {}", result.error());
            Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
        }
    };

    m_parser.on_data = [this](StringView data) { handle_data(data); };
    m_parser.on_error = [this]() { handle_error(); };
}

ErrorOr<NonnullRefPtr<Client>> Client::create(int id, NonnullOwnPtr<Core::Stream::TCPSocket> socket, int ptm_fd)
{
    auto client = adopt_ref(*new Client(id, move(socket), ptm_fd));

    auto result = client->send_commands({
        { CMD_WILL, SUB_SUPPRESS_GO_AHEAD },
        { CMD_WILL, SUB_ECHO },
        { CMD_DO, SUB_SUPPRESS_GO_AHEAD },
        { CMD_DONT, SUB_ECHO },
    });
    if (result.is_error()) {
        client->quit();
        return result.release_error();
    }

    return client;
}

ErrorOr<void> Client::drain_socket()
{
    NonnullRefPtr<Client> protect(*this);

    auto buffer = TRY(ByteBuffer::create_uninitialized(1024));

    while (TRY(m_socket->can_read_without_blocking())) {
        auto read_bytes = TRY(m_socket->read(buffer));

        m_parser.write(StringView { read_bytes });

        if (m_socket->is_eof()) {
            Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
            break;
        }
    }

    return {};
}

ErrorOr<void> Client::drain_pty()
{
    u8 buffer[BUFSIZ];
    ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
    if (nread < 0) {
        Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
        return static_cast<ErrnoCode>(errno);
    }
    if (nread == 0) {
        Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
        return {};
    }

    return send_data({ buffer, (size_t)nread });
}

void Client::handle_data(StringView data)
{
    write(m_ptm_fd, data.characters_without_null_termination(), data.length());
}

ErrorOr<void> Client::handle_command(Command const& command)
{
    switch (command.command) {
    case CMD_DO:
        // no response - we've already advertised our options, and none of
        // them can be disabled (or re-enabled) after connecting.
        break;
    case CMD_DONT:
        // no response - we only "support" two options (echo and suppress
        // go-ahead), and both of them are always enabled.
        break;
    case CMD_WILL:
        switch (command.subcommand) {
        case SUB_ECHO:
            // we always want to be the ones in control of the output. tell
            // the client to disable local echo.
            TRY(send_command({ CMD_DONT, SUB_ECHO }));
            break;
        case SUB_SUPPRESS_GO_AHEAD:
            TRY(send_command({ CMD_DO, SUB_SUPPRESS_GO_AHEAD }));
            break;
        default:
            // don't respond to unknown commands
            break;
        }
        break;
    case CMD_WONT:
        // no response - we don't care about anything the client says they
        // won't do.
        break;
    }

    return {};
}

void Client::handle_error()
{
    Core::deferred_invoke([this, strong_this = NonnullRefPtr(*this)] { quit(); });
}

ErrorOr<void> Client::send_data(StringView data)
{
    bool fast = true;
    for (size_t i = 0; i < data.length(); i++) {
        u8 c = data[i];
        if (c == '\n' || c == 0xff)
            fast = false;
    }

    if (fast) {
        TRY(m_socket->write({ data.characters_without_null_termination(), data.length() }));
        return {};
    }

    StringBuilder builder;
    for (size_t i = 0; i < data.length(); i++) {
        u8 c = data[i];

        switch (c) {
        case '\n':
            builder.append("\r\n"sv);
            break;
        case IAC:
            builder.append("\xff\xff"sv);
            break;
        default:
            builder.append(c);
            break;
        }
    }

    auto builder_contents = builder.to_byte_buffer();
    TRY(m_socket->write(builder_contents));
    return {};
}

ErrorOr<void> Client::send_command(Command command)
{
    return send_commands({ command });
}

ErrorOr<void> Client::send_commands(Vector<Command> commands)
{
    auto buffer = TRY(ByteBuffer::create_uninitialized(commands.size() * 3));
    OutputMemoryStream stream { buffer };

    for (auto& command : commands)
        stream << (u8)IAC << command.command << command.subcommand;

    VERIFY(stream.is_end());
    TRY(m_socket->write({ buffer.data(), buffer.size() }));
    return {};
}

void Client::quit()
{
    m_ptm_notifier->set_enabled(false);
    close(m_ptm_fd);
    m_socket->close();
    if (on_exit)
        on_exit();
}