summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: cdddc3163aa78e4abce724173ffb329529486b09 (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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/* Services -- main source file.
 *
 * (C) 2003-2012 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 *
 * Based on the original code of Epona by Lara.
 * Based on the original code of Services by Andy Church.
 *
 * This program 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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 (see the file COPYING); if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "services.h"
#include "timers.h"
#include "extern.h"
#include "uplink.h"
#include "config.h"
#include "protocol.h"
#include "servers.h"
#include "bots.h"
#include "dns.h"
#include "signals.h"
#include "socketengine.h"

#ifndef _WIN32
#include <limits.h>
#else
#include <process.h>
#endif

/******** Global variables! ********/

/* Command-line options: (note that configuration variables are in config.c) */
Anope::string services_dir;	/* -dir dirname */
Anope::string services_bin;	/* Binary as specified by the user */
Anope::string binary_dir; /* Used to store base path for Anope */
int debug = 0;				/* -debug */
bool readonly = false;		/* -readonly */
bool nofork = false;		/* -nofork */
bool nothird = false;		/* -nothrid */
bool noexpire = false;		/* -noexpire */
bool protocoldebug = false;	/* -protocoldebug */

/* Set to 1 if we are to quit */
bool quitting = false;
int return_code = 0;

/* Set to true if we are restarting */
bool restarting = false;

/* Contains a message as to why services is terminating */
Anope::string quitmsg;

/* At what time were we started? */
time_t start_time = time(NULL);

time_t Anope::CurTime = time(NULL);

/******** Local variables! ********/

/*************************************************************************/

class UpdateTimer : public Timer
{
 public:
	UpdateTimer(time_t timeout) : Timer(timeout, Anope::CurTime, true) { }

	void Tick(time_t)
	{
		save_databases();
	}
};

UplinkSocket *UplinkSock = NULL;
int CurrentUplink = -1;

static void Connect();

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

	void Tick(time_t)
	{
		try
		{
			Connect();
		}
		catch (const SocketException &ex)
		{
			Log(LOG_TERMINAL) << "Unable to connect to uplink #" << (CurrentUplink + 1) << " (" << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port << "): " << ex.GetReason();
		}
	}
};

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

UplinkSocket::~UplinkSocket()
{
	if (ircdproto && Me && !Me->GetLinks().empty() && Me->GetLinks()[0]->IsSynced())
	{
		FOREACH_MOD(I_OnServerDisconnect, OnServerDisconnect());

		for (Anope::insensitive_map<User *>::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 */
				ircdproto->SendQuit(u, "Shutting down");
				BotInfo* bi = findbot(u->nick);
				if (bi != NULL)
					bi->introduced = false;
			}
		}

		ircdproto->SendSquit(Me, quitmsg);

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

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

	UplinkSock = NULL;

	Me->SetFlag(SERVER_SYNCING);

	if (AtTerm())
	{
		if (static_cast<unsigned>(CurrentUplink + 1) == Config->Uplinks.size())
		{
			quitting = true;
			quitmsg = "Unable to connect to any uplink";
			return_code = -1;
		}
		else
		{
			new ReconnectTimer(1);
		}
	}
	else if (!quitting)
	{
		int Retry = Config->RetryWait;
		if (Retry <= 0)
			Retry = 60;

		Log() << "Disconnected, retrying in " << Retry << " seconds";
		new ReconnectTimer(Retry);
	}
}

bool UplinkSocket::Read(const Anope::string &buf)
{
	process(buf);
	return true;
}

void UplinkSocket::OnConnect()
{
	Log(LOG_TERMINAL) << "Successfully connected to uplink #" << (CurrentUplink + 1) << " " << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port;
	ircdproto->SendConnect();
	FOREACH_MOD(I_OnServerConnect, OnServerConnect());
}

void UplinkSocket::OnError(const Anope::string &error)
{
	Log(LOG_TERMINAL) << "Unable to connect to uplink #" << (CurrentUplink + 1) << " (" << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port << ")" << (!error.empty() ? (": " + error) : "");
}

UplinkSocket::Message::Message() : server(NULL), user(NULL)
{
}

UplinkSocket::Message::Message(const Server *s) : server(s), user(NULL)
{
}

UplinkSocket::Message::Message(const User *u) : server(NULL), user(u)
{
	if (!u)
		server = Me;
}

UplinkSocket::Message::~Message()
{
	Anope::string message_source = "";

	if (this->server != NULL)
	{
		if (this->server != Me && !this->server->HasFlag(SERVER_JUPED))
		{
			Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << this->server->GetName() << " who is not from me?";
			return;
		}

		if (ircd->ts6)
			message_source = this->server->GetSID();
		else
			message_source = this->server->GetName();
	}
	else if (this->user != NULL)
	{
		if (this->user->server != Me && !this->user->server->HasFlag(SERVER_JUPED))
		{
			Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << this->user->nick << " who is not from me?";
			return;
		}

		const BotInfo *bi = findbot(this->user->nick);
		if (bi != NULL && bi->introduced == false)
		{
			Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << bi->nick << " when not introduced";
			return;
		}

		if (ircd->ts6)
			message_source = this->user->GetUID();
		else
			message_source = this->user->nick;
	}

	if (!UplinkSock)
	{
		if (!message_source.empty())
			Log(LOG_DEBUG) << "Attempted to send \"" << message_source << " " << this->buffer.str() << "\" with UplinkSock NULL";
		else
			Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" with UplinkSock NULL";
		return;
	}

	if (!message_source.empty())
	{
		UplinkSock->Write(":" + message_source + " " + this->buffer.str());
		Log(LOG_RAWIO) << "Sent: :" << message_source << " " << this->buffer.str();
	}
	else
	{
		UplinkSock->Write(this->buffer.str());
		Log(LOG_RAWIO) << "Sent: " << this->buffer.str();
	}
}

static void Connect()
{
	if (static_cast<unsigned>(++CurrentUplink) >= Config->Uplinks.size())
		CurrentUplink = 0;

	ServerConfig::Uplink *u = Config->Uplinks[CurrentUplink];

	new UplinkSocket();
	if (!Config->LocalHost.empty())
		UplinkSock->Bind(Config->LocalHost);
	FOREACH_MOD(I_OnPreServerConnect, OnPreServerConnect());
	DNSQuery rep = DNSManager::BlockingQuery(u->host, u->ipv6 ? DNS_QUERY_AAAA : DNS_QUERY_A);
	Anope::string reply_ip = !rep.answers.empty() ? rep.answers.front().rdata : u->host;
	Log(LOG_TERMINAL) << "Attempting to connect to uplink #" << (CurrentUplink + 1) << " " << u->host << " (" << reply_ip << "), port " << u->port;
	UplinkSock->Connect(reply_ip, u->port);
}

/*************************************************************************/

void save_databases()
{
	if (readonly)
		return;

	EventReturn MOD_RESULT;
	FOREACH_RESULT(I_OnSaveDatabase, OnSaveDatabase());
	Log(LOG_DEBUG) << "Saving databases";
}

/*************************************************************************/

std::vector<Signal *> Signal::SignalHandlers;

void Signal::SignalHandler(int signal)
{
	for (unsigned i = 0, j = SignalHandlers.size(); i < j; ++i)
		if (SignalHandlers[i]->signal == signal)
			SignalHandlers[i]->Notify();
}

Signal::Signal(int s) : Pipe(), signal(s)
{
	memset(&this->old, 0, sizeof(this->old));

	this->action.sa_flags = 0;
	sigemptyset(&this->action.sa_mask);
	this->action.sa_handler = SignalHandler;
	
	if (sigaction(s, &this->action, &this->old) == -1)
		throw CoreException("Unable to install signal " + stringify(s) + ": " + Anope::LastError());

	SignalHandlers.push_back(this);
}

Signal::~Signal()
{
	std::vector<Signal *>::iterator it = std::find(SignalHandlers.begin(), SignalHandlers.end(), this);
	if (it != SignalHandlers.end())
		SignalHandlers.erase(it);
	
	sigaction(this->signal, &this->old, NULL);
}

/*************************************************************************/

/** The following comes from InspIRCd to get the full path of the Anope executable
 */
Anope::string GetFullProgDir(const Anope::string &argv0)
{
	char buffer[PATH_MAX];
#ifdef _WIN32
	/* Windows has specific API calls to get the EXE path that never fail.
	 * For once, Windows has something of use, compared to the POSIX code
	 * for this, this is positively neato.
	 */
	if (GetModuleFileName(NULL, buffer, PATH_MAX))
	{
		Anope::string fullpath = buffer;
		Anope::string::size_type n = fullpath.rfind("\\");
		services_bin = fullpath.substr(n + 1, fullpath.length());
		return fullpath.substr(0, n);
	}
#else
	// Get the current working directory
	if (getcwd(buffer, PATH_MAX))
	{
		Anope::string remainder = argv0;

		services_bin = remainder;
		Anope::string::size_type n = services_bin.rfind("/");
		Anope::string fullpath;
		if (services_bin[0] == '/')
			fullpath = services_bin.substr(0, n);
		else
			fullpath = Anope::string(buffer) + "/" + services_bin.substr(0, n);
		services_bin = services_bin.substr(n + 1, remainder.length());
		return fullpath;
	}
#endif
	return "/";
}

/*************************************************************************/

/* Main routine.  (What does it look like? :-) ) */

int main(int ac, char **av, char **envp)
{
#ifndef _WIN32
	/* If we're root, issue a warning now */
	if (!getuid() && !getgid())
	{
		std::cerr << "WARNING: You are currently running Anope as the root superuser. Anope does not" << std::endl;
		std::cerr << "         require root privileges to run, and it is discouraged that you run Anope" << std::endl;
		std::cerr << "         as the root superuser." << std::endl;
		sleep(3);
	}
#endif

	binary_dir = GetFullProgDir(av[0]);
	if (binary_dir[binary_dir.length() - 1] == '.')
		binary_dir = binary_dir.substr(0, binary_dir.length() - 2);

#ifdef _WIN32
	Anope::string::size_type n = binary_dir.rfind('\\');
#else
	Anope::string::size_type n = binary_dir.rfind('/');
#endif
	services_dir = binary_dir.substr(0, n);

	/* Clean out the module runtime directory prior to running, just in case files were left behind during a previous run */
	ModuleManager::CleanupRuntimeDirectory();

#ifdef _WIN32
	OnStartup();
#endif

	try
	{
		/* General initialization first */
		Init(ac, av);
	}
	catch (const FatalException &ex)
	{
		Log() << ex.GetReason();
		return -1;
	}

	try
	{
		Connect();
	}
	catch (const SocketException &ex)
	{
		Log(LOG_TERMINAL) << "Unable to connect to uplink #" << CurrentUplink << " (" << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port << "): " << ex.GetReason();
	}

	/* Set up timers */
	time_t last_check = Anope::CurTime;
	UpdateTimer updateTimer(Config->UpdateTimeout);

	/*** Main loop. ***/
	while (!quitting)
	{
		Log(LOG_DEBUG_2) << "Top of main loop";

		/* Process timers */
		if (Anope::CurTime - last_check >= Config->TimeoutCheck)
		{
			TimerManager::TickTimers(Anope::CurTime);
			last_check = Anope::CurTime;
		}

		/* Process the socket engine */
		SocketEngine::Process();
	}

	if (restarting)
	{
		FOREACH_MOD(I_OnRestart, OnRestart());
	}
	else
	{
		FOREACH_MOD(I_OnShutdown, OnShutdown());
	}

	if (quitmsg.empty())
		quitmsg = "Terminating, reason unknown";
	Log() << quitmsg;

	delete UplinkSock;

	ModuleManager::UnloadAll();
	SocketEngine::Shutdown();
	for (Module *m; (m = ModuleManager::FindFirstOf(PROTOCOL)) != NULL;)
		ModuleManager::UnloadModule(m, NULL);

	ModuleManager::CleanupRuntimeDirectory();

#ifdef _WIN32
	OnShutdown();
#endif

	if (restarting)
	{
		chdir(binary_dir.c_str());
		av[0] = const_cast<char *>(("./" + services_bin).c_str());
		execve(services_bin.c_str(), av, envp);
		Log() << "Restart failed";
		return_code = -1;
	}

	return return_code;
}