summaryrefslogtreecommitdiff
path: root/Applications/IRCClient/IRCClient.cpp
blob: d8b6f63b7626c6f19e71bd28bb9d8b4c923e19e4 (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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#include "IRCClient.h"
#include "IRCChannel.h"
#include "IRCQuery.h"
#include "IRCLogBuffer.h"
#include "IRCWindow.h"
#include "IRCWindowListModel.h"
#include <LibGUI/GNotifier.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>

//#define IRC_DEBUG

enum IRCNumeric {
    RPL_NAMREPLY = 353,
    RPL_ENDOFNAMES = 366,
};

IRCClient::IRCClient(const String& address, int port)
    : m_hostname(address)
    , m_port(port)
    , m_nickname("anon")
    , m_log(IRCLogBuffer::create())
{
    m_client_window_list_model = new IRCWindowListModel(*this);
}

IRCClient::~IRCClient()
{
}

bool IRCClient::connect()
{
    if (m_socket_fd != -1) {
        ASSERT_NOT_REACHED();
    }

    m_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (m_socket_fd < 0) {
        perror("socket");
        exit(1);
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(m_port);
    int rc = inet_pton(AF_INET, m_hostname.characters(), &addr.sin_addr);
    if (rc < 0) {
        perror("inet_pton");
        exit(1);
    }

    printf("Connecting to %s...", m_hostname.characters());
    fflush(stdout);
    rc = ::connect(m_socket_fd, (struct sockaddr*)&addr, sizeof(addr));
    if (rc < 0) {
        perror("connect");
        exit(1);
    }
    printf("ok!\n");

    m_notifier = make<GNotifier>(m_socket_fd, GNotifier::Read);
    m_notifier->on_ready_to_read = [this] (GNotifier&) { receive_from_server(); };

    send_user();
    send_nick();

    if (on_connect)
        on_connect();
    return true;
}

void IRCClient::receive_from_server()
{
    char buffer[4096];
    int nread = recv(m_socket_fd, buffer, sizeof(buffer) - 1, 0);
    if (nread < 0) {
        perror("recv");
        exit(1);
    }
    if (nread == 0) {
        printf("IRCClient: Connection closed!\n");
        exit(1);
    }
    buffer[nread] = '\0';
#if 0
    printf("Received: '%s'\n", buffer);
#endif

    for (int i = 0; i < nread; ++i) {
        char ch = buffer[i];
        if (ch == '\r')
            continue;
        if (ch == '\n') {
            process_line();
            m_line_buffer.clear_with_capacity();
            continue;
        }
        m_line_buffer.append(ch);
    }
}

void IRCClient::process_line()
{
    Message msg;
    Vector<char> prefix;
    Vector<char> command;
    Vector<char> current_parameter;
    enum {
        Start,
        InPrefix,
        InCommand,
        InStartOfParameter,
        InParameter,
        InTrailingParameter,
    } state = Start;

    for (char ch : m_line_buffer) {
        switch (state) {
        case Start:
            if (ch == ':') {
                state = InPrefix;
                continue;
            }
            state = InCommand;
            [[fallthrough]];
        case InCommand:
            if (ch == ' ') {
                state = InStartOfParameter;
                continue;
            }
            command.append(ch);
            continue;
        case InPrefix:
            if (ch == ' ') {
                state = InCommand;
                continue;
            }
            prefix.append(ch);
            continue;
        case InStartOfParameter:
            if (ch == ':') {
                state = InTrailingParameter;
                continue;
            }
            state = InParameter;
            [[fallthrough]];
        case InParameter:
            if (ch == ' ') {
                if (!current_parameter.is_empty())
                    msg.arguments.append(String(current_parameter.data(), current_parameter.size()));
                current_parameter.clear_with_capacity();
                state = InStartOfParameter;
                continue;
            }
            current_parameter.append(ch);
            continue;
        case InTrailingParameter:
            current_parameter.append(ch);
            continue;
        }
    }
    if (!current_parameter.is_empty())
        msg.arguments.append(String(current_parameter.data(), current_parameter.size()));
    msg.prefix = String(prefix.data(), prefix.size());
    msg.command = String(command.data(), command.size());
    handle(msg, String(m_line_buffer.data(), m_line_buffer.size()));
}

void IRCClient::send(const String& text)
{
    int rc = ::send(m_socket_fd, text.characters(), text.length(), 0);
    if (rc < 0) {
        perror("send");
        exit(1);
    }
}

void IRCClient::send_user()
{
    send(String::format("USER %s 0 * :%s\r\n", m_nickname.characters(), m_nickname.characters()));
}

void IRCClient::send_nick()
{
    send(String::format("NICK %s\r\n", m_nickname.characters()));
}

void IRCClient::send_pong(const String& server)
{
    send(String::format("PONG %s\r\n", server.characters()));
    sleep(1);
}

void IRCClient::join_channel(const String& channel_name)
{
    send(String::format("JOIN %s\r\n", channel_name.characters()));
}

void IRCClient::handle(const Message& msg, const String&)
{
#ifdef IRC_DEBUG
    printf("IRCClient::execute: prefix='%s', command='%s', arguments=%d\n",
        msg.prefix.characters(),
        msg.command.characters(),
        msg.arguments.size()
    );

    int i = 0;
    for (auto& arg : msg.arguments) {
        printf("    [%d]: %s\n", i, arg.characters());
        ++i;
    }
#endif

    bool is_numeric;
    int numeric = msg.command.to_uint(is_numeric);

    if (is_numeric) {
        switch (numeric) {
        case RPL_NAMREPLY:
            handle_namreply(msg);
            return;
        }
    }

    if (msg.command == "PING")
        return handle_ping(msg);

    if (msg.command == "JOIN")
        return handle_join(msg);

    if (msg.command == "PRIVMSG")
        return handle_privmsg(msg);

    if (msg.arguments.size() >= 2)
        m_log->add_message(0, "Server", String::format("[%s] %s", msg.command.characters(), msg.arguments[1].characters()));
}

void IRCClient::send_privmsg(const String& target, const String& text)
{
    send(String::format("PRIVMSG %s :%s\r\n", target.characters(), text.characters()));
}

void IRCClient::handle_user_input_in_channel(const String& channel_name, const String& input)
{
    if (input.is_empty())
        return;
    ensure_channel(channel_name).say(input);
}

void IRCClient::handle_user_input_in_query(const String& query_name, const String& input)
{
    if (input.is_empty())
        return;
    ensure_query(query_name).say(input);
}

void IRCClient::handle_user_input_in_server(const String& input)
{
    if (input.is_empty())
        return;
}

bool IRCClient::is_nick_prefix(char ch) const
{
    switch (ch) {
    case '@':
    case '+':
    case '~':
    case '&':
    case '%':
        return true;
    }
    return false;
}

void IRCClient::handle_privmsg(const Message& msg)
{
    if (msg.arguments.size() < 2)
        return;
    if (msg.prefix.is_empty())
        return;
    auto parts = msg.prefix.split('!');
    auto sender_nick = parts[0];
    auto target = msg.arguments[0];

#ifdef IRC_DEBUG
    printf("handle_privmsg: sender_nick='%s', target='%s'\n", sender_nick.characters(), target.characters());
#endif

    if (sender_nick.is_empty())
        return;

    char sender_prefix = 0;
    if (is_nick_prefix(sender_nick[0])) {
        sender_prefix = sender_nick[0];
        sender_nick = sender_nick.substring(1, sender_nick.length() - 1);
    }

    {
        auto it = m_channels.find(target);
        if (it != m_channels.end()) {
            (*it).value->add_message(sender_prefix, sender_nick, msg.arguments[1]);
            return;
        }
    }
    auto& query = ensure_query(sender_nick);
    query.add_message(sender_prefix, sender_nick, msg.arguments[1]);
}

IRCQuery& IRCClient::ensure_query(const String& name)
{
    auto it = m_queries.find(name);
    if (it != m_queries.end())
        return *(*it).value;
    auto query = IRCQuery::create(*this, name);
    auto& query_reference = *query;
    m_queries.set(name, query.copy_ref());
    return query_reference;
}

IRCChannel& IRCClient::ensure_channel(const String& name)
{
    auto it = m_channels.find(name);
    if (it != m_channels.end())
        return *(*it).value;
    auto channel = IRCChannel::create(*this, name);
    auto& channel_reference = *channel;
    m_channels.set(name, channel.copy_ref());
    return channel_reference;
}

void IRCClient::handle_ping(const Message& msg)
{
    if (msg.arguments.size() < 0)
        return;
    m_log->add_message(0, "Server", "Ping? Pong!");
    send_pong(msg.arguments[0]);
}

void IRCClient::handle_join(const Message& msg)
{
    if (msg.arguments.size() != 1)
        return;
    auto& channel_name = msg.arguments[0];
    ensure_channel(channel_name);
}

void IRCClient::handle_namreply(const Message& msg)
{
    if (msg.arguments.size() < 4)
        return;

    auto& channel_name = msg.arguments[2];

    auto it = m_channels.find(channel_name);
    if (it == m_channels.end()) {
        fprintf(stderr, "Warning: Got RPL_NAMREPLY for untracked channel %s\n", channel_name.characters());
        return;
    }
    auto& channel = *(*it).value;

    auto members = msg.arguments[3].split(' ');
    for (auto& member : members) {
        if (member.is_empty())
            continue;
        char prefix = 0;
        if (is_nick_prefix(member[0]))
            prefix = member[0];
        channel.add_member(member, prefix);
    }

    channel.dump();
}

void IRCClient::register_subwindow(IRCWindow& subwindow)
{
    if (subwindow.type() == IRCWindow::Server) {
        m_server_subwindow = &subwindow;
        subwindow.set_log_buffer(*m_log);
    }
    m_windows.append(&subwindow);
    m_client_window_list_model->update();
}

void IRCClient::unregister_subwindow(IRCWindow& subwindow)
{
    if (subwindow.type() == IRCWindow::Server) {
        m_server_subwindow = &subwindow;
    }
    for (int i = 0; i < m_windows.size(); ++i) {
        if (m_windows.at(i) == &subwindow) {
            m_windows.remove(i);
            break;
        }
    }
    m_client_window_list_model->update();
}