irc_client.cpp 42.6 KB
Newer Older
1
#include <utility>
2
#include <utils/timed_events.hpp>
3
#include <database/database.hpp>
4
#include <irc/irc_message.hpp>
5 6 7 8
#include <irc/irc_client.hpp>
#include <bridge/bridge.hpp>
#include <irc/irc_user.hpp>

louiz’'s avatar
louiz’ committed
9
#include <logger/logger.hpp>
10
#include <config/config.hpp>
louiz’'s avatar
louiz’ committed
11
#include <utils/tolower.hpp>
12
#include <utils/split.hpp>
13
#include <utils/string.hpp>
14

15
#include <sstream>
16 17
#include <iostream>
#include <stdexcept>
18
#include <algorithm>
louiz’'s avatar
louiz’ committed
19
#include <cstring>
20

21
#include <chrono>
louiz’'s avatar
louiz’ committed
22
#include <string>
23

24
#include "biboumi.h"
louiz’'s avatar
louiz’ committed
25

louiz’'s avatar
louiz’ committed
26
using namespace std::string_literals;
27
using namespace std::chrono_literals;
louiz’'s avatar
louiz’ committed
28

29 30 31 32
/**
 * Define a map of functions to be called for each IRC command we can
 * handle.
 */
louiz’'s avatar
louiz’ committed
33
using IrcCallback = void (IrcClient::*)(const IrcMessage&);
34 35

static const std::unordered_map<std::string,
louiz’'s avatar
louiz’ committed
36
                                std::pair<IrcCallback, std::pair<std::size_t, std::size_t>>> irc_callbacks = {
37 38 39
  {"NOTICE", {&IrcClient::on_notice, {2, 0}}},
  {"002", {&IrcClient::forward_server_message, {2, 0}}},
  {"003", {&IrcClient::forward_server_message, {2, 0}}},
louiz’'s avatar
louiz’ committed
40
  {"004", {&IrcClient::on_server_myinfo, {4, 0}}},
41 42 43 44 45 46 47
  {"005", {&IrcClient::on_isupport_message, {0, 0}}},
  {"RPL_LISTSTART", {&IrcClient::on_rpl_liststart, {0, 0}}},
  {"321", {&IrcClient::on_rpl_liststart, {0, 0}}},
  {"RPL_LIST", {&IrcClient::on_rpl_list, {0, 0}}},
  {"322", {&IrcClient::on_rpl_list, {0, 0}}},
  {"RPL_LISTEND", {&IrcClient::on_rpl_listend, {0, 0}}},
  {"323", {&IrcClient::on_rpl_listend, {0, 0}}},
louiz’'s avatar
louiz’ committed
48 49
  {"RPL_NOTOPIC", {&IrcClient::on_empty_topic, {0, 0}}},
  {"331", {&IrcClient::on_empty_topic, {0, 0}}},
50
  {"341", {&IrcClient::on_invited, {3, 0}}},
51 52 53 54 55 56 57 58 59 60 61
  {"RPL_MOTDSTART", {&IrcClient::empty_motd, {0, 0}}},
  {"375", {&IrcClient::empty_motd, {0, 0}}},
  {"RPL_MOTD", {&IrcClient::on_motd_line, {2, 0}}},
  {"372", {&IrcClient::on_motd_line, {2, 0}}},
  {"RPL_MOTDEND", {&IrcClient::send_motd, {0, 0}}},
  {"376", {&IrcClient::send_motd, {0, 0}}},
  {"JOIN", {&IrcClient::on_channel_join, {1, 0}}},
  {"PRIVMSG", {&IrcClient::on_channel_message, {2, 0}}},
  {"353", {&IrcClient::set_and_forward_user_list, {4, 0}}},
  {"332", {&IrcClient::on_topic_received, {2, 0}}},
  {"TOPIC", {&IrcClient::on_topic_received, {2, 0}}},
62 63
  {"333", {&IrcClient::on_topic_who_time_received, {4, 0}}},
  {"RPL_TOPICWHOTIME", {&IrcClient::on_topic_who_time_received, {4, 0}}},
64
  {"366", {&IrcClient::on_channel_completely_joined, {2, 0}}},
65 66
  {"367", {&IrcClient::on_banlist, {3, 0}}},
  {"368", {&IrcClient::on_banlist_end, {3, 0}}},
67
  {"396", {&IrcClient::on_own_host_received, {2, 0}}},
68 69 70
  {"432", {&IrcClient::on_erroneous_nickname, {2, 0}}},
  {"433", {&IrcClient::on_nickname_conflict, {2, 0}}},
  {"438", {&IrcClient::on_nickname_change_too_fast, {2, 0}}},
71
  {"443", {&IrcClient::on_useronchannel, {3, 0}}},
72
  {"475", {&IrcClient::on_channel_bad_key, {3, 0}}},
73
  {"ERR_USERONCHANNEL", {&IrcClient::on_useronchannel, {3, 0}}},
74 75 76 77 78 79 80 81 82
  {"001", {&IrcClient::on_welcome_message, {1, 0}}},
  {"PART", {&IrcClient::on_part, {1, 0}}},
  {"ERROR", {&IrcClient::on_error, {1, 0}}},
  {"QUIT", {&IrcClient::on_quit, {0, 0}}},
  {"NICK", {&IrcClient::on_nick, {1, 0}}},
  {"MODE", {&IrcClient::on_mode, {1, 0}}},
  {"PING", {&IrcClient::send_pong_command, {1, 0}}},
  {"PONG", {&IrcClient::on_pong, {0, 0}}},
  {"KICK", {&IrcClient::on_kick, {3, 0}}},
louiz’'s avatar
louiz’ committed
83
  {"INVITE", {&IrcClient::on_invite, {2, 0}}},
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

  {"401", {&IrcClient::on_generic_error, {2, 0}}},
  {"402", {&IrcClient::on_generic_error, {2, 0}}},
  {"403", {&IrcClient::on_generic_error, {2, 0}}},
  {"404", {&IrcClient::on_generic_error, {2, 0}}},
  {"405", {&IrcClient::on_generic_error, {2, 0}}},
  {"406", {&IrcClient::on_generic_error, {2, 0}}},
  {"407", {&IrcClient::on_generic_error, {2, 0}}},
  {"408", {&IrcClient::on_generic_error, {2, 0}}},
  {"409", {&IrcClient::on_generic_error, {2, 0}}},
  {"410", {&IrcClient::on_generic_error, {2, 0}}},
  {"411", {&IrcClient::on_generic_error, {2, 0}}},
  {"412", {&IrcClient::on_generic_error, {2, 0}}},
  {"414", {&IrcClient::on_generic_error, {2, 0}}},
  {"421", {&IrcClient::on_generic_error, {2, 0}}},
  {"422", {&IrcClient::on_generic_error, {2, 0}}},
  {"423", {&IrcClient::on_generic_error, {2, 0}}},
  {"424", {&IrcClient::on_generic_error, {2, 0}}},
  {"431", {&IrcClient::on_generic_error, {2, 0}}},
  {"436", {&IrcClient::on_generic_error, {2, 0}}},
  {"441", {&IrcClient::on_generic_error, {2, 0}}},
  {"442", {&IrcClient::on_generic_error, {2, 0}}},
  {"444", {&IrcClient::on_generic_error, {2, 0}}},
  {"446", {&IrcClient::on_generic_error, {2, 0}}},
  {"451", {&IrcClient::on_generic_error, {2, 0}}},
  {"461", {&IrcClient::on_generic_error, {2, 0}}},
  {"462", {&IrcClient::on_generic_error, {2, 0}}},
  {"463", {&IrcClient::on_generic_error, {2, 0}}},
  {"464", {&IrcClient::on_generic_error, {2, 0}}},
  {"465", {&IrcClient::on_generic_error, {2, 0}}},
  {"467", {&IrcClient::on_generic_error, {2, 0}}},
  {"470", {&IrcClient::on_generic_error, {2, 0}}},
  {"471", {&IrcClient::on_generic_error, {2, 0}}},
  {"472", {&IrcClient::on_generic_error, {2, 0}}},
  {"473", {&IrcClient::on_generic_error, {2, 0}}},
  {"474", {&IrcClient::on_generic_error, {2, 0}}},
  {"476", {&IrcClient::on_generic_error, {2, 0}}},
  {"477", {&IrcClient::on_generic_error, {2, 0}}},
  {"481", {&IrcClient::on_generic_error, {2, 0}}},
  {"482", {&IrcClient::on_generic_error, {2, 0}}},
  {"483", {&IrcClient::on_generic_error, {2, 0}}},
  {"484", {&IrcClient::on_generic_error, {2, 0}}},
  {"485", {&IrcClient::on_generic_error, {2, 0}}},
  {"487", {&IrcClient::on_generic_error, {2, 0}}},
  {"491", {&IrcClient::on_generic_error, {2, 0}}},
  {"501", {&IrcClient::on_generic_error, {2, 0}}},
  {"502", {&IrcClient::on_generic_error, {2, 0}}},
};
132

133 134 135
IrcClient::IrcClient(std::shared_ptr<Poller>& poller, std::string hostname,
                     std::string nickname, std::string username,
                     std::string realname, std::string user_hostname,
136
                     Bridge& bridge):
137
  TCPClientSocketHandler(poller),
138 139 140 141 142
  hostname(std::move(hostname)),
  user_hostname(std::move(user_hostname)),
  username(std::move(username)),
  realname(std::move(realname)),
  current_nick(std::move(nickname)),
louiz’'s avatar
louiz’ committed
143
  bridge(bridge),
louiz’'s avatar
louiz’ committed
144
  welcomed(false),
145 146
  chanmodes({"", "", "", ""}),
  chantypes({'#', '&'})
147
{
148
#ifdef USE_DATABASE
149
  auto options = Database::get_irc_server_options(this->bridge.get_bare_jid(),
150
                                                  this->get_hostname());
151
  std::vector<std::string> ports = utils::split(options.col<Database::Ports>(), ';', false);
152 153 154
  for (auto it = ports.rbegin(); it != ports.rend(); ++it)
    this->ports_to_try.emplace(*it, false);
# ifdef BOTAN_FOUND
155
  ports = utils::split(options.col<Database::TlsPorts>(), ';', false);
156 157 158 159 160
  for (auto it = ports.rbegin(); it != ports.rend(); ++it)
    this->ports_to_try.emplace(*it, true);
# endif // BOTAN_FOUND

#else  // not USE_DATABASE
louiz’'s avatar
louiz’ committed
161
  this->ports_to_try.emplace("6667", false); // standard non-encrypted port
162
# ifdef BOTAN_FOUND
louiz’'s avatar
louiz’ committed
163 164
  this->ports_to_try.emplace("6670", true);  // non-standard but I want it for some servers
  this->ports_to_try.emplace("6697", true);  // standard encrypted port
165 166
# endif // BOTAN_FOUND
#endif // USE_DATABASE
167 168 169 170
}

IrcClient::~IrcClient()
{
171 172
  // This event may or may not exist (if we never got connected, it
  // doesn't), but it's ok
173
  TimedEventsManager::instance().cancel("PING" + this->hostname + this->bridge.get_jid());
174 175
}

176 177
void IrcClient::start()
{
178 179
  if (this->is_connecting() || this->is_connected())
    return;
180 181 182 183 184
  if (this->ports_to_try.empty())
    {
      this->bridge.send_xmpp_message(this->hostname, "", "Can not connect to IRC server: no port specified.");
      return;
    }
louiz’'s avatar
louiz’ committed
185 186 187 188
  std::string port;
  bool tls;
  std::tie(port, tls) = this->ports_to_try.top();
  this->ports_to_try.pop();
louiz’'s avatar
louiz’ committed
189
  this->bind_addr = Config::get("outgoing_bind", "");
190
  std::string address = this->hostname;
louiz’'s avatar
louiz’ committed
191

192
#ifdef USE_DATABASE
193 194
  auto options = Database::get_irc_server_options(this->bridge.get_bare_jid(),
                                                  this->get_hostname());
195
# ifdef BOTAN_FOUND
196
  this->credential_manager.set_trusted_fingerprint(options.col<Database::TrustedFingerprint>());
197
# endif
198 199
  if (!options.col<Database::Address>().empty())
    address = options.col<Database::Address>();
200
#endif
201 202 203 204
  this->bridge.send_xmpp_message(this->hostname, "", "Connecting to " +
                                  address + ":" + port + " (" +
                                  (tls ? "encrypted" : "not encrypted") + ")");
  this->connect(address, port, tls);
205 206 207 208
}

void IrcClient::on_connection_failed(const std::string& reason)
{
209
  this->bridge.send_xmpp_message(this->hostname, "",
210
                                  "Connection failed: " + reason);
211 212 213 214 215

  if (this->hostname_resolution_failed)
    while (!this->ports_to_try.empty())
      this->ports_to_try.pop();

louiz’'s avatar
louiz’ committed
216
  if (this->ports_to_try.empty())
217
    {
louiz’'s avatar
louiz’ committed
218
      // Send an error message for all room that the user wanted to join
219
      for (const auto& tuple: this->channels_to_join)
louiz’'s avatar
louiz’ committed
220
        {
221
          Iid iid(std::get<0>(tuple) + "%" + this->hostname, this->chantypes);
222
          this->bridge.send_presence_error(iid, this->current_nick,
223 224
                                            "cancel", "item-not-found",
                                            "", reason);
louiz’'s avatar
louiz’ committed
225
        }
226
    }
louiz’'s avatar
louiz’ committed
227 228
  else                          // try the next port
    this->start();
229 230
}

louiz’'s avatar
louiz’ committed
231 232
void IrcClient::on_connected()
{
louiz’'s avatar
louiz’ committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  const auto webirc_password = Config::get("webirc_password", "");
  static std::string resolved_ip;

  if (!webirc_password.empty())
    {
      if (!resolved_ip.empty())
        this->send_webirc_command(webirc_password, resolved_ip);
      else
        {  // Start resolving the hostname of the user, and call
           // on_connected again when it’s done
          this->dns_resolver.resolve(this->user_hostname, "5222",
                                     [this](const struct addrinfo* addr)
                                     {
                                       resolved_ip = addr_to_string(addr);
                                       // Only continue the process if we
                                       // didn’t get connected while we were
                                       // resolving
                                       if (this->is_connected())
                                         this->on_connected();
                                     },
                                     [this](const char* error_msg)
                                     {
                                       if (this->is_connected())
                                         {
257
                                           this->on_connection_close("Could not resolve hostname " + this->user_hostname +
louiz’'s avatar
louiz’ committed
258 259 260 261 262 263 264 265
                                                                     ": " + error_msg);
                                           this->send_quit_command("");
                                         }
                                     });
          return;
        }
    }

louiz’'s avatar
louiz’ committed
266 267 268
  this->send_message({"CAP", {"REQ", "multi-prefix"}});
  this->send_message({"CAP", {"END"}});

269
#ifdef USE_DATABASE
270
  auto options = Database::get_irc_server_options(this->bridge.get_bare_jid(),
271
                                                  this->get_hostname());
272 273
  if (!options.col<Database::Pass>().empty())
    this->send_pass_command(options.col<Database::Pass>());
274
#endif
275

276
  this->send_nick_command(this->current_nick);
277

278
#ifdef USE_DATABASE
279 280
  if (Config::get("realname_customization", "true") == "true")
    {
281 282 283 284
      if (!options.col<Database::Username>().empty())
        this->username = options.col<Database::Username>();
      if (!options.col<Database::Realname>().empty())
        this->realname = options.col<Database::Realname>();
285 286
      this->send_user_command(username, realname);
    }
287 288 289
  else
    this->send_user_command(this->username, this->realname);
#else
290
  this->send_user_command(this->username, this->realname);
291
#endif
louiz’'s avatar
louiz’ committed
292
  this->send_gateway_message("Connected to IRC server"s + (this->use_tls ? " (encrypted)": "") + ".");
293
  this->send_pending_data();
294
  this->bridge.on_irc_client_connected(this->get_hostname());
louiz’'s avatar
louiz’ committed
295 296
}

297
void IrcClient::on_connection_close(const std::string& error_msg)
298
{
299
  std::string message = "Connection closed";
300 301
  if (!error_msg.empty())
    message += ": " + error_msg;
302 303
  else
    message += ".";
304 305
  const IrcMessage error{"ERROR", {message}};
  this->on_error(error);
306
  log_warning(message);
307
  this->bridge.on_irc_client_disconnected(this->get_hostname());
308 309
}

louiz’'s avatar
louiz’ committed
310
IrcChannel* IrcClient::get_channel(const std::string& n)
311
{
louiz’'s avatar
louiz’ committed
312
  const std::string name = utils::tolower(n);
313 314 315 316 317 318 319 320 321 322 323
  try
    {
      return this->channels.at(name).get();
    }
  catch (const std::out_of_range& exception)
    {
      this->channels.emplace(name, std::make_unique<IrcChannel>());
      return this->channels.at(name).get();
    }
}

louiz’'s avatar
louiz’ committed
324 325
bool IrcClient::is_channel_joined(const std::string& name)
{
louiz’'s avatar
louiz’ committed
326 327
  IrcChannel* channel = this->get_channel(name);
  return channel->joined;
louiz’'s avatar
louiz’ committed
328 329
}

louiz’'s avatar
louiz’ committed
330 331 332 333 334
std::string IrcClient::get_own_nick() const
{
  return this->current_nick;
}

335
void IrcClient::parse_in_buffer(const size_t)
336
{
louiz’'s avatar
louiz’ committed
337 338 339 340 341 342
  while (true)
    {
      auto pos = this->in_buf.find("\r\n");
      if (pos == std::string::npos)
        break ;
      IrcMessage message(this->in_buf.substr(0, pos));
343
      this->consume_in_buffer(pos + 2);
344
      log_debug("IRC RECEIVING: (", this->get_hostname(), ") ", message);
345 346 347

      // Call the standard callback (if any), associated with the command
      // name that we just received.
348 349
      auto it = irc_callbacks.find(message.command);
      if (it != irc_callbacks.end())
350
        {
351 352 353 354 355 356
          const auto& limits = it->second.second;
          // Check that the Message is well formed before actually calling
          // the callback. limits.first is the min number of arguments,
          // second is the max
          if (message.arguments.size() < limits.first ||
              (limits.second > 0 && message.arguments.size() > limits.second))
357 358
            log_warning("Invalid number of arguments for IRC command “", message.command,
                        "”: ", message.arguments.size());
359 360 361 362 363 364
          else
            {
              const auto& cb = it->second.first;
              try {
                (this->*(cb))(message);
              } catch (const std::exception& e) {
365
                log_error("Unhandled exception: ", e.what());
366 367
              }
            }
368
        }
369
      else
370
        {
371
          log_info("No handler for command ", message.command,
372 373 374
                   ", forwarding the arguments to the user");
          this->on_unknown_message(message);
        }
375
      // Try to find a waiting_iq, which response will be triggered by this IrcMessage
376
      this->bridge.trigger_on_irc_message(this->hostname, message);
louiz’'s avatar
louiz’ committed
377 378 379 380 381
    }
}

void IrcClient::send_message(IrcMessage&& message)
{
382
  log_debug("IRC SENDING: (", this->get_hostname(), ") ", message);
louiz’'s avatar
louiz’ committed
383 384 385
  std::string res;
  if (!message.prefix.empty())
    res += ":" + std::move(message.prefix) + " ";
386
  res += message.command;
louiz’'s avatar
louiz’ committed
387 388
  for (const std::string& arg: message.arguments)
    {
389
      if (arg.find(' ') != std::string::npos ||
louiz’'s avatar
louiz’ committed
390
          (!arg.empty() && arg[0] == ':'))
louiz’'s avatar
louiz’ committed
391 392 393 394 395 396 397
        {
          res += " :" + arg;
          break;
        }
      res += " " + arg;
    }
  res += "\r\n";
398
  this->send_data(std::move(res));
louiz’'s avatar
louiz’ committed
399 400
}

louiz’'s avatar
louiz’ committed
401 402
void IrcClient::send_raw(const std::string& txt)
{
403
  log_debug("IRC SENDING (raw): (", this->get_hostname(), ") ", txt);
louiz’'s avatar
louiz’ committed
404 405 406
  this->send_data(txt + "\r\n");
}

louiz’'s avatar
louiz’ committed
407 408
void IrcClient::send_user_command(const std::string& username, const std::string& realname)
{
louiz’'s avatar
louiz’ committed
409
  this->send_message(IrcMessage("USER", {username, this->user_hostname, "ignored", realname}));
louiz’'s avatar
louiz’ committed
410 411 412 413 414 415 416
}

void IrcClient::send_nick_command(const std::string& nick)
{
  this->send_message(IrcMessage("NICK", {nick}));
}

417 418 419 420 421
void IrcClient::send_pass_command(const std::string& password)
{
  this->send_message(IrcMessage("PASS", {password}));
}

louiz’'s avatar
louiz’ committed
422 423 424 425 426
void IrcClient::send_webirc_command(const std::string& password, const std::string& user_ip)
{
  this->send_message(IrcMessage("WEBIRC", {password, "biboumi", this->user_hostname, user_ip}));
}

427 428 429 430 431
void IrcClient::send_kick_command(const std::string& chan_name, const std::string& target, const std::string& reason)
{
  this->send_message(IrcMessage("KICK", {chan_name, target, reason}));
}

432 433
void IrcClient::send_list_command()
{
434
  this->send_message(IrcMessage("LIST", {"*"}));
435 436
}

437 438 439 440 441
void IrcClient::send_invitation(const std::string& chan_name, const std::string& nick)
{
  this->send_message(IrcMessage("INVITE", {nick, chan_name}));
}

442 443 444 445 446
void IrcClient::send_topic_command(const std::string& chan_name, const std::string& topic)
{
  this->send_message(IrcMessage("TOPIC", {chan_name, topic}));
}

447
void IrcClient::send_quit_command(const std::string& reason)
louiz’'s avatar
louiz’ committed
448
{
449
  this->send_message(IrcMessage("QUIT", {reason}));
louiz’'s avatar
louiz’ committed
450 451
}

452
void IrcClient::send_join_command(const std::string& chan_name, const std::string& password)
louiz’'s avatar
louiz’ committed
453
{
louiz’'s avatar
louiz’ committed
454
  if (this->welcomed == false)
455 456 457 458 459 460
    {
      const auto it = std::find_if(begin(this->channels_to_join), end(this->channels_to_join),
                                   [&chan_name](const auto& pair) { return std::get<0>(pair) == chan_name; });
      if (it == end(this->channels_to_join))
        this->channels_to_join.emplace_back(chan_name, password);
    }
461 462
  else if (password.empty())
    this->send_message(IrcMessage("JOIN", {chan_name}));
louiz’'s avatar
louiz’ committed
463
  else
464
    this->send_message(IrcMessage("JOIN", {chan_name, password}));
465
  this->start();
466 467
}

louiz’'s avatar
louiz’ committed
468
bool IrcClient::send_channel_message(const std::string& chan_name, const std::string& body)
469
{
louiz’'s avatar
louiz’ committed
470 471 472
  IrcChannel* channel = this->get_channel(chan_name);
  if (channel->joined == false)
    {
473
      log_warning("Cannot send message to channel ", chan_name, ", it is not joined");
louiz’'s avatar
louiz’ committed
474 475
      return false;
    }
476 477
  // The max size is 512, taking into account the whole message, not just
  // the text we send.
478 479 480
  // This includes our own nick, constants for username and host (because these
  // are notoriously hard to know what the server will use), in addition to the basic
  // components of the message we send (command name, chan name, \r\n etc.)
481
  //  : + NICK + ! + USER + @ + HOST + <space> + PRIVMSG + <space> + CHAN + <space> + : + \r\n
482 483 484 485
  // 63 is the maximum hostname length defined by the protocol.  10 seems to be
  // the username limit.
  constexpr auto max_username_size = 10;
  constexpr auto max_hostname_size = 63;
486
  const auto line_size = 512 -
487
                         this->current_nick.size() - max_username_size - max_hostname_size -
488
                         ::strlen(":!@ PRIVMSG ") - chan_name.length() - ::strlen(" :\r\n");
489 490 491
  const auto lines = cut(body, line_size);
  for (const auto& line: lines)
    this->send_message(IrcMessage("PRIVMSG", {chan_name, line}));
louiz’'s avatar
louiz’ committed
492 493 494
  return true;
}

louiz’'s avatar
louiz’ committed
495
void IrcClient::send_private_message(const std::string& username, const std::string& body, const std::string& type)
louiz’'s avatar
louiz’ committed
496
{
497 498 499
  std::string::size_type pos = 0;
  while (pos < body.size())
    {
louiz’'s avatar
louiz’ committed
500
      this->send_message(IrcMessage(std::string(type), {username, body.substr(pos, 400)}));
501 502
      pos += 400;
    }
503 504 505
  // We always try to insert and we don't care if the username was already
  // in the set.
  this->nicks_to_treat_as_private.insert(username);
louiz’'s avatar
louiz’ committed
506 507
}

louiz’'s avatar
louiz’ committed
508 509
void IrcClient::send_part_command(const std::string& chan_name, const std::string& status_message)
{
louiz’'s avatar
louiz’ committed
510
  this->send_message(IrcMessage("PART", {chan_name, status_message}));
louiz’'s avatar
louiz’ committed
511 512 513 514 515 516 517 518
}

void IrcClient::send_mode_command(const std::string& chan_name, const std::vector<std::string>& arguments)
{
  std::vector<std::string> args(arguments);
  args.insert(args.begin(), chan_name);
  IrcMessage m("MODE", std::move(args));
  this->send_message(std::move(m));
louiz’'s avatar
louiz’ committed
519 520
}

louiz’'s avatar
louiz’ committed
521 522 523 524
void IrcClient::send_pong_command(const IrcMessage& message)
{
  const std::string id = message.arguments[0];
  this->send_message(IrcMessage("PONG", {id}));
525 526
}

louiz’'s avatar
louiz’ committed
527
void IrcClient::on_pong(const IrcMessage&)
528 529 530
{
}

531 532 533 534 535
void IrcClient::send_ping_command()
{
  this->send_message(IrcMessage("PING", {"biboumi"}));
}

536 537 538 539 540
void IrcClient::forward_server_message(const IrcMessage& message)
{
  const std::string from = message.prefix;
  const std::string body = message.arguments[1];

541
  this->bridge.send_xmpp_message(this->hostname, from, body);
542
}
louiz’'s avatar
louiz’ committed
543

544 545 546
void IrcClient::on_notice(const IrcMessage& message)
{
  std::string from = message.prefix;
547
  std::string to = message.arguments[0];
548 549
  const std::string body = message.arguments[1];

550 551 552 553 554 555 556 557 558
  // Handle notices starting with [#channame] as if they were sent to that channel
  if (body.size() > 3 && body[0] == '[')
    {
      const auto chan_prefix = body[1];
      auto end = body.find(']');
      if (this->chantypes.find(chan_prefix) != this->chantypes.end() && end != std::string::npos)
        to = body.substr(1, end - 1);
    }

559 560 561 562
  if (!body.empty() && body[0] == '\01' && body[body.size() - 1] == '\01')
    // Do not forward the notice to the user if it's a CTCP command
    return ;

563
  if (!to.empty() && this->chantypes.find(to[0]) == this->chantypes.end())
564
    {
louiz’'s avatar
louiz’ committed
565
      // The notice is for us precisely.
566 567 568 569 570 571 572 573 574

      // Find out if we already sent a private message to this user. If yes
      // we treat that message as a private message coming from
      // it. Otherwise we treat it as a notice coming from the server.
      IrcUser user(from);
      std::string nick = utils::tolower(user.nick);
      if (this->nicks_to_treat_as_private.find(nick) !=
          this->nicks_to_treat_as_private.end())
        { // We previously sent a message to that nick)
575
          this->bridge.send_message({nick, this->hostname, Iid::Type::User}, nick, body,
576 577 578
                                     false);
        }
      else
579
        this->bridge.send_xmpp_message(this->hostname, from, body);
580
    }
581 582
  else
    {
583 584 585
      // The notice was directed at a channel we are in. Modify the message
      // to indicate that it is a notice, and make it a MUC message coming
      // from the MUC JID
586
      IrcMessage modified_message(std::move(from), "PRIVMSG", {to, "\u000303[notice]\u0003 " + body});
587 588 589 590
      this->on_channel_message(modified_message);
    }
}

louiz’'s avatar
louiz’ committed
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
void IrcClient::on_isupport_message(const IrcMessage& message)
{
  const size_t len = message.arguments.size();
  for (size_t i = 1; i < len; ++i)
  {
    const std::string token = message.arguments[i];
    if (token.substr(0, 10) == "CHANMODES=")
    {
      this->chanmodes = utils::split(token.substr(11), ',');
      // make sure we have 4 strings
      this->chanmodes.resize(4);
    }
    else if (token.substr(0, 7) == "PREFIX=")
      {
        size_t i = 8;           // jump PREFIX=(
        size_t j = 9;
        // Find the ) char
        while (j < token.size() && token[j] != ')')
          j++;
        j++;
        while (j < token.size() && token[i] != ')')
612 613 614 615
          {
            this->sorted_user_modes.push_back(token[i]);
            this->prefix_to_mode[token[j++]] = token[i++];
          }
louiz’'s avatar
louiz’ committed
616
      }
617 618 619 620 621
    else if (token.substr(0, 10) == "CHANTYPES=")
      {
        // Remove the default types, they apply only if no other value is
        // specified.
        this->chantypes.clear();
622
        size_t i = 10;
623 624 625
        while (i < token.size())
          this->chantypes.insert(token[i++]);
      }
louiz’'s avatar
louiz’ committed
626 627
  }
}
628

louiz’'s avatar
louiz’ committed
629 630 631 632
void IrcClient::on_server_myinfo(const IrcMessage&)
{
}

633 634
void IrcClient::send_gateway_message(const std::string& message, const std::string& from)
{
635
  this->bridge.send_xmpp_message(this->hostname, from, message);
636 637
}

638 639
void IrcClient::set_and_forward_user_list(const IrcMessage& message)
{
louiz’'s avatar
louiz’ committed
640
  const std::string chan_name = utils::tolower(message.arguments[2]);
641 642 643 644
  IrcChannel* channel = this->get_channel(chan_name);
  std::vector<std::string> nicks = utils::split(message.arguments[3], ' ');
  for (const std::string& nick: nicks)
    {
645 646 647 648
      // Just create this dummy user to parse and get its modes
      IrcUser tmp_user{nick, this->prefix_to_mode};
      // Does this concern ourself
      if (channel->get_self() && channel->find_user(tmp_user.nick) == channel->get_self())
649
        {
650 651
          // We now know our own modes, that’s all.
          channel->get_self()->modes = tmp_user.modes;
652 653
        }
      else
654 655 656
        { // Otherwise this is a new user
          const IrcUser *user = channel->add_user(nick, this->prefix_to_mode);
          this->bridge.send_user_join(this->hostname, chan_name, user, user->get_most_significant_mode(this->sorted_user_modes), false);
657 658 659 660
        }
    }
}

louiz’'s avatar
louiz’ committed
661
void IrcClient::on_channel_join(const IrcMessage& message)
662
{
louiz’'s avatar
louiz’ committed
663
  const std::string chan_name = utils::tolower(message.arguments[0]);
louiz’'s avatar
louiz’ committed
664
  IrcChannel* channel;
665
  channel = this->get_channel(chan_name);
louiz’'s avatar
louiz’ committed
666
  const std::string nick = message.prefix;
667
  IrcUser* user = channel->add_user(nick, this->prefix_to_mode);
louiz’'s avatar
louiz’ committed
668
  if (channel->joined == false)
669
    channel->set_self(user);
louiz’'s avatar
louiz’ committed
670
  else
671
    this->bridge.send_user_join(this->hostname, chan_name, user, user->get_most_significant_mode(this->sorted_user_modes), false);
672 673
}

louiz’'s avatar
louiz’ committed
674 675 676 677 678
void IrcClient::on_channel_message(const IrcMessage& message)
{
  const IrcUser user(message.prefix);
  const std::string nick = user.nick;
  Iid iid;
louiz’'s avatar
louiz’ committed
679 680
  iid.set_local(message.arguments[0]);
  iid.set_server(this->hostname);
louiz’'s avatar
louiz’ committed
681
  const std::string body = message.arguments[1];
louiz’'s avatar
louiz’ committed
682
  bool muc = true;
louiz’'s avatar
louiz’ committed
683
  if (!this->get_channel(iid.get_local())->joined)
louiz’'s avatar
louiz’ committed
684
    {
685
      iid.type = Iid::Type::User;
louiz’'s avatar
louiz’ committed
686
      iid.set_local(nick);
louiz’'s avatar
louiz’ committed
687 688
      muc = false;
    }
louiz’'s avatar
louiz’ committed
689
  else
690
    iid.type = Iid::Type::Channel;
691 692 693
  if (!body.empty() && body[0] == '\01')
    {
      if (body.substr(1, 6) == "ACTION")
694
        this->bridge.send_message(iid, nick,
695
                  "/me" + body.substr(7, body.size() - 8), muc);
696
      else if (body.substr(1, 8) == "VERSION\01")
697
        this->bridge.send_iq_version_request(nick, this->hostname);
698
      else if (body.substr(1, 5) == "PING ")
699
        this->bridge.send_xmpp_ping_request(utils::tolower(nick), this->hostname,
700
                                             body.substr(6, body.size() - 7));
701 702
    }
  else
703
    this->bridge.send_message(iid, nick, body, muc);
louiz’'s avatar
louiz’ committed
704 705
}

706 707 708 709 710 711 712 713 714 715 716 717
void IrcClient::on_rpl_liststart(const IrcMessage&)
{
}

void IrcClient::on_rpl_list(const IrcMessage&)
{
}

void IrcClient::on_rpl_listend(const IrcMessage&)
{
}

louiz’'s avatar
louiz’ committed
718
void IrcClient::empty_motd(const IrcMessage&)
719 720 721 722
{
  this->motd.erase();
}

723 724 725 726 727 728 729 730
void IrcClient::on_invited(const IrcMessage& message)
{
  const std::string& chan_name = message.arguments[2];
  const std::string& invited_nick = message.arguments[1];

  this->bridge.send_xmpp_message(this->hostname, "", invited_nick + " has been invited to " + chan_name);
}

louiz’'s avatar
louiz’ committed
731 732
void IrcClient::on_empty_topic(const IrcMessage& message)
{
733
  const std::string chan_name = utils::tolower(message.arguments[1]);
734
  log_debug("empty topic for ", chan_name);
louiz’'s avatar
louiz’ committed
735 736 737 738 739
  IrcChannel* channel = this->get_channel(chan_name);
  if (channel)
    channel->topic.clear();
}

740 741 742 743 744 745 746 747 748
void IrcClient::on_motd_line(const IrcMessage& message)
{
  const std::string body = message.arguments[1];
  // We could send the MOTD without a line break between each IRC-message,
  // but sometimes it contains some ASCII art, we use line breaks to keep
  // them intact.
  this->motd += body+"\n";
}

louiz’'s avatar
louiz’ committed
749
void IrcClient::send_motd(const IrcMessage&)
750
{
751
  this->bridge.send_xmpp_message(this->hostname, "", this->motd);
752 753
}

754 755
void IrcClient::on_topic_received(const IrcMessage& message)
{
756
  const std::string chan_name = utils::tolower(message.arguments[message.arguments.size() - 2]);
757
  IrcUser author(message.prefix);
758
  IrcChannel* channel = this->get_channel(chan_name);
759
  channel->topic = message.arguments[message.arguments.size() - 1];
760
  channel->topic_author = author.nick;
louiz’'s avatar
louiz’ committed
761
  if (channel->joined)
762 763 764 765 766 767 768 769 770
    this->bridge.send_topic(this->hostname, chan_name, channel->topic, channel->topic_author);
}

void IrcClient::on_topic_who_time_received(const IrcMessage& message)
{
  IrcUser author(message.arguments[2]);
  const std::string chan_name = utils::tolower(message.arguments[1]);
  IrcChannel* channel = this->get_channel(chan_name);
  channel->topic_author = author.nick;
771 772 773 774
}

void IrcClient::on_channel_completely_joined(const IrcMessage& message)
{
louiz’'s avatar
louiz’ committed
775
  const std::string chan_name = utils::tolower(message.arguments[1]);
776
  IrcChannel* channel = this->get_channel(chan_name);
777
  channel->joined = true;
778 779
  this->bridge.send_user_join(this->hostname, chan_name, channel->get_self(),
                              channel->get_self()->get_most_significant_mode(this->sorted_user_modes), true);
780
  this->bridge.send_room_history(this->hostname, chan_name, this->history_limit);
781
  this->bridge.send_topic(this->hostname, chan_name, channel->topic, channel->topic_author);
782
}
louiz’'s avatar
louiz’ committed
783

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
void IrcClient::on_banlist(const IrcMessage& message)
{
  const std::string chan_name = utils::tolower(message.arguments[1]);
  IrcChannel* channel = this->get_channel(chan_name);
  if (channel->joined)
    {
      Iid iid;
      iid.set_local(chan_name);
      iid.set_server(this->hostname);
      iid.type = Iid::Type::Channel;
      std::string body{message.arguments[2] + " banned"};
      if (message.arguments.size() >= 4)
        {
          IrcUser by(message.arguments[3], this->prefix_to_mode);
          body += " by " + by.nick;
        }
      if (message.arguments.size() >= 5)
        body += " on " + message.arguments[4];

      this->bridge.send_message(iid, "", body, true);
    }
}

void IrcClient::on_banlist_end(const IrcMessage& message)
{
  const std::string chan_name = utils::tolower(message.arguments[1]);
  IrcChannel* channel = this->get_channel(chan_name);
  if (channel->joined)
    {
      Iid iid;
      iid.set_local(chan_name);
      iid.set_server(this->hostname);
      iid.type = Iid::Type::Channel;
      this->bridge.send_message(iid, "", message.arguments[2], true);
    }
}

821 822 823 824 825 826 827 828 829 830 831 832
void IrcClient::on_own_host_received(const IrcMessage& message)
{
  this->own_host = message.arguments[1];
  const std::string from = message.prefix;
  if (message.arguments.size() >= 3)
    this->bridge.send_xmpp_message(this->hostname, from,
                                   this->own_host + " " + message.arguments[2]);
  else
    this->bridge.send_xmpp_message(this->hostname, from, this->own_host +
                                                         " is now your displayed host");
}

833 834 835 836 837 838 839
void IrcClient::on_erroneous_nickname(const IrcMessage& message)
{
  const std::string error_msg = message.arguments.size() >= 3 ?
    message.arguments[2]: "Erroneous nickname";
  this->send_gateway_message(error_msg + ": " + message.arguments[1], message.prefix);
}

840 841 842 843
void IrcClient::on_nickname_conflict(const IrcMessage& message)
{
  const std::string nickname = message.arguments[1];
  this->on_generic_error(message);
844
  for (const auto& pair: this->channels)
845 846
  {
    Iid iid;
847
    iid.set_local(pair.first);
louiz’'s avatar
louiz’ committed
848
    iid.set_server(this->hostname);
849
    iid.type = Iid::Type::Channel;
850
    this->bridge.send_nickname_conflict_error(iid, nickname);
851 852 853
  }
}

854 855 856 857 858 859 860
void IrcClient::on_nickname_change_too_fast(const IrcMessage& message)
{
  const std::string nickname = message.arguments[1];
  std::string txt;
  if (message.arguments.size() >= 3)
    txt = message.arguments[2];
  this->on_generic_error(message);
861
  for (const auto& pair: this->channels)
862 863
  {
    Iid iid;
864
    iid.set_local(pair.first);
865
    iid.set_server(this->hostname);
866
    iid.type = Iid::Type::Channel;
867
    this->bridge.send_presence_error(iid, nickname,
868 869 870 871
                                      "cancel", "not-acceptable",
                                      "", txt);
  }
}
872 873 874 875 876 877 878
void IrcClient::on_generic_error(const IrcMessage& message)
{
  const std::string error_msg = message.arguments.size() >= 3 ?
    message.arguments[2]: "Unspecified error";
  this->send_gateway_message(message.arguments[1] + ": " + error_msg, message.prefix);
}

879 880 881 882 883 884
void IrcClient::on_useronchannel(const IrcMessage& message)
{
  this->send_gateway_message(message.arguments[1] + " " + message.arguments[3] + " "
                             + message.arguments[2]);
}

louiz’'s avatar
louiz’ committed
885 886 887 888
void IrcClient::on_welcome_message(const IrcMessage& message)
{
  this->current_nick = message.arguments[0];
  this->welcomed = true;
889
#ifdef USE_DATABASE
890
  auto options = Database::get_irc_server_options(this->bridge.get_bare_jid(),
891
                                                  this->get_hostname());
892 893 894
  const auto commands = Database::get_after_connection_commands(options);
  for (const auto& command: commands)
    this->send_raw(command.col<Database::AfterConnectionCommand>());
895
#endif
896 897
  // Install a repeated events to regularly send a PING
  TimedEventsManager::instance().add_event(TimedEvent(240s, std::bind(&IrcClient::send_ping_command, this),
898
                                                      "PING" + this->hostname + this->bridge.get_jid()));
899 900 901 902
  std::string channels{};
  std::string channels_with_key{};
  std::string keys{};

903
  for (const auto& tuple: this->channels_to_join)
904 905 906 907 908 909 910
    {
      const auto& chan = std::get<0>(tuple);
      const auto& key = std::get<1>(tuple);
      if (chan.empty())
        continue;
      if (!key.empty())
        {
911 912 913 914 915 916
          if (keys.size() + channels_with_key.size() >= 300)
            { // Arbitrary size, to make sure we never send more than 512
              this->send_join_command(channels_with_key, keys);
              channels_with_key.clear();
              keys.clear();
            }
917 918 919 920 921 922 923 924 925
          if (!keys.empty())
            keys += ",";
          keys += key;
          if (!channels_with_key.empty())
            channels_with_key += ",";
          channels_with_key += chan;
        }
      else
        {
926 927 928 929 930
          if (channels.size() >= 300)
            { // Arbitrary size, to make sure we never send more than 512
              this->send_join_command(channels, {});
              channels.clear();
            }
931 932 933 934 935 936 937 938 939
          if (!channels.empty())
            channels += ",";
          channels += chan;
        }
    }
  if (!channels.empty())
    this->send_join_command(channels, {});
  if (!channels_with_key.empty())
    this->send_join_command(channels_with_key, keys);
louiz’'s avatar
louiz’ committed
940 941
  this->channels_to_join.clear();
}
louiz’'s avatar
louiz’ committed
942 943 944

void IrcClient::on_part(const IrcMessage& message)
{
louiz’'s avatar
louiz’ committed
945
  const std::string chan_name = message.arguments[0];
louiz’'s avatar
louiz’ committed
946
  IrcChannel* channel = this->get_channel(chan_name);
947 948
  if (!channel->joined)
    return ;
louiz’'s avatar
louiz’ committed
949 950 951 952 953 954 955
  std::string txt;
  if (message.arguments.size() >= 2)
    txt = message.arguments[1];
  const IrcUser* user = channel->find_user(message.prefix);
  if (user)
    {
      std::string nick = user->nick;
956
      bool self = channel->get_self() && channel->get_self()->nick == nick;
957
      auto user_ptr = channel->remove_user(user);
louiz’'s avatar
louiz’ committed
958
      if (self)
louiz’'s avatar
louiz’ committed
959
      {
louiz’'s avatar
louiz’ committed
960
        this->channels.erase(utils::tolower(chan_name));