2 // Copyright (c) 1997, 1998 Etienne BERNARD
3 // Copyright (C) 2002,2003,2005 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., 51 Franklin Street, Fifth Floor, Boston, MA
30 #include <sys/types.h>
39 #include "DCCConnection.H"
40 #include "DCCChatConnection.H"
41 #include "ChannelList.H"
42 #include "DCCManager.H"
43 #include "DCCPerson.H"
47 #include "ServerConnection.H"
48 #include "ServerList.H"
50 #include "StringTokenizer.H"
52 #include "UserCommands.H"
58 #include "BotInterp.H"
62 unsigned int Bot::MAX_MESSAGES = 2;
63 unsigned int Bot::MAX_NICKLENGTH = 9;
65 #define DEFAULT_NICKNAME "Bobot"
66 #define DEFAULT_USERNAME "bobot"
67 #define DEFAULT_IRCNAME "I'm a bobot++!"
68 #define DEFAULT_COMMANDCHAR '!'
69 #define DEFAULT_USERLISTFILENAME "bot.users"
70 #define DEFAULT_SHITLISTFILENAME "bot.shit"
71 #define DEFAULT_HELPFILENAME "bot.help"
72 #define DEFAULT_SCRIPTLOGFILENAME "script.log"
73 #define DEFAULT_LOGFILENAME "bot.log"
74 #define DEFAULT_LOGDIR getenv ("HOME") + String("/.bobotpp/logs/")
75 #define DEFAULT_INITFILENAME "bot.init"
77 #define DEFAULT_AUTOEXECFILENAME "bot.autoexec"
80 Bot::Bot(String filename, bool debug_on)
81 : nickName(DEFAULT_NICKNAME),
82 wantedNickName(DEFAULT_NICKNAME),
83 userName(DEFAULT_USERNAME),
84 ircName(DEFAULT_IRCNAME),
85 versionString(VERSION_STRING),
88 commandChar(DEFAULT_COMMANDCHAR),
89 userListFileName(DEFAULT_USERLISTFILENAME),
90 shitListFileName(DEFAULT_SHITLISTFILENAME),
91 helpFileName(DEFAULT_HELPFILENAME),
92 initFileName(DEFAULT_INITFILENAME),
97 startTime(time(NULL)),
98 currentTime(startTime),
99 lastNickNameChange(startTime),
100 lastChannelJoin(startTime),
103 receivedUserhostID(0),
104 logFileName(DEFAULT_LOGFILENAME),
105 logs_dir (DEFAULT_LOGDIR),
106 configFileName (filename)
108 ,scriptLogFileName(DEFAULT_SCRIPTLOGFILENAME),
109 autoexecFileName(DEFAULT_AUTOEXECFILENAME)
112 #ifdef HAVE_STL_CLEAR
113 wantedChannels.clear();
114 ignoredUserhosts.clear();
119 init_user_functions ();
121 set_log_dir (logs_dir);
122 set_log_file (logFileName);
125 channelList = new ChannelList();
126 serverList = new ServerList();
128 userList = new UserList(userListFileName);
129 shitList = new ShitList(shitListFileName);
130 dccConnections = new DCCManager ();
132 // Let's read the alias file
133 std::ifstream initFile(initFileName);
137 // FIXME: these variables are current String instead of
138 // std::string because String>> reads an entire line. This code
139 // needs to be rewritten to use std::string and std::getline (or
140 // better yet, be removed entirely once BotConfig is in place)
141 String temp, alias, command;
144 while (initFile >> temp, temp.length() != 0)
146 StringTokenizer st(temp);
149 temp = Utils::trim_str (temp);
156 if (st.count_tokens (' ') != 2)
158 std::cerr << "Error when reading alias file (" << initFileName
159 << ") line " << line << "...\n";
163 alias = Utils::to_upper (st.next_token());
164 command = Utils::to_upper (st.next_token());
166 // Does the function already exist ?
167 if (!userFunctions[alias])
169 if (userFunction *u = userFunctions[command])
170 userFunctions[alias] =
172 userFunction(u->function,
174 u->needsChannelName);
180 std::srand (std::time (0)); // srand for bot-random
183 botInterp = new BotInterp(this, logs_dir + scriptLogFileName);
184 Interp::Startup2 (this);
185 botInterp->LoadScript(autoexecFileName);
192 while (spyList.size() != 0) {
193 p = (*spyList.begin()).second;
194 spyList.erase(spyList.begin());
197 delete dccConnections;
198 destroy_user_functions ();
201 while (wantedChannels.size() != 0) {
202 w = (*wantedChannels.begin()).second;
203 wantedChannels.erase(wantedChannels.begin());
212 delete serverConnection;
213 logLine("Stopping log.");
218 Bot::logLine(String line)
221 std::time_t current_time = time(0);
223 d = localtime(¤t_time);
224 logFile << "[" << std::setfill('0') << std::setw(2)
225 << d->tm_mday << "/" << std::setfill('0') << std::setw(2)
226 << d->tm_mon + 1 << "/"
227 << d->tm_year + 1900 << " - " << std::setfill('0') << std::setw(2)
228 << d->tm_hour << ":" << std::setfill('0') << std::setw(2)
229 << d->tm_min << ":" << std::setfill('0') << std::setw(2)
238 std::ifstream file(configFileName);
243 logLine(String("I cannot find the file ") + configFileName);
247 while (!file.eof()) {
251 if (temp.length() == 0 || temp[(unsigned int)0] == '#') {
256 StringTokenizer st(temp);
257 String command = Utils::to_upper (Utils::trim_str (st.next_token('=')));
258 String parameters = Utils::trim_str (st.next_token('='));
260 if (command == "NICK" || command == "NICKNAME")
261 nickName = wantedNickName = parameters;
262 else if (command == "USERNAME")
263 userName = parameters;
264 else if (command == "IRCNAME" || command == "REALNAME")
265 ircName = parameters;
266 else if (command == "CMDCHAR" || command == "COMMAND")
267 commandChar = parameters[(unsigned int)0];
268 else if (command == "USERLIST")
269 userListFileName = parameters;
270 else if (command == "SHITLIST")
271 shitListFileName = parameters;
272 else if (command == "CHANNEL") {
273 if (parameters.indexOf(':') == -1) {
274 std::cout << "Warning. The 'channel' syntax has changed."
275 << " Please see the README file for more information."
276 << " I will use compatibility mode, but you're really"
277 << " missing something.\n";
278 StringTokenizer st2(parameters);
279 String name = Utils::to_lower (st2.next_token());
280 String key = st2.next_token();
281 wantedChannels[name] = new wantedChannel("", "", key);
283 StringTokenizer st2(parameters);
284 String name = Utils::to_lower (st2.next_token(':'));
285 String mode = st2.next_token(':');
286 String keep = st2.next_token(':');
287 String key = st2.next_token(':');
288 wantedChannels[name] = new wantedChannel(mode, keep, key);
291 else if (command == "LOGFILE")
293 if (parameters != logFileName)
295 if (parameters[(unsigned int)0] == '/')
297 StringTokenizer log_st (parameters);
298 std::string log_dir = "/";
300 for (unsigned int m = log_st.count_tokens ('/');
304 log_dir += log_st.next_token ('/') + "/";
307 std::cerr << "==" << log_dir << std::endl;
309 set_log_dir (log_dir);
310 set_log_file (log_st.rest ());
313 set_log_file (parameters);
317 else if (command == "SCRIPTLOGFILE")
318 scriptLogFileName = parameters;
319 else if (command == "AUTOEXECFILE")
320 autoexecFileName = parameters;
322 else if (command == "INITFILE")
323 initFileName = parameters;
324 else if (command == "LOCALIP")
325 localIP = parameters;
326 else if (command == "MAXNICKLENGTH")
327 MAX_NICKLENGTH = std::atoi (parameters);
328 else if (command == "SERVER") {
329 if (parameters.indexOf(' ') == -1)
330 serverList->addServer(new Server(parameters));
332 StringTokenizer st2(parameters);
333 String name = st2.next_token();
334 int port = std::atoi(st2.next_token().c_str());
335 serverList->addServer(new Server(name,
340 else if (command == "")
345 logLine(String("Syntax error in file ") + configFileName +
346 ", line " + String((long)line));
364 waitForInput(); // This is the main event loop
365 dccConnections->checkStale ();
367 if (!serverConnection->queue->flush())
371 // Run hooks/disconnect
372 this->botInterp->RunHooks
374 serverConnection->server->getHostName (),
376 (Utils::str2scm (serverConnection->server->getHostName ()),
392 struct timeval timer;
394 int sock = serverConnection->getFileDescriptor();
395 int maxSocketNumber = sock;
404 DCC_MAP* dccmap = &dccConnections->dcc_map;
405 for (DCC_MAP::iterator it = dccmap->begin ();
406 it != dccmap->end(); ++it) {
407 int s = it->second->dcc->getFileDescriptor();
413 if (s > maxSocketNumber)
420 switch (select(maxSocketNumber + 1, &rd, NULL, NULL, &timer)) {
421 case 0: /* timeout */
425 default: /* normal */
429 if (FD_ISSET(sock, &rd))
431 if (serverConnection->handleInput())
434 dccConnections->checkInput (rd);
437 if (currentTime < std::time(0)) { // Actions that we do each second
438 currentTime = std::time(0);
439 for (std::map<String, unsigned int, std::less<String> >::iterator
440 it = ignoredUserhosts.begin();
441 it != ignoredUserhosts.end(); ++it)
442 if ((*it).second > 0)
445 for (std::map<String, Channel *, std::less<String> >::iterator it = channelList->begin ();
446 it != channelList->end ();
449 it->second->purge_expired_bans ();
452 botInterp->RunTimers(currentTime);
454 tm *thisTime = localtime(¤tTime);
455 if (thisTime->tm_sec == 0)
458 std::snprintf(s, 6, "%02d:%02d", thisTime->tm_hour, thisTime->tm_min);
460 botInterp->RunHooks(Hook::TIMER, String(s),
461 scm_list_n (Utils::str2scm (std::string (s)),
468 if (currentTime >= (time_t)(lastNickNameChange + Bot::NICK_CHANGE) &&
469 nickName != wantedNickName) {
470 lastNickNameChange = currentTime;
471 serverConnection->queue->sendNick(wantedNickName);
474 if (currentTime >= (std::time_t)(lastChannelJoin + Bot::CHANNEL_JOIN)) {
475 lastChannelJoin = currentTime;
476 for (std::map<String, wantedChannel *, std::less<String> >::iterator it =
477 wantedChannels.begin(); it != wantedChannels.end();
479 if (channelList->getChannel((*it).first) == 0)
480 serverConnection->queue->sendJoin((*it).first, (*it).second->key);
483 if (currentTime >= (std::time_t)(serverConnection->serverLastSpoken
484 + Bot::PING_TIME) && !sentPing)
486 serverConnection->queue->sendPing("Testing connection");
490 if (currentTime >= (std::time_t)(serverConnection->serverLastSpoken
498 // We can change server if we will not lose op on a channel
500 Bot::canChangeServer()
505 for (std::map<String, Channel *, std::less<String> >::iterator it =
506 channelList->begin();
507 it != channelList->end(); ++it) {
508 channel = (*it).first;
509 c = channelList->getChannel(channel);
510 if (c->countOp == 1 &&
511 c->count > 1 && this->iAmOp(channel))
523 channelList->clear();
525 if (serverConnection)
526 userList->removeFirst();
528 delete serverConnection;
531 Server * s = serverList->nextServer();
533 std::cout << "No server found. Exiting..." << std::endl;
536 serverConnection = new ServerConnection(this, s, localIP);
537 if (!serverConnection->connect()) {
539 // We sleep 10 seconds, to avoid connection flood
541 delete serverConnection;
552 channelList->clear();
554 userList->removeFirst();
556 delete serverConnection;
559 new ServerConnection(this, serverList->currentServer(), localIP);
561 serverConnection->connect();
565 Bot::connect(int serverNumber)
568 channelList->clear();
570 userList->removeFirst();
572 delete serverConnection;
575 new ServerConnection(this, serverList->get(serverNumber), localIP);
577 serverConnection->connect();
581 Bot::addDCC(Person * from, unsigned long address, int port, int type)
583 DCCConnection *d = 0;
587 d = new DCCChatConnection(this, from->getAddress (),
597 logLine ("DCC Connection failed from " + from->getAddress ());
601 logLine ("DCC CHAT accepted from" + from->getAddress ());
602 dccConnections->addConnection (d);
608 for (std::map<String, Channel *, std::less<String> >::iterator it =
609 channelList->begin();
610 it != channelList->end(); ++it)
611 serverConnection->queue->sendWho((*it).first);
615 Bot::getUserhost(String channel, String nick)
622 c = channelList->getChannel(channel);
624 nick = nick.toLower();
627 if (c && c->hasNick(nick))
628 return c->getUser(nick)->userhost;
630 unsigned long num = sentUserhostID++;
632 serverConnection->queue->sendUserhost(nick);
633 userhostMap[num] = "+";
635 while (userhostMap[num] == "+") {
637 serverConnection->queue->flush();
640 // We have got our answer
641 String res = userhostMap[num];
642 userhostMap.erase(num);
648 Bot::iAmOp(String channel)
650 User * me = channelList->getChannel(channel)->getUser(nickName);
651 return (me->mode & User::OP_MODE);
655 Bot::init_user_functions ()
658 #define uf(f, l, b) new userFunction (f, l, b);
659 userFunctions["ACTION"] = uf (UserCommands::Action, User::USER, true);
660 userFunctions["ADDUSER"] = uf (UserCommands::AddUser, User::FRIEND, false);
661 userFunctions["ADDSERVER"] = uf (UserCommands::AddServer, User::FRIEND,
663 userFunctions["ADDSHIT"] = uf (UserCommands::AddShit, User::FRIEND, false);
664 userFunctions["ALIAS"] = uf (UserCommands::Alias, User::MASTER, false);
665 userFunctions["BAN"] = uf (UserCommands::Ban, User::USER, true);
666 userFunctions["BANLIST"] = uf (UserCommands::BanList, User::USER, true);
667 userFunctions["CHANNELS"] =
668 uf (UserCommands::Channels, User::FRIEND, false);
669 userFunctions["CYCLE"] = uf (UserCommands::Cycle, User::FRIEND, true);
670 userFunctions["DCCLIST"] = uf (UserCommands::DCCList, User::FRIEND, false);
671 userFunctions["DEBAN"] = uf (UserCommands::Deban, User::USER, true);
672 userFunctions["DELSERVER"] = uf (UserCommands::DelServer, User::FRIEND,
674 userFunctions["DELUSER"] = uf (UserCommands::DelUser, User::FRIEND, false);
675 userFunctions["DELSHIT"] = uf (UserCommands::DelShit, User::FRIEND, false);
676 userFunctions["DEOP"] = uf (UserCommands::Deop, User::TRUSTED_USER, true);
677 userFunctions["DIE"] = uf (UserCommands::Die, User::MASTER, false);
678 userFunctions["DO"] = uf (UserCommands::Do, User::MASTER, false);
680 userFunctions["EXECUTE"] = uf (UserCommands::Execute, User::MASTER, false);
682 userFunctions["HELP"] = uf (UserCommands::Help, User::NONE, false);
683 userFunctions["IDENT"] = uf (UserCommands::Ident, User::NONE, true);
684 userFunctions["INVITE"] = uf (UserCommands::Invite, User::USER, true);
685 userFunctions["JOIN"] = uf (UserCommands::Join, User::FRIEND, false);
686 userFunctions["KEEP"] = uf (UserCommands::Keep, User::FRIEND, true);
687 userFunctions["KICK"] = uf (UserCommands::Kick, User::USER, true);
688 userFunctions["KICKBAN"] = uf (UserCommands::KickBan, User::USER, true);
689 userFunctions["LOAD"] = uf (UserCommands::Load, User::FRIEND, false);
691 userFunctions["LOADSCRIPT"] = uf (UserCommands::LoadScript, User::MASTER,
694 userFunctions["LOCK"] = uf (UserCommands::Lock, User::FRIEND, true);
695 userFunctions["MODE"] = uf (UserCommands::Mode, User::FRIEND, true);
696 userFunctions["MSG"] = uf (UserCommands::Msg, User::USER, false);
697 userFunctions["NAMES"] = uf (UserCommands::Names, User::USER, true);
698 userFunctions["NEXTSERVER"] = uf (UserCommands::NextServer, User::FRIEND,
700 userFunctions["NICK"] = uf (UserCommands::Nick, User::FRIEND, false);
701 userFunctions["NSLOOKUP"] = uf (UserCommands::NsLookup, User::USER, false);
702 userFunctions["OP"] = uf (UserCommands::Op, User::TRUSTED_USER, true);
703 userFunctions["PART"] = uf (UserCommands::Part, User::FRIEND, true);
704 userFunctions["PASSWORD"] = uf (UserCommands::Password, User::USER, true);
705 userFunctions["RECONNECT"] =
706 uf (UserCommands::Reconnect, User::FRIEND, false);
707 userFunctions["RSPYMESSAGE"] =
708 uf (UserCommands::RSpyMessage, User::USER, false);
709 userFunctions["SAVE"] = uf (UserCommands::Save, User::FRIEND, false);
710 userFunctions["SAY"] = uf (UserCommands::Say, User::USER, true);
711 userFunctions["SERVER"] = uf (UserCommands::Server, User::FRIEND, false);
712 userFunctions["SERVERLIST"] =
713 uf (UserCommands::ServerList, User::FRIEND, false);
714 userFunctions["SETFLOODRATE"] =
715 uf (UserCommands::SetFloodRate, User::MASTER, false);
716 userFunctions["SETVERSION"] =
717 uf (UserCommands::SetVersion, User::MASTER, false);
718 userFunctions["SHITLIST"] =
719 uf (UserCommands::ShitList, User::FRIEND, false);
720 userFunctions["SPYLIST"] = uf (UserCommands::SpyList, User::USER, false);
721 userFunctions["SPYMESSAGE"] =
722 uf (UserCommands::SpyMessage, User::USER, false);
723 userFunctions["STATS"] = uf (UserCommands::Stats, User::FRIEND, true);
724 userFunctions["TBAN"] = uf (UserCommands::TBan, User::USER, true);
725 userFunctions["TKBAN"] = uf (UserCommands::TKBan, User::USER, true);
726 userFunctions["TOPIC"] = uf (UserCommands::Topic, User::USER, true);
727 userFunctions["UNLOCK"] = uf (UserCommands::Unlock, User::FRIEND, true);
728 userFunctions["USERLIST"] =
729 uf (UserCommands::UserList, User::FRIEND, false);
730 userFunctions["WHO"] = uf (UserCommands::Who, User::NONE, true);
731 userFunctions["WHOIS"] = uf (UserCommands::Whois, User::FRIEND, true);
737 void erase_userf (std::pair<std::string, class userFunction*> it)
744 Bot::destroy_user_functions ()
746 std::for_each (userFunctions.begin (),
747 userFunctions.end (),
749 userFunctions.erase (userFunctions.begin (),
750 userFunctions.end ());
754 Bot::set_log_file (String name)
760 logFile.open(logs_dir + logFileName, std::ios_base::out |
761 std::ios_base::ate | std::ios_base::app);
763 logFile.open(logs_dir + logFileName, ios::out | ios::ate
767 logLine("Starting log.");
771 Bot::set_log_dir (String dir)
775 DIR *temp = opendir (logs_dir);
779 mkdir (logs_dir, S_IRWXU);