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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
|
/* Initialization and related routines.
*
* (C) 2003-2021 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.
*/
#include "services.h"
#include "config.h"
#include "users.h"
#include "protocol.h"
#include "bots.h"
#include "xline.h"
#include "socketengine.h"
#include "servers.h"
#include "language.h"
#ifndef _WIN32
#include <sys/wait.h>
#include <sys/stat.h>
#include <cerrno>
#include <grp.h>
#include <pwd.h>
#include <sys/types.h>
#endif
Anope::string Anope::ConfigDir = "conf", Anope::DataDir = "data", Anope::ModuleDir = "lib", Anope::LocaleDir = "locale", Anope::LogDir = "logs";
/* Vector of pairs of command line arguments and their params */
static std::vector<std::pair<Anope::string, Anope::string> > CommandLineArguments;
/** Called on startup to organize our starting arguments in a better way
* and check for errors
* @param ac number of args
* @param av args
*/
static void ParseCommandLineArguments(int ac, char **av)
{
for (int i = 1; i < ac; ++i)
{
Anope::string option = av[i];
Anope::string param;
while (!option.empty() && option[0] == '-')
option.erase(option.begin());
size_t t = option.find('=');
if (t != Anope::string::npos)
{
param = option.substr(t + 1);
option.erase(t);
}
if (option.empty())
continue;
CommandLineArguments.emplace_back(option, param);
}
}
/** Check if an argument was given on startup and its parameter
* @param name The argument name
* @param shortname A shorter name, eg --debug and -d
* @param param A string to put the param, if any, of the argument
* @return true if name/shortname was found, false if not
*/
static bool GetCommandLineArgument(const Anope::string &name, char shortname, Anope::string ¶m)
{
param.clear();
for (std::vector<std::pair<Anope::string, Anope::string> >::iterator it = CommandLineArguments.begin(), it_end = CommandLineArguments.end(); it != it_end; ++it)
{
if (it->first.equals_ci(name) || (it->first.length() == 1 && it->first[0] == shortname))
{
param = it->second;
return true;
}
}
return false;
}
/** Check if an argument was given on startup
* @param name The argument name
* @param shortname A shorter name, eg --debug and -d
* @return true if name/shortname was found, false if not
*/
static bool GetCommandLineArgument(const Anope::string &name, char shortname = 0)
{
Anope::string Unused;
return GetCommandLineArgument(name, shortname, Unused);
}
bool Anope::AtTerm()
{
return isatty(fileno(stdout)) && isatty(fileno(stdin)) && isatty(fileno(stderr));
}
static void setuidgid();
void Anope::Fork()
{
#ifndef _WIN32
kill(getppid(), SIGUSR2);
if (!freopen("/dev/null", "r", stdin))
Log() << "Unable to redirect stdin to /dev/null: " << Anope::LastError();
if (!freopen("/dev/null", "w", stdout))
Log() << "Unable to redirect stdout to /dev/null: " << Anope::LastError();
if (!freopen("/dev/null", "w", stderr))
Log() << "Unable to redirect stderr to /dev/null: " << Anope::LastError();
setpgid(0, 0);
setuidgid();
#else
FreeConsole();
#endif
}
void Anope::HandleSignal()
{
switch (Signal)
{
case SIGHUP:
{
Anope::SaveDatabases();
try
{
Configuration::Conf *new_config = new Configuration::Conf();
Configuration::Conf *old = Config;
Config = new_config;
Config->Post(old);
delete old;
}
catch (const ConfigException &ex)
{
Log() << "Error reloading configuration file: " << ex.GetReason();
}
break;
}
case SIGTERM:
case SIGINT:
#ifndef _WIN32
Log() << "Received " << strsignal(Signal) << " signal (" << Signal << "), exiting.";
Anope::QuitReason = Anope::string("Services terminating via signal ") + strsignal(Signal) + " (" + stringify(Signal) + ")";
#else
Log() << "Received signal " << Signal << ", exiting.";
Anope::QuitReason = Anope::string("Services terminating via signal ") + stringify(Signal);
#endif
Anope::Quitting = true;
Anope::SaveDatabases();
break;
}
Signal = 0;
}
#ifndef _WIN32
static void parent_signal_handler(int signal)
{
if (signal == SIGUSR2)
{
Anope::Quitting = true;
}
else if (signal == SIGCHLD)
{
Anope::ReturnValue = -1;
Anope::Quitting = true;
int status = 0;
wait(&status);
if (WIFEXITED(status))
Anope::ReturnValue = WEXITSTATUS(status);
}
}
#endif
static void SignalHandler(int sig)
{
Anope::Signal = sig;
}
static void InitSignals()
{
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SignalHandler;
sigaction(SIGHUP, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
sa.sa_handler = SIG_IGN;
#ifndef _WIN32
sigaction(SIGCHLD, &sa, NULL);
#endif
sigaction(SIGPIPE, &sa, NULL);
}
/* Remove our PID file. Done at exit. */
static void remove_pidfile()
{
remove(Config->GetBlock("serverinfo")->Get<const Anope::string>("pid").c_str());
}
/* Create our PID file and write the PID to it. */
static void write_pidfile()
{
FILE *pidfile = fopen(Config->GetBlock("serverinfo")->Get<const Anope::string>("pid").c_str(), "w");
if (pidfile)
{
#ifdef _WIN32
fprintf(pidfile, "%d\n", static_cast<int>(GetCurrentProcessId()));
#else
fprintf(pidfile, "%d\n", static_cast<int>(getpid()));
#endif
fclose(pidfile);
atexit(remove_pidfile);
}
else
throw CoreException("Can not write to PID file " + Config->GetBlock("serverinfo")->Get<const Anope::string>("pid"));
}
static void setuidgid()
{
#ifndef _WIN32
Configuration::Block *options = Config->GetBlock("options");
uid_t uid = -1;
gid_t gid = -1;
if (!options->Get<const Anope::string>("user").empty())
{
errno = 0;
struct passwd *u = getpwnam(options->Get<const Anope::string>("user").c_str());
if (u == NULL)
Log() << "Unable to setuid to " << options->Get<const Anope::string>("user") << ": " << Anope::LastError();
else
uid = u->pw_uid;
}
if (!options->Get<const Anope::string>("group").empty())
{
errno = 0;
struct group *g = getgrnam(options->Get<const Anope::string>("group").c_str());
if (g == NULL)
Log() << "Unable to setgid to " << options->Get<const Anope::string>("group") << ": " << Anope::LastError();
else
gid = g->gr_gid;
}
for (unsigned i = 0; i < Config->LogInfos.size(); ++i)
{
LogInfo& li = Config->LogInfos[i];
for (unsigned j = 0; j < li.logfiles.size(); ++j)
{
LogFile* lf = li.logfiles[j];
errno = 0;
if (chown(lf->filename.c_str(), uid, gid) != 0)
Log() << "Unable to change the ownership of " << lf->filename << " to " << uid << "/" << gid << ": " << Anope::LastError();
}
}
if (static_cast<int>(gid) != -1)
{
if (setgid(gid) == -1)
Log() << "Unable to setgid to " << options->Get<const Anope::string>("group") << ": " << Anope::LastError();
else
Log() << "Successfully set group to " << options->Get<const Anope::string>("group");
}
if (static_cast<int>(uid) != -1)
{
if (setuid(uid) == -1)
Log() << "Unable to setuid to " << options->Get<const Anope::string>("user") << ": " << Anope::LastError();
else
Log() << "Successfully set user to " << options->Get<const Anope::string>("user");
}
#endif
}
void Anope::Init(int ac, char **av)
{
/* Set file creation mask and group ID. */
#if defined(DEFUMASK) && HAVE_UMASK
umask(DEFUMASK);
#endif
Serialize::RegisterTypes();
/* Parse command line arguments */
ParseCommandLineArguments(ac, av);
if (GetCommandLineArgument("version", 'v'))
{
Log(LOG_TERMINAL) << "Anope-" << Anope::Version() << " -- " << Anope::VersionBuildString();
throw CoreException();
}
if (GetCommandLineArgument("help", 'h'))
{
Log(LOG_TERMINAL) << "Anope-" << Anope::Version() << " -- " << Anope::VersionBuildString();
Log(LOG_TERMINAL) << "Anope IRC Services (https://www.anope.org/)";
Log(LOG_TERMINAL) << "Usage ./" << Anope::ServicesBin << " [options] ...";
Log(LOG_TERMINAL) << "-c, --config=filename.conf";
Log(LOG_TERMINAL) << " --confdir=conf file directory";
Log(LOG_TERMINAL) << " --dbdir=database directory";
Log(LOG_TERMINAL) << "-d, --debug[=level]";
Log(LOG_TERMINAL) << "-h, --help";
Log(LOG_TERMINAL) << " --localedir=locale directory";
Log(LOG_TERMINAL) << " --logdir=logs directory";
Log(LOG_TERMINAL) << " --modulesdir=modules directory";
Log(LOG_TERMINAL) << "-e, --noexpire";
Log(LOG_TERMINAL) << "-n, --nofork";
Log(LOG_TERMINAL) << " --nothird";
Log(LOG_TERMINAL) << " --protocoldebug";
Log(LOG_TERMINAL) << "-r, --readonly";
Log(LOG_TERMINAL) << "-s, --support";
Log(LOG_TERMINAL) << "-v, --version";
Log(LOG_TERMINAL) << "";
Log(LOG_TERMINAL) << "Further support is available from https://www.anope.org/";
Log(LOG_TERMINAL) << "Or visit us on IRC at irc.anope.org #anope";
throw CoreException();
}
if (GetCommandLineArgument("nofork", 'n'))
Anope::NoFork = true;
if (GetCommandLineArgument("support", 's'))
{
Anope::NoFork = Anope::NoThird = true;
++Anope::Debug;
}
if (GetCommandLineArgument("readonly", 'r'))
Anope::ReadOnly = true;
if (GetCommandLineArgument("nothird"))
Anope::NoThird = true;
if (GetCommandLineArgument("noexpire", 'e'))
Anope::NoExpire = true;
if (GetCommandLineArgument("protocoldebug"))
Anope::ProtocolDebug = true;
Anope::string arg;
if (GetCommandLineArgument("debug", 'd', arg))
{
if (!arg.empty())
{
int level = arg.is_number_only() ? convertTo<int>(arg) : -1;
if (level > 0)
Anope::Debug = level;
else
throw CoreException("Invalid option given to --debug");
}
else
++Anope::Debug;
}
if (GetCommandLineArgument("config", 'c', arg))
{
if (arg.empty())
throw CoreException("The --config option requires a file name");
ServicesConf = Configuration::File(arg, false);
}
if (GetCommandLineArgument("confdir", 0, arg))
{
if (arg.empty())
throw CoreException("The --confdir option requires a path");
Anope::ConfigDir = arg;
}
if (GetCommandLineArgument("dbdir", 0, arg))
{
if (arg.empty())
throw CoreException("The --dbdir option requires a path");
Anope::DataDir = arg;
}
if (GetCommandLineArgument("localedir", 0, arg))
{
if (arg.empty())
throw CoreException("The --localedir option requires a path");
Anope::LocaleDir = arg;
}
if (GetCommandLineArgument("modulesdir", 0, arg))
{
if (arg.empty())
throw CoreException("The --modulesdir option requires a path");
Anope::ModuleDir = arg;
}
if (GetCommandLineArgument("logdir", 0, arg))
{
if (arg.empty())
throw CoreException("The --logdir option requires a path");
Anope::LogDir = arg;
}
/* Chdir to Services data directory. */
if (chdir(Anope::ServicesDir.c_str()) < 0)
{
throw CoreException("Unable to chdir to " + Anope::ServicesDir + ": " + Anope::LastError());
}
Log(LOG_TERMINAL) << "Anope " << Anope::Version() << ", " << Anope::VersionBuildString();
#ifdef _WIN32
if (!SupportedWindowsVersion())
throw CoreException(GetWindowsVersion() + " is not a supported version of Windows");
#else
/* If we're root, issue a warning now */
if (!getuid() && !getgid())
{
/* If we are configured to setuid later, don't issue a warning */
Configuration::Block *options = Config->GetBlock("options");
if (options->Get<const Anope::string>("user").empty())
{
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
#ifdef _WIN32
Log(LOG_TERMINAL) << "Using configuration file " << Anope::ConfigDir << "\\" << ServicesConf.GetName();
#else
Log(LOG_TERMINAL) << "Using configuration file " << Anope::ConfigDir << "/" << ServicesConf.GetName();
/* Fork to background */
if (!Anope::NoFork)
{
/* Install these before fork() - it is possible for the child to
* connect and kill() the parent before it is able to install the
* handler.
*/
struct sigaction sa, old_sigusr2, old_sigchld;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = parent_signal_handler;
sigaction(SIGUSR2, &sa, &old_sigusr2);
sigaction(SIGCHLD, &sa, &old_sigchld);
int i = fork();
if (i > 0)
{
sigset_t mask;
sigemptyset(&mask);
sigsuspend(&mask);
exit(Anope::ReturnValue);
}
else if (i == -1)
{
Log() << "Error, unable to fork: " << Anope::LastError();
Anope::NoFork = true;
}
/* Child doesn't need these */
sigaction(SIGUSR2, &old_sigusr2, NULL);
sigaction(SIGCHLD, &old_sigchld, NULL);
}
#endif
/* Initialize the socket engine. Note that some engines can not survive a fork(), so this must be here. */
SocketEngine::Init();
/* Read configuration file; exit if there are problems. */
try
{
Config = new Configuration::Conf();
}
catch (const ConfigException &ex)
{
Log(LOG_TERMINAL) << ex.GetReason();
Log(LOG_TERMINAL) << "*** Support resources: Read through the anope.conf self-contained";
Log(LOG_TERMINAL) << "*** documentation. Read the documentation files found in the 'docs'";
Log(LOG_TERMINAL) << "*** folder. Visit our portal located at https://www.anope.org/. Join";
Log(LOG_TERMINAL) << "*** our support channel on /server irc.anope.org channel #anope.";
throw CoreException("Configuration file failed to validate");
}
/* Create me */
Configuration::Block *block = Config->GetBlock("serverinfo");
Me = new Server(NULL, block->Get<const Anope::string>("name"), 0, block->Get<const Anope::string>("description"), block->Get<const Anope::string>("id"));
for (botinfo_map::const_iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it)
{
it->second->server = Me;
++Me->users;
}
/* Announce ourselves to the logfile. */
Log() << "Anope " << Anope::Version() << " starting up" << (Anope::Debug || Anope::ReadOnly ? " (options:" : "") << (Anope::Debug ? " debug" : "") << (Anope::ReadOnly ? " readonly" : "") << (Anope::Debug || Anope::ReadOnly ? ")" : "");
InitSignals();
/* Initialize multi-language support */
Language::InitLanguages();
/* Initialize random number generator */
block = Config->GetBlock("options");
srand(block->Get<unsigned>("seed") ^ time(NULL));
/* load modules */
Log() << "Loading modules...";
for (int i = 0; i < Config->CountBlock("module"); ++i)
ModuleManager::LoadModule(Config->GetBlock("module", i)->Get<const Anope::string>("name"), NULL);
#ifndef _WIN32
/* We won't background later, so we should setuid now */
if (Anope::NoFork)
setuidgid();
#endif
Module *protocol = ModuleManager::FindFirstOf(PROTOCOL);
if (protocol == NULL)
throw CoreException("You must load a protocol module!");
/* Write our PID to the PID file. */
write_pidfile();
Log() << "Using IRCd protocol " << protocol->name;
/* Auto assign sid if applicable */
if (IRCD->RequiresID)
{
Anope::string sid = IRCD->SID_Retrieve();
if (Me->GetSID() == Me->GetName())
Me->SetSID(sid);
for (botinfo_map::iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it)
it->second->GenerateUID();
}
/* Load up databases */
Log() << "Loading databases...";
EventReturn MOD_RESULT;
FOREACH_RESULT(OnLoadDatabase, MOD_RESULT, ());
static_cast<void>(MOD_RESULT);
Log() << "Databases loaded";
FOREACH_MOD(OnPostInit, ());
for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it)
it->second->Sync();
Serialize::CheckTypes();
}
|