2 // Copyright (c) 1997, 1998 Etienne BERNARD
3 // Copyright (C) 2002 Clinton Ebadi
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
26 #include <sys/types.h>
30 #include "DCCConnection.H"
31 #include "StringTokenizer.H"
32 #include "ServerConnection.H"
34 #include "UserCommands.H"
35 #include "DCCManager.H"
37 #define DEFAULT_NICKNAME "Bobot"
38 #define DEFAULT_USERNAME "bobot"
39 #define DEFAULT_IRCNAME "I'm a bobot++!"
40 #define DEFAULT_COMMANDCHAR '!'
41 #define DEFAULT_USERLISTFILENAME "bot.users"
42 #define DEFAULT_SHITLISTFILENAME "bot.shit"
43 #define DEFAULT_HELPFILENAME "bot.help"
44 #define DEFAULT_SCRIPTLOGFILENAME "script.log"
45 #define DEFAULT_LOGFILENAME "bot.log"
46 #define DEFAULT_LOGDIR getenv ("HOME") + String("/.bobotpp/logs/")
47 #define DEFAULT_INITFILENAME "bot.init"
49 #define DEFAULT_AUTOEXECFILENAME "bot.autoexec"
52 Bot::Bot(String filename, bool debug_on)
53 : nickName(DEFAULT_NICKNAME),
54 wantedNickName(DEFAULT_NICKNAME),
55 userName(DEFAULT_USERNAME),
56 ircName(DEFAULT_IRCNAME),
57 versionString(VERSION_STRING),
60 commandChar(DEFAULT_COMMANDCHAR),
61 configFileName(filename),
62 userListFileName(DEFAULT_USERLISTFILENAME),
63 shitListFileName(DEFAULT_SHITLISTFILENAME),
64 logFileName(DEFAULT_LOGFILENAME),
65 logs_dir (DEFAULT_LOGDIR),
66 helpFileName(DEFAULT_HELPFILENAME),
67 initFileName(DEFAULT_INITFILENAME),
69 scriptLogFileName(DEFAULT_SCRIPTLOGFILENAME),
70 autoexecFileName(DEFAULT_AUTOEXECFILENAME),
73 debug(debug_on), stop(false), sentPing(false),
74 startTime(time(NULL)), currentTime(startTime),
75 lastNickNameChange(startTime), lastChannelJoin(startTime),
76 serverConnection(0), sentUserhostID(0), receivedUserhostID(0)
79 wantedChannels.clear();
80 ignoredUserhosts.clear();
85 init_user_functions ();
87 set_log_dir (logs_dir);
88 set_log_file (logFileName);
91 channelList = new ChannelList();
92 serverList = new ServerList();
94 userList = new UserList(userListFileName);
95 shitList = new ShitList(shitListFileName);
96 todoList = new TodoList();
97 dccConnections = new DCCManager ();
99 // Let's read the alias file
100 std::ifstream initFile(initFileName);
103 String temp, alias, command;
105 while (initFile >> temp, temp.length() != 0) {
107 StringTokenizer st(temp);
109 if (temp[0]=='#') continue;
110 if (st.countTokens(' ') != 2) {
111 std::cerr << "Error when reading alias file (" << initFileName
112 << ") line " << line << "...\n";
115 alias = st.nextToken().toUpper();
116 command = st.nextToken().toUpper();
118 // Does the function already exist ?
119 if (!userFunctions[alias])
121 if (userFunction *u = userFunctions[command])
122 userFunctions[alias] =
124 userFunction(u->function,
126 u->needsChannelName);
132 std::srand (std::time (0)); // srand for bot-random
134 botInterp = new BotInterp(this, logs_dir + scriptLogFileName);
135 botInterp->LoadScript(autoexecFileName);
142 while (spyList.size() != 0) {
143 p = (*spyList.begin()).second;
144 spyList.erase(spyList.begin());
147 delete dccConnections;
148 destroy_user_functions ();
151 while (wantedChannels.size() != 0) {
152 w = (*wantedChannels.begin()).second;
153 wantedChannels.erase(wantedChannels.begin());
163 delete serverConnection;
164 logLine("Stopping log.");
169 Bot::logLine(String line)
172 std::time_t current_time = time(0);
174 d = localtime(¤t_time);
175 logFile << "[" << std::setfill('0') << std::setw(2)
176 << d->tm_mday << "/" << std::setfill('0') << std::setw(2)
177 << d->tm_mon + 1 << "/"
178 << d->tm_year + 1900 << " - " << std::setfill('0') << std::setw(2)
179 << d->tm_hour << ":" << std::setfill('0') << std::setw(2)
180 << d->tm_min << ":" << std::setfill('0') << std::setw(2)
189 std::ifstream file(configFileName);
194 logLine(String("I cannot find the file ") + configFileName);
198 while (!file.eof()) {
202 if (temp.length() == 0 || temp[0] == '#') {
207 StringTokenizer st(temp);
208 String command = st.nextToken('=').trim().toUpper();
209 String parameters = st.nextToken('=').trim();
211 if (command == "NICK" || command == "NICKNAME")
212 nickName = wantedNickName = parameters;
213 else if (command == "USERNAME")
214 userName = parameters;
215 else if (command == "IRCNAME" || command == "REALNAME")
216 ircName = parameters;
217 else if (command == "CMDCHAR" || command == "COMMAND")
218 commandChar = parameters[0];
219 else if (command == "USERLIST")
220 userListFileName = parameters;
221 else if (command == "SHITLIST")
222 shitListFileName = parameters;
223 else if (command == "CHANNEL") {
224 if (parameters.indexOf(':') == -1) {
225 std::cout << "Warning. The 'channel' syntax has changed."
226 << " Please see the README file for more information."
227 << " I will use compatibility mode, but you're really"
228 << " missing something.\n";
229 StringTokenizer st2(parameters);
230 String name = st2.nextToken().toLower();
231 String key = st2.nextToken();
232 wantedChannels[name] = new wantedChannel("", "", key);
234 StringTokenizer st2(parameters);
235 String name = st2.nextToken(':').toLower();
236 String mode = st2.nextToken(':');
237 String keep = st2.nextToken(':');
238 String key = st2.nextToken(':');
239 wantedChannels[name] = new wantedChannel(mode, keep, key);
242 else if (command == "LOGFILE")
244 if (parameters != logFileName)
246 if (parameters[0] == '/')
249 set_log_file (parameters.subString (1));
252 set_log_file (parameters);
256 else if (command == "SCRIPTLOGFILE")
257 scriptLogFileName = parameters;
258 else if (command == "AUTOEXECFILE")
259 autoexecFileName = parameters;
261 else if (command == "INITFILE")
262 initFileName = parameters;
263 else if (command == "LOCALIP")
264 localIP = parameters;
265 else if (command == "SERVER") {
266 if (parameters.indexOf(' ') == -1)
267 serverList->addServer(new Server(parameters));
269 StringTokenizer st2(parameters);
270 String name = st2.nextToken();
271 int port = std::atoi(st2.nextToken());
272 serverList->addServer(new Server(name,
278 logLine(String("Syntax error in file ") + configFileName +
279 ", line " + String((long)line));
296 waitForInput(); // This is the main event loop
297 dccConnections->checkStale ();
298 if (!serverConnection->queue->flush())
311 struct timeval timer;
313 int sock = serverConnection->getFileDescriptor();
314 int maxSocketNumber = sock;
323 DCC_MAP* dccmap = &dccConnections->dcc_map;
324 for (DCC_MAP::iterator it = dccmap->begin ();
325 it != dccmap->end(); ++it) {
326 int s = it->second->dcc->getFileDescriptor();
332 if (s > maxSocketNumber)
339 switch (select(maxSocketNumber + 1, &rd, NULL, NULL, &timer)) {
340 case 0: /* timeout */
344 default: /* normal */
348 if (FD_ISSET(sock, &rd))
350 if (serverConnection->handleInput())
353 // std::list<DCCConnection *>::iterator it = dccConnections.begin();
354 // std::list<DCCConnection *>::iterator it2;
356 // while (it != dccConnections.end()) {
359 // #ifdef _HPUX_SOURCE
360 // if (rd & (*it2)->getFileDescriptor()) {
362 // if (FD_ISSET((*it2)->getFileDescriptor(), &rd)) {
364 // if ((*it2)->handleInput()) {
366 // dccConnections.erase(it2);
371 dccConnections->checkInput (rd);
374 if (currentTime < std::time(0)) { // Actions that we do each second
375 currentTime = std::time(0);
376 for (std::map<String, unsigned int, std::less<String> >::iterator
377 it = ignoredUserhosts.begin();
378 it != ignoredUserhosts.end(); ++it)
379 if ((*it).second > 0)
383 while ((line = todoList->getNext()) != "") {
384 serverConnection->queue->sendChannelMode(line);
387 botInterp->RunTimers(currentTime);
391 tm *thisTime = localtime(¤tTime);
392 if (thisTime->tm_sec == 0) {
394 std::sprintf(s, "%2d:%2d", thisTime->tm_hour, thisTime->tm_min);
395 botInterp->RunHooks(Hook::TIMER, String(s),
396 gh_list(Utils::string2SCM(String(s)),
403 if (currentTime >= (time_t)(lastNickNameChange + Bot::NICK_CHANGE) &&
404 nickName != wantedNickName) {
405 lastNickNameChange = currentTime;
406 serverConnection->queue->sendNick(wantedNickName);
409 if (currentTime >= (std::time_t)(lastChannelJoin + Bot::CHANNEL_JOIN)) {
410 lastChannelJoin = currentTime;
411 for (std::map<String, wantedChannel *, std::less<String> >::iterator it =
412 wantedChannels.begin(); it != wantedChannels.end();
414 if (channelList->getChannel((*it).first) == 0)
415 serverConnection->queue->sendJoin((*it).first, (*it).second->key);
418 // std::list<DCCConnection *>::iterator it2;
420 // for (std::list<DCCConnection *>::iterator it = dccConnections.begin();
421 // it != dccConnections.end(); ) {
424 // if ((*it2)->autoRemove && currentTime >= (std::time_t)((*it2)->lastSpoken + Bot::DCC_DELAY)) {
426 // dccConnections.erase(it2);
430 if (currentTime >= (std::time_t)(serverConnection->serverLastSpoken + Bot::PING_TIME) && !sentPing) {
431 serverConnection->queue->sendPing("Testing connection");
435 if (currentTime >= (std::time_t)(serverConnection->serverLastSpoken + Bot::TIMEOUT)) {
441 // We can change server if we will not lose op on a channel
443 Bot::canChangeServer()
448 for (std::map<String, Channel *, std::less<String> >::iterator it =
449 channelList->begin();
450 it != channelList->end(); ++it) {
451 channel = (*it).first;
452 c = channelList->getChannel(channel);
453 if (c->countOp == 1 &&
454 c->count > 1 && this->iAmOp(channel))
466 channelList->clear();
468 if (serverConnection)
469 userList->removeFirst();
471 delete serverConnection;
474 Server * s = serverList->nextServer();
476 std::cout << "No server found. Exiting..." << std::endl;
479 serverConnection = new ServerConnection(this, s, localIP);
480 if (!serverConnection->connect()) {
482 // We sleep 10 seconds, to avoid connection flood
484 delete serverConnection;
495 channelList->clear();
497 userList->removeFirst();
499 delete serverConnection;
502 new ServerConnection(this, serverList->currentServer(), localIP);
504 serverConnection->connect();
508 Bot::connect(int serverNumber)
511 channelList->clear();
513 userList->removeFirst();
515 delete serverConnection;
518 new ServerConnection(this, serverList->get(serverNumber), localIP);
520 serverConnection->connect();
524 Bot::addDCC(Person * from, unsigned long address, int port)
526 DCCConnection * d = new DCCConnection(this, from->getAddress (),
531 logLine ("DCC Connection failed from " + from->getAddress ());
534 logLine ("DCC CHAT accepted from" + from->getAddress ());
535 dccConnections->addConnection (d);
541 for (std::map<String, Channel *, std::less<String> >::iterator it =
542 channelList->begin();
543 it != channelList->end(); ++it)
544 serverConnection->queue->sendWho((*it).first);
548 Bot::getUserhost(String channel, String nick)
555 c = channelList->getChannel(channel);
557 nick = nick.toLower();
560 if (c && c->hasNick(nick))
561 return c->getUser(nick)->userhost;
563 unsigned long num = sentUserhostID++;
565 serverConnection->queue->sendUserhost(nick);
566 userhostMap[num] = "+";
568 while (userhostMap[num] == "+") {
570 serverConnection->queue->flush();
573 // We have got our answer
574 String res = userhostMap[num];
575 userhostMap.erase(num);
581 Bot::iAmOp(String channel)
583 User * me = channelList->getChannel(channel)->getUser(nickName);
584 return (me->mode & User::OP_MODE);
588 Bot::init_user_functions ()
591 #define uf(f, l, b) new userFunction (f, l, b);
592 userFunctions["ACTION"] = uf (UserCommands::Action, User::USER, true);
593 userFunctions["ADDUSER"] = uf (UserCommands::AddUser, User::FRIEND, false);
594 userFunctions["ADDSERVER"] = uf (UserCommands::AddServer, User::FRIEND,
596 userFunctions["ADDSHIT"] = uf (UserCommands::AddShit, User::FRIEND, false);
597 userFunctions["ALIAS"] = uf (UserCommands::Alias, User::MASTER, false);
598 userFunctions["BAN"] = uf (UserCommands::Ban, User::USER, true);
599 userFunctions["BANLIST"] = uf (UserCommands::BanList, User::USER, true);
600 userFunctions["CHANNELS"] =
601 uf (UserCommands::Channels, User::FRIEND, false);
602 userFunctions["CYCLE"] = uf (UserCommands::Cycle, User::FRIEND, true);
603 userFunctions["DCCLIST"] = uf (UserCommands::DCCList, User::FRIEND, false);
604 userFunctions["DEBAN"] = uf (UserCommands::Deban, User::USER, true);
605 userFunctions["DELSERVER"] = uf (UserCommands::DelServer, User::FRIEND,
607 userFunctions["DELUSER"] = uf (UserCommands::DelUser, User::FRIEND, false);
608 userFunctions["DELSHIT"] = uf (UserCommands::DelShit, User::FRIEND, false);
609 userFunctions["DEOP"] = uf (UserCommands::Deop, User::TRUSTED_USER, true);
610 userFunctions["DIE"] = uf (UserCommands::Die, User::MASTER, false);
611 userFunctions["DO"] = uf (UserCommands::Do, User::MASTER, false);
613 userFunctions["EXECUTE"] = uf (UserCommands::Execute, User::MASTER, false);
615 userFunctions["HELP"] = uf (UserCommands::Help, User::NONE, false);
616 userFunctions["IDENT"] = uf (UserCommands::Ident, User::NONE, true);
617 userFunctions["INVITE"] = uf (UserCommands::Invite, User::USER, true);
618 userFunctions["JOIN"] = uf (UserCommands::Join, User::FRIEND, false);
619 userFunctions["KEEP"] = uf (UserCommands::Keep, User::FRIEND, true);
620 userFunctions["KICK"] = uf (UserCommands::Kick, User::USER, true);
621 userFunctions["KICKBAN"] = uf (UserCommands::KickBan, User::USER, true);
622 userFunctions["LOAD"] = uf (UserCommands::Load, User::FRIEND, false);
624 userFunctions["LOADSCRIPT"] = uf (UserCommands::LoadScript, User::MASTER,
627 userFunctions["LOCK"] = uf (UserCommands::Lock, User::FRIEND, true);
628 userFunctions["MODE"] = uf (UserCommands::Mode, User::FRIEND, true);
629 userFunctions["MSG"] = uf (UserCommands::Msg, User::USER, false);
630 userFunctions["NAMES"] = uf (UserCommands::Names, User::USER, true);
631 userFunctions["NEXTSERVER"] = uf (UserCommands::NextServer, User::FRIEND,
633 userFunctions["NICK"] = uf (UserCommands::Nick, User::FRIEND, false);
634 userFunctions["NSLOOKUP"] = uf (UserCommands::NsLookup, User::USER, false);
635 userFunctions["OP"] = uf (UserCommands::Op, User::TRUSTED_USER, true);
636 userFunctions["PART"] = uf (UserCommands::Part, User::FRIEND, true);
637 userFunctions["PASSWORD"] = uf (UserCommands::Password, User::USER, true);
638 userFunctions["RECONNECT"] =
639 uf (UserCommands::Reconnect, User::FRIEND, false);
640 userFunctions["RSPYMESSAGE"] =
641 uf (UserCommands::RSpyMessage, User::USER, false);
642 userFunctions["SAVE"] = uf (UserCommands::Save, User::FRIEND, false);
643 userFunctions["SAY"] = uf (UserCommands::Say, User::USER, true);
644 userFunctions["SERVER"] = uf (UserCommands::Server, User::FRIEND, false);
645 userFunctions["SERVERLIST"] =
646 uf (UserCommands::ServerList, User::FRIEND, false);
647 userFunctions["SETVERSION"] =
648 uf (UserCommands::SetVersion, User::MASTER, false);
649 userFunctions["SHITLIST"] =
650 uf (UserCommands::ShitList, User::FRIEND, false);
651 userFunctions["SPYLIST"] = uf (UserCommands::SpyList, User::USER, false);
652 userFunctions["SPYMESSAGE"] =
653 uf (UserCommands::SpyMessage, User::USER, false);
654 userFunctions["STATS"] = uf (UserCommands::Stats, User::FRIEND, true);
655 userFunctions["TBAN"] = uf (UserCommands::TBan, User::USER, true);
656 userFunctions["TKBAN"] = uf (UserCommands::TKBan, User::USER, true);
657 userFunctions["TOPIC"] = uf (UserCommands::Topic, User::USER, true);
658 userFunctions["UNLOCK"] = uf (UserCommands::Unlock, User::FRIEND, true);
659 userFunctions["USERLIST"] =
660 uf (UserCommands::UserList, User::FRIEND, false);
661 userFunctions["WHO"] = uf (UserCommands::Who, User::NONE, true);
662 userFunctions["WHOIS"] = uf (UserCommands::Whois, User::FRIEND, true);
668 void erase_userf (std::pair<std::string, class userFunction*> it)
675 Bot::destroy_user_functions ()
677 std::for_each (userFunctions.begin (),
678 userFunctions.end (),
680 userFunctions.erase (userFunctions.begin (),
681 userFunctions.end ());
685 Bot::set_log_file (String name)
691 logFile.open(logs_dir + logFileName, std::ios_base::out |
692 std::ios_base::ate | std::ios_base::app);
694 logFile.open(logs_dir + logFileName, ios::out | ios::ate
698 logLine("Starting log.");
702 Bot::set_log_dir (String dir)