summaryrefslogtreecommitdiff
path: root/src/uplink.cpp
blob: bd069843c982846016d594c75418df9230a34472 (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
/*
 * Anope IRC Services
 *
 * Copyright (C) 2012-2017 Anope Team <team@anope.org>
 *
 * This file is part of Anope. Anope is free software; you can
 * redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software
 * Foundation, version 2.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see see <http://www.gnu.org/licenses/>.
 */

#include "uplink.h"
#include "logger.h"
#include "config.h"
#include "protocol.h"
#include "servers.h"
#include "event.h"
#include "bots.h"
#include "timers.h"
#include "modules.h"

UplinkSocket *UplinkSock = NULL;

class ReconnectTimer : public Timer
{
 public:
	ReconnectTimer(int wait) : Timer(wait) { }

	void Tick(time_t) override
	{
		try
		{
			Uplink::Connect();
		}
		catch (const SocketException &ex)
		{
			Anope::Logger.Terminal(_("Unable to connect to uplink #{0} ({1}:{2}): {3}"),
					Anope::CurrentUplink + 1, Config->Uplinks[Anope::CurrentUplink].host,
					Config->Uplinks[Anope::CurrentUplink].port, ex.GetReason());
		}
	}
};

Uplink::PingTimer::PingTimer(time_t timeout) : Timer(timeout, Anope::CurTime, true)
{
}

void Uplink::PingTimer::Tick(time_t)
{
	Server *uplink;
	time_t ping_time = Config->GetBlock("options")->Get<time_t>("ping_time", "60");

	if (!UplinkSock || Anope::CurTime - UplinkSock->last_read <= ping_time)
		return;

	if (Me->GetLinks().empty())
		return;

	if (UplinkSock->pinged)
	{
		Anope::Logger.Log(_("No response from uplink in {0} seconds, disconnecting"), ping_time);

		UplinkSock->error = true;
		Anope::QuitReason = "Ping timeout";
		delete UplinkSock;
		Anope::QuitReason.clear();
		return;
	}

	Anope::Logger.Debug("Pinging uplink");

	uplink = Me->GetLinks().front();
	UplinkSock->pinged = true;

	IRCD->Send<messages::Ping>(Me->GetName(), uplink->GetName());
}

void Uplink::Connect()
{
	if (Config->Uplinks.empty())
	{
		Anope::Logger.Log(_("Warning: There are no configured uplinks."));
		return;
	}

	if (static_cast<unsigned>(++Anope::CurrentUplink) >= Config->Uplinks.size())
		Anope::CurrentUplink = 0;

	Configuration::Uplink &u = Config->Uplinks[Anope::CurrentUplink];

	new UplinkSocket();
	if (!Config->GetBlock("serverinfo")->Get<Anope::string>("localhost").empty())
		UplinkSock->Bind(Config->GetBlock("serverinfo")->Get<Anope::string>("localhost"));
	EventManager::Get()->Dispatch(&Event::PreServerConnect::OnPreServerConnect);
	Anope::string ip = Anope::Resolve(u.host, u.ipv6 ? AF_INET6 : AF_INET);
	Anope::Logger.Terminal(_("Attempting to connect to uplink #{0} {1} ({2}), port {3}"), Anope::CurrentUplink + 1, u.host, ip, u.port);
	UplinkSock->Connect(ip, u.port);
}

UplinkSocket::UplinkSocket() : Socket(-1, Config->Uplinks[Anope::CurrentUplink].ipv6), ConnectionSocket(), BufferedSocket()
{
	UplinkSock = this;
}

UplinkSocket::~UplinkSocket()
{
	if (!error && !Anope::Quitting)
	{
		this->OnError("");
		Module *protocol = ModuleManager::FindFirstOf(PROTOCOL);
		if (protocol && !protocol->name.find("inspircd"))
			Anope::Logger.Terminal(_("Check that you have loaded m_spanningtree.so on InspIRCd, and are not connecting Anope to an SSL enabled port without configuring SSL in Anope (or vice versa)"));
		else
			Anope::Logger.Terminal(_("Check that you are not connecting Anope to an SSL enabled port without configuring SSL in Anope (or vice versa)"));
	}

	if (IRCD && Servers::GetUplink() && Servers::GetUplink()->IsSynced())
	{
		EventManager::Get()->Dispatch(&Event::ServerDisconnect::OnServerDisconnect);

		for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it)
		{
			User *u = it->second;

			if (u->server == Me)
			{
				/* Don't use quitmsg here, it may contain information you don't want people to see */
				IRCD->SendQuit(u, "Shutting down");
				ServiceBot* bi = ServiceBot::Find(u->GetUID());
				if (bi != NULL)
					bi->introduced = false;
			}
		}

		IRCD->Send<messages::SQuit>(Me, Anope::QuitReason);

		this->ProcessWrite(); // Write out the last bit
	}

	for (unsigned i = Me->GetLinks().size(); i > 0; --i)
		if (!Me->GetLinks()[i - 1]->IsJuped())
			Me->GetLinks()[i - 1]->Delete(Me->GetName() + " " + Me->GetLinks()[i - 1]->GetName());

	UplinkSock = NULL;

	Me->Unsync();

	if (Anope::AtTerm())
	{
		if (static_cast<unsigned>(Anope::CurrentUplink + 1) == Config->Uplinks.size())
		{
			Anope::QuitReason = "Unable to connect to any uplink";
			Anope::Quitting = true;
			Anope::ReturnValue = -1;
		}
		else
		{
			new ReconnectTimer(1);
		}
	}
	else if (!Anope::Quitting)
	{
		time_t retry = Config->GetBlock("options")->Get<time_t>("retrywait");

		Anope::Logger.Log(_("Disconnected, retrying in {0} seconds"), retry);
		new ReconnectTimer(retry);
	}
}

bool UplinkSocket::ProcessRead()
{
	last_read = Anope::CurTime;
	pinged = false;

	bool b = BufferedSocket::ProcessRead();
	for (Anope::string buf; (buf = this->GetLine()).empty() == false;)
	{
		Anope::Process(buf);
		User::QuitUsers();
		Channel::DeleteChannels();
	}
	return b;
}

void UplinkSocket::OnConnect()
{
	Anope::Logger.Terminal(_("Successfully connected to uplink #{0} {1}:{2}"), Anope::CurrentUplink + 1, Config->Uplinks[Anope::CurrentUplink].host, Config->Uplinks[Anope::CurrentUplink].port);
	IRCD->Handshake();
	EventManager::Get()->Dispatch(&Event::ServerConnect::OnServerConnect);
}

void UplinkSocket::OnError(const Anope::string &err)
{
	if (!this->flags[SF_CONNECTED])
		Anope::Logger.Terminal(_("Unable to connect to uplink #{0} ({1}:{2}): {3}{4}"), Anope::CurrentUplink + 1, Config->Uplinks[Anope::CurrentUplink].host, Config->Uplinks[Anope::CurrentUplink].port, !err.empty() ? (": " + err) : "");
	else
		Anope::Logger.Terminal(_("Lost connection from uplink #{0} ({1}:{2}): {3}{4}"), Anope::CurrentUplink + 1, Config->Uplinks[Anope::CurrentUplink].host, Config->Uplinks[Anope::CurrentUplink].port, !err.empty() ? (": " + err) : "");
	error |= !err.empty();
}

void Uplink::SendMessage(IRCMessage &message)
{
	const MessageSource &source = message.GetSource();
	Anope::string buffer = IRCD->Format(message);

	if (source.GetServer() != NULL)
	{
		const Server *s = source.GetServer();

		if (s != Me && !s->IsJuped())
		{
			Anope::Logger.Debug("Attempted to send \"{0}\" from {1} who is not from me?", buffer, s->GetName());
			return;
		}
	}
	else if (source.GetUser() != NULL)
	{
		const User *u = source.GetUser();

		if (u->server != Me && !u->server->IsJuped())
		{
			Anope::Logger.Debug("Attempted to send \"{0}\" from {1} who is not from me?", buffer, u->nick);
			return;
		}

		const ServiceBot *bi = source.GetBot();
		if (bi != NULL && bi->introduced == false)
		{
			Anope::Logger.Debug("Attempted to send \"{0}\" from {1} when not introduced", buffer, bi->nick);
			return;
		}
	}

	if (!UplinkSock)
	{
		Anope::Logger.Debug("Attempted to send \"{0}\" when not connected", buffer);
		return;
	}

	UplinkSock->Write(buffer);
	Anope::Logger.RawIO("Sent: {0}", buffer);
}