diff options
author | Naram Qashat <cyberbotx@cyberbotx.com> | 2010-06-20 18:42:58 -0400 |
---|---|---|
committer | Naram Qashat <cyberbotx@cyberbotx.com> | 2010-06-20 18:42:58 -0400 |
commit | 381c9c8870fad4c544f29deec22ba4be3549a731 (patch) | |
tree | f5f26e2dd380910b0ddd26e3d885d6bf56d40181 /src | |
parent | 2528dc80bd1b3e6b2c09db23eb51659e30128110 (diff) |
The first of a few "CBX OCDing over code style" commits, focusing on include/* and src/* but not src/core/* or src/modules/*.
Diffstat (limited to 'src')
76 files changed, 2240 insertions, 2603 deletions
diff --git a/src/actions.cpp b/src/actions.cpp index 00ed01100..bff5b36fa 100644 --- a/src/actions.cpp +++ b/src/actions.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -91,7 +89,7 @@ void common_unban(ChannelInfo *ci, const std::string &nick) if (!ci->c->bans || !ci->c->bans->count) return; - if (u->hostip == NULL) + if (!u->hostip) { host = host_resolve(u->host); /* we store the just resolved hostname so we don't @@ -108,14 +106,12 @@ void common_unban(ChannelInfo *ci, const std::string &nick) if (ircd->svsmode_unban) ircdproto->SendBanDel(ci->c, nick); else - { for (ban = ci->c->bans->entries; ban; ban = next) { next = ban->next; if (entry_match(ban, u->nick.c_str(), u->GetIdent().c_str(), u->host, ip) || entry_match(ban, u->nick.c_str(), u->GetIdent().c_str(), u->GetDisplayedHost().c_str(), ip)) ci->c->RemoveMode(NULL, CMODE_BAN, ban->mask); } - } /* host_resolve() sstrdup us this info so we gotta free it */ if (host) delete [] host; diff --git a/src/base64.cpp b/src/base64.cpp index 3f576e96a..2071ad40a 100644 --- a/src/base64.cpp +++ b/src/base64.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ /* @@ -35,8 +33,7 @@ long base64dec(const char *b64) return 0; } -static const char Base64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char Pad64 = '='; /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) @@ -109,7 +106,7 @@ int b64_encode(const char *src, size_t srclength, char *target, size_t targsize) unsigned char output[4]; size_t i; - while (2 < srclength) + while (srclength > 2) { input[0] = *src++; input[1] = *src++; @@ -173,14 +170,14 @@ int b64_decode(const char *src, char *target, size_t targsize) while ((ch = *src++) != '\0') { - if (isspace(ch)) /* Skip whitespace anywhere. */ + if (isspace(ch)) /* Skip whitespace anywhere. */ continue; if (ch == Pad64) break; pos = const_cast<char *>(strchr(Base64, ch)); - if (!pos) /* A non-base64 character. */ + if (!pos) /* A non-base64 character. */ return -1; switch (state) @@ -236,16 +233,16 @@ int b64_decode(const char *src, char *target, size_t targsize) * on a byte boundary, and/or with erroneous trailing characters. */ - if (ch == Pad64) /* We got a pad char. */ + if (ch == Pad64) /* We got a pad char. */ { - ch = *src++; /* Skip it, get next. */ + ch = *src++; /* Skip it, get next. */ switch (state) { - case 0: /* Invalid = in first position */ - case 1: /* Invalid = in second position */ + case 0: /* Invalid = in first position */ + case 1: /* Invalid = in second position */ return -1; - case 2: /* Valid, means one byte of info */ + case 2: /* Valid, means one byte of info */ /* Skip any number of spaces. */ for (; ch != '\0'; ch = *src++) if (!isspace(ch)) @@ -253,11 +250,11 @@ int b64_decode(const char *src, char *target, size_t targsize) /* Make sure there is another trailing = sign. */ if (ch != Pad64) return -1; - ch = *src++; /* Skip the = */ + ch = *src++; /* Skip the = */ /* Fall through to "single trailing =" case. */ /* FALLTHROUGH */ - case 3: /* Valid, means two bytes of info */ + case 3: /* Valid, means two bytes of info */ /* * We know this char is an =. Is there anything but * whitespace after it? @@ -289,12 +286,12 @@ int b64_decode(const char *src, char *target, size_t targsize) return tarindex; } -const char* encode_ip(unsigned char *ip) +const char *encode_ip(unsigned char *ip) { static char buf[25]; unsigned char *cp; - struct in_addr ia; /* For IPv4 */ - char *s_ip; /* Signed ip string */ + struct in_addr ia; /* For IPv4 */ + char *s_ip; /* Signed ip string */ if (!ip) return "*"; @@ -319,11 +316,11 @@ int decode_ip(const char *buf) b64_decode(buf, targ, 25); ia = *reinterpret_cast<struct in_addr *>(targ); - if (len == 24) /* IPv6 */ + if (len == 24) /* IPv6 */ return 0; - else if (len == 8) /* IPv4 */ + else if (len == 8) /* IPv4 */ return ia.s_addr; - else /* Error?? */ + else /* Error?? */ return 0; } diff --git a/src/bots.cpp b/src/bots.cpp index e9021b188..424120d2d 100644 --- a/src/bots.cpp +++ b/src/bots.cpp @@ -3,9 +3,6 @@ * Copyright (C) 2008-2010 Anope Team <team@anope.org> * * Please read COPYING and README for further details. - * - * - * */ #include "services.h" @@ -35,33 +32,19 @@ BotInfo::BotInfo(const std::string &nnick, const std::string &nuser, const std:: ci::string ci_nick(nnick.c_str()); if (Config.s_ChanServ && ci_nick == Config.s_ChanServ) - { ChanServ = this; - } else if (Config.s_BotServ && ci_nick == Config.s_BotServ) - { BotServ = this; - } else if (Config.s_HostServ && ci_nick == Config.s_HostServ) - { HostServ = this; - } else if (Config.s_OperServ && ci_nick == Config.s_OperServ) - { OperServ = this; - } else if (Config.s_MemoServ && ci_nick == Config.s_MemoServ) - { MemoServ = this; - } else if (Config.s_NickServ && ci_nick == Config.s_NickServ) - { NickServ = this; - } else if (Config.s_GlobalNoticer && ci_nick == Config.s_GlobalNoticer) - { Global = this; - } BotListByNick[this->nick.c_str()] = this; if (!this->uid.empty()) @@ -78,14 +61,12 @@ BotInfo::BotInfo(const std::string &nnick, const std::string &nuser, const std:: BotInfo::~BotInfo() { - for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(); it != RegisteredChannelList.end(); ++it) + for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; ++it) { ChannelInfo *ci = it->second; if (ci->bi == this) - { ci->bi = NULL; - } } BotListByNick.erase(this->nick.c_str()); @@ -105,7 +86,7 @@ void BotInfo::ChangeNick(const char *newnick) void BotInfo::RejoinAll() { - for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(); it != RegisteredChannelList.end(); ++it) + for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; ++it) { ChannelInfo *ci = it->second; diff --git a/src/botserv.cpp b/src/botserv.cpp index 2dd96706d..624d1df83 100644 --- a/src/botserv.cpp +++ b/src/botserv.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ /*************************************************************************/ @@ -17,19 +15,20 @@ #include "modules.h" #include "language.h" -static UserData *get_user_data(Channel * c, User * u); +static UserData *get_user_data(Channel *c, User *u); -static void check_ban(ChannelInfo * ci, User * u, int ttbtype); -static void bot_kick(ChannelInfo * ci, User * u, int message, ...); +static void check_ban(ChannelInfo *ci, User *u, int ttbtype); +static void bot_kick(ChannelInfo *ci, User *u, int message, ...); E void moduleAddBotServCmds(); /*************************************************************************/ -/* *INDENT-OFF* */ -void moduleAddBotServCmds() { + +void moduleAddBotServCmds() +{ ModuleManager::LoadModuleList(Config.BotServCoreModules); } -/* *INDENT-ON* */ + /*************************************************************************/ /*************************************************************************/ @@ -39,7 +38,7 @@ void get_botserv_stats(long *nrec, long *memuse) { long count = 0, mem = 0; - for (botinfo_map::const_iterator it = BotListByNick.begin(); it != BotListByNick.end(); ++it) + for (botinfo_map::const_iterator it = BotListByNick.begin(), it_end = BotListByNick.end(); it != it_end; ++it) { BotInfo *bi = it->second; @@ -62,9 +61,8 @@ void get_botserv_stats(long *nrec, long *memuse) void bs_init() { - if (Config.s_BotServ) { + if (Config.s_BotServ) moduleAddBotServCmds(); - } } /*************************************************************************/ @@ -75,7 +73,7 @@ void botserv(User *u, BotInfo *bi, const std::string &buf) { if (!u || !bi || buf.empty()) return; - + if (buf.find("\1PING ", 0, 6) != std::string::npos && buf[buf.length() - 1] == '\1') { std::string command = buf; @@ -84,23 +82,20 @@ void botserv(User *u, BotInfo *bi, const std::string &buf) ircdproto->SendCTCP(bi, u->nick.c_str(), "%s", command.c_str()); } else - { mod_run_cmd(bi, u, buf); - } } /*************************************************************************/ /* Handles all messages that are sent to registered channels where a * bot is on. - * */ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) { if (!u || !ci || !ci->c || buf.empty()) return; - + /* Answer to ping if needed */ if (buf.find("\1PING ", 0, 6) != std::string::npos && buf[buf.length() - 1] == '\1') { @@ -180,17 +175,16 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) /* Caps kicker */ if (ci->botflags.HasFlag(BS_KICK_CAPS) && realbuf.length() >= ci->capsmin) { - int i = 0; - int l = 0; + int i = 0, l = 0; - for (unsigned j = 0; j < realbuf.length(); ++j) + for (unsigned j = 0, end = realbuf.length(); j < end; ++j) { if (isupper(realbuf[j])) ++i; else if (islower(realbuf[j])) ++l; } - + /* i counts uppercase chars, l counts lowercase chars. Only * alphabetic chars (so islower || isupper) qualify for the * percentage of caps to kick for; the rest is ignored. -GD @@ -212,33 +206,24 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) /* Normalize the buffer */ const char *nbuf = normalizeBuffer(realbuf.c_str()); - for (unsigned i = 0; i < ci->GetBadWordCount(); ++i) + for (unsigned i = 0, end = ci->GetBadWordCount(); i < end; ++i) { BadWord *bw = ci->GetBadWord(i); if (bw->type == BW_ANY && ((Config.BSCaseSensitive && strstr(nbuf, bw->word.c_str())) || (!Config.BSCaseSensitive && stristr(nbuf, bw->word.c_str())))) - { mustkick = true; - } else if (bw->type == BW_SINGLE) { size_t len = bw->word.length(); - if ((Config.BSCaseSensitive && nbuf == bw->word) || (!Config.BSCaseSensitive && (!stricmp(nbuf, bw->word.c_str())))) - { + if ((Config.BSCaseSensitive && nbuf == bw->word) || (!Config.BSCaseSensitive && (!stricmp(nbuf, bw->word.c_str())))) mustkick = true; - } - else if ((strchr(nbuf, ' ') == nbuf + len) && ((Config.BSCaseSensitive && nbuf == bw->word) - || (!Config.BSCaseSensitive && (stristr(nbuf, bw->word.c_str()) == nbuf)))) - { + else if ((strchr(nbuf, ' ') == nbuf + len) && ((Config.BSCaseSensitive && nbuf == bw->word) || (!Config.BSCaseSensitive && (stristr(nbuf, bw->word.c_str()) == nbuf)))) mustkick = true; - } else { if ((strrchr(nbuf, ' ') == nbuf + strlen(nbuf) - len - 1) && ((Config.BSCaseSensitive && (strstr(nbuf, bw->word.c_str()) == nbuf + strlen(nbuf) - len)) || (!Config.BSCaseSensitive && (stristr(nbuf, bw->word.c_str()) == nbuf + strlen(nbuf) - len)))) - { mustkick = true; - } else { char *wordbuf = new char[len + 3]; @@ -248,10 +233,8 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) wordbuf[len + 2] = '\0'; memcpy(wordbuf + 1, bw->word.c_str(), len); - if ((Config.BSCaseSensitive && (strstr(nbuf, wordbuf))) || (!Config.BSCaseSensitive && (stristr(nbuf, wordbuf)))) - { + if ((Config.BSCaseSensitive && strstr(nbuf, wordbuf)) || (!Config.BSCaseSensitive && stristr(nbuf, wordbuf))) mustkick = true; - } delete [] wordbuf; } @@ -261,10 +244,8 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) { size_t len = bw->word.length(); - if ((Config.BSCaseSensitive && (!strncmp(nbuf, bw->word.c_str(), len))) || (!Config.BSCaseSensitive && (!strnicmp(nbuf, bw->word.c_str(), len)))) - { + if ((Config.BSCaseSensitive && !strncmp(nbuf, bw->word.c_str(), len)) || (!Config.BSCaseSensitive && !strnicmp(nbuf, bw->word.c_str(), len))) mustkick = true; - } else { char *wordbuf = new char[len + 2]; @@ -273,10 +254,8 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) wordbuf[0] = ' '; wordbuf[len + 1] = '\0'; - if ((Config.BSCaseSensitive && (strstr(nbuf, wordbuf))) || (!Config.BSCaseSensitive && (stristr(nbuf, wordbuf)))) - { + if ((Config.BSCaseSensitive && strstr(nbuf, wordbuf)) || (!Config.BSCaseSensitive && stristr(nbuf, wordbuf))) mustkick = true; - } delete [] wordbuf; } @@ -285,11 +264,8 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) { size_t len = bw->word.length(); - if ((Config.BSCaseSensitive && (!strncmp(nbuf + strlen(nbuf) - len, bw->word.c_str(), len))) - || (!Config.BSCaseSensitive && (!strnicmp(nbuf + strlen(nbuf) - len, bw->word.c_str(), len)))) - { + if ((Config.BSCaseSensitive && !strncmp(nbuf + strlen(nbuf) - len, bw->word.c_str(), len)) || (!Config.BSCaseSensitive && !strnicmp(nbuf + strlen(nbuf) - len, bw->word.c_str(), len))) mustkick = true; - } else { char *wordbuf = new char[len + 2]; @@ -298,10 +274,8 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) wordbuf[len] = ' '; wordbuf[len + 1] = '\0'; - if ((Config.BSCaseSensitive && (strstr(nbuf, wordbuf))) || (!Config.BSCaseSensitive && (stristr(nbuf, wordbuf)))) - { + if ((Config.BSCaseSensitive && strstr(nbuf, wordbuf)) || (!Config.BSCaseSensitive && stristr(nbuf, wordbuf))) mustkick = true; - } delete [] wordbuf; } @@ -341,7 +315,7 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) ud->lines = 0; } - ud->lines++; + ++ud->lines; if (ud->lines >= ci->floodlines) { check_ban(ci, u, TTB_FLOOD); @@ -356,7 +330,7 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) UserData *ud = get_user_data(ci->c, u); if (!ud) return; - + if (ud->lastline && stricmp(ud->lastline, buf.c_str())) { delete [] ud->lastline; @@ -367,7 +341,7 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) { if (!ud->lastline) ud->lastline = sstrdup(buf.c_str()); - ud->times++; + ++ud->times; } if (ud->times >= ci->repeattimes) @@ -381,9 +355,7 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) /* return if the user is on the ignore list */ if (get_ignore(u->nick.c_str()) != NULL) - { return; - } /* Fantaisist commands */ if (ci->botflags.HasFlag(BS_FANTASY) && buf[0] == *Config.BSFantasyCharacter && !was_action) @@ -391,7 +363,7 @@ void botchanmsgs(User *u, ChannelInfo *ci, const std::string &buf) spacesepstream sep(buf); std::string token; - if (sep.GetToken(token) && (token[0] == *Config.BSFantasyCharacter)) + if (sep.GetToken(token) && token[0] == *Config.BSFantasyCharacter) { /* Strip off the fantasy character */ token.erase(token.begin()); @@ -461,13 +433,12 @@ BotInfo *findbot(const ci::string &nick) return NULL; } - /*************************************************************************/ /* Returns ban data associated with an user if it exists, allocates it otherwise. */ -static BanData *get_ban_data(Channel * c, User * u) +static BanData *get_ban_data(Channel *c, User *u) { char mask[BUFSIZE]; BanData *bd, *next; @@ -476,11 +447,12 @@ static BanData *get_ban_data(Channel * c, User * u) if (!c || !u) return NULL; - snprintf(mask, sizeof(mask), "%s@%s", u->GetIdent().c_str(), - u->GetDisplayedHost().c_str()); + snprintf(mask, sizeof(mask), "%s@%s", u->GetIdent().c_str(), u->GetDisplayedHost().c_str()); - for (bd = c->bd; bd; bd = next) { - if (now - bd->last_use > Config.BSKeepData) { + for (bd = c->bd; bd; bd = next) + { + if (now - bd->last_use > Config.BSKeepData) + { if (bd->next) bd->next->prev = bd->prev; if (bd->prev) @@ -493,7 +465,8 @@ static BanData *get_ban_data(Channel * c, User * u) delete bd; continue; } - if (!stricmp(bd->mask, mask)) { + if (!stricmp(bd->mask, mask)) + { bd->last_use = now; return bd; } @@ -527,7 +500,7 @@ static UserData *get_user_data(Channel *c, User *u) if (!c || !u) return NULL; - for (CUserList::iterator it = c->users.begin(); it != c->users.end(); ++it) + for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ++it) { UserContainer *uc = *it; @@ -574,31 +547,22 @@ void bot_join(ChannelInfo * ci) next = ban->next; if (entry_match(ban, ci->bi->nick.c_str(), ci->bi->user.c_str(), ci->bi->host.c_str(), 0)) - { ci->c->RemoveMode(NULL, CMODE_BAN, ban->mask); - } } } std::string Limit; int limit = 0; if (ci->c->GetParam(CMODE_LIMIT, Limit)) - { limit = atoi(Limit.c_str()); - } /* Should we be invited? */ - if (ci->c->HasMode(CMODE_INVITE) - || (limit && ci->c->users.size() >= limit)) - ircdproto->SendNoticeChanops(ci->bi, ci->c, - "%s invited %s into the channel.", - ci->bi->nick.c_str(), ci->bi->nick.c_str()); + if (ci->c->HasMode(CMODE_INVITE) || (limit && ci->c->users.size() >= limit)) + ircdproto->SendNoticeChanops(ci->bi, ci->c, "%s invited %s into the channel.", ci->bi->nick.c_str(), ci->bi->nick.c_str()); } ircdproto->SendJoin(ci->bi, ci->c->name.c_str(), ci->c->creation_time); - for (std::list<ChannelModeStatus *>::iterator it = BotModes.begin(); it != BotModes.end(); ++it) - { + for (std::list<ChannelModeStatus *>::iterator it = BotModes.begin(), it_end = BotModes.end(); it != it_end; ++it) ci->c->SetMode(ci->bi, *it, ci->bi->nick, false); - } FOREACH_MOD(I_OnBotJoin, OnBotJoin(ci, ci->bi)); } @@ -620,7 +584,7 @@ static void check_ban(ChannelInfo *ci, User *u, int ttbtype) if (u->server->IsULined()) return; - bd->ttb[ttbtype]++; + ++bd->ttb[ttbtype]; if (ci->ttb[ttbtype] && bd->ttb[ttbtype] >= ci->ttb[ttbtype]) { /* Should not use == here because bd->ttb[ttbtype] could possibly be > ci->ttb[ttbtype] @@ -642,7 +606,7 @@ static void check_ban(ChannelInfo *ci, User *u, int ttbtype) /* This makes a bot kick an user. Works somewhat like notice_lang in fact ;) */ -static void bot_kick(ChannelInfo * ci, User * u, int message, ...) +static void bot_kick(ChannelInfo *ci, User *u, int message, ...) { va_list args; char buf[1024]; @@ -665,7 +629,7 @@ static void bot_kick(ChannelInfo * ci, User * u, int message, ...) /* Makes a simple ban and kicks the target */ -void bot_raw_ban(User * requester, ChannelInfo * ci, char *nick, const char *reason) +void bot_raw_ban(User *requester, ChannelInfo *ci, char *nick, const char *reason) { char mask[BUFSIZE]; User *u = finduser(nick); @@ -673,23 +637,19 @@ void bot_raw_ban(User * requester, ChannelInfo * ci, char *nick, const char *rea if (!u) return; - if ((ModeManager::FindUserModeByName(UMODE_PROTECTED))) + if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && requester != u) { - if (u->IsProtected() && (requester != u)) { - ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(ACCESS_DENIED)); - return; - } + ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(ACCESS_DENIED)); + return; } - if (ci->HasFlag(CI_PEACE) && stricmp(requester->nick.c_str(), nick) && (get_access(u, ci) >= get_access(requester, ci))) + if (ci->HasFlag(CI_PEACE) && stricmp(requester->nick.c_str(), nick) && get_access(u, ci) >= get_access(requester, ci)) return; - if (ModeManager::FindChannelModeByName(CMODE_EXCEPT)) + if (ModeManager::FindChannelModeByName(CMODE_EXCEPT) && is_excepted(ci, u) == 1) { - if (is_excepted(ci, u) == 1) { - ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(BOT_EXCEPT)); - return; - } + ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(BOT_EXCEPT)); + return; } get_idealban(ci, u, mask, sizeof(mask)); @@ -707,22 +667,20 @@ void bot_raw_ban(User * requester, ChannelInfo * ci, char *nick, const char *rea /* Makes a kick with a "dynamic" reason ;) */ -void bot_raw_kick(User * requester, ChannelInfo * ci, char *nick, const char *reason) +void bot_raw_kick(User *requester, ChannelInfo *ci, char *nick, const char *reason) { User *u = finduser(nick); if (!u || !ci->c->FindUser(u)) return; - if ((ModeManager::FindUserModeByName(UMODE_PROTECTED))) + if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && requester != u) { - if (u->IsProtected() && (requester != u)) { - ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(ACCESS_DENIED)); - return; - } + ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(ACCESS_DENIED)); + return; } - if (ci->HasFlag(CI_PEACE) && stricmp(requester->nick.c_str(), nick) && (get_access(u, ci) >= get_access(requester, ci))) + if (ci->HasFlag(CI_PEACE) && stricmp(requester->nick.c_str(), nick) && get_access(u, ci) >= get_access(requester, ci)) return; if (ci->HasFlag(CI_SIGNKICK) || (ci->HasFlag(CI_SIGNKICK_LEVEL) && !check_access(requester, ci, CA_SIGNKICK))) @@ -735,12 +693,11 @@ void bot_raw_kick(User * requester, ChannelInfo * ci, char *nick, const char *re /* Makes a mode operation on a channel for a nick */ -void bot_raw_mode(User * requester, ChannelInfo * ci, const char *mode, char *nick) +void bot_raw_mode(User *requester, ChannelInfo *ci, const char *mode, char *nick) { - char buf[BUFSIZE]; + char buf[BUFSIZE] = ""; User *u; - *buf = '\0'; u = finduser(nick); if (!u || !ci->c->FindUser(u)) @@ -748,15 +705,13 @@ void bot_raw_mode(User * requester, ChannelInfo * ci, const char *mode, char *ni snprintf(buf, BUFSIZE - 1, "%ld", static_cast<long>(time(NULL))); - if ((ModeManager::FindUserModeByName(UMODE_PROTECTED))) { - if (u->IsProtected() && *mode == '-' && (requester != u)) { - ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(ACCESS_DENIED)); - return; - } + if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && *mode == '-' && requester != u) + { + ircdproto->SendPrivmsg(ci->bi, ci->name.c_str(), "%s", getstring(ACCESS_DENIED)); + return; } - if (*mode == '-' && ci->HasFlag(CI_PEACE) - && stricmp(requester->nick.c_str(), nick) && (get_access(u, ci) >= get_access(requester, ci))) + if (*mode == '-' && ci->HasFlag(CI_PEACE) && stricmp(requester->nick.c_str(), nick) && get_access(u, ci) >= get_access(requester, ci)) return; ci->c->SetModes(NULL, "%s %s", mode, nick); @@ -776,69 +731,70 @@ char *normalizeBuffer(const char *buf) len = strlen(buf); newbuf = new char[len + 1]; - for (i = 0; i < len; i++) { - switch (buf[i]) { + for (i = 0; i < len; ++i) + { + switch (buf[i]) + { /* ctrl char */ - case 1: - break; + case 1: + break; /* Bold ctrl char */ - case 2: - break; + case 2: + break; /* Color ctrl char */ - case 3: - /* If the next character is a digit, its also removed */ - if (isdigit(buf[i + 1])) { - i++; - - /* not the best way to remove colors - * which are two digit but no worse then - * how the Unreal does with +S - TSL - */ - if (isdigit(buf[i + 1])) { - i++; - } - - /* Check for background color code - * and remove it as well - */ - if (buf[i + 1] == ',') { - i++; + case 3: + /* If the next character is a digit, its also removed */ + if (isdigit(buf[i + 1])) + { + ++i; - if (isdigit(buf[i + 1])) { - i++; - } /* not the best way to remove colors * which are two digit but no worse then * how the Unreal does with +S - TSL */ - if (isdigit(buf[i + 1])) { - i++; + if (isdigit(buf[i + 1])) + ++i; + + /* Check for background color code + * and remove it as well + */ + if (buf[i + 1] == ',') + { + ++i; + + if (isdigit(buf[i + 1])) + ++i; + /* not the best way to remove colors + * which are two digit but no worse then + * how the Unreal does with +S - TSL + */ + if (isdigit(buf[i + 1])) + ++i; } } - } - break; + break; /* line feed char */ - case 10: - break; + case 10: + break; /* carriage returns char */ - case 13: - break; + case 13: + break; /* Reverse ctrl char */ - case 22: - break; + case 22: + break; /* Underline ctrl char */ - case 31: - break; + case 31: + break; /* A valid char gets copied into the new buffer */ - default: - newbuf[j] = buf[i]; - j++; + default: + newbuf[j] = buf[i]; + ++j; } } /* Terminate the string */ newbuf[j] = 0; - return (newbuf); + return newbuf; } diff --git a/src/channels.cpp b/src/channels.cpp index b2c839083..1a846d1bd 100644 --- a/src/channels.cpp +++ b/src/channels.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -69,28 +67,16 @@ Channel::~Channel() delete [] this->topic; if (this->bans && this->bans->count) - { while (this->bans->entries) entry_delete(this->bans, this->bans->entries); - } - if (ModeManager::FindChannelModeByName(CMODE_EXCEPT)) - { - if (this->excepts && this->excepts->count) - { - while (this->excepts->entries) - entry_delete(this->excepts, this->excepts->entries); - } - } + if (ModeManager::FindChannelModeByName(CMODE_EXCEPT) && this->excepts && this->excepts->count) + while (this->excepts->entries) + entry_delete(this->excepts, this->excepts->entries); - if (ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE)) - { - if (this->invites && this->invites->count) - { - while (this->invites->entries) - entry_delete(this->invites, this->invites->entries); - } - } + if (ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE) && this->invites && this->invites->count) + while (this->invites->entries) + entry_delete(this->invites, this->invites->entries); ChannelList.erase(this->name.c_str()); } @@ -120,9 +106,9 @@ void Channel::JoinUser(User *user) uc->Status = Status; this->users.push_back(uc); - if (get_ignore(user->nick.c_str()) == NULL) + if (!get_ignore(user->nick.c_str())) { - if (this->ci && (check_access(user, this->ci, CA_MEMO)) && (this->ci->memos.memos.size() > 0)) + if (this->ci && check_access(user, this->ci, CA_MEMO) && this->ci->memos.memos.size() > 0) { if (this->ci->memos.memos.size() == 1) notice_lang(Config.s_MemoServ, user, MEMO_X_ONE_NOTICE, this->ci->memos.memos.size(), this->ci->name.c_str()); @@ -143,26 +129,17 @@ void Channel::JoinUser(User *user) * But don't join the bot if the channel is persistant - Adam * But join persistant channels when syncing with our uplink- DP **/ - if (Config.s_BotServ && this->ci && this->ci->bi && (!Me->IsSynced() || !this->ci->HasFlag(CI_PERSIST))) - { - if (this->users.size() == Config.BSMinUsers) - bot_join(this->ci); - } - if (Config.s_BotServ && this->ci && this->ci->bi) + if (Config.s_BotServ && this->ci && this->ci->bi && (!Me->IsSynced() || !this->ci->HasFlag(CI_PERSIST)) && this->users.size() == Config.BSMinUsers) + bot_join(this->ci); + /* Only display the greet if the main uplink we're connected + * to has synced, or we'll get greet-floods when the net + * recovers from a netsplit. -GD + */ + if (Config.s_BotServ && this->ci && this->ci->bi && this->users.size() >= Config.BSMinUsers && this->ci->botflags.HasFlag(BS_GREET) && user->Account() && user->Account()->greet && + check_access(user, this->ci, CA_GREET) && user->server->IsSynced()) { - if (this->users.size() >= Config.BSMinUsers && (this->ci->botflags.HasFlag(BS_GREET)) - && user->Account() && user->Account()->greet && check_access(user, this->ci, CA_GREET)) - { - /* Only display the greet if the main uplink we're connected - * to has synced, or we'll get greet-floods when the net - * recovers from a netsplit. -GD - */ - if (user->server->IsSynced()) - { - ircdproto->SendPrivmsg(this->ci->bi, this->name.c_str(), "[%s] %s", user->Account()->display, user->Account()->greet); - this->ci->bi->lastmsg = time(NULL); - } - } + ircdproto->SendPrivmsg(this->ci->bi, this->name.c_str(), "[%s] %s", user->Account()->display, user->Account()->greet); + this->ci->bi->lastmsg = time(NULL); } } @@ -174,9 +151,9 @@ void Channel::DeleteUser(User *user) if (this->ci) update_cs_lastseen(user, this->ci); - CUserList::iterator cit; - for (cit = this->users.begin(); (*cit)->user != user && cit != this->users.end(); ++cit); - if (cit == this->users.end()) + CUserList::iterator cit, cit_end = this->users.end(); + for (cit = this->users.begin(); (*cit)->user != user && cit != cit_end; ++cit); + if (cit == cit_end) { Alog(LOG_DEBUG) << "Channel::DeleteUser() tried to delete nonexistant user " << user->nick << " from channel " << this->name; return; @@ -186,9 +163,9 @@ void Channel::DeleteUser(User *user) delete *cit; this->users.erase(cit); - UChannelList::iterator uit; - for (uit = user->chans.begin(); (*uit)->chan != this && uit != user->chans.end(); ++uit); - if (uit == user->chans.end()) + UChannelList::iterator uit, uit_end = user->chans.end(); + for (uit = user->chans.begin(); (*uit)->chan != this && uit != uit_end; ++uit); + if (uit == uit_end) { Alog(LOG_DEBUG) << "Channel::DeleteUser() tried to delete nonexistant channel " << this->name << " from " << user->nick << "'s channel list"; return; @@ -200,20 +177,20 @@ void Channel::DeleteUser(User *user) /* Channel is persistant, it shouldn't be deleted and the service bot should stay */ if (this->HasFlag(CH_PERSIST) || (this->ci && this->ci->HasFlag(CI_PERSIST))) return; - + /* Channel is syncing from a netburst, don't destroy it as more users are probably wanting to join immediatly * We also don't part the bot here either, if necessary we will part it after the sync */ if (this->HasFlag(CH_SYNCING)) return; - + /* Additionally, do not delete this channel if ChanServ/a BotServ bot is inhabiting it */ if (this->ci && this->ci->HasFlag(CI_INHABIT)) return; if (Config.s_BotServ && this->ci && this->ci->bi && this->users.size() <= Config.BSMinUsers - 1) ircdproto->SendPart(this->ci->bi, this, NULL); - + if (this->users.empty()) delete this; } @@ -224,7 +201,7 @@ void Channel::DeleteUser(User *user) */ UserContainer *Channel::FindUser(User *u) { - for (CUserList::iterator it = this->users.begin(); it != this->users.end(); ++it) + for (CUserList::iterator it = this->users.begin(), it_end = this->users.end(); it != it_end; ++it) if ((*it)->user == u) return *it; return NULL; @@ -312,9 +289,7 @@ void Channel::SetModeInternal(ChannelMode *cm, const std::string ¶m, bool En /* Set the status on the user */ ChannelContainer *cc = u->FindChannel(this); if (cc) - { cc->Status->SetFlag(cm->Name); - } /* Enforce secureops, etc */ chan_set_correct_modes(u, this, 0); @@ -347,9 +322,7 @@ void Channel::SetModeInternal(ChannelMode *cm, const std::string ¶m, bool En /* They could be resetting the mode to change its params */ std::map<ChannelModeName, std::string>::iterator it = Params.find(cm->Name); if (it != Params.end()) - { Params.erase(it); - } Params.insert(std::make_pair(cm->Name, param)); } @@ -368,15 +341,11 @@ void Channel::SetModeInternal(ChannelMode *cm, const std::string ¶m, bool En /* Non registered channels can not be +r */ if (!ci && HasMode(CMODE_REGISTERED)) - { RemoveMode(NULL, CMODE_REGISTERED); - } /* Non registered channel has no mlock */ if (!ci) - { return; - } /* If this channel has this mode locked negative */ if (ci->HasMLock(cm->Name, false)) @@ -403,10 +372,8 @@ void Channel::SetModeInternal(ChannelMode *cm, const std::string ¶m, bool En /* We have the wrong param set */ if (cparam.empty() || ciparam.empty() || cparam != ciparam) - { /* Reset the mode with the correct param */ SetMode(NULL, cm, ciparam); - } } } @@ -437,9 +404,7 @@ void Channel::RemoveModeInternal(ChannelMode *cm, const std::string ¶m, bool if (bi) { if (std::find(BotModes.begin(), BotModes.end(), cm) != BotModes.end()) - { this->SetMode(bi, cm, bi->nick); - } /* We don't track bots */ return; } @@ -456,9 +421,7 @@ void Channel::RemoveModeInternal(ChannelMode *cm, const std::string ¶m, bool /* Remove the status on the user */ ChannelContainer *cc = u->FindChannel(this); if (cc) - { cc->Status->UnsetFlag(cm->Name); - } return; } @@ -482,9 +445,7 @@ void Channel::RemoveModeInternal(ChannelMode *cm, const std::string ¶m, bool { std::map<ChannelModeName, std::string>::iterator it = Params.find(cm->Name); if (it != Params.end()) - { Params.erase(it); - } } if (cm->Name == CMODE_PERM) @@ -547,13 +508,8 @@ void Channel::SetMode(BotInfo *bi, ChannelMode *cm, const std::string ¶m, bo else if (cm->Type == MODE_PARAM && HasMode(cm->Name)) { std::string cparam; - if (GetParam(cm->Name, cparam)) - { - if (cparam == param) - { - return; - } - } + if (GetParam(cm->Name, cparam) && cparam == param) + return; } else if (cm->Type == MODE_STATUS) { @@ -684,9 +640,7 @@ const bool Channel::HasParam(ChannelModeName Name) std::map<ChannelModeName, std::string>::iterator it = Params.find(Name); if (it != Params.end()) - { return true; - } return false; } @@ -707,9 +661,7 @@ void Channel::ClearModes(BotInfo *bi) if (cm && this->HasMode(cm->Name)) { if (cm->Type == MODE_REGULAR) - { this->RemoveMode(NULL, cm); - } else if (cm->Type == MODE_PARAM) { std::string param; @@ -733,14 +685,12 @@ void Channel::ClearBans(BotInfo *bi) cml = dynamic_cast<ChannelModeList *>(ModeManager::FindChannelModeByName(CMODE_BAN)); if (cml && this->bans && this->bans->count) - { for (entry = this->bans->entries; entry; entry = nexte) { nexte = entry->next; this->RemoveMode(bi, CMODE_BAN, entry->mask); } - } } /** Clear all the excepts from the channel @@ -754,14 +704,12 @@ void Channel::ClearExcepts(BotInfo *bi) cml = dynamic_cast<ChannelModeList *>(ModeManager::FindChannelModeByName(CMODE_EXCEPT)); if (cml && this->excepts && this->excepts->count) - { for (entry = this->excepts->entries; entry; entry = nexte) { nexte = entry->next; this->RemoveMode(bi, CMODE_EXCEPT, entry->mask); } - } } /** Clear all the invites from the channel @@ -775,14 +723,12 @@ void Channel::ClearInvites(BotInfo *bi) cml = dynamic_cast<ChannelModeList *>(ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE)); if (cml && this->invites && this->invites->count) - { for (entry = this->invites->entries; entry; entry = nexte) { nexte = entry->next; this->RemoveMode(bi, CMODE_INVITEOVERRIDE, entry->mask); } - } } /** Set a string of modes on the channel @@ -802,7 +748,7 @@ void Channel::SetModes(BotInfo *bi, bool EnforceMLock, const char *cmodes, ...) spacesepstream sep(buf); sep.GetToken(modebuf); - for (unsigned i = 0; i < modebuf.size(); ++i) + for (unsigned i = 0, end = modebuf.size(); i < end; ++i) { ChannelMode *cm; @@ -829,7 +775,7 @@ void Channel::SetModes(BotInfo *bi, bool EnforceMLock, const char *cmodes, ...) else this->SetMode(bi, cm, "", EnforceMLock); } - else if (add == 0) + else if (!add) { if (cm->Type != MODE_REGULAR && sep.GetToken(sbuf)) this->RemoveMode(bi, cm, sbuf, EnforceMLock); @@ -852,7 +798,7 @@ void ChanSetInternalModes(Channel *c, int ac, const char **av) return; int k = 0, j = 0, add = -1; - for (unsigned int i = 0; i < strlen(av[0]); ++i) + for (unsigned int i = 0, end = strlen(av[0]); i < end; ++i) { ChannelMode *cm; @@ -899,15 +845,11 @@ void ChanSetInternalModes(Channel *c, int ac, const char **av) c->RemoveModeInternal(cm, av[j]); } else - { Alog() << "warning: ChanSetInternalModes() recieved more modes requiring params than params, modes: " << merge_args(ac, av) << ", ac: " << ac << ", j: " << j; - } } if (j + k + 1 < ac) - { Alog() << "warning: ChanSetInternalModes() recieved more params than modes requiring them, modes: " << merge_args(ac, av) << ", ac: " << ac << ", j: " << j << " k: " << k; - } } /** Kick a user from a channel internally @@ -935,7 +877,7 @@ void Channel::KickInternal(const std::string &source, const std::string &nick, c } Alog(LOG_DEBUG) << "Channel::KickInternal kicking " << user->nick << " from " << this->name; - + if (user->FindChannel(this)) { FOREACH_MOD(I_OnUserKicked, OnUserKicked(this, user, source, reason)); @@ -962,7 +904,7 @@ bool Channel::Kick(BotInfo *bi, User *u, const char *reason, ...) /* May not kick ulines */ if (u->server->IsULined()) return false; - + /* Do not kick protected clients */ if (u->IsProtected()) return false; @@ -989,7 +931,7 @@ char *chan_get_modes(Channel * chan, int complete, int plus) if (chan->HasModes()) { - for (std::list<Mode *>::iterator it = ModeManager::Modes.begin(); it != ModeManager::Modes.end(); ++it) + for (std::list<Mode *>::iterator it = ModeManager::Modes.begin(), it_end = ModeManager::Modes.end(); it != it_end; ++it) { if ((*it)->Class != MC_CHANNEL) continue; @@ -1069,7 +1011,7 @@ void get_channel_stats(long *nrec, long *memuse) { Channel *chan = cit->second; - count++; + ++count; mem += sizeof(*chan); if (chan->topic) mem += strlen(chan->topic) + 1; @@ -1084,14 +1026,15 @@ void get_channel_stats(long *nrec, long *memuse) mem += get_memuse(chan->excepts); if (ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE)) mem += get_memuse(chan->invites); - for (CUserList::iterator it = chan->users.begin(); it != chan->users.end(); ++it) + for (CUserList::iterator it = chan->users.begin(), it_end = chan->users.end(); it != it_end; ++it) { mem += sizeof(*it); mem += sizeof((*it)->ud); if ((*it)->ud.lastline) mem += strlen((*it)->ud.lastline) + 1; } - for (bd = chan->bd; bd; bd = bd->next) { + for (bd = chan->bd; bd; bd = bd->next) + { if (bd->mask) mem += strlen(bd->mask) + 1; mem += sizeof(*bd); @@ -1106,12 +1049,12 @@ void get_channel_stats(long *nrec, long *memuse) /* Is the given nick on the given channel? This function supports links. */ -User *nc_on_chan(Channel * c, NickCore * nc) +User *nc_on_chan(Channel *c, NickCore *nc) { if (!c || !nc) return NULL; - for (CUserList::iterator it = c->users.begin(); it != c->users.end(); ++it) + for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ++it) { UserContainer *uc = *it; @@ -1148,7 +1091,7 @@ void do_join(const char *source, int ac, const char **av) { if (buf[0] == '0') { - for (UChannelList::iterator it = user->chans.begin(); it != user->chans.end();) + for (UChannelList::iterator it = user->chans.begin(), it_end = user->chans.end(); it != it_end; ) { ChannelContainer *cc = *it++; @@ -1165,9 +1108,7 @@ void do_join(const char *source, int ac, const char **av) /* Channel doesn't exist, create it */ if (!chan) - { chan = new Channel(av[0], ctime); - } /* Join came with a TS */ if (ac == 2) @@ -1231,9 +1172,7 @@ void do_kick(const std::string &source, int ac, const char **av) std::string buf; commasepstream sep(av[1]); while (sep.GetToken(buf)) - { c->KickInternal(source, buf, av[2]); - } } /*************************************************************************/ @@ -1246,7 +1185,7 @@ void do_kick(const std::string &source, int ac, const char **av) void do_part(const char *source, int ac, const char **av) { User *user = finduser(source); - if (!user) + if (!user) { Alog(LOG_DEBUG) << "PART from nonexistent user " << source << ": " << merge_args(ac, av); return; @@ -1257,11 +1196,9 @@ void do_part(const char *source, int ac, const char **av) while (sep.GetToken(buf)) { Channel *c = findchan(buf); - + if (!c) - { Alog(LOG_DEBUG) << "Recieved PART from " << user->nick << " for nonexistant channel " << buf; - } Alog(LOG_DEBUG) << source << " leaves " << buf; @@ -1289,34 +1226,31 @@ void do_cmode(const char *source, int ac, const char **av) { Channel *c; ChannelInfo *ci; - unsigned int i; + unsigned i, end; const char *t; if (Capab.HasFlag(CAPAB_TSMODE) || UseTSMODE) { - for (i = 0; i < strlen(av[1]); i++) + for (i = 0, end = strlen(av[1]); i < end; ++i) if (!isdigit(av[1][i])) break; - if (av[1][i] == '\0') + if (!av[1][i]) { t = av[0]; av[0] = av[1]; av[1] = t; - ac--; - av++; + --ac; + ++av; } else Alog() << "TSMODE enabled but MODE has no valid TS"; } /* :42XAAAAAO TMODE 1106409026 #ircops +b *!*@*.aol.com */ - if (ircd->ts6) + if (ircd->ts6 && isdigit(av[0][0])) { - if (isdigit(av[0][0])) - { - ac--; - av++; - } + --ac; + ++av; } c = findchan(av[0]); @@ -1338,11 +1272,11 @@ void do_cmode(const char *source, int ac, const char **av) c->server_modecount = 0; c->server_modetime = time(NULL); } - c->server_modecount++; + ++c->server_modecount; } - ac--; - av++; + --ac; + ++av; ChanSetInternalModes(c, ac, av); } @@ -1358,16 +1292,17 @@ void do_topic(const char *source, int ac, const char **av) time_t topic_time; char *topicsetter; - if (ircd->sjb64) { + if (ircd->sjb64) + { ts = base64dects(av[2]); Alog(LOG_DEBUG) << "encoded TOPIC TS " << av[2] << " converted to " << ts; - } else { - ts = strtoul(av[2], NULL, 10); } + else + ts = strtoul(av[2], NULL, 10); topic_time = ts; - if (!c) + if (!c) { Alog(LOG_DEBUG) << "TOPIC " << merge_args(ac - 1, av + 1) << " for nonexistent channel " << av[0]; return; @@ -1387,25 +1322,25 @@ void do_topic(const char *source, int ac, const char **av) * channel exactly, there's no need to update anything and we can as * well just return silently without updating anything. -GD */ - if ((ac > 3) && *av[3] && ci && ci->last_topic - && (strcmp(av[3], ci->last_topic) == 0) - && (strcmp(topicsetter, ci->last_topic_setter.c_str()) == 0)) { + if (ac > 3 && *av[3] && ci && ci->last_topic && !strcmp(av[3], ci->last_topic) && !strcmp(topicsetter, ci->last_topic_setter.c_str())) + { delete [] topicsetter; return; } - if (check_topiclock(c, topic_time)) { + if (check_topiclock(c, topic_time)) + { delete [] topicsetter; return; } - if (c->topic) { + if (c->topic) + { delete [] c->topic; c->topic = NULL; } - if (ac > 3 && *av[3]) { + if (ac > 3 && *av[3]) c->topic = sstrdup(av[3]); - } c->topic_setter = topicsetter; c->topic_time = topic_time; @@ -1429,7 +1364,7 @@ void do_topic(const char *source, int ac, const char **av) * @param give_modes Set to 1 to give modes, 0 to not give modes * @return void **/ -void chan_set_correct_modes(User * user, Channel * c, int give_modes) +void chan_set_correct_modes(User *user, Channel *c, int give_modes) { ChannelInfo *ci; ChannelMode *owner, *admin, *op, *halfop, *voice; @@ -1443,7 +1378,7 @@ void chan_set_correct_modes(User * user, Channel * c, int give_modes) if (!c || !(ci = c->ci)) return; - if ((ci->HasFlag(CI_FORBIDDEN)) || (*(c->name.c_str()) == '+')) + if (ci->HasFlag(CI_FORBIDDEN) || *(c->name.c_str()) == '+') return; Alog(LOG_DEBUG) << "Setting correct user modes for " << user->nick << " on " << c->name << " (" << (give_modes ? "" : "not ") << "giving modes)"; @@ -1488,7 +1423,7 @@ void chan_set_correct_modes(User * user, Channel * c, int give_modes) */ void MassChannelModes(BotInfo *bi, const std::string &modes) { - for (channel_map::const_iterator it = ChannelList.begin(); it != ChannelList.end(); ++it) + for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it) { Channel *c = it->second; @@ -1502,11 +1437,11 @@ void MassChannelModes(BotInfo *bi, const std::string &modes) void restore_unsynced_topics() { - for (channel_map::const_iterator it = ChannelList.begin(); it != ChannelList.end(); ++it) + for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it) { Channel *c = it->second; - if (!(c->topic_sync)) + if (!c->topic_sync) restore_topic(c->name.c_str()); } } @@ -1535,28 +1470,34 @@ Entry *entry_create(char *mask) entry->mask = sstrdup(mask); host = strchr(mask, '@'); - if (host) { + if (host) + { *host++ = '\0'; /* If the user is purely a wildcard, ignore it */ if (str_is_pure_wildcard(mask)) user = NULL; - else { - + else + { /* There might be a nick too */ user = strchr(mask, '!'); - if (user) { + if (user) + { *user++ = '\0'; /* If the nick is purely a wildcard, ignore it */ if (str_is_pure_wildcard(mask)) nick = NULL; else nick = mask; - } else { + } + else + { nick = NULL; user = mask; } } - } else { + } + else + { /* It is possibly an extended ban/invite mask, but we do * not support these at this point.. ~ Viper */ /* If there's no user in the mask, assume a pure wildcard */ @@ -1564,7 +1505,8 @@ Entry *entry_create(char *mask) host = mask; } - if (nick) { + if (nick) + { entry->nick = sstrdup(nick); /* Check if we have a wildcard user */ if (str_is_wildcard(nick)) @@ -1573,7 +1515,8 @@ Entry *entry_create(char *mask) entry->SetFlag(ENTRYTYPE_NICK); } - if (user) { + if (user) + { entry->user = sstrdup(user); /* Check if we have a wildcard user */ if (str_is_wildcard(user)) @@ -1583,13 +1526,17 @@ Entry *entry_create(char *mask) } /* Only check the host if it's not a pure wildcard */ - if (*host && !str_is_pure_wildcard(host)) { - if (ircd->cidrchanbei && str_is_cidr(host, &ip, &cidr, &cidrhost)) { + if (*host && !str_is_pure_wildcard(host)) + { + if (ircd->cidrchanbei && str_is_cidr(host, &ip, &cidr, &cidrhost)) + { entry->cidr_ip = ip; entry->cidr_mask = cidr; entry->SetFlag(ENTRYTYPE_CIDR4); host = cidrhost; - } else if (ircd->cidrchanbei && strchr(host, '/')) { + } + else if (ircd->cidrchanbei && strchr(host, '/')) + { /* Most IRCd's don't enforce sane bans therefore it is not * so unlikely we will encounter this. * Currently we only support strict CIDR without taking into @@ -1600,7 +1547,9 @@ Entry *entry_create(char *mask) * but do not use if during matching.. ~ Viper */ entry->ClearFlags(); entry->SetFlag(ENTRYTYPE_NONE); - } else { + } + else + { entry->host = sstrdup(host); if (str_is_wildcard(host)) entry->SetFlag(ENTRYTYPE_HOST_WILD); @@ -1613,14 +1562,13 @@ Entry *entry_create(char *mask) return entry; } - /** * Create an entry and add it at the beginning of given list. * @param list The List the mask should be added to * @param mask The mask to parse and add to the list * @return Pointer to newly added entry. NULL if it fails. */ -Entry *entry_add(EList * list, const char *mask) +Entry *entry_add(EList *list, const char *mask) { Entry *e; char *hostmask; @@ -1637,18 +1585,17 @@ Entry *entry_add(EList * list, const char *mask) if (list->entries) list->entries->prev = e; list->entries = e; - list->count++; + ++list->count; return e; } - /** * Delete the given entry from a given list. * @param list Linked list from which entry needs to be removed. * @param e The entry to be deleted, must be member of list. */ -void entry_delete(EList * list, Entry * e) +void entry_delete(EList *list, Entry *e) { if (!list || !e) return; @@ -1670,10 +1617,9 @@ void entry_delete(EList * list, Entry * e) delete [] e->mask; delete e; - list->count--; + --list->count; } - /** * Create and initialize a new entrylist * @return Pointer to the created EList object @@ -1689,7 +1635,6 @@ EList *list_create() return list; } - /** * Match the given Entry to the given user/host and optional IP addy * @param e Entry struct to match against @@ -1731,7 +1676,7 @@ int entry_match(Entry *e, const ci::string &nick, const ci::string &user, const * @param ip IP to match against, set to 0 to not match this * @return 1 for a match, 0 for no match */ -int entry_match_mask(Entry * e, const char *mask, uint32 ip) +int entry_match_mask(Entry *e, const char *mask, uint32 ip) { char *hostmask, *nick, *user, *host; int res; @@ -1739,17 +1684,23 @@ int entry_match_mask(Entry * e, const char *mask, uint32 ip) hostmask = sstrdup(mask); host = strchr(hostmask, '@'); - if (host) { + if (host) + { *host++ = '\0'; user = strchr(hostmask, '!'); - if (user) { + if (user) + { *user++ = '\0'; nick = hostmask; - } else { + } + else + { nick = NULL; user = hostmask; } - } else { + } + else + { nick = NULL; user = NULL; host = hostmask; @@ -1772,18 +1723,16 @@ int entry_match_mask(Entry * e, const char *mask, uint32 ip) * @param ip The ip to match * @return Returns the first matching entry, if none, NULL is returned. */ -Entry *elist_match(EList * list, const char *nick, const char *user, const char *host, - uint32 ip) +Entry *elist_match(EList *list, const char *nick, const char *user, const char *host, uint32 ip) { Entry *e; if (!list || !list->entries) return NULL; - for (e = list->entries; e; e = e->next) { + for (e = list->entries; e; e = e->next) if (entry_match(e, nick ? nick : "", user ? user : "", host ? host : "", ip)) return e; - } /* We matched none */ return NULL; @@ -1796,7 +1745,7 @@ Entry *elist_match(EList * list, const char *nick, const char *user, const char * @param ip The ip to match * @return Returns the first matching entry, if none, NULL is returned. */ -Entry *elist_match_mask(EList * list, const char *mask, uint32 ip) +Entry *elist_match_mask(EList *list, const char *mask, uint32 ip) { char *hostmask, *nick, *user, *host; Entry *res; @@ -1807,17 +1756,23 @@ Entry *elist_match_mask(EList * list, const char *mask, uint32 ip) hostmask = sstrdup(mask); host = strchr(hostmask, '@'); - if (host) { + if (host) + { *host++ = '\0'; user = strchr(hostmask, '!'); - if (user) { + if (user) + { *user++ = '\0'; nick = hostmask; - } else { + } + else + { nick = NULL; user = hostmask; } - } else { + } + else + { nick = NULL; user = NULL; host = hostmask; @@ -1837,7 +1792,7 @@ Entry *elist_match_mask(EList * list, const char *mask, uint32 ip) * @param user The user to match against the entries * @return Returns the first matching entry, if none, NULL is returned. */ -Entry *elist_match_user(EList * list, User * u) +Entry *elist_match_user(EList *list, User *u) { Entry *res; char *host; @@ -1846,16 +1801,16 @@ Entry *elist_match_user(EList * list, User * u) if (!list || !list->entries || !u) return NULL; - if (u->hostip == NULL) { + if (u->hostip == NULL) + { host = host_resolve(u->host); /* we store the just resolved hostname so we don't * need to do this again */ - if (host) { + if (host) u->hostip = sstrdup(host); - } - } else { - host = sstrdup(u->hostip); } + else + host = sstrdup(u->hostip); /* Convert the host to an IP.. */ if (host) @@ -1880,17 +1835,16 @@ Entry *elist_match_user(EList * list, User * u) * @param mask The *!*@* mask to match * @return Returns the first matching entry, if none, NULL is returned. */ -Entry *elist_find_mask(EList * list, const char *mask) +Entry *elist_find_mask(EList *list, const char *mask) { Entry *e; if (!list || !list->entries || !mask) return NULL; - for (e = list->entries; e; e = e->next) { + for (e = list->entries; e; e = e->next) if (!stricmp(e->mask, mask)) return e; - } return NULL; } @@ -1900,7 +1854,7 @@ Entry *elist_find_mask(EList * list, const char *mask) * @param list The list we should estimate the mem use of. * @return Returns the memory useage of the given list. */ -long get_memuse(EList * list) +long get_memuse(EList *list) { Entry *e; long mem = 0; @@ -1910,8 +1864,10 @@ long get_memuse(EList * list) mem += sizeof(EList *); mem += sizeof(Entry *) * list->count; - if (list->entries) { - for (e = list->entries; e; e = e->next) { + if (list->entries) + { + for (e = list->entries; e; e = e->next) + { if (e->nick) mem += strlen(e->nick) + 1; if (e->user) diff --git a/src/chanserv.cpp b/src/chanserv.cpp index 10acd3731..ff698d68f 100644 --- a/src/chanserv.cpp +++ b/src/chanserv.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ /*************************************************************************/ @@ -20,113 +18,112 @@ registered_channel_map RegisteredChannelList; static int def_levels[][2] = { - { CA_AUTOOP, 5 }, - { CA_AUTOVOICE, 3 }, - { CA_AUTODEOP, -1 }, - { CA_NOJOIN, -2 }, - { CA_INVITE, 5 }, - { CA_AKICK, 10 }, - { CA_SET, ACCESS_QOP }, - { CA_CLEAR, ACCESS_FOUNDER }, - { CA_UNBAN, 5 }, - { CA_OPDEOP, 5 }, - { CA_ACCESS_LIST, 1 }, - { CA_ACCESS_CHANGE, 10 }, - { CA_MEMO, 10 }, - { CA_ASSIGN, ACCESS_FOUNDER }, - { CA_BADWORDS, 10 }, - { CA_NOKICK, 1 }, - { CA_FANTASIA, 3 }, - { CA_SAY, 5 }, - { CA_GREET, 5 }, - { CA_VOICEME, 3 }, - { CA_VOICE, 5 }, - { CA_GETKEY, 5 }, - { CA_AUTOHALFOP, 4 }, - { CA_AUTOPROTECT, 10 }, - { CA_OPDEOPME, 5 }, - { CA_HALFOPME, 4 }, - { CA_HALFOP, 5 }, - { CA_PROTECTME, 10 }, - { CA_PROTECT, ACCESS_QOP }, - { CA_KICKME, 5 }, - { CA_KICK, 5 }, - { CA_SIGNKICK, ACCESS_FOUNDER }, - { CA_BANME, 5 }, - { CA_BAN, 5 }, - { CA_TOPIC, ACCESS_FOUNDER }, - { CA_INFO, ACCESS_QOP }, + { CA_AUTOOP, 5 }, + { CA_AUTOVOICE, 3 }, + { CA_AUTODEOP, -1 }, + { CA_NOJOIN, -2 }, + { CA_INVITE, 5 }, + { CA_AKICK, 10 }, + { CA_SET, ACCESS_QOP }, + { CA_CLEAR, ACCESS_FOUNDER }, + { CA_UNBAN, 5 }, + { CA_OPDEOP, 5 }, + { CA_ACCESS_LIST, 1 }, + { CA_ACCESS_CHANGE, 10 }, + { CA_MEMO, 10 }, + { CA_ASSIGN, ACCESS_FOUNDER }, + { CA_BADWORDS, 10 }, + { CA_NOKICK, 1 }, + { CA_FANTASIA, 3 }, + { CA_SAY, 5 }, + { CA_GREET, 5 }, + { CA_VOICEME, 3 }, + { CA_VOICE, 5 }, + { CA_GETKEY, 5 }, + { CA_AUTOHALFOP, 4 }, + { CA_AUTOPROTECT, 10 }, + { CA_OPDEOPME, 5 }, + { CA_HALFOPME, 4 }, + { CA_HALFOP, 5 }, + { CA_PROTECTME, 10 }, + { CA_PROTECT, ACCESS_QOP }, + { CA_KICKME, 5 }, + { CA_KICK, 5 }, + { CA_SIGNKICK, ACCESS_FOUNDER }, + { CA_BANME, 5 }, + { CA_BAN, 5 }, + { CA_TOPIC, ACCESS_FOUNDER }, + { CA_INFO, ACCESS_QOP }, { CA_AUTOOWNER, ACCESS_QOP }, - { CA_OWNER, ACCESS_FOUNDER }, + { CA_OWNER, ACCESS_FOUNDER }, { CA_OWNERME, ACCESS_QOP }, { CA_FOUNDER, ACCESS_QOP }, { -1 } }; - LevelInfo levelinfo[] = { - { CA_AUTODEOP, "AUTODEOP", CHAN_LEVEL_AUTODEOP }, - { CA_AUTOHALFOP, "AUTOHALFOP", CHAN_LEVEL_AUTOHALFOP }, - { CA_AUTOOP, "AUTOOP", CHAN_LEVEL_AUTOOP }, - { CA_AUTOPROTECT, "AUTOPROTECT", CHAN_LEVEL_AUTOPROTECT }, - { CA_AUTOVOICE, "AUTOVOICE", CHAN_LEVEL_AUTOVOICE }, - { CA_NOJOIN, "NOJOIN", CHAN_LEVEL_NOJOIN }, - { CA_SIGNKICK, "SIGNKICK", CHAN_LEVEL_SIGNKICK }, - { CA_ACCESS_LIST, "ACC-LIST", CHAN_LEVEL_ACCESS_LIST }, - { CA_ACCESS_CHANGE, "ACC-CHANGE", CHAN_LEVEL_ACCESS_CHANGE }, - { CA_AKICK, "AKICK", CHAN_LEVEL_AKICK }, - { CA_SET, "SET", CHAN_LEVEL_SET }, - { CA_BAN, "BAN", CHAN_LEVEL_BAN }, - { CA_BANME, "BANME", CHAN_LEVEL_BANME }, - { CA_CLEAR, "CLEAR", CHAN_LEVEL_CLEAR }, - { CA_GETKEY, "GETKEY", CHAN_LEVEL_GETKEY }, - { CA_HALFOP, "HALFOP", CHAN_LEVEL_HALFOP }, - { CA_HALFOPME, "HALFOPME", CHAN_LEVEL_HALFOPME }, - { CA_INFO, "INFO", CHAN_LEVEL_INFO }, - { CA_KICK, "KICK", CHAN_LEVEL_KICK }, - { CA_KICKME, "KICKME", CHAN_LEVEL_KICKME }, - { CA_INVITE, "INVITE", CHAN_LEVEL_INVITE }, - { CA_OPDEOP, "OPDEOP", CHAN_LEVEL_OPDEOP }, - { CA_OPDEOPME, "OPDEOPME", CHAN_LEVEL_OPDEOPME }, - { CA_PROTECT, "PROTECT", CHAN_LEVEL_PROTECT }, - { CA_PROTECTME, "PROTECTME", CHAN_LEVEL_PROTECTME }, - { CA_TOPIC, "TOPIC", CHAN_LEVEL_TOPIC }, - { CA_UNBAN, "UNBAN", CHAN_LEVEL_UNBAN }, - { CA_VOICE, "VOICE", CHAN_LEVEL_VOICE }, - { CA_VOICEME, "VOICEME", CHAN_LEVEL_VOICEME }, - { CA_MEMO, "MEMO", CHAN_LEVEL_MEMO }, - { CA_ASSIGN, "ASSIGN", CHAN_LEVEL_ASSIGN }, - { CA_BADWORDS, "BADWORDS", CHAN_LEVEL_BADWORDS }, - { CA_FANTASIA, "FANTASIA", CHAN_LEVEL_FANTASIA }, - { CA_GREET, "GREET", CHAN_LEVEL_GREET }, - { CA_NOKICK, "NOKICK", CHAN_LEVEL_NOKICK }, - { CA_SAY, "SAY", CHAN_LEVEL_SAY }, + { CA_AUTODEOP, "AUTODEOP", CHAN_LEVEL_AUTODEOP }, + { CA_AUTOHALFOP, "AUTOHALFOP", CHAN_LEVEL_AUTOHALFOP }, + { CA_AUTOOP, "AUTOOP", CHAN_LEVEL_AUTOOP }, + { CA_AUTOPROTECT, "AUTOPROTECT", CHAN_LEVEL_AUTOPROTECT }, + { CA_AUTOVOICE, "AUTOVOICE", CHAN_LEVEL_AUTOVOICE }, + { CA_NOJOIN, "NOJOIN", CHAN_LEVEL_NOJOIN }, + { CA_SIGNKICK, "SIGNKICK", CHAN_LEVEL_SIGNKICK }, + { CA_ACCESS_LIST, "ACC-LIST", CHAN_LEVEL_ACCESS_LIST }, + { CA_ACCESS_CHANGE, "ACC-CHANGE", CHAN_LEVEL_ACCESS_CHANGE }, + { CA_AKICK, "AKICK", CHAN_LEVEL_AKICK }, + { CA_SET, "SET", CHAN_LEVEL_SET }, + { CA_BAN, "BAN", CHAN_LEVEL_BAN }, + { CA_BANME, "BANME", CHAN_LEVEL_BANME }, + { CA_CLEAR, "CLEAR", CHAN_LEVEL_CLEAR }, + { CA_GETKEY, "GETKEY", CHAN_LEVEL_GETKEY }, + { CA_HALFOP, "HALFOP", CHAN_LEVEL_HALFOP }, + { CA_HALFOPME, "HALFOPME", CHAN_LEVEL_HALFOPME }, + { CA_INFO, "INFO", CHAN_LEVEL_INFO }, + { CA_KICK, "KICK", CHAN_LEVEL_KICK }, + { CA_KICKME, "KICKME", CHAN_LEVEL_KICKME }, + { CA_INVITE, "INVITE", CHAN_LEVEL_INVITE }, + { CA_OPDEOP, "OPDEOP", CHAN_LEVEL_OPDEOP }, + { CA_OPDEOPME, "OPDEOPME", CHAN_LEVEL_OPDEOPME }, + { CA_PROTECT, "PROTECT", CHAN_LEVEL_PROTECT }, + { CA_PROTECTME, "PROTECTME", CHAN_LEVEL_PROTECTME }, + { CA_TOPIC, "TOPIC", CHAN_LEVEL_TOPIC }, + { CA_UNBAN, "UNBAN", CHAN_LEVEL_UNBAN }, + { CA_VOICE, "VOICE", CHAN_LEVEL_VOICE }, + { CA_VOICEME, "VOICEME", CHAN_LEVEL_VOICEME }, + { CA_MEMO, "MEMO", CHAN_LEVEL_MEMO }, + { CA_ASSIGN, "ASSIGN", CHAN_LEVEL_ASSIGN }, + { CA_BADWORDS, "BADWORDS", CHAN_LEVEL_BADWORDS }, + { CA_FANTASIA, "FANTASIA", CHAN_LEVEL_FANTASIA }, + { CA_GREET, "GREET", CHAN_LEVEL_GREET }, + { CA_NOKICK, "NOKICK", CHAN_LEVEL_NOKICK }, + { CA_SAY, "SAY", CHAN_LEVEL_SAY }, { CA_AUTOOWNER, "AUTOOWNER", CHAN_LEVEL_AUTOOWNER }, - { CA_OWNER, "OWNER", CHAN_LEVEL_OWNER }, - { CA_OWNERME, "OWNERME", CHAN_LEVEL_OWNERME }, - { CA_FOUNDER, "FOUNDER", CHAN_LEVEL_FOUNDER }, - { -1 } + { CA_OWNER, "OWNER", CHAN_LEVEL_OWNER }, + { CA_OWNERME, "OWNERME", CHAN_LEVEL_OWNERME }, + { CA_FOUNDER, "FOUNDER", CHAN_LEVEL_FOUNDER }, + { -1 } }; int levelinfo_maxwidth = 0; /*************************************************************************/ -void moduleAddChanServCmds() { +void moduleAddChanServCmds() +{ ModuleManager::LoadModuleList(Config.ChanServCoreModules); } -/* *INDENT-ON* */ /*************************************************************************/ /* Returns modes for mlock in a nice way. */ -char *get_mlock_modes(ChannelInfo * ci, int complete) +char *get_mlock_modes(ChannelInfo *ci, int complete) { static char res[BUFSIZE]; char *end, *value; ChannelMode *cm; ChannelModeParam *cmp; - std::map<char, ChannelMode *>::iterator it; + std::map<char, ChannelMode *>::iterator it, it_end; std::string param; memset(&res, '\0', sizeof(res)); @@ -138,7 +135,7 @@ char *get_mlock_modes(ChannelInfo * ci, int complete) { *end++ = '+'; - for (it = ModeManager::ChannelModesByChar.begin(); it != ModeManager::ChannelModesByChar.end(); ++it) + for (it = ModeManager::ChannelModesByChar.begin(), it_end = ModeManager::ChannelModesByChar.end(); it != it_end; ++it) { cm = it->second; @@ -151,7 +148,7 @@ char *get_mlock_modes(ChannelInfo * ci, int complete) { *end++ = '-'; - for (it = ModeManager::ChannelModesByChar.begin(); it != ModeManager::ChannelModesByChar.end(); ++it) + for (it = ModeManager::ChannelModesByChar.begin(), it_end = ModeManager::ChannelModesByChar.end(); it != it_end; ++it) { cm = it->second; @@ -162,7 +159,7 @@ char *get_mlock_modes(ChannelInfo * ci, int complete) if (ci->GetMLockCount(true) && complete) { - for (it = ModeManager::ChannelModesByChar.begin(); it != ModeManager::ChannelModesByChar.end(); ++it) + for (it = ModeManager::ChannelModesByChar.begin(), it_end = ModeManager::ChannelModesByChar.end(); it != it_end; ++it) { cm = it->second; @@ -197,11 +194,11 @@ void get_chanserv_stats(long *nrec, long *memuse) long count = 0, mem = 0; std::string param; - for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(); it != RegisteredChannelList.end(); ++it) + for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; ++it) { ChannelInfo *ci = it->second; - count++; + ++count; mem += sizeof(*ci); if (ci->desc) mem += strlen(ci->desc) + 1; @@ -231,12 +228,11 @@ void get_chanserv_stats(long *nrec, long *memuse) mem += strlen(ci->forbidreason) + 1; if (ci->levels) mem += sizeof(*ci->levels) * CA_SIZE; - mem += ci->memos.memos.size() * sizeof(Memo); - for (unsigned j = 0; j < ci->memos.memos.size(); j++) - { + unsigned memos = ci->memos.memos.size(); + mem += memos * sizeof(Memo); + for (unsigned j = 0; j < memos; ++j) if (ci->memos.memos[j]->text) mem += strlen(ci->memos.memos[j]->text) + 1; - } if (ci->ttb) mem += sizeof(*ci->ttb) * TTB_SIZE; mem += ci->GetBadWordCount() * sizeof(BadWord); @@ -263,7 +259,7 @@ void chanserv(User *u, const std::string &buf) { if (!u || buf.empty()) return; - + if (buf.find("\1PING ", 0, 6) != std::string::npos && buf[buf.length() - 1] == '\1') { std::string command = buf; @@ -272,9 +268,7 @@ void chanserv(User *u, const std::string &buf) ircdproto->SendCTCP(ChanServ, u->nick.c_str(), "%s", command.c_str()); } else - { mod_run_cmd(ChanServ, u, buf); - } } /*************************************************************************/ @@ -288,7 +282,7 @@ void check_modes(Channel *c) time_t t = time(NULL); ChannelInfo *ci; ChannelMode *cm; - std::map<char, ChannelMode *>::iterator it; + std::map<char, ChannelMode *>::iterator it, it_end; std::string param, ciparam; if (!c) @@ -320,13 +314,11 @@ void check_modes(Channel *c) if (!(ci = c->ci)) { if (c->HasMode(CMODE_REGISTERED)) - { c->RemoveMode(NULL, CMODE_REGISTERED); - } return; } - for (it = ModeManager::ChannelModesByChar.begin(); it != ModeManager::ChannelModesByChar.end(); ++it) + for (it = ModeManager::ChannelModesByChar.begin(), it_end = ModeManager::ChannelModesByChar.end(); it != it_end; ++it) { cm = it->second; @@ -352,13 +344,11 @@ void check_modes(Channel *c) /* If the channel doesnt have the mode, or it does and it isn't set correctly */ if (!c->HasMode(cm->Name) || (!param.empty() && !ciparam.empty() && param != ciparam)) - { c->SetMode(NULL, cm, ciparam); - } } } - for (it = ModeManager::ChannelModesByChar.begin(); it != ModeManager::ChannelModesByChar.end(); ++it) + for (it = ModeManager::ChannelModesByChar.begin(), it_end = ModeManager::ChannelModesByChar.end(); it != it_end; ++it) { cm = it->second; @@ -384,7 +374,7 @@ void check_modes(Channel *c) /*************************************************************************/ -int check_valid_admin(User * user, Channel * chan, int servermode) +int check_valid_admin(User *user, Channel *chan, int servermode) { ChannelMode *cm; @@ -420,7 +410,7 @@ int check_valid_admin(User * user, Channel * chan, int servermode) * aren't, deop them. If serverop is 1, the +o was done by a server. * Return 1 if the user is allowed to be opped, 0 otherwise. */ -int check_valid_op(User * user, Channel * chan, int servermode) +int check_valid_op(User *user, Channel *chan, int servermode) { ChannelMode *owner, *protect, *halfop; if (!chan || !chan->ci) @@ -507,7 +497,8 @@ void restore_topic(const char *chan) return; /* We can be sure that the topic will be in sync when we return -GD */ c->topic_sync = 1; - if (!(ci->HasFlag(CI_KEEPTOPIC))) { + if (!(ci->HasFlag(CI_KEEPTOPIC))) + { /* We need to reset the topic here, since it's currently empty and * should be updated with a TOPIC from the IRCd soon. -GD */ @@ -518,26 +509,25 @@ void restore_topic(const char *chan) } if (c->topic) delete [] c->topic; - if (ci->last_topic) { + if (ci->last_topic) + { c->topic = sstrdup(ci->last_topic); c->topic_setter = ci->last_topic_setter; c->topic_time = ci->last_topic_time; - } else { + } + else + { c->topic = NULL; c->topic_setter = whosends(ci)->nick; } - if (ircd->join2set) { - if (whosends(ci) == ChanServ) { - ircdproto->SendJoin(ChanServ, chan, c->creation_time); - c->SetMode(NULL, CMODE_OP, Config.s_ChanServ); - } + if (ircd->join2set && whosends(ci) == ChanServ) + { + ircdproto->SendJoin(ChanServ, chan, c->creation_time); + c->SetMode(NULL, CMODE_OP, Config.s_ChanServ); } ircdproto->SendTopic(whosends(ci), c, c->topic_setter.c_str(), c->topic ? c->topic : ""); - if (ircd->join2set) { - if (whosends(ci) == ChanServ) { - ircdproto->SendPart(ChanServ, c, NULL); - } - } + if (ircd->join2set && whosends(ci) == ChanServ) + ircdproto->SendPart(ChanServ, c, NULL); } /*************************************************************************/ @@ -545,40 +535,45 @@ void restore_topic(const char *chan) /* See if the topic is locked on the given channel, and return 1 (and fix * the topic) if so. */ -int check_topiclock(Channel * c, time_t topic_time) +int check_topiclock(Channel *c, time_t topic_time) { ChannelInfo *ci; - if (!c) + if (!c) { Alog(LOG_DEBUG) << "check_topiclock called with NULL values"; return 0; } - if (!(ci = c->ci) || !(ci->HasFlag(CI_TOPICLOCK))) + if (!(ci = c->ci) || !ci->HasFlag(CI_TOPICLOCK)) return 0; if (c->topic) delete [] c->topic; - if (ci->last_topic) { + if (ci->last_topic) + { c->topic = sstrdup(ci->last_topic); c->topic_setter = ci->last_topic_setter; - } else { + } + else + { c->topic = NULL; /* Bot assigned & Symbiosis ON?, the bot will set the topic - doc */ /* Altough whosends() also checks for Config.BSMinUsers -GD */ c->topic_setter = whosends(ci)->nick; } - if (ircd->topictsforward) { + if (ircd->topictsforward) + { /* Because older timestamps are rejected */ /* Some how the topic_time from do_topic is 0 set it to current + 1 */ - if (!topic_time) { + if (!topic_time) c->topic_time = time(NULL) + 1; - } else { + else c->topic_time = topic_time + 1; - } - } else { + } + else + { /* If no last topic, we can't use last topic time! - doc */ if (ci->last_topic) c->topic_time = ci->last_topic_time; @@ -586,20 +581,16 @@ int check_topiclock(Channel * c, time_t topic_time) c->topic_time = time(NULL) + 1; } - if (ircd->join2set) { - if (whosends(ci) == ChanServ) { - ircdproto->SendJoin(ChanServ, c->name.c_str(), c->creation_time); - c->SetMode(NULL, CMODE_OP, Config.s_ChanServ); - } + if (ircd->join2set && whosends(ci) == ChanServ) + { + ircdproto->SendJoin(ChanServ, c->name.c_str(), c->creation_time); + c->SetMode(NULL, CMODE_OP, Config.s_ChanServ); } ircdproto->SendTopic(whosends(ci), c, c->topic_setter.c_str(), c->topic ? c->topic : ""); - if (ircd->join2set) { - if (whosends(ci) == ChanServ) { - ircdproto->SendPart(ChanServ, c, NULL); - } - } + if (ircd->join2set && whosends(ci) == ChanServ) + ircdproto->SendPart(ChanServ, c, NULL); return 1; } @@ -611,10 +602,10 @@ void expire_chans() { if (!Config.CSExpire) return; - + time_t now = time(NULL); - for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(); it != RegisteredChannelList.end();) + for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; ) { ChannelInfo *ci = it->second; ++it; @@ -638,39 +629,44 @@ void expire_chans() /*************************************************************************/ // XXX this is slightly inefficient -void cs_remove_nick(const NickCore * nc) +void cs_remove_nick(const NickCore *nc) { int j; ChanAccess *ca; AutoKick *akick; - for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(); it != RegisteredChannelList.end(); ++it) + for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; ++it) { ChannelInfo *ci = it->second; - if (ci->founder == nc) { - if (ci->successor) { + if (ci->founder == nc) + { + if (ci->successor) + { NickCore *nc2 = ci->successor; - if (!nc2->IsServicesOper() && Config.CSMaxReg && nc2->channelcount >= Config.CSMaxReg) { - Alog() << Config.s_ChanServ << ": Successor (" << nc2->display << " ) of " << ci->name << " owns too many channels, deleting channel", + if (!nc2->IsServicesOper() && Config.CSMaxReg && nc2->channelcount >= Config.CSMaxReg) + { + Alog() << Config.s_ChanServ << ": Successor (" << nc2->display << " ) of " << ci->name << " owns too many channels, deleting channel", delete ci; continue; - } else { + } + else + { Alog() << Config.s_ChanServ << ": Transferring foundership of " << ci->name << " from deleted nick " << nc->display << " to successor " << nc2->display; ci->founder = nc2; ci->successor = NULL; nc2->channelcount++; } - } else { + } + else + { Alog() << Config.s_ChanServ << ": Deleting channel " << ci->name << "owned by deleted nick " << nc->display; - if ((ModeManager::FindChannelModeByName(CMODE_REGISTERED))) + if (ModeManager::FindChannelModeByName(CMODE_REGISTERED)) { /* Maybe move this to delchan() ? */ if (ci->c && ci->c->HasMode(CMODE_REGISTERED)) - { ci->c->RemoveMode(NULL, CMODE_REGISTERED); - } } delete ci; @@ -727,14 +723,12 @@ ChannelInfo *cs_findchan(const ci::string &chan) * the user does _not_ have access to the channel (i.e. matches the NOJOIN * criterion). */ -int check_access(User * user, ChannelInfo * ci, int what) +int check_access(User *user, ChannelInfo *ci, int what) { - int level; - int limit; + int level, limit; - if (!user || !ci) { + if (!user || !ci) return 0; - } level = get_access(user, ci); limit = ci->levels[what]; @@ -745,16 +739,16 @@ int check_access(User * user, ChannelInfo * ci, int what) /* Superadmin always wins. Always. */ if (user->isSuperAdmin) - return (what == CA_AUTODEOP || what == CA_NOJOIN ? 0 : 1); + return what == CA_AUTODEOP || what == CA_NOJOIN ? 0 : 1; /* If the access of the level we are checking is disabled, they *always* get denied */ if (limit == ACCESS_INVALID) return 0; /* If the level of the user is >= the level for "founder" of this channel and "founder" isn't disabled, they can do anything */ if (ci->levels[CA_FOUNDER] != ACCESS_INVALID && level >= ci->levels[CA_FOUNDER]) - return (what == CA_AUTODEOP || what == CA_NOJOIN ? 0 : 1); + return what == CA_AUTODEOP || what == CA_NOJOIN ? 0 : 1; /* Hacks to make flags work */ - if (what == CA_AUTODEOP && (ci->HasFlag(CI_SECUREOPS)) && level == 0) + if (what == CA_AUTODEOP && (ci->HasFlag(CI_SECUREOPS)) && !level) return 1; if (what == CA_AUTODEOP || what == CA_NOJOIN) @@ -769,7 +763,7 @@ int check_access(User * user, ChannelInfo * ci, int what) /* Reset channel access level values to their default state. */ -void reset_levels(ChannelInfo * ci) +void reset_levels(ChannelInfo *ci) { int i; @@ -782,7 +776,7 @@ void reset_levels(ChannelInfo * ci) if (ci->levels) delete [] ci->levels; ci->levels = new int16[CA_SIZE]; - for (i = 0; def_levels[i][0] >= 0; i++) + for (i = 0; def_levels[i][0] >= 0; ++i) ci->levels[def_levels[i][0]] = def_levels[i][1]; } @@ -807,7 +801,6 @@ bool IsFounder(User *user, ChannelInfo *ci) return false; } - /** Return the access level for the user on the channel. * If the channel doesn't exist, the user isn't on the access list, or the * channel is CI_SECURE and the user isn't identified, return 0 @@ -849,15 +842,14 @@ int get_access(User *user, ChannelInfo *ci) /*************************************************************************/ -void update_cs_lastseen(User * user, ChannelInfo * ci) +void update_cs_lastseen(User *user, ChannelInfo *ci) { ChanAccess *access; if (!ci || !user || !user->Account()) return; - if (IsFounder(user, ci) || user->IsIdentified() - || (user->IsRecognized() && !ci->HasFlag(CI_SECURE))) + if (IsFounder(user, ci) || user->IsIdentified() || (user->IsRecognized() && !ci->HasFlag(CI_SECURE))) if ((access = ci->GetAccess(user->Account()))) access->last_seen = time(NULL); } @@ -867,7 +859,7 @@ void update_cs_lastseen(User * user, ChannelInfo * ci) /* Returns the best ban possible for an user depending of the bantype value. */ -int get_idealban(ChannelInfo * ci, User * u, char *ret, int retlen) +int get_idealban(ChannelInfo *ci, User *u, char *ret, int retlen) { char *mask; @@ -876,38 +868,35 @@ int get_idealban(ChannelInfo * ci, User * u, char *ret, int retlen) std::string vident = u->GetIdent(); - switch (ci->bantype) { - case 0: - snprintf(ret, retlen, "*!%s@%s", vident.c_str(), - u->GetDisplayedHost().c_str()); - return 1; - case 1: - if (vident[0] == '~') - snprintf(ret, retlen, "*!*%s@%s", - vident.c_str(), u->GetDisplayedHost().c_str()); - else - snprintf(ret, retlen, "*!%s@%s", - vident.c_str(), u->GetDisplayedHost().c_str()); - - return 1; - case 2: - snprintf(ret, retlen, "*!*@%s", u->GetDisplayedHost().c_str()); - return 1; - case 3: - mask = create_mask(u); - snprintf(ret, retlen, "*!%s", mask); - delete [] mask; - return 1; - - default: - return 0; + switch (ci->bantype) + { + case 0: + snprintf(ret, retlen, "*!%s@%s", vident.c_str(), u->GetDisplayedHost().c_str()); + return 1; + case 1: + if (vident[0] == '~') + snprintf(ret, retlen, "*!*%s@%s", vident.c_str(), u->GetDisplayedHost().c_str()); + else + snprintf(ret, retlen, "*!%s@%s", vident.c_str(), u->GetDisplayedHost().c_str()); + + return 1; + case 2: + snprintf(ret, retlen, "*!*@%s", u->GetDisplayedHost().c_str()); + return 1; + case 3: + mask = create_mask(u); + snprintf(ret, retlen, "*!%s", mask); + delete [] mask; + return 1; + + default: + return 0; } } - /*************************************************************************/ -int get_access_level(ChannelInfo * ci, NickAlias * na) +int get_access_level(ChannelInfo *ci, NickAlias *na) { ChanAccess *access; @@ -929,10 +918,10 @@ int get_access_level(ChannelInfo *ci, NickCore *nc) { if (!ci || !nc) return 0; - + if (nc == ci->founder) return ACCESS_FOUNDER; - + ChanAccess *access = ci->GetAccess(nc); if (!access) @@ -974,7 +963,7 @@ AutoKick *is_stuck(ChannelInfo * ci, const char *mask) if (!ci) return NULL; - for (unsigned i = 0; i < ci->GetAkickCount(); ++i) + for (unsigned i = 0, akicks = ci->GetAkickCount(); i < akicks; ++i) { AutoKick *akick = ci->GetAkick(i); @@ -994,22 +983,24 @@ AutoKick *is_stuck(ChannelInfo * ci, const char *mask) /* Ban the stuck mask in a safe manner. */ -void stick_mask(ChannelInfo * ci, AutoKick * akick) +void stick_mask(ChannelInfo *ci, AutoKick *akick) { Entry *ban; - if (!ci) { + if (!ci) return; - } - if (ci->c->bans && ci->c->bans->entries != 0) { - for (ban = ci->c->bans->entries; ban; ban = ban->next) { + if (ci->c->bans && ci->c->bans->entries) + { + for (ban = ci->c->bans->entries; ban; ban = ban->next) + { /* If akick is already covered by a wider ban. Example: c->bans[i] = *!*@*.org and akick->u.mask = *!*@*.epona.org */ if (entry_match_mask(ban, akick->mask.c_str(), 0)) return; - if (ircd->reversekickcheck) { + if (ircd->reversekickcheck) + { /* If akick is wider than a ban already in place. Example: c->bans[i] = *!*@irc.epona.org and akick->u.mask = *!*@*.epona.org */ if (Anope::Match(ban->mask, akick->mask.c_str(), false)) @@ -1024,12 +1015,12 @@ void stick_mask(ChannelInfo * ci, AutoKick * akick) /* Ban the stuck mask in a safe manner. */ -void stick_all(ChannelInfo * ci) +void stick_all(ChannelInfo *ci) { if (!ci) return; - for (unsigned i = 0; i < ci->GetAkickCount(); ++i) + for (unsigned i = 0, akicks = ci->GetAkickCount(); i < akicks; ++i) { AutoKick *akick = ci->GetAkick(i); @@ -1050,17 +1041,16 @@ void ChanServTimer::Tick(time_t) { if (!c->ci) return; - + c->ci->UnsetFlag(CI_INHABIT); /* If the channel has users again, don't part it and halt */ if (!c->users.empty()) return; - + ircdproto->SendPart(ChanServ, c, NULL); - + /* Now delete the channel as it is empty */ if (!c->HasFlag(CH_PERSIST) && !c->ci->HasFlag(CI_PERSIST)) delete c; } - diff --git a/src/command.cpp b/src/command.cpp index 922f298c3..5c4bc4ee4 100644 --- a/src/command.cpp +++ b/src/command.cpp @@ -3,14 +3,12 @@ * Copyright (C) 2008-2010 Anope Team <team@anope.org> * * Please read COPYING and README for further details. - * - * - * */ + #include "services.h" #include "modules.h" -Command::Command(const ci::string &sname, size_t min_params, size_t max_params, const std::string &spermission) : MaxParams(max_params), MinParams(min_params), name(sname), permission(spermission) +Command::Command(const ci::string &sname, size_t min_params, size_t max_params, const ci::string &spermission) : MaxParams(max_params), MinParams(min_params), name(sname), permission(spermission) { this->module = NULL; this->service = NULL; @@ -33,7 +31,7 @@ void Command::OnSyntaxError(User *u, const ci::string &subcommand) { } -void Command::SetPermission(const std::string &reststr) +void Command::SetPermission(const ci::string &reststr) { this->permission = reststr; } @@ -47,4 +45,3 @@ bool Command::DelSubcommand(const ci::string &cname) { return false; } - diff --git a/src/commands.cpp b/src/commands.cpp index f066b2885..4eec6cd61 100644 --- a/src/commands.cpp +++ b/src/commands.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -20,7 +18,7 @@ Command *FindCommand(BotInfo *bi, const ci::string &name) { if (!bi || bi->Commands.empty() || name.empty()) return NULL; - + std::map<ci::string, Command *>::iterator it = bi->Commands.find(name); if (it != bi->Commands.end()) @@ -35,9 +33,7 @@ void mod_run_cmd(BotInfo *bi, User *u, const std::string &message) ci::string cmd; if (sep.GetToken(cmd)) - { mod_run_cmd(bi, u, FindCommand(bi, cmd), cmd, sep.GetRemaining().c_str()); - } } void mod_run_cmd(BotInfo *bi, User *u, Command *c, const ci::string &command, const ci::string &message) @@ -58,15 +54,12 @@ void mod_run_cmd(BotInfo *bi, User *u, Command *c, const ci::string &command, co return; } - if (!c->HasFlag(CFLAG_ALLOW_UNREGISTERED)) + // Command requires registered users only + if (!c->HasFlag(CFLAG_ALLOW_UNREGISTERED) && !u->IsIdentified()) { - // Command requires registered users only - if (!u->IsIdentified()) - { - notice_lang(bi->nick, u, NICK_IDENTIFY_REQUIRED, Config.s_NickServ); - Alog() << "Access denied for unregistered user " << u->nick << " with service " << bi->nick << " and command " << command; - return; - } + notice_lang(bi->nick, u, NICK_IDENTIFY_REQUIRED, Config.s_NickServ); + Alog() << "Access denied for unregistered user " << u->nick << " with service " << bi->nick << " and command " << command; + return; } std::vector<ci::string> params; @@ -81,9 +74,7 @@ void mod_run_cmd(BotInfo *bi, User *u, Command *c, const ci::string &command, co endparam += " "; } else - { params.push_back(curparam); - } } if (!endparam.empty()) @@ -112,18 +103,16 @@ void mod_run_cmd(BotInfo *bi, User *u, Command *c, const ci::string &command, co ChannelInfo *ci = cs_findchan(params[0]); if (ci) { - if ((ci->HasFlag(CI_FORBIDDEN)) && (!c->HasFlag(CFLAG_ALLOW_FORBIDDEN))) + if (ci->HasFlag(CI_FORBIDDEN) && !c->HasFlag(CFLAG_ALLOW_FORBIDDEN)) { notice_lang(bi->nick, u, CHAN_X_FORBIDDEN, ci->name.c_str()); - Alog() << "Access denied for user " << u->nick << " with service " << bi->nick - << " and command " << command << " because of FORBIDDEN channel " << ci->name; + Alog() << "Access denied for user " << u->nick << " with service " << bi->nick << " and command " << command << " because of FORBIDDEN channel " << ci->name; return; } - else if ((ci->HasFlag(CI_SUSPENDED)) && (!c->HasFlag(CFLAG_ALLOW_SUSPENDED))) + else if (ci->HasFlag(CI_SUSPENDED) && !c->HasFlag(CFLAG_ALLOW_SUSPENDED)) { notice_lang(bi->nick, u, CHAN_X_FORBIDDEN, ci->name.c_str()); - Alog() << "Access denied for user " << u->nick << " with service " << bi->nick - <<" and command " << command << " because of SUSPENDED channel " << ci->name; + Alog() << "Access denied for user " << u->nick << " with service " << bi->nick <<" and command " << command << " because of SUSPENDED channel " << ci->name; return; } } @@ -142,23 +131,17 @@ void mod_run_cmd(BotInfo *bi, User *u, Command *c, const ci::string &command, co } // If the command requires a permission, and they aren't registered or don't have the required perm, DENIED - if (!c->permission.empty()) + if (!c->permission.empty() && !u->Account()->HasCommand(c->permission)) { - if (!u->Account()->HasCommand(c->permission)) - { - notice_lang(bi->nick, u, ACCESS_DENIED); - Alog() << "Access denied for user " << u->nick << " with service " << bi->nick << " and command " << command; - return; - } - + notice_lang(bi->nick, u, ACCESS_DENIED); + Alog() << "Access denied for user " << u->nick << " with service " << bi->nick << " and command " << command; + return; } ret = c->Execute(u, params); if (ret == MOD_CONT) - { FOREACH_MOD(I_OnPostCommand, OnPostCommand(u, c->service, c->name.c_str(), params)); - } } /** @@ -173,7 +156,7 @@ void mod_help_cmd(BotInfo *bi, User *u, const ci::string &cmd) { if (!bi || !u || cmd.empty()) return; - + spacesepstream tokens(cmd); ci::string token; tokens.GetToken(token); @@ -196,11 +179,10 @@ void mod_help_cmd(BotInfo *bi, User *u, const ci::string &cmd) if (!c->HasFlag(CFLAG_ALLOW_UNREGISTERED) && !u->IsIdentified()) notice_lang(bi->nick, u, COMMAND_IDENTIFY_REQUIRED); /* User doesn't have the proper permission to use this command */ - else if (!c->permission.empty() && (!u->Account() || (!u->Account()->HasCommand(c->permission)))) + else if (!c->permission.empty() && (!u->Account() || !u->Account()->HasCommand(c->permission))) notice_lang(bi->nick, u, COMMAND_CANNOT_USE); /* User can use this command */ else notice_lang(bi->nick, u, COMMAND_CAN_USE); } } - diff --git a/src/compat.cpp b/src/compat.cpp index eb3088fe9..2fdb57b86 100644 --- a/src/compat.cpp +++ b/src/compat.cpp @@ -6,9 +6,7 @@ * 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. - * - * + * Based on the original code of Services by Andy Church. */ #include "services.h" @@ -18,18 +16,19 @@ #if !HAVE_STRICMP && !HAVE_STRCASECMP /* stricmp, strnicmp: Case-insensitive versions of strcmp() and - * strncmp(). + * strncmp(). */ int stricmp(const char *s1, const char *s2) { register int c; - while ((c = tolower(*s1)) == tolower(*s2)) { - if (c == 0) + while ((c = tolower(*s1)) == tolower(*s2)) + { + if (!c) return 0; - s1++; - s2++; + ++s1; + ++s2; } if (c < tolower(*s2)) return -1; @@ -42,17 +41,18 @@ int strnicmp(const char *s1, const char *s2, size_t len) if (!len) return 0; - while ((c = tolower(*s1)) == tolower(*s2) && len > 0) { - if (c == 0 || --len == 0) + while ((c = tolower(*s1)) == tolower(*s2) && len > 0) + { + if (!c || !--len) return 0; - s1++; - s2++; + ++s1; + ++s2; } if (c < tolower(*s2)) return -1; return 1; } + #endif /*************************************************************************/ - diff --git a/src/config.cpp b/src/config.cpp index a1264abce..da1ec1647 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -17,28 +15,28 @@ /*************************************************************************/ -std::string services_conf = "services.conf"; // Services configuration file name +ci::string services_conf = "services.conf"; // Services configuration file name ServerConfig Config; -static std::string Modules; -static std::string EncModules; -static std::string DBModules; -static std::string HostCoreModules; -static std::string MemoCoreModules; -static std::string BotCoreModules; -static std::string OperCoreModules; -static std::string NickCoreModules; -static std::string ChanCoreModules; -static std::string DefCon1; -static std::string DefCon2; -static std::string DefCon3; -static std::string DefCon4; +static ci::string Modules; +static ci::string EncModules; +static ci::string DBModules; +static ci::string HostCoreModules; +static ci::string MemoCoreModules; +static ci::string BotCoreModules; +static ci::string OperCoreModules; +static ci::string NickCoreModules; +static ci::string ChanCoreModules; +static ci::string DefCon1; +static ci::string DefCon2; +static ci::string DefCon3; +static ci::string DefCon4; static char *UlineServers; -static std::string OSNotifications; -static std::string BSDefaults; -static std::string CSDefaults; +static ci::string OSNotifications; +static ci::string BSDefaults; +static ci::string CSDefaults; static char *temp_nsuserhost; -static std::string NSDefaults; +static ci::string NSDefaults; /*************************************************************************/ @@ -72,18 +70,18 @@ bool DoneConfItem(ServerConfig *, const char *) return true; } -void ServerConfig::ValidateNoSpaces(const char *p, const std::string &tag, const std::string &val) +void ServerConfig::ValidateNoSpaces(const char *p, const ci::string &tag, const ci::string &val) { for (const char *ptr = p; *ptr; ++ptr) if (*ptr == ' ') - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> cannot contain spaces"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> cannot contain spaces"); } /* NOTE: Before anyone asks why we're not using inet_pton for this, it is because inet_pton and friends do not return so much detail, * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address. * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message. */ -void ServerConfig::ValidateIP(const char *p, const std::string &tag, const std::string &val, bool wild) +void ServerConfig::ValidateIP(const char *p, const ci::string &tag, const ci::string &val, bool wild) { int num_dots = 0, num_seps = 0; bool not_numbers = false, not_hex = false; @@ -91,26 +89,23 @@ void ServerConfig::ValidateIP(const char *p, const std::string &tag, const std:: if (*p) { if (*p == '.') - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is not an IP address"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is not an IP address"); for (const char *ptr = p; *ptr; ++ptr) { if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/')) continue; - if (*ptr != ':' && *ptr != '.') + if (*ptr != ':' && *ptr != '.' && (*ptr < '0' || *ptr > '9')) { - if (*ptr < '0' || *ptr > '9') - { - not_numbers = true; - if (toupper(*ptr) < 'A' || toupper(*ptr) > 'F') - not_hex = true; - } + not_numbers = true; + if (toupper(*ptr) < 'A' || toupper(*ptr) > 'F') + not_hex = true; } switch (*ptr) { case ' ': - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is not an IP address"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is not an IP address"); case '.': ++num_dots; break; @@ -119,26 +114,26 @@ void ServerConfig::ValidateIP(const char *p, const std::string &tag, const std:: } } if (num_dots > 3) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is an IPv4 address with too many fields!"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is an IPv4 address with too many fields!"); if (num_seps > 8) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is an IPv6 address with too many fields!"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is an IPv6 address with too many fields!"); if (!num_seps && num_dots < 3 && !wild) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> looks to be a malformed IPv4 address"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> looks to be a malformed IPv4 address"); if (!num_seps && num_dots == 3 && not_numbers) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> contains non-numeric characters in an IPv4 address"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> contains non-numeric characters in an IPv4 address"); if (num_seps && not_hex) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> contains non-hexdecimal characters in an IPv6 address"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> contains non-hexdecimal characters in an IPv6 address"); if (num_seps && num_dots != 3 && num_dots && !wild) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is a malformed IPv6 4in6 address"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is a malformed IPv6 4in6 address"); } } -void ServerConfig::ValidateHostname(const char *p, const std::string &tag, const std::string &val) +void ServerConfig::ValidateHostname(const char *p, const ci::string &tag, const ci::string &val) { if (!strcasecmp(p, "localhost")) return; @@ -147,13 +142,13 @@ void ServerConfig::ValidateHostname(const char *p, const std::string &tag, const if (*p) { if (*p == '.') - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is not a valid hostname"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is not a valid hostname"); for (const char *ptr = p; *ptr; ++ptr) { switch (*ptr) { case ' ': - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is not a valid hostname"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is not a valid hostname"); case '.': ++num_dots; break; @@ -163,7 +158,7 @@ void ServerConfig::ValidateHostname(const char *p, const std::string &tag, const } } if (!num_dots && !num_seps) - throw ConfigException(std::string("The value of <") + tag + ":" + val + "> is not a valid hostname"); + throw ConfigException(ci::string("The value of <") + tag + ":" + val + "> is not a valid hostname"); } } @@ -185,7 +180,7 @@ bool ValidateEmailReg(ServerConfig *, const char *tag, const char *value, ValueI { if (Config.NSEmailReg) { - if (std::string(value) == "preregexpire") + if (ci::string(value) == "preregexpire") { if (!data.GetInteger()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> must be non-zero when e-mail registration are enabled!"); @@ -240,12 +235,12 @@ bool ValidateBotServ(ServerConfig *, const char *tag, const char *value, ValueIt { if (Config.s_BotServ) { - if (std::string(value) == "description") + if (ci::string(value) == "description") { if (data.GetValue().empty()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> cannot be empty when BotServ is enabled!"); } - else if (std::string(value) == "minusers" || std::string(value) == "badwordsmax" || std::string(value) == "keepdata") + else if (ci::string(value) == "minusers" || ci::string(value) == "badwordsmax" || ci::string(value) == "keepdata") { if (!data.GetInteger()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> must be non-zero when BotServ is enabled!"); @@ -258,7 +253,7 @@ bool ValidateHostServ(ServerConfig *, const char *tag, const char *value, ValueI { if (Config.s_HostServ) { - if (std::string(value) == "description") + if (ci::string(value) == "description") { if (data.GetValue().empty()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> cannot be empty when HostServ is enabled!"); @@ -271,7 +266,7 @@ bool ValidateLimitSessions(ServerConfig *, const char *tag, const char *value, V { if (Config.LimitSessions) { - if (std::string(value) == "maxsessionlimit" || std::string(value) == "exceptionexpiry") + if (ci::string(value) == "maxsessionlimit" || ci::string(value) == "exceptionexpiry") { if (!data.GetInteger()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> must be non-zero when session limiting is enabled!"); @@ -282,7 +277,7 @@ bool ValidateLimitSessions(ServerConfig *, const char *tag, const char *value, V bool ValidateDefCon(ServerConfig *, const char *tag, const char *value, ValueItem &data) { - if (std::string(value) == "defaultlevel") + if (ci::string(value) == "defaultlevel") { int level = data.GetInteger(); if (!level) @@ -292,17 +287,17 @@ bool ValidateDefCon(ServerConfig *, const char *tag, const char *value, ValueIte } else if (Config.DefConLevel) { - if ((std::string(value).substr(0, 5) == "level" && isdigit(value[5])) || std::string(value) == "chanmodes" || std::string(value) == "akillreason") + if ((ci::string(value).substr(0, 5) == "level" && isdigit(value[5])) || ci::string(value) == "chanmodes" || ci::string(value) == "akillreason") { if (data.GetValue().empty()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> cannot be empty when DefCon is enabled!"); } - else if (std::string(value) == "message" && Config.GlobalOnDefconMore) + else if (ci::string(value) == "message" && Config.GlobalOnDefconMore) { if (data.GetValue().empty()) throw ConfigException("The value for <defcon:message> cannot be empty when globalondefconmore is enabled!"); } - else if (std::string(value) == "sessionlimit" || std::string(value) == "akillexpire") + else if (ci::string(value) == "sessionlimit" || ci::string(value) == "akillexpire") { if (!data.GetInteger()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> must be non-zero when DefCon is enabled!"); @@ -332,7 +327,7 @@ bool ValidateMail(ServerConfig *, const char *tag, const char *value, ValueItem { if (Config.UseMail) { - if (std::string(value) == "sendmailpath" || std::string(value) == "sendfrom") + if (ci::string(value) == "sendmailpath" || ci::string(value) == "sendfrom") { if (data.GetValue().empty()) throw ConfigException(std::string("The value for <") + tag + ":" + value + "> cannot be empty when e-mail is enabled!"); @@ -415,7 +410,7 @@ bool DoneUplinks(ServerConfig *, const char *, bool bail) static bool InitOperTypes(ServerConfig *, const char *, bool) { - for (std::list<OperType *>::iterator it = Config.MyOperTypes.begin(); it != Config.MyOperTypes.end(); ++it) + for (std::list<OperType *>::iterator it = Config.MyOperTypes.begin(), it_end = Config.MyOperTypes.end(); it != it_end; ++it) delete *it; Config.MyOperTypes.clear(); @@ -435,7 +430,7 @@ static bool DoOperType(ServerConfig *conf, const char *, const char **, ValueLis OperType *ot = new OperType(name); - std::string tok; + ci::string tok; spacesepstream cmdstr(commands); while (cmdstr.GetToken(tok)) ot->AddCommand(tok); @@ -443,14 +438,14 @@ static bool DoOperType(ServerConfig *conf, const char *, const char **, ValueLis spacesepstream privstr(privs); while (privstr.GetToken(tok)) ot->AddPriv(tok); - + commasepstream inheritstr(inherits); while (inheritstr.GetToken(tok)) { /* Strip leading ' ' after , */ if (tok.size() > 1 && tok[0] == ' ') tok.erase(tok.begin()); - for (std::list<OperType *>::iterator it = Config.MyOperTypes.begin(); it != Config.MyOperTypes.end(); ++it) + for (std::list<OperType *>::iterator it = Config.MyOperTypes.begin(), it_end = Config.MyOperTypes.end(); it != it_end; ++it) { if ((*it)->GetName() == tok) { @@ -474,7 +469,7 @@ static bool DoneOperTypes(ServerConfig *, const char *, bool) static bool InitOpers(ServerConfig *, const char *, bool) { - for (nickcore_map::const_iterator it = NickCoreList.begin(); it != NickCoreList.end(); ++it) + for (nickcore_map::const_iterator it = NickCoreList.begin(), it_end = NickCoreList.end(); it != it_end; ++it) it->second->ot = NULL; Config.Opers.clear(); @@ -502,9 +497,9 @@ static bool DoOper(ServerConfig *conf, const char *, const char **, ValueList &v static bool DoneOpers(ServerConfig *, const char *, bool) { // XXX: this is duplicated in config.c - for (std::list<std::pair<std::string, std::string> >::iterator it = Config.Opers.begin(); it != Config.Opers.end(); ++it) + for (std::list<std::pair<ci::string, ci::string> >::iterator it = Config.Opers.begin(), it_end = Config.Opers.end(); it != it_end; ++it) { - std::string nick = it->first, type = it->second; + ci::string nick = it->first, type = it->second; NickAlias *na = findnick(nick); if (!na) @@ -515,7 +510,7 @@ static bool DoneOpers(ServerConfig *, const char *, bool) // Nick with no core (wtf?) abort(); - for (std::list<OperType *>::iterator tit = Config.MyOperTypes.begin(); tit != Config.MyOperTypes.end(); ++tit) + for (std::list<OperType *>::iterator tit = Config.MyOperTypes.begin(), tit_end = Config.MyOperTypes.end(); tit != tit_end; ++tit) { OperType *ot = *tit; if (ot->GetName() == type) @@ -585,6 +580,10 @@ int ServerConfig::Read(bool bail) * std::string blarg; * {"tag", "value", "", new ValueContainerString(&blarg), DT_STRING, <validation>}, * + * If you want to create a directive using a case-insensitive string: + * std::string blarg; + * {"tag", "value", "", new ValueContainerCIString(&blarg), DT_CISTRING, <validation>}, + * * If you want to create a directive using a boolean: * bool blarg; * {"tag", "value", "no", new ValueContainerBool(&blarg), DT_BOOLEAN, <validation>}, @@ -608,7 +607,7 @@ int ServerConfig::Read(bool bail) * For the second-to-last argument, you can or (|) in the following values: * DT_NORELOAD - The variable can't be changed on a reload of the configuration * DT_ALLOW_WILD - Allows wildcards/CIDR in DT_IPADDRESS - * DT_ALLOW_NEWLINE - Allows new line characters in DT_CHARPTR and DT_STRING + * DT_ALLOW_NEWLINE - Allows new line characters in DT_CHARPTR, DT_STRING, and DT_CISTRING * * We may need to add some other validation functions to handle certain things, we can handle that later. * Any questions about these, w00t, feel free to ask. */ @@ -628,9 +627,9 @@ int ServerConfig::Read(bool bail) {"networkinfo", "nicklen", "0", new ValueContainerUInt(&Config.NickLen), DT_UINTEGER | DT_NORELOAD, ValidateNickLen}, {"networkinfo", "userlen", "10", new ValueContainerUInt(&Config.UserLen), DT_UINTEGER | DT_NORELOAD, NoValidation}, {"networkinfo", "hostlen", "64", new ValueContainerUInt(&Config.HostLen), DT_UINTEGER | DT_NORELOAD, NoValidation}, - {"options", "encryption", "", new ValueContainerString(&EncModules), DT_STRING | DT_NORELOAD, ValidateNotEmpty}, + {"options", "encryption", "", new ValueContainerCIString(&EncModules), DT_CISTRING | DT_NORELOAD, ValidateNotEmpty}, {"options", "passlen", "32", new ValueContainerUInt(&Config.PassLen), DT_UINTEGER | DT_NORELOAD, NoValidation}, - {"options", "database", "", new ValueContainerString(&DBModules), DT_STRING | DT_NORELOAD, ValidateNotEmpty}, + {"options", "database", "", new ValueContainerCIString(&DBModules), DT_CISTRING | DT_NORELOAD, ValidateNotEmpty}, {"options", "userkey1", "0", new ValueContainerLUInt(&Config.UserKey1), DT_LUINTEGER, NoValidation}, {"options", "userkey2", "0", new ValueContainerLUInt(&Config.UserKey2), DT_LUINTEGER, NoValidation}, {"options", "userkey3", "0", new ValueContainerLUInt(&Config.UserKey3), DT_LUINTEGER, NoValidation}, @@ -660,16 +659,16 @@ int ServerConfig::Read(bool bail) {"options", "newscount", "3", new ValueContainerUInt(&Config.NewsCount), DT_UINTEGER, NoValidation}, {"options", "ulineservers", "", new ValueContainerChar(&UlineServers), DT_CHARPTR, NoValidation}, {"options", "enablelogchannel", "no", new ValueContainerBool(&LogChan), DT_BOOLEAN, NoValidation}, - {"options", "mlock", "+nrt", new ValueContainerString(&Config.MLock), DT_STRING, NoValidation}, - {"options", "botmodes", "", new ValueContainerString(&Config.BotModes), DT_STRING, NoValidation}, + {"options", "mlock", "+nrt", new ValueContainerCIString(&Config.MLock), DT_CISTRING, NoValidation}, + {"options", "botmodes", "", new ValueContainerCIString(&Config.BotModes), DT_CISTRING, NoValidation}, {"options", "maxretries", "10", new ValueContainerUInt(&Config.MaxRetries), DT_UINTEGER, NoValidation}, {"options", "retrywait", "60", new ValueContainerInt(&Config.RetryWait), DT_INTEGER, ValidateNotZero}, {"nickserv", "nick", "NickServ", new ValueContainerChar(&Config.s_NickServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"nickserv", "description", "Nickname Registration Service", new ValueContainerChar(&Config.desc_NickServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"nickserv", "emailregistration", "no", new ValueContainerBool(&Config.NSEmailReg), DT_BOOLEAN, NoValidation}, - {"nickserv", "modules", "", new ValueContainerString(&NickCoreModules), DT_STRING, NoValidation}, + {"nickserv", "modules", "", new ValueContainerCIString(&NickCoreModules), DT_CISTRING, NoValidation}, {"nickserv", "forceemail", "no", new ValueContainerBool(&Config.NSForceEmail), DT_BOOLEAN, ValidateEmailReg}, - {"nickserv", "defaults", "secure memosignon memoreceive", new ValueContainerString(&NSDefaults), DT_STRING, NoValidation}, + {"nickserv", "defaults", "secure memosignon memoreceive", new ValueContainerCIString(&NSDefaults), DT_CISTRING, NoValidation}, {"nickserv", "defaultlanguage", "0", new ValueContainerUInt(&Config.NSDefLanguage), DT_UINTEGER, ValidateLanguage}, {"nickserv", "regdelay", "0", new ValueContainerTime(&Config.NSRegDelay), DT_TIME, NoValidation}, {"nickserv", "resenddelay", "0", new ValueContainerTime(&Config.NSResendDelay), DT_TIME, NoValidation}, @@ -696,8 +695,8 @@ int ServerConfig::Read(bool bail) {"mail", "dontquoteaddresses", "no", new ValueContainerBool(&Config.DontQuoteAddresses), DT_BOOLEAN, NoValidation}, {"chanserv", "nick", "ChanServ", new ValueContainerChar(&Config.s_ChanServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"chanserv", "description", "Channel Registration Service", new ValueContainerChar(&Config.desc_ChanServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, - {"chanserv", "modules", "", new ValueContainerString(&ChanCoreModules), DT_STRING, NoValidation}, - {"chanserv", "defaults", "keeptopic secure securefounder signkick", new ValueContainerString(&CSDefaults), DT_STRING, NoValidation}, + {"chanserv", "modules", "", new ValueContainerCIString(&ChanCoreModules), DT_CISTRING, NoValidation}, + {"chanserv", "defaults", "keeptopic secure securefounder signkick", new ValueContainerCIString(&CSDefaults), DT_CISTRING, NoValidation}, {"chanserv", "maxregistered", "0", new ValueContainerUInt(&Config.CSMaxReg), DT_UINTEGER, NoValidation}, {"chanserv", "expire", "14d", new ValueContainerTime(&Config.CSExpire), DT_TIME, NoValidation}, {"chanserv", "defbantype", "2", new ValueContainerInt(&Config.CSDefBantype), DT_INTEGER, ValidateBantype}, @@ -710,15 +709,15 @@ int ServerConfig::Read(bool bail) {"chanserv", "opersonly", "no", new ValueContainerBool(&Config.CSOpersOnly), DT_BOOLEAN, NoValidation}, {"memoserv", "nick", "MemoServ", new ValueContainerChar(&Config.s_MemoServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"memoserv", "description", "Memo Service", new ValueContainerChar(&Config.desc_MemoServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, - {"memoserv", "modules", "", new ValueContainerString(&MemoCoreModules), DT_STRING, NoValidation}, + {"memoserv", "modules", "", new ValueContainerCIString(&MemoCoreModules), DT_CISTRING, NoValidation}, {"memoserv", "maxmemos", "0", new ValueContainerUInt(&Config.MSMaxMemos), DT_UINTEGER, NoValidation}, {"memoserv", "senddelay", "0", new ValueContainerTime(&Config.MSSendDelay), DT_TIME, NoValidation}, {"memoserv", "notifyall", "no", new ValueContainerBool(&Config.MSNotifyAll), DT_BOOLEAN, NoValidation}, {"memoserv", "memoreceipt", "0", new ValueContainerUInt(&Config.MSMemoReceipt), DT_UINTEGER, NoValidation}, {"botserv", "nick", "", new ValueContainerChar(&Config.s_BotServ), DT_CHARPTR | DT_NORELOAD, NoValidation}, {"botserv", "description", "Bot Service", new ValueContainerChar(&Config.desc_BotServ), DT_CHARPTR | DT_NORELOAD, ValidateBotServ}, - {"botserv", "modules", "", new ValueContainerString(&BotCoreModules), DT_STRING, NoValidation}, - {"botserv", "defaults", "", new ValueContainerString(&BSDefaults), DT_STRING, NoValidation}, + {"botserv", "modules", "", new ValueContainerCIString(&BotCoreModules), DT_CISTRING, NoValidation}, + {"botserv", "defaults", "", new ValueContainerCIString(&BSDefaults), DT_CISTRING, NoValidation}, {"botserv", "minusers", "0", new ValueContainerUInt(&Config.BSMinUsers), DT_UINTEGER, ValidateBotServ}, {"botserv", "badwordsmax", "0", new ValueContainerUInt(&Config.BSBadWordsMax), DT_UINTEGER, ValidateBotServ}, {"botserv", "keepdata", "0", new ValueContainerTime(&Config.BSKeepData), DT_TIME, ValidateBotServ}, @@ -728,12 +727,12 @@ int ServerConfig::Read(bool bail) {"botserv", "fantasycharacter", "!", new ValueContainerChar(&Config.BSFantasyCharacter), DT_CHARPTR, NoValidation}, {"hostserv", "nick", "", new ValueContainerChar(&Config.s_HostServ), DT_CHARPTR | DT_NORELOAD, NoValidation}, {"hostserv", "description", "vHost Service", new ValueContainerChar(&Config.desc_HostServ), DT_CHARPTR | DT_NORELOAD, ValidateHostServ}, - {"hostserv", "modules", "", new ValueContainerString(&HostCoreModules), DT_STRING, NoValidation}, + {"hostserv", "modules", "", new ValueContainerCIString(&HostCoreModules), DT_CISTRING, NoValidation}, {"operserv", "nick", "OperServ", new ValueContainerChar(&Config.s_OperServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"operserv", "description", "Operator Service", new ValueContainerChar(&Config.desc_OperServ), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"operserv", "globalnick", "Global", new ValueContainerChar(&Config.s_GlobalNoticer), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, {"operserv", "globaldescription", "Global Noticer", new ValueContainerChar(&Config.desc_GlobalNoticer), DT_CHARPTR | DT_NORELOAD, ValidateNotEmpty}, - {"operserv", "modules", "", new ValueContainerString(&OperCoreModules), DT_STRING, NoValidation}, + {"operserv", "modules", "", new ValueContainerCIString(&OperCoreModules), DT_CISTRING, NoValidation}, {"operserv", "superadmin", "no", new ValueContainerBool(&Config.SuperAdmin), DT_BOOLEAN, NoValidation}, {"operserv", "logmaxusers", "no", new ValueContainerBool(&Config.LogMaxUsers), DT_BOOLEAN, NoValidation}, {"operserv", "autokillexpiry", "0", new ValueContainerTime(&Config.AutokillExpiry), DT_TIME, ValidateNotZero}, @@ -744,7 +743,7 @@ int ServerConfig::Read(bool bail) {"operserv", "akillonadd", "no", new ValueContainerBool(&Config.AkillOnAdd), DT_BOOLEAN, NoValidation}, {"operserv", "killonsnline", "no", new ValueContainerBool(&Config.KillonSNline), DT_BOOLEAN, NoValidation}, {"operserv", "killonsqline", "no", new ValueContainerBool(&Config.KillonSQline), DT_BOOLEAN, NoValidation}, - {"operserv", "notifications", "", new ValueContainerString(&OSNotifications), DT_STRING, NoValidation}, + {"operserv", "notifications", "", new ValueContainerCIString(&OSNotifications), DT_CISTRING, NoValidation}, {"operserv", "limitsessions", "no", new ValueContainerBool(&Config.LimitSessions), DT_BOOLEAN, NoValidation}, {"operserv", "defaultsessionlimit", "0", new ValueContainerUInt(&Config.DefSessionLimit), DT_UINTEGER, NoValidation}, {"operserv", "maxsessionlimit", "0", new ValueContainerUInt(&Config.MaxSessionLimit), DT_UINTEGER, ValidateLimitSessions}, @@ -756,10 +755,10 @@ int ServerConfig::Read(bool bail) {"operserv", "addakiller", "no", new ValueContainerBool(&Config.AddAkiller), DT_BOOLEAN, NoValidation}, {"operserv", "opersonly", "no", new ValueContainerBool(&Config.OSOpersOnly), DT_BOOLEAN, NoValidation}, {"defcon", "defaultlevel", "0", new ValueContainerInt(&DefConLevel), DT_INTEGER, ValidateDefCon}, - {"defcon", "level4", "", new ValueContainerString(&DefCon4), DT_STRING, ValidateDefCon}, - {"defcon", "level3", "", new ValueContainerString(&DefCon3), DT_STRING, ValidateDefCon}, - {"defcon", "level2", "", new ValueContainerString(&DefCon2), DT_STRING, ValidateDefCon}, - {"defcon", "level1", "", new ValueContainerString(&DefCon1), DT_STRING, ValidateDefCon}, + {"defcon", "level4", "", new ValueContainerCIString(&DefCon4), DT_CISTRING, ValidateDefCon}, + {"defcon", "level3", "", new ValueContainerCIString(&DefCon3), DT_CISTRING, ValidateDefCon}, + {"defcon", "level2", "", new ValueContainerCIString(&DefCon2), DT_CISTRING, ValidateDefCon}, + {"defcon", "level1", "", new ValueContainerCIString(&DefCon1), DT_CISTRING, ValidateDefCon}, {"defcon", "sessionlimit", "0", new ValueContainerInt(&Config.DefConSessionLimit), DT_INTEGER, ValidateDefCon}, {"defcon", "akillexpire", "0", new ValueContainerTime(&Config.DefConAKILL), DT_TIME, ValidateDefCon}, {"defcon", "chanmodes", "", new ValueContainerChar(&Config.DefConChanModes), DT_CHARPTR, ValidateDefCon}, @@ -878,6 +877,12 @@ int ServerConfig::Read(bool bail) vcs->Set(vi.GetValue()); } break; + case DT_CISTRING: + { + ValueContainerCIString *vcs = dynamic_cast<ValueContainerCIString *>(Values[Index].val); + vcs->Set(vi.GetCIValue()); + } + break; case DT_INTEGER: { int val = vi.GetInteger(); @@ -985,8 +990,17 @@ int ServerConfig::Read(bool bail) break; case DT_STRING: { - std::string item; - if (ConfValue(config_data, std::string(MultiValues[Index].tag), std::string(MultiValues[Index].items[valuenum]), std::string(MultiValues[Index].items_default[valuenum]), tagnum, item, allow_newlines)) + ci::string item; + if (ConfValue(config_data, ci::string(MultiValues[Index].tag), ci::string(MultiValues[Index].items[valuenum]), ci::string(MultiValues[Index].items_default[valuenum]), tagnum, item, allow_newlines)) + vl.push_back(ValueItem(item)); + else + vl.push_back(ValueItem("")); + } + break; + case DT_CISTRING: + { + ci::string item; + if (ConfValue(config_data, ci::string(MultiValues[Index].tag), ci::string(MultiValues[Index].items[valuenum]), ci::string(MultiValues[Index].items_default[valuenum]), tagnum, item, allow_newlines)) vl.push_back(ValueItem(item)); else vl.push_back(ValueItem("")); @@ -1005,8 +1019,8 @@ int ServerConfig::Read(bool bail) break; case DT_TIME: { - std::string item; - if (ConfValue(config_data, std::string(MultiValues[Index].tag), std::string(MultiValues[Index].items[valuenum]), std::string(MultiValues[Index].items_default[valuenum]), tagnum, item, allow_newlines)) + ci::string item; + if (ConfValue(config_data, ci::string(MultiValues[Index].tag), ci::string(MultiValues[Index].items[valuenum]), ci::string(MultiValues[Index].items_default[valuenum]), tagnum, item, allow_newlines)) { #ifdef _WIN32 long time = static_cast<long>(dotime(item.c_str())); @@ -1031,7 +1045,7 @@ int ServerConfig::Read(bool bail) MultiValues[Index].finish_function(this, MultiValues[Index].tag, bail); } } - catch (ConfigException &ce) + catch (const ConfigException &ce) { ReportConfigError(ce.GetReason(), bail); if (!CheckedAllValues) @@ -1054,7 +1068,8 @@ int ServerConfig::Read(bool bail) bool ServerConfig::LoadConf(ConfigDataHash &target, const char *filename, std::ostringstream &errorstream) { - std::string line, wordbuffer, section, itemname; + std::string line; + ci::string section, wordbuffer, itemname; std::ifstream conf(filename); int linenumber = 0; bool in_word = false, in_quote = false, in_ml_comment = false; @@ -1173,7 +1188,7 @@ bool ServerConfig::LoadConf(ConfigDataHash &target, const char *filename, std::o wordbuffer.clear(); itemname.clear(); } - target.insert(std::pair<std::string, KeyValList>(section, sectiondata)); + target.insert(std::pair<ci::string, KeyValList>(section, sectiondata)); section.clear(); sectiondata.clear(); } @@ -1244,6 +1259,11 @@ bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, return LoadConf(target, filename.c_str(), errorstream); } +bool ServerConfig::LoadConf(ConfigDataHash &target, const ci::string &filename, std::ostringstream &errorstream) +{ + return LoadConf(target, filename.c_str(), errorstream); +} + bool ServerConfig::ConfValue(ConfigDataHash &target, const char *tag, const char *var, int index, char *result, int length, bool allow_linefeeds) { return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds); @@ -1251,18 +1271,18 @@ bool ServerConfig::ConfValue(ConfigDataHash &target, const char *tag, const char bool ServerConfig::ConfValue(ConfigDataHash &target, const char *tag, const char *var, const char *default_value, int index, char *result, int length, bool allow_linefeeds) { - std::string value; - bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds); + ci::string value; + bool r = ConfValue(target, ci::string(tag), ci::string(var), ci::string(default_value), index, value, allow_linefeeds); strlcpy(result, value.c_str(), length); return r; } -bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds) +bool ServerConfig::ConfValue(ConfigDataHash &target, const ci::string &tag, const ci::string &var, int index, ci::string &result, bool allow_linefeeds) { return ConfValue(target, tag, var, "", index, result, allow_linefeeds); } -bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds) +bool ServerConfig::ConfValue(ConfigDataHash &target, const ci::string &tag, const ci::string &var, const ci::string &default_value, int index, ci::string &result, bool allow_linefeeds) { ConfigDataHash::size_type pos = index; if (pos < target.count(tag)) @@ -1280,7 +1300,7 @@ bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, con if (!allow_linefeeds && j->second.find('\n') != std::string::npos) { Alog(LOG_DEBUG) << "Value of <" << tag << ":" << var << "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces."; - std::string::iterator n = j->second.begin(), nend = j->second.end(); + ci::string::iterator n = j->second.begin(), nend = j->second.end(); for (; n != nend; ++n) if (*n == '\n') *n = ' '; @@ -1311,25 +1331,25 @@ bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, con bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char *tag, const char *var, int index, int &result) { - return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result); + return ConfValueInteger(target, ci::string(tag), ci::string(var), "", index, result); } bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char *tag, const char *var, const char *default_value, int index, int &result) { - return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result); + return ConfValueInteger(target, ci::string(tag), ci::string(var), ci::string(default_value), index, result); } -bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result) +bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const ci::string &tag, const ci::string &var, int index, int &result) { return ConfValueInteger(target, tag, var, "", index, result); } -bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result) +bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const ci::string &tag, const ci::string &var, const ci::string &default_value, int index, int &result) { - std::string value; + ci::string value; std::istringstream stream; bool r = ConfValue(target, tag, var, default_value, index, value); - stream.str(value); + stream.str(value.c_str()); if (!(stream >> result)) return false; else @@ -1372,22 +1392,22 @@ bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &t bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char *tag, const char *var, int index) { - return ConfValueBool(target, std::string(tag), std::string(var), "", index); + return ConfValueBool(target, ci::string(tag), ci::string(var), "", index); } bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char *tag, const char *var, const char *default_value, int index) { - return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index); + return ConfValueBool(target, ci::string(tag), ci::string(var), ci::string(default_value), index); } -bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index) +bool ServerConfig::ConfValueBool(ConfigDataHash &target, const ci::string &tag, const ci::string &var, int index) { return ConfValueBool(target, tag, var, "", index); } -bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index) +bool ServerConfig::ConfValueBool(ConfigDataHash &target, const ci::string &tag, const ci::string &var, const ci::string &default_value, int index) { - std::string result; + ci::string result; if (!ConfValue(target, tag, var, default_value, index, result)) return false; @@ -1401,15 +1421,20 @@ int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char *tag) int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag) { + return target.count(tag.c_str()); +} + +int ServerConfig::ConfValueEnum(ConfigDataHash &target, const ci::string &tag) +{ return target.count(tag); } int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char *tag, int index) { - return ConfVarEnum(target, std::string(tag), index); + return ConfVarEnum(target, ci::string(tag), index); } -int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index) +int ServerConfig::ConfVarEnum(ConfigDataHash &target, const ci::string &tag, int index) { ConfigDataHash::size_type pos = index; @@ -1451,6 +1476,8 @@ ValueItem::ValueItem(const char *value) : v(value) { } ValueItem::ValueItem(const std::string &value) : v(value) { } +ValueItem::ValueItem(const ci::string &value) : v(value.c_str()) { } + void ValueItem::Set(const char *value) { v = value; @@ -1461,6 +1488,11 @@ void ValueItem::Set(const std::string &value) v = value; } +void ValueItem::Set(const ci::string &value) +{ + v = value.c_str(); +} + void ValueItem::Set(int value) { std::stringstream n; @@ -1470,7 +1502,8 @@ void ValueItem::Set(int value) int ValueItem::GetInteger() { - if (v.empty()) return 0; + if (v.empty()) + return 0; return atoi(v.c_str()); } @@ -1502,8 +1535,8 @@ void error(int linenum, const char *message, ...) else Alog() << services_conf << ": " << buf; - - if (!nofork && isatty(2)) { + if (!nofork && isatty(2)) + { if (linenum) fprintf(stderr, "%s:%d: %s\n", services_conf.c_str(), linenum, buf); else @@ -1513,18 +1546,24 @@ void error(int linenum, const char *message, ...) /*************************************************************************/ -#define CHECK(v) do { \ - if (!v) { \ - error(0, #v " missing"); \ - retval = 0; \ - } \ +#define CHECK(v) \ +do \ +{ \ + if (!v) \ + {\ + error(0, #v " missing"); \ + retval = 0; \ + } \ } while (0) -#define CHEK2(v,n) do { \ - if (!v) { \ - error(0, #n " missing"); \ - retval = 0; \ - } \ +#define CHEK2(v, n) \ +do \ +{ \ + if (!v) \ + { \ + error(0, #n " missing"); \ + retval = 0; \ + } \ } while (0) /* Read the entire configuration file. If an error occurs while reading @@ -1533,7 +1572,6 @@ void error(int linenum, const char *message, ...) * * If reload is 1, will reload the configuration file. * --lara - * */ int read_config(int reload) @@ -1545,11 +1583,15 @@ int read_config(int reload) retval = Config.Read(reload ? false : true); if (!retval) return 0; // Temporary until most of the below is modified to use the new parser -- CyberBotX - if (temp_nsuserhost) { - if (!(s = strchr(temp_nsuserhost, '@'))) { + if (temp_nsuserhost) + { + if (!(s = strchr(temp_nsuserhost, '@'))) + { Config.NSEnforcerUser = temp_nsuserhost; Config.NSEnforcerHost = Config.ServiceHost; - } else { + } + else + { *s++ = 0; Config.NSEnforcerUser = temp_nsuserhost; Config.NSEnforcerHost = s; @@ -1562,34 +1604,50 @@ int read_config(int reload) Config.NSDefFlags.SetFlag(NI_MEMO_SIGNON); Config.NSDefFlags.SetFlag(NI_MEMO_RECEIVE); } - else if (NSDefaults != "none") { + else if (NSDefaults != "none") + { spacesepstream options(NSDefaults); - std::string option; + ci::string option; while (options.GetToken(option)) { - if (option == "kill") Config.NSDefFlags.SetFlag(NI_KILLPROTECT); - else if (option == "killquick") Config.NSDefFlags.SetFlag(NI_KILL_QUICK); - else if (option == "secure") Config.NSDefFlags.SetFlag(NI_SECURE); - else if (option == "private") Config.NSDefFlags.SetFlag(NI_PRIVATE); - else if (option == "msg") { - if (!Config.UsePrivmsg) Alog() << "msg in <nickserv:defaults> can only be used when UsePrivmsg is set"; - else Config.NSDefFlags.SetFlag(NI_MSG); + if (option == "kill") + Config.NSDefFlags.SetFlag(NI_KILLPROTECT); + else if (option == "killquick") + Config.NSDefFlags.SetFlag(NI_KILL_QUICK); + else if (option == "secure") + Config.NSDefFlags.SetFlag(NI_SECURE); + else if (option == "private") + Config.NSDefFlags.SetFlag(NI_PRIVATE); + else if (option == "msg") + { + if (!Config.UsePrivmsg) + Alog() << "msg in <nickserv:defaults> can only be used when UsePrivmsg is set"; + else + Config.NSDefFlags.SetFlag(NI_MSG); } - else if (option == "hideemail") Config.NSDefFlags.SetFlag(NI_HIDE_EMAIL); - else if (option == "hideusermask") Config.NSDefFlags.SetFlag(NI_HIDE_MASK); - else if (option == "hidequit") Config.NSDefFlags.SetFlag(NI_HIDE_QUIT); - else if (option == "memosignon") Config.NSDefFlags.SetFlag(NI_MEMO_SIGNON); - else if (option == "memoreceive") Config.NSDefFlags.SetFlag(NI_MEMO_RECEIVE); - else if (option == "autoop") Config.NSDefFlags.SetFlag(NI_AUTOOP); + else if (option == "hideemail") + Config.NSDefFlags.SetFlag(NI_HIDE_EMAIL); + else if (option == "hideusermask") + Config.NSDefFlags.SetFlag(NI_HIDE_MASK); + else if (option == "hidequit") + Config.NSDefFlags.SetFlag(NI_HIDE_QUIT); + else if (option == "memosignon") + Config.NSDefFlags.SetFlag(NI_MEMO_SIGNON); + else if (option == "memoreceive") + Config.NSDefFlags.SetFlag(NI_MEMO_RECEIVE); + else if (option == "autoop") + Config.NSDefFlags.SetFlag(NI_AUTOOP); } } - if (reload) { + if (reload) + { if ((Config.NSDefLanguage = langlist[Config.NSDefLanguage]) < 0) Config.NSDefLanguage = DEF_LANGUAGE; } - if (Config.CSDefBantype < 0 || Config.CSDefBantype > 3) { + if (Config.CSDefBantype < 0 || Config.CSDefBantype > 3) + { error(0, "Value of CSDefBantype must be between 0 and 3 included"); retval = 0; } @@ -1601,78 +1659,126 @@ int read_config(int reload) Config.CSDefFlags.SetFlag(CI_SECUREFOUNDER); Config.CSDefFlags.SetFlag(CI_SIGNKICK); } - else if (CSDefaults != "none") { + else if (CSDefaults != "none") + { spacesepstream options(CSDefaults); - std::string option; - while (options.GetToken(option)) { - if (option == "keeptopic") Config.CSDefFlags.SetFlag(CI_KEEPTOPIC); - else if (option == "topiclock") Config.CSDefFlags.SetFlag(CI_TOPICLOCK); - else if (option == "private") Config.CSDefFlags.SetFlag(CI_PRIVATE); - else if (option == "restricted") Config.CSDefFlags.SetFlag(CI_RESTRICTED); - else if (option == "secure") Config.CSDefFlags.SetFlag(CI_SECURE); - else if (option == "secureops") Config.CSDefFlags.SetFlag(CI_SECUREOPS); - else if (option == "securefounder") Config.CSDefFlags.SetFlag(CI_SECUREFOUNDER); - else if (option == "signkick") Config.CSDefFlags.SetFlag(CI_SIGNKICK); - else if (option == "signkicklevel") Config.CSDefFlags.SetFlag(CI_SIGNKICK_LEVEL); - else if (option == "opnotice") Config.CSDefFlags.SetFlag(CI_OPNOTICE); - else if (option == "xop") Config.CSDefFlags.SetFlag(CI_XOP); - else if (option == "peace") Config.CSDefFlags.SetFlag(CI_PEACE); - else if (option == "persist") Config.CSDefFlags.SetFlag(CI_PERSIST); + ci::string option; + while (options.GetToken(option)) + { + if (option == "keeptopic") + Config.CSDefFlags.SetFlag(CI_KEEPTOPIC); + else if (option == "topiclock") + Config.CSDefFlags.SetFlag(CI_TOPICLOCK); + else if (option == "private") + Config.CSDefFlags.SetFlag(CI_PRIVATE); + else if (option == "restricted") + Config.CSDefFlags.SetFlag(CI_RESTRICTED); + else if (option == "secure") + Config.CSDefFlags.SetFlag(CI_SECURE); + else if (option == "secureops") + Config.CSDefFlags.SetFlag(CI_SECUREOPS); + else if (option == "securefounder") + Config.CSDefFlags.SetFlag(CI_SECUREFOUNDER); + else if (option == "signkick") + Config.CSDefFlags.SetFlag(CI_SIGNKICK); + else if (option == "signkicklevel") + Config.CSDefFlags.SetFlag(CI_SIGNKICK_LEVEL); + else if (option == "opnotice") + Config.CSDefFlags.SetFlag(CI_OPNOTICE); + else if (option == "xop") + Config.CSDefFlags.SetFlag(CI_XOP); + else if (option == "peace") + Config.CSDefFlags.SetFlag(CI_PEACE); + else if (option == "persist") + Config.CSDefFlags.SetFlag(CI_PERSIST); } } - if (!BSDefaults.empty()) { + if (!BSDefaults.empty()) + { spacesepstream options(BSDefaults); - std::string option; - while (options.GetToken(option)) { - if (option == "dontkickops") Config.BSDefFlags.SetFlag(BS_DONTKICKOPS); - else if (option == "dontkickvoices") Config.BSDefFlags.SetFlag(BS_DONTKICKVOICES); - else if (option == "greet") Config.BSDefFlags.SetFlag(BS_GREET); - else if (option == "fantasy") Config.BSDefFlags.SetFlag(BS_FANTASY); - else if (option == "symbiosis") Config.BSDefFlags.SetFlag(BS_SYMBIOSIS); + ci::string option; + while (options.GetToken(option)) + { + if (option == "dontkickops") + Config.BSDefFlags.SetFlag(BS_DONTKICKOPS); + else if (option == "dontkickvoices") + Config.BSDefFlags.SetFlag(BS_DONTKICKVOICES); + else if (option == "greet") + Config.BSDefFlags.SetFlag(BS_GREET); + else if (option == "fantasy") + Config.BSDefFlags.SetFlag(BS_FANTASY); + else if (option == "symbiosis") + Config.BSDefFlags.SetFlag(BS_SYMBIOSIS); } } Config.WallOper = Config.WallBadOS = Config.WallOSGlobal = Config.WallOSMode = Config.WallOSClearmodes = Config.WallOSKick = Config.WallOSAkill = Config.WallOSSNLine = Config.WallOSSQLine = - Config.WallOSSZLine = Config.WallOSNoOp = Config.WallOSJupe = Config.WallAkillExpire = Config.WallSNLineExpire = Config.WallSQLineExpire = Config.WallSZLineExpire = Config.WallExceptionExpire = Config.WallGetpass = Config.WallSetpass = Config.WallForbid = - Config.WallDrop = false; - if (!OSNotifications.empty()) { + Config.WallOSSZLine = Config.WallOSNoOp = Config.WallOSJupe = Config.WallAkillExpire = Config.WallSNLineExpire = Config.WallSQLineExpire = Config.WallSZLineExpire = Config.WallExceptionExpire = + Config.WallGetpass = Config.WallSetpass = Config.WallForbid = Config.WallDrop = false; + if (!OSNotifications.empty()) + { spacesepstream notifications(OSNotifications); - std::string notice; - while (notifications.GetToken(notice)) { - if (notice == "oper") Config.WallOper = true; - else if (notice == "bados") Config.WallBadOS = true; - else if (notice == "osglobal") Config.WallOSGlobal = true; - else if (notice == "osmode") Config.WallOSMode = true; - else if (notice == "osclearmodes") Config.WallOSClearmodes = true; - else if (notice == "oskick") Config.WallOSKick = true; - else if (notice == "osakill") Config.WallOSAkill = true; - else if (notice == "ossnline") Config.WallOSSNLine = true; - else if (notice == "ossqline") Config.WallOSSQLine = true; - else if (notice == "osszline") Config.WallOSSZLine = true; - else if (notice == "osnoop") Config.WallOSNoOp = true; - else if (notice == "osjupe") Config.WallOSJupe = true; - else if (notice == "akillexpire") Config.WallAkillExpire = true; - else if (notice == "snlineexpire") Config.WallSNLineExpire = true; - else if (notice == "sqlineexpire") Config.WallSQLineExpire = true; - else if (notice == "szlineexpire") Config.WallSZLineExpire = true; - else if (notice == "exceptionexpire") Config.WallExceptionExpire = true; - else if (notice == "getpass") Config.WallGetpass = true; - else if (notice == "setpass") Config.WallSetpass = true; - else if (notice == "forbid") Config.WallForbid = true; - else if (notice == "drop") Config.WallDrop = true; + ci::string notice; + while (notifications.GetToken(notice)) + { + if (notice == "oper") + Config.WallOper = true; + else if (notice == "bados") + Config.WallBadOS = true; + else if (notice == "osglobal") + Config.WallOSGlobal = true; + else if (notice == "osmode") + Config.WallOSMode = true; + else if (notice == "osclearmodes") + Config.WallOSClearmodes = true; + else if (notice == "oskick") + Config.WallOSKick = true; + else if (notice == "osakill") + Config.WallOSAkill = true; + else if (notice == "ossnline") + Config.WallOSSNLine = true; + else if (notice == "ossqline") + Config.WallOSSQLine = true; + else if (notice == "osszline") + Config.WallOSSZLine = true; + else if (notice == "osnoop") + Config.WallOSNoOp = true; + else if (notice == "osjupe") + Config.WallOSJupe = true; + else if (notice == "akillexpire") + Config.WallAkillExpire = true; + else if (notice == "snlineexpire") + Config.WallSNLineExpire = true; + else if (notice == "sqlineexpire") + Config.WallSQLineExpire = true; + else if (notice == "szlineexpire") + Config.WallSZLineExpire = true; + else if (notice == "exceptionexpire") + Config.WallExceptionExpire = true; + else if (notice == "getpass") + Config.WallGetpass = true; + else if (notice == "setpass") + Config.WallSetpass = true; + else if (notice == "forbid") + Config.WallForbid = true; + else if (notice == "drop") + Config.WallDrop = true; } } /* Ulines */ - if (UlineServers) { + if (UlineServers) + { Config.NumUlines = 0; s = strtok(UlineServers, " "); - do { - if (s) { - Config.NumUlines++; + do + { + if (s) + { + ++Config.NumUlines; Config.Ulines = static_cast<char **>(realloc(Config.Ulines, sizeof(char *) * Config.NumUlines)); Config.Ulines[Config.NumUlines - 1] = sstrdup(s); } @@ -1690,25 +1796,22 @@ int read_config(int reload) Config.ChanServCoreModules = BuildStringList(!ChanCoreModules.empty() ? ChanCoreModules : ""); Config.NickServCoreModules = BuildStringList(!NickCoreModules.empty() ? NickCoreModules : ""); - if (Config.LimitSessions) { + if (Config.LimitSessions) + { if (Config.MaxSessionKill && !Config.SessionAutoKillExpiry) - Config.SessionAutoKillExpiry = 1800; /* 30 minutes */ + Config.SessionAutoKillExpiry = 1800; /* 30 minutes */ } - if (Config.s_BotServ) { + if (Config.s_BotServ) + { if (!Config.BSFantasyCharacter || !*Config.BSFantasyCharacter) Config.BSFantasyCharacter = sstrdup("!"); - if (*Config.BSFantasyCharacter && (strlen(Config.BSFantasyCharacter) > 1)) { - printf - ("*** Config.BSFantasyCharacter is more than 1 character long. Only the first\n" - "*** character ('%c') will be used. The others will be ignored.\n", - *Config.BSFantasyCharacter); - } + if (*Config.BSFantasyCharacter && strlen(Config.BSFantasyCharacter) > 1) + printf("*** Config.BSFantasyCharacter is more than 1 character long. Only the first\n*** character ('%c') will be used. The others will be ignored.\n", *Config.BSFantasyCharacter); } /* Check the user keys */ - if ((Config.UserKey1 == Config.UserKey2) || (Config.UserKey1 == Config.UserKey3) - || (Config.UserKey3 == Config.UserKey2)) + if (Config.UserKey1 == Config.UserKey2 || Config.UserKey1 == Config.UserKey3 || Config.UserKey3 == Config.UserKey2) Alog() << "Every UserKey must be different. It's for YOUR safety! Remember that!"; /** @@ -1719,10 +1822,12 @@ int read_config(int reload) /* Build DefCon's */ DefCon.resize(6); DefCon[5].reset(); - for (unsigned int level = 1; level < 5; ++level) { + for (unsigned int level = 1; level < 5; ++level) + { DefCon[level] = 0; - std::string *levelDefinition = NULL; - switch (level) { + ci::string *levelDefinition = NULL; + switch (level) + { case 1: levelDefinition = &DefCon1; break; @@ -1736,37 +1841,44 @@ int read_config(int reload) levelDefinition = &DefCon4; } spacesepstream operations(*levelDefinition); - std::string operation; - while (operations.GetToken(operation)) { - if (operation == "nonewchannels") AddDefCon(level, DEFCON_NO_NEW_CHANNELS); - else if (operation == "nonewnicks") AddDefCon(level, DEFCON_NO_NEW_NICKS); - else if (operation == "nomlockchanges") AddDefCon(level, DEFCON_NO_MLOCK_CHANGE); - else if (operation == "forcechanmodes") AddDefCon(level, DEFCON_FORCE_CHAN_MODES); - else if (operation == "reducedsessions") AddDefCon(level, DEFCON_REDUCE_SESSION); - else if (operation == "nonewclients") AddDefCon(level, DEFCON_NO_NEW_CLIENTS); - else if (operation == "operonly") AddDefCon(level, DEFCON_OPER_ONLY); - else if (operation == "silentoperonly") AddDefCon(level, DEFCON_SILENT_OPER_ONLY); - else if (operation == "akillnewclients") AddDefCon(level, DEFCON_AKILL_NEW_CLIENTS); - else if (operation == "nonewmemos") AddDefCon(level, DEFCON_NO_NEW_MEMOS); + ci::string operation; + while (operations.GetToken(operation)) + { + if (operation == "nonewchannels") + AddDefCon(level, DEFCON_NO_NEW_CHANNELS); + else if (operation == "nonewnicks") + AddDefCon(level, DEFCON_NO_NEW_NICKS); + else if (operation == "nomlockchanges") + AddDefCon(level, DEFCON_NO_MLOCK_CHANGE); + else if (operation == "forcechanmodes") + AddDefCon(level, DEFCON_FORCE_CHAN_MODES); + else if (operation == "reducedsessions") + AddDefCon(level, DEFCON_REDUCE_SESSION); + else if (operation == "nonewclients") + AddDefCon(level, DEFCON_NO_NEW_CLIENTS); + else if (operation == "operonly") + AddDefCon(level, DEFCON_OPER_ONLY); + else if (operation == "silentoperonly") + AddDefCon(level, DEFCON_SILENT_OPER_ONLY); + else if (operation == "akillnewclients") + AddDefCon(level, DEFCON_AKILL_NEW_CLIENTS); + else if (operation == "nonewmemos") + AddDefCon(level, DEFCON_NO_NEW_MEMOS); } } /* Check any defcon needed settings */ - for (defconCount = 1; defconCount <= 5; defconCount++) + for (defconCount = 1; defconCount <= 5; ++defconCount) { if (CheckDefCon(defconCount, DEFCON_REDUCE_SESSION)) - { CHECK(Config.DefConSessionLimit); - } if (CheckDefCon(defconCount, DEFCON_AKILL_NEW_CLIENTS)) { CHECK(Config.DefConAKILL); CHECK(Config.DefConAkillReason); } if (CheckDefCon(defconCount, DEFCON_FORCE_CHAN_MODES)) - { CHECK(Config.DefConChanModes); - } } } @@ -1776,13 +1888,13 @@ int read_config(int reload) if (!Config.LogChannel && LogChan) LogChan = false; - if (!retval) { - printf - ("\n*** Support resources: Read through the services.conf self-contained \n*** documentation. Read the documentation files found in the 'docs' \n*** folder. Visit our portal located at http://www.anope.org/. Join \n*** our support channel on /server irc.anope.org channel #anope.\n\n"); + if (!retval) + { + printf("\n*** Support resources: Read through the services.conf self-contained \n*** documentation. Read the documentation files found in the 'docs' \n" + "*** folder. Visit our portal located at http://www.anope.org/. Join \n*** our support channel on /server irc.anope.org channel #anope.\n\n"); } return retval; } - /*************************************************************************/ diff --git a/src/configreader.cpp b/src/configreader.cpp index 906e3df7f..fc9a7cb28 100644 --- a/src/configreader.cpp +++ b/src/configreader.cpp @@ -33,12 +33,12 @@ ConfigReader::ConfigReader(const std::string &filename) : data(new ConfigDataHas std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds) { /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */ - std::string result; + ci::string result; - if (!Config.ConfValue(*this->data, tag, name, default_value, index, result, allow_linefeeds)) + if (!Config.ConfValue(*this->data, ci::string(tag.c_str()), ci::string(name.c_str()), ci::string(default_value.c_str()), index, result, allow_linefeeds)) this->error = CONF_VALUE_NOT_FOUND; - return result; + return result.c_str(); } std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds) @@ -48,7 +48,7 @@ std::string ConfigReader::ReadValue(const std::string &tag, const std::string &n bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index) { - return Config.ConfValueBool(*this->data, tag, name, default_value, index); + return Config.ConfValueBool(*this->data, ci::string(tag.c_str()), ci::string(name.c_str()), ci::string(default_value.c_str()), index); } bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index) @@ -60,7 +60,7 @@ int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, c { int result; - if (!Config.ConfValueInteger(*this->data, tag, name, default_value, index, result)) + if (!Config.ConfValueInteger(*this->data, ci::string(tag.c_str()), ci::string(name.c_str()), ci::string(default_value.c_str()), index, result)) { this->error = CONF_VALUE_NOT_FOUND; return 0; @@ -99,7 +99,7 @@ int ConfigReader::Enumerate(const std::string &tag) int ConfigReader::EnumerateValues(const std::string &tag, int index) { - return Config.ConfVarEnum(*this->data, tag, index); + return Config.ConfVarEnum(*this->data, ci::string(tag.c_str()), index); } bool ConfigReader::Verify() diff --git a/src/core/cs_set_bantype.cpp b/src/core/cs_set_bantype.cpp index 985c6f1e6..fca1e6fdc 100644 --- a/src/core/cs_set_bantype.cpp +++ b/src/core/cs_set_bantype.cpp @@ -18,7 +18,7 @@ class CommandCSSetBanType : public Command { public: - CommandCSSetBanType(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetBanType(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_description.cpp b/src/core/cs_set_description.cpp index 44e6090bf..0900f4792 100644 --- a/src/core/cs_set_description.cpp +++ b/src/core/cs_set_description.cpp @@ -18,7 +18,7 @@ class CommandCSSetDescription : public Command { public: - CommandCSSetDescription(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetDescription(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } @@ -86,7 +86,7 @@ class CSSetDescription : public Module Command *c = FindCommand(ChanServ, "SET"); if (c) c->AddSubcommand(new CommandCSSetDescription("DESC")); - + c = FindCommand(ChanServ, "SASEt"); if (c) c->AddSubcommand(new CommandCSSASetDescription("DESC")); diff --git a/src/core/cs_set_email.cpp b/src/core/cs_set_email.cpp index d226a3b06..9923f6061 100644 --- a/src/core/cs_set_email.cpp +++ b/src/core/cs_set_email.cpp @@ -18,7 +18,7 @@ class CommandCSSetEMail : public Command { public: - CommandCSSetEMail(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 1, 2, cpermission) + CommandCSSetEMail(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 1, 2, cpermission) { } diff --git a/src/core/cs_set_entrymsg.cpp b/src/core/cs_set_entrymsg.cpp index b7c223546..321f00f73 100644 --- a/src/core/cs_set_entrymsg.cpp +++ b/src/core/cs_set_entrymsg.cpp @@ -18,7 +18,7 @@ class CommandCSSetEntryMsg : public Command { public: - CommandCSSetEntryMsg(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 1, 2, cpermission) + CommandCSSetEntryMsg(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 1, 2, cpermission) { } diff --git a/src/core/cs_set_founder.cpp b/src/core/cs_set_founder.cpp index 6a456a0f6..c1dbfb62f 100644 --- a/src/core/cs_set_founder.cpp +++ b/src/core/cs_set_founder.cpp @@ -18,7 +18,7 @@ class CommandCSSetFounder : public Command { public: - CommandCSSetFounder(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetFounder(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } @@ -121,7 +121,7 @@ class CSSetFounder : public Module Command *c = FindCommand(ChanServ, "SET"); if (c) c->AddSubcommand(new CommandCSSetFounder("FOUNDER")); - + c = FindCommand(ChanServ, "SASET"); if (c) c->AddSubcommand(new CommandCSSASetFounder("FOUNDER")); diff --git a/src/core/cs_set_keeptopic.cpp b/src/core/cs_set_keeptopic.cpp index 87a4660cf..819d3e9c8 100644 --- a/src/core/cs_set_keeptopic.cpp +++ b/src/core/cs_set_keeptopic.cpp @@ -18,7 +18,7 @@ class CommandCSSetKeepTopic : public Command { public: - CommandCSSetKeepTopic(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetKeepTopic(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_mlock.cpp b/src/core/cs_set_mlock.cpp index d75363ac4..87d55790a 100644 --- a/src/core/cs_set_mlock.cpp +++ b/src/core/cs_set_mlock.cpp @@ -18,7 +18,7 @@ class CommandCSSetMLock : public Command { public: - CommandCSSetMLock(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 1, 0, cpermission) + CommandCSSetMLock(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 1, 0, cpermission) { } diff --git a/src/core/cs_set_opnotice.cpp b/src/core/cs_set_opnotice.cpp index b889869bd..3c4950d6f 100644 --- a/src/core/cs_set_opnotice.cpp +++ b/src/core/cs_set_opnotice.cpp @@ -18,7 +18,7 @@ class CommandCSSetOpNotice : public Command { public: - CommandCSSetOpNotice(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetOpNotice(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } @@ -91,7 +91,7 @@ class CSSetOpNotice : public Module Command *c = FindCommand(ChanServ, "SET"); if (c) c->AddSubcommand(new CommandCSSetOpNotice("OPNOTICE")); - + c = FindCommand(ChanServ, "SASET"); if (c) c->AddSubcommand(new CommandCSSASetOpNotice("OPNOTICE")); diff --git a/src/core/cs_set_peace.cpp b/src/core/cs_set_peace.cpp index 05cf5f863..613dad6fd 100644 --- a/src/core/cs_set_peace.cpp +++ b/src/core/cs_set_peace.cpp @@ -18,7 +18,7 @@ class CommandCSSetPeace : public Command { public: - CommandCSSetPeace(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetPeace(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_persist.cpp b/src/core/cs_set_persist.cpp index 0e713c715..592e54485 100644 --- a/src/core/cs_set_persist.cpp +++ b/src/core/cs_set_persist.cpp @@ -18,7 +18,7 @@ class CommandCSSetPersist : public Command { public: - CommandCSSetPersist(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetPersist(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } @@ -79,7 +79,7 @@ class CommandCSSetPersist : public Command if (!cm && !Config.s_BotServ && ci->bi) { /* Unassign bot */ - ChanServ->UnAssign(NULL, ci); + ChanServ->UnAssign(NULL, ci); } if (ci->c && ci->c->users.empty()) @@ -142,7 +142,7 @@ class CSSetPersist : public Module Command *c = FindCommand(ChanServ, "SET"); if (c) c->AddSubcommand(new CommandCSSetPersist("PERSIST")); - + c = FindCommand(ChanServ, "SASET"); if (c) c->AddSubcommand(new CommandCSSASetPersist("PERSIST")); diff --git a/src/core/cs_set_private.cpp b/src/core/cs_set_private.cpp index 9f96828df..53e482000 100644 --- a/src/core/cs_set_private.cpp +++ b/src/core/cs_set_private.cpp @@ -18,7 +18,7 @@ class CommandCSSetPrivate : public Command { public: - CommandCSSetPrivate(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetPrivate(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_restricted.cpp b/src/core/cs_set_restricted.cpp index 7e0cc42b3..8fe4c244e 100644 --- a/src/core/cs_set_restricted.cpp +++ b/src/core/cs_set_restricted.cpp @@ -18,7 +18,7 @@ class CommandCSSetRestricted : public Command { public: - CommandCSSetRestricted(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetRestricted(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_secure.cpp b/src/core/cs_set_secure.cpp index bdcffdb21..4c70a43de 100644 --- a/src/core/cs_set_secure.cpp +++ b/src/core/cs_set_secure.cpp @@ -18,7 +18,7 @@ class CommandCSSetSecure : public Command { public: - CommandCSSetSecure(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetSecure(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_securefounder.cpp b/src/core/cs_set_securefounder.cpp index 9d4a99d20..c999dffd1 100644 --- a/src/core/cs_set_securefounder.cpp +++ b/src/core/cs_set_securefounder.cpp @@ -18,7 +18,7 @@ class CommandCSSetSecureFounder : public Command { public: - CommandCSSetSecureFounder(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetSecureFounder(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_secureops.cpp b/src/core/cs_set_secureops.cpp index dc510f71a..88deb7a90 100644 --- a/src/core/cs_set_secureops.cpp +++ b/src/core/cs_set_secureops.cpp @@ -18,7 +18,7 @@ class CommandCSSetSecureOps : public Command { public: - CommandCSSetSecureOps(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetSecureOps(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } @@ -91,7 +91,7 @@ class CSSetSecureOps : public Module Command *c = FindCommand(ChanServ, "SET"); if (c) c->AddSubcommand(new CommandCSSetSecureOps("SECUREOPS")); - + c = FindCommand(ChanServ, "SASET"); if (c) c->AddSubcommand(new CommandCSSASetSecureOps("SECUREOPS")); diff --git a/src/core/cs_set_signkick.cpp b/src/core/cs_set_signkick.cpp index 2e24f8d38..a54548b1f 100644 --- a/src/core/cs_set_signkick.cpp +++ b/src/core/cs_set_signkick.cpp @@ -18,7 +18,7 @@ class CommandCSSetSignKick : public Command { public: - CommandCSSetSignKick(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetSignKick(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_successor.cpp b/src/core/cs_set_successor.cpp index 3de30631a..30b9060ba 100644 --- a/src/core/cs_set_successor.cpp +++ b/src/core/cs_set_successor.cpp @@ -18,7 +18,7 @@ class CommandCSSetSuccessor : public Command { public: - CommandCSSetSuccessor(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 1, 2, cpermission) + CommandCSSetSuccessor(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 1, 2, cpermission) { } diff --git a/src/core/cs_set_topiclock.cpp b/src/core/cs_set_topiclock.cpp index 14934f551..4edea3961 100644 --- a/src/core/cs_set_topiclock.cpp +++ b/src/core/cs_set_topiclock.cpp @@ -18,7 +18,7 @@ class CommandCSSetTopicLock : public Command { public: - CommandCSSetTopicLock(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetTopicLock(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } diff --git a/src/core/cs_set_url.cpp b/src/core/cs_set_url.cpp index 06c49da4f..241c0645b 100644 --- a/src/core/cs_set_url.cpp +++ b/src/core/cs_set_url.cpp @@ -18,7 +18,7 @@ class CommandCSSetURL : public Command { public: - CommandCSSetURL(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 1, 2, cpermission) + CommandCSSetURL(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 1, 2, cpermission) { } diff --git a/src/core/cs_set_xop.cpp b/src/core/cs_set_xop.cpp index 398cf4c1b..648eefba1 100644 --- a/src/core/cs_set_xop.cpp +++ b/src/core/cs_set_xop.cpp @@ -20,7 +20,7 @@ class CommandCSSetXOP : public Command { public: - CommandCSSetXOP(const ci::string &cname, const std::string &cpermission = "") : Command(cname, 2, 2, cpermission) + CommandCSSetXOP(const ci::string &cname, const ci::string &cpermission = "") : Command(cname, 2, 2, cpermission) { } @@ -54,7 +54,7 @@ class CommandCSSetXOP : public Command access->level = ACCESS_SOP; else if (CHECKLEV(CA_AUTOOP) || CHECKLEV(CA_OPDEOP) || CHECKLEV(CA_OPDEOPME)) access->level = ACCESS_AOP; - else if (ModeManager::FindChannelModeByName(CMODE_HALFOP) && (CHECKLEV(CA_AUTOHALFOP) || CHECKLEV(CA_HALFOP) + else if (ModeManager::FindChannelModeByName(CMODE_HALFOP) && (CHECKLEV(CA_AUTOHALFOP) || CHECKLEV(CA_HALFOP) || CHECKLEV(CA_HALFOPME))) access->level = ACCESS_HOP; else if (CHECKLEV(CA_AUTOVOICE) || CHECKLEV(CA_VOICE) || CHECKLEV(CA_VOICEME)) diff --git a/src/core/enc_md5.cpp b/src/core/enc_md5.cpp index 1c46ca72b..5ec245a7b 100644 --- a/src/core/enc_md5.cpp +++ b/src/core/enc_md5.cpp @@ -382,10 +382,10 @@ class EMD5 : public Module this->OnEncrypt(plaintext, buf); if (!password.compare(buf)) { - /* if we are NOT the first module in the list, + /* if we are NOT the first module in the list, * we want to re-encrypt the pass with the new encryption */ - if (Config.EncModuleList.front().compare(this->name)) + if (Config.EncModuleList.front() == this->name) { enc_encrypt(plaintext, password); } diff --git a/src/core/enc_none.cpp b/src/core/enc_none.cpp index 280c86bd2..c89db82ae 100644 --- a/src/core/enc_none.cpp +++ b/src/core/enc_none.cpp @@ -53,7 +53,7 @@ class ENone : public Module return EVENT_ALLOW; } - EventReturn OnCheckPassword(const std::string &hashm, std::string &plaintext, std::string &password) + EventReturn OnCheckPassword(const std::string &hashm, std::string &plaintext, std::string &password) { if (hashm != "plain") return EVENT_CONTINUE; @@ -61,10 +61,10 @@ class ENone : public Module this->OnEncrypt(plaintext, buf); if(!password.compare(buf)) { - /* if we are NOT the first module in the list, + /* if we are NOT the first module in the list, * we want to re-encrypt the pass with the new encryption */ - if (Config.EncModuleList.front().compare(this->name)) + if (Config.EncModuleList.front() == this->name) { enc_encrypt(plaintext, password); } diff --git a/src/core/enc_old.cpp b/src/core/enc_old.cpp index 68eece13c..307e42316 100644 --- a/src/core/enc_old.cpp +++ b/src/core/enc_old.cpp @@ -385,10 +385,10 @@ class EOld : public Module this->OnEncrypt(plaintext, buf); if (!password.compare(buf)) { - /* if we are NOT the first module in the list, + /* if we are NOT the first module in the list, * we want to re-encrypt the pass with the new encryption */ - if (Config.EncModuleList.front().compare(this->name)) + if (Config.EncModuleList.front() == this->name) { enc_encrypt(plaintext, password); } diff --git a/src/core/enc_sha1.cpp b/src/core/enc_sha1.cpp index b4ac2a4e2..82c3f97a1 100644 --- a/src/core/enc_sha1.cpp +++ b/src/core/enc_sha1.cpp @@ -239,10 +239,10 @@ class ESHA1 : public Module this->OnEncrypt(plaintext, buf); if (!password.compare(buf)) { - /* when we are NOT the first module in the list, + /* when we are NOT the first module in the list, * we want to re-encrypt the pass with the new encryption */ - if (Config.EncModuleList.front().compare(this->name)) + if (Config.EncModuleList.front() == this->name) { enc_encrypt(plaintext, password); } diff --git a/src/core/enc_sha256.cpp b/src/core/enc_sha256.cpp index ef1ed7a00..7d29b43d2 100644 --- a/src/core/enc_sha256.cpp +++ b/src/core/enc_sha256.cpp @@ -156,7 +156,7 @@ class ESHA256 : public Module return buf2; } - /* splits the appended IV from the password string so it can be used for the next encryption */ + /* splits the appended IV from the password string so it can be used for the next encryption */ /* password format: <hashmethod>:<password_b64>:<iv_b64> */ void GetIVFromPass(std::string &password) { @@ -302,7 +302,7 @@ class ESHA256 : public Module Alog(LOG_DEBUG_2) << "(enc_sha256) hashed password from [" << src << "] to [" << buf.str() << " ]"; dest.assign(buf.str()); return EVENT_ALLOW; - + } EventReturn OnEncryptInPlace(std::string &buf) @@ -310,14 +310,14 @@ class ESHA256 : public Module return this->OnEncrypt(buf, buf); } - EventReturn OnDecrypt(const std::string &hashm, std::string &src, std::string &dest) + EventReturn OnDecrypt(const std::string &hashm, std::string &src, std::string &dest) { if (hashm != "sha256") return EVENT_CONTINUE; return EVENT_STOP; } - EventReturn OnCheckPassword(const std::string &hashm, std::string &plaintext, std::string &password) + EventReturn OnCheckPassword(const std::string &hashm, std::string &plaintext, std::string &password) { if (hashm != "sha256") return EVENT_CONTINUE; @@ -329,10 +329,10 @@ class ESHA256 : public Module if(!password.compare(buf)) { - /* if we are NOT the first module in the list, + /* if we are NOT the first module in the list, * we want to re-encrypt the pass with the new encryption */ - if (Config.EncModuleList.front().compare(this->name)) + if (Config.EncModuleList.front() == this->name) { enc_encrypt(plaintext, password ); } diff --git a/src/core/ns_group.cpp b/src/core/ns_group.cpp index ffb94296b..cc5da7860 100644 --- a/src/core/ns_group.cpp +++ b/src/core/ns_group.cpp @@ -27,7 +27,7 @@ class CommandNSGroup : public Command NickAlias *na, *target; const char *nick = params[0].c_str(); std::string pass = params[1].c_str(); - std::list<std::pair<std::string, std::string> >::iterator it; + std::list<std::pair<ci::string, ci::string> >::iterator it; if (Config.NSEmailReg && findrequestnick(u->nick)) { @@ -51,7 +51,7 @@ class CommandNSGroup : public Command { for (it = Config.Opers.begin(); it != Config.Opers.end(); ++it) { - if (!is_oper(u) && u->nick.find(it->first) != std::string::npos) + if (!is_oper(u) && u->nick.find(it->first.c_str()) != std::string::npos) { notice_lang(Config.s_NickServ, u, NICK_CANNOT_BE_REGISTERED, u->nick.c_str()); return MOD_CONT; @@ -183,7 +183,7 @@ class CommandNSUngroup : public Command { oldcore->aliases.erase(it); } - + if (!stricmp(oldcore->display, na->nick)) { change_core_display(oldcore); @@ -255,7 +255,7 @@ class CommandNSGList : public Command for (std::list<NickAlias *>::iterator it = nc->aliases.begin(); it != nc->aliases.end(); ++it) { NickAlias *na2 = *it; - + if (!(wont_expire = na2->HasFlag(NS_NO_EXPIRE))) { expt = na2->last_seen + Config.NSExpire; diff --git a/src/core/ns_register.cpp b/src/core/ns_register.cpp index f8bf1691f..26b8976b1 100644 --- a/src/core/ns_register.cpp +++ b/src/core/ns_register.cpp @@ -85,7 +85,7 @@ class CommandNSConfirm : public Command validate_user(user); } } - + FOREACH_MOD(I_OnNickRegister, OnNickRegister(na)); return MOD_CONT; @@ -196,7 +196,7 @@ class CommandNSRegister : public CommandNSConfirm 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; - std::list<std::pair<std::string, std::string> >::iterator it; + std::list<std::pair<ci::string, ci::string> >::iterator it; if (readonly) { @@ -237,7 +237,7 @@ class CommandNSRegister : public CommandNSConfirm { for (it = Config.Opers.begin(); it != Config.Opers.end(); ++it) { - std::string nick = it->first; + ci::string nick = it->first; if (stristr(u->nick.c_str(), nick.c_str()) && !is_oper(u)) { diff --git a/src/core/os_staff.cpp b/src/core/os_staff.cpp index 930f8db7b..842791187 100644 --- a/src/core/os_staff.cpp +++ b/src/core/os_staff.cpp @@ -25,10 +25,10 @@ class CommandOSStaff : public Command { notice_lang(Config.s_OperServ, u, OPER_STAFF_LIST_HEADER); - for (std::list<std::pair<std::string, std::string> >::iterator it = Config.Opers.begin(); it != Config.Opers.end(); ++it) + for (std::list<std::pair<ci::string, ci::string> >::iterator it = Config.Opers.begin(); it != Config.Opers.end(); ++it) { int found = 0; - std::string nick = it->first, type = it->second; + ci::string nick = it->first, type = it->second; NickAlias *na = findnick(nick); if (na) diff --git a/src/encrypt.cpp b/src/encrypt.cpp index 4f76ee895..1910c00f9 100644 --- a/src/encrypt.cpp +++ b/src/encrypt.cpp @@ -6,9 +6,7 @@ * 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. - * - * + * Based on the original code of Services by Andy Church. */ #include "services.h" @@ -16,7 +14,7 @@ /******************************************************************************/ -/** +/** * Encrypt string `src' of length `len', placing the result in buffer * `dest' of size `size'. Returns 0 on success, -1 on error. **/ @@ -39,7 +37,7 @@ int enc_encrypt_in_place(std::string &buf) EventReturn MOD_RESULT; FOREACH_RESULT(I_OnEncryptInPlace, OnEncryptInPlace(buf)); if (MOD_RESULT == EVENT_ALLOW) - return 0; + return 0; return -1; } @@ -54,15 +52,15 @@ int enc_decrypt(const std::string &src, std::string &dest) size_t pos = src.find(":"); if (pos == std::string::npos) { - Alog() << "Error: enc_decrypt() called with invalid password string (" << src << ")"; + Alog() << "Error: enc_decrypt() called with invalid password string (" << src << ")"; return -1; } - std::string hashm(src.begin(), src.begin()+pos); + std::string hashm(src.begin(), src.begin() + pos); EventReturn MOD_RESULT; FOREACH_RESULT(I_OnDecrypt, OnDecrypt(hashm, src, dest)); if (MOD_RESULT == EVENT_ALLOW) - return 1; + return 1; return -1; } @@ -82,13 +80,11 @@ int enc_check_password(std::string &plaintext, std::string &password) Alog() << "Error: enc_check_password() called with invalid password string (" << password << ")"; return 0; } - hashm.assign(password.begin(), password.begin()+pos); + hashm.assign(password.begin(), password.begin() + pos); EventReturn MOD_RESULT; FOREACH_RESULT(I_OnCheckPassword, OnCheckPassword(hashm, plaintext, password)); if (MOD_RESULT == EVENT_ALLOW) - return 1; + return 1; return 0; } - -/* EOF */ diff --git a/src/hashcomp.cpp b/src/hashcomp.cpp index 462064235..3afef7b46 100644 --- a/src/hashcomp.cpp +++ b/src/hashcomp.cpp @@ -6,8 +6,6 @@ * * These classes have been copied from InspIRCd and modified * for use in Anope. - * - * */ #include "services.h" @@ -175,7 +173,7 @@ size_t hash_compare_std_string::operator()(const std::string &s) const for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) t = 5 * t + static_cast<const unsigned char>(*it); - + return t; } @@ -189,7 +187,7 @@ size_t hash_compare_ci_string::operator()(const ci::string &s) const for (ci::string::const_iterator it = s.begin(); it != s.end(); ++it) t = 5 * t + ascii_case_insensitive_map[static_cast<const unsigned char>(*it)]; - + return t; } @@ -203,7 +201,6 @@ size_t hash_compare_irc_string::operator()(const irc::string &s) const for (irc::string::const_iterator it = s.begin(); it != s.end(); ++it) t = 5 * t + rfc_case_insensitive_map[static_cast<const unsigned char>(*it)]; - + return t; } - diff --git a/src/hostserv.cpp b/src/hostserv.cpp index 8cce7783f..f59ac8c6e 100644 --- a/src/hostserv.cpp +++ b/src/hostserv.cpp @@ -7,16 +7,13 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" #include "modules.h" #include "language.h" -E int do_hs_sync(NickCore * nc, char *vIdent, char *hostmask, - char *creator, time_t time); +E int do_hs_sync(NickCore *nc, char *vIdent, char *hostmask, char *creator, time_t time); E void moduleAddHostServCmds(); @@ -38,7 +35,7 @@ void get_hostserv_stats(long *nrec, long *memuse) { long count = 0, mem = 0; - for (nickalias_map::const_iterator it = NickAliasList.begin(); it != NickAliasList.end(); ++it) + for (nickalias_map::const_iterator it = NickAliasList.begin(), it_end = NickAliasList.end(); it != it_end; ++it) { NickAlias *na = it->second; @@ -66,9 +63,8 @@ void get_hostserv_stats(long *nrec, long *memuse) */ void hostserv_init() { - if (Config.s_HostServ) { + if (Config.s_HostServ) moduleAddHostServCmds(); - } } /*************************************************************************/ @@ -83,7 +79,7 @@ void hostserv(User *u, const std::string &buf) { if (!u || buf.empty()) return; - + if (buf.find("\1PING ", 0, 6) != std::string::npos && buf[buf.length() - 1] == '\1') { std::string command = buf; @@ -92,13 +88,9 @@ void hostserv(User *u, const std::string &buf) ircdproto->SendCTCP(HostServ, u->nick.c_str(), "%s", command.c_str()); } else if (!ircd->vhost) - { notice_lang(Config.s_HostServ, u, SERVICE_OFFLINE, Config.s_HostServ); - } else - { mod_run_cmd(HostServ, u, buf); - } } /** Set a vhost for the user @@ -166,7 +158,7 @@ const time_t HostInfo::GetTime() const } /*************************************************************************/ -/* Start of Generic Functions */ +/* Start of Generic Functions */ /*************************************************************************/ /** Sync all vhosts in a group to the same thing @@ -177,7 +169,7 @@ void HostServSyncVhosts(NickAlias *na) if (!na || !na->hostinfo.HasVhost()) return; - for (std::list<NickAlias *>::iterator it = na->nc->aliases.begin(); it != na->nc->aliases.end(); ++it) + for (std::list<NickAlias *>::iterator it = na->nc->aliases.begin(), it_end = na->nc->aliases.end(); it != it_end; ++it) { NickAlias *nick = *it; nick->hostinfo.SetVhost(na->hostinfo.GetIdent(), na->hostinfo.GetHost(), na->hostinfo.GetCreator()); @@ -204,9 +196,7 @@ void do_on_id(User *u) u->vhost = sstrdup(na->hostinfo.GetHost().c_str()); } if (ircd->vident && !na->hostinfo.GetIdent().empty()) - { u->SetVIdent(na->hostinfo.GetIdent()); - } u->UpdateHost(); if (!na->hostinfo.GetIdent().empty()) @@ -215,5 +205,3 @@ void do_on_id(User *u) notice_lang(Config.s_HostServ, u, HOST_ACTIVATED, na->hostinfo.GetHost().c_str()); } } - - diff --git a/src/init.cpp b/src/init.cpp index 5bc9f01d1..fc5b61a03 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -23,7 +21,6 @@ extern void moduleAddIRCDMsgs(); void introduce_user(const std::string &user) { - /* Watch out for infinite loops... */ #define LTSIZE 20 static int lasttimes[LTSIZE]; @@ -35,10 +32,10 @@ void introduce_user(const std::string &user) /* We make the bots go online */ /* XXX: it might be nice to have this inside BotInfo's constructor, or something? */ - for (botinfo_map::const_iterator it = BotListByNick.begin(); it != BotListByNick.end(); ++it) + for (botinfo_map::const_iterator it = BotListByNick.begin(), it_end = BotListByNick.end(); it != it_end; ++it) { BotInfo *bi = it->second; - + ci::string ci_bi_nick(bi->nick.c_str()); if (user.empty() || ci_bi_nick == user) { @@ -61,15 +58,19 @@ static int set_group() struct group *gr; setgrent(); - while ((gr = getgrent()) != NULL) { - if (strcmp(gr->gr_name, RUNGROUP) == 0) + while ((gr = getgrent()) != NULL) + { + if (!strcmp(gr->gr_name, RUNGROUP)) break; } endgrent(); - if (gr) { + if (gr) + { setgid(gr->gr_gid); return 0; - } else { + } + else + { Alog() << "Unknown group `" << RUNGROUP << "'"; return -1; } @@ -130,8 +131,8 @@ bool GetCommandLineArgument(const std::string &name, char shortname) bool GetCommandLineArgument(const std::string &name, char shortname, std::string ¶m) { param.clear(); - - for (std::vector<std::pair<std::string, std::string> >::iterator it = CommandLineArguments.begin(); it != CommandLineArguments.end(); ++it) + + for (std::vector<std::pair<std::string, std::string> >::iterator it = CommandLineArguments.begin(), it_end = CommandLineArguments.end(); it != it_end; ++it) { if (it->first == name || it->first[0] == shortname) { @@ -161,7 +162,8 @@ static void write_pidfile() FILE *pidfile; pidfile = fopen(Config.PIDFilename, "w"); - if (pidfile) { + if (pidfile) + { #ifdef _WIN32 fprintf(pidfile, "%d\n", static_cast<int>(GetCurrentProcessId())); #else @@ -169,9 +171,9 @@ static void write_pidfile() #endif fclose(pidfile); atexit(remove_pidfile); - } else { - log_perror("Warning: cannot write to PID file %s", Config.PIDFilename); } + else + log_perror("Warning: cannot write to PID file %s", Config.PIDFilename); } /*************************************************************************/ @@ -224,9 +226,7 @@ int init_primary(int ac, char **av) } if (GetCommandLineArgument("nofork", 'n')) - { nofork = 1; - } if (GetCommandLineArgument("support", 's')) { @@ -235,24 +235,16 @@ int init_primary(int ac, char **av) } if (GetCommandLineArgument("readonly", 'r')) - { readonly = 1; - } if (GetCommandLineArgument("nothird")) - { nothird = 1; - } if (GetCommandLineArgument("noexpire", 'e')) - { noexpire = 1; - } if (GetCommandLineArgument("protocoldebug")) - { protocoldebug = 1; - } std::string Arg; if (GetCommandLineArgument("debug", 'd', Arg)) @@ -279,7 +271,7 @@ int init_primary(int ac, char **av) Alog(LOG_TERMINAL) << "The --config option requires a file name"; return -1; } - services_conf = Arg; + services_conf = Arg.c_str(); } if (GetCommandLineArgument("dir", 0, Arg)) @@ -303,26 +295,25 @@ int init_primary(int ac, char **av) } /* Chdir to Services data directory. */ - if (chdir(services_dir.c_str()) < 0) { + if (chdir(services_dir.c_str()) < 0) + { fprintf(stderr, "chdir(%s): %s\n", services_dir.c_str(), strerror(errno)); return -1; } /* Open logfile, and complain if we didn't. */ - if (open_log() < 0) { + if (open_log() < 0) + { openlog_errno = errno; - if (started_from_term) { - fprintf(stderr, "Warning: unable to open log file %s: %s\n", - log_filename.c_str(), strerror(errno)); - } else { + if (started_from_term) + fprintf(stderr, "Warning: unable to open log file %s: %s\n", log_filename.c_str(), strerror(errno)); + else openlog_failed = 1; - } } /* Read configuration file; exit if there are problems. */ - if (!read_config(0)) { + if (!read_config(0)) return -1; - } /* Add IRCD Protocol Module; exit if there are errors */ if (protocol_module_init()) @@ -377,26 +368,31 @@ int init_secondary(int ac, char **av) if (!nofork) { int i; - if ((i = fork()) < 0) { + if ((i = fork()) < 0) + { perror("fork()"); return -1; - } else if (i != 0) { + } + else if (i != 0) + { Alog(LOG_TERMINAL) << "PID " << i; exit(0); } - if (started_from_term) { + if (started_from_term) + { close(0); close(1); close(2); } - if (setpgid(0, 0) < 0) { + if (setpgid(0, 0) < 0) + { perror("setpgid()"); return -1; } } #else - if (!SupportedWindowsVersion()) { - + if (!SupportedWindowsVersion()) + { char *winver = GetWindowsVersion(); Alog() << winver << " is not a supported version of Windows"; @@ -404,9 +400,9 @@ int init_secondary(int ac, char **av) delete [] winver; return -1; - } - if (!nofork) { + if (!nofork) + { Alog(LOG_TERMINAL) << "PID " << GetCurrentProcessId(); Alog() << "Launching Anope into the background"; FreeConsole(); @@ -417,13 +413,9 @@ int init_secondary(int ac, char **av) write_pidfile(); /* Announce ourselves to the logfile. */ - Alog() << "Anope " << version_number << " (ircd protocol: " << version_protocol << ") starting up" - << (debug || readonly ? " (options:" : "") << (debug ? " debug" : "") - << (readonly ? " readonly" : "") << (debug || readonly ? ")" : ""); + Alog() << "Anope " << version_number << " (ircd protocol: " << version_protocol << ") starting up" << (debug || readonly ? " (options:" : "") << (debug ? " debug" : "") << (readonly ? " readonly" : "") << (debug || readonly ? ")" : ""); start_time = time(NULL); - - /* If in read-only mode, close the logfile again. */ if (readonly) close_log(); @@ -441,7 +433,6 @@ int init_secondary(int ac, char **av) lang_init(); Alog(LOG_DEBUG) << "Loaded languages"; - /* Initialize subservices */ ns_init(); cs_init(); diff --git a/src/ircd.cpp b/src/ircd.cpp index 70d961d81..c06237a1b 100644 --- a/src/ircd.cpp +++ b/src/ircd.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -32,7 +30,8 @@ void anope_SendNumeric(const char *source, int numeric, const char *dest, const { va_list args; char buf[BUFSIZE] = ""; - if (fmt) { + if (fmt) + { va_start(args, fmt); vsnprintf(buf, BUFSIZE - 1, fmt, args); va_end(args); @@ -43,7 +42,7 @@ void anope_SendNumeric(const char *source, int numeric, const char *dest, const /** * Set routines for modules to set the prefered function for dealing with things. **/ -void pmodule_ircd_var(IRCDVar * ircdvar) +void pmodule_ircd_var(IRCDVar *ircdvar) { ircd = ircdvar; } diff --git a/src/language.cpp b/src/language.cpp index 3f5c900e9..473df39e8 100644 --- a/src/language.cpp +++ b/src/language.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -27,29 +25,29 @@ int langlist[NUM_LANGS]; /* Order in which languages should be displayed: (alphabetical) */ static int langorder[NUM_LANGS] = { - LANG_EN_US, /* English (US) */ - LANG_FR, /* French */ - LANG_DE, /* German */ - LANG_IT, /* Italian */ - LANG_JA_JIS, /* Japanese (JIS encoding) */ - LANG_JA_EUC, /* Japanese (EUC encoding) */ - LANG_JA_SJIS, /* Japanese (SJIS encoding) */ - LANG_PT, /* Portugese */ - LANG_ES, /* Spanish */ - LANG_TR, /* Turkish */ - LANG_CAT, /* Catalan */ - LANG_GR, /* Greek */ - LANG_NL, /* Dutch */ - LANG_RU, /* Russian */ - LANG_HUN, /* Hungarian */ - LANG_PL, /* Polish */ + LANG_EN_US, /* English (US) */ + LANG_FR, /* French */ + LANG_DE, /* German */ + LANG_IT, /* Italian */ + LANG_JA_JIS, /* Japanese (JIS encoding) */ + LANG_JA_EUC, /* Japanese (EUC encoding) */ + LANG_JA_SJIS, /* Japanese (SJIS encoding) */ + LANG_PT, /* Portugese */ + LANG_ES, /* Spanish */ + LANG_TR, /* Turkish */ + LANG_CAT, /* Catalan */ + LANG_GR, /* Greek */ + LANG_NL, /* Dutch */ + LANG_RU, /* Russian */ + LANG_HUN, /* Hungarian */ + LANG_PL, /* Polish */ }; /*************************************************************************/ /* Load a language file. */ -static int read_int32(int32 * ptr, FILE * f) +static int read_int32(int32 *ptr, FILE *f) { int a = fgetc(f); int b = fgetc(f); @@ -70,28 +68,33 @@ static void load_lang(int index, const char *filename) Alog(LOG_DEBUG) << "Loading language " << index << " from file `languages/" << filename << "'"; snprintf(buf, sizeof(buf), "languages/%s", filename); #ifndef _WIN32 - if (!(f = fopen(buf, "r"))) { + const char *mode = "r"; #else - if (!(f = fopen(buf, "rb"))) { + const char *mode = "rb"; #endif + if (!(f = fopen(buf, mode))) + { log_perror("Failed to load language %d (%s)", index, filename); return; - } else if (read_int32(&num, f) < 0) { + } + else if (read_int32(&num, f) < 0) + { Alog() << "Failed to read number of strings for language " << index << "(" << filename << ")"; return; - } else if (num != NUM_STRINGS) { - Alog() << "Warning: Bad number of strings (" << num << " , wanted " << NUM_STRINGS << ") " - << "for language " << index << " (" << filename << ")"; } + else if (num != NUM_STRINGS) + Alog() << "Warning: Bad number of strings (" << num << " , wanted " << NUM_STRINGS << ") for language " << index << " (" << filename << ")"; langtexts[index] = new char *[NUM_STRINGS]; if (num > NUM_STRINGS) num = NUM_STRINGS; - for (i = 0; i < num; i++) { + for (i = 0; i < num; ++i) + { int32 pos, len; fseek(f, i * 8 + 4, SEEK_SET); - if (read_int32(&pos, f) < 0 || read_int32(&len, f) < 0) { + if (read_int32(&pos, f) < 0 || read_int32(&len, f) < 0) + { Alog() << "Failed to read entry " << i << " in language " << index << " (" << filename << ") TOC"; - while (--i >= 0) + while (--i >= 0) { if (langtexts[index][i]) delete [] langtexts[index][i]; @@ -100,32 +103,41 @@ static void load_lang(int index, const char *filename) langtexts[index] = NULL; return; } - if (len == 0) { + if (!len) langtexts[index][i] = NULL; - } else if (len >= 65536) { + else if (len >= 65536) + { Alog() << "Entry " << i << " in language " << index << " (" << filename << ") is too long (over 64k) -- corrupt TOC?"; - while (--i >= 0) { + while (--i >= 0) + { if (langtexts[index][i]) delete [] langtexts[index][i]; } delete [] langtexts[index]; langtexts[index] = NULL; return; - } else if (len < 0) { + } + else if (len < 0) + { Alog() << "Entry " << i << " in language " << index << " (" << filename << ") has negative length -- corrupt TOC?"; - while (--i >= 0) { + while (--i >= 0) + { if (langtexts[index][i]) delete [] langtexts[index][i]; } delete [] langtexts[index]; langtexts[index] = NULL; return; - } else { + } + else + { langtexts[index][i] = new char[len + 1]; fseek(f, pos, SEEK_SET); - if (fread(langtexts[index][i], 1, len, f) != len) { + if (fread(langtexts[index][i], 1, len, f) != len) + { Alog() << "Failed to read string " << i << " in language " << index << "(" << filename << ")"; - while (--i >= 0) { + while (--i >= 0) + { if (langtexts[index][i]) delete [] langtexts[index][i]; } @@ -148,16 +160,18 @@ void lang_sanitize() int len = 0; char tmp[2000]; char *newstr = NULL; - for (i = 0; i < NUM_LANGS; i++) { - for (j = 0; j < NUM_STRINGS; j++) { - if (strstr(langtexts[i][j], "%R")) { + for (i = 0; i < NUM_LANGS; ++i) + { + for (j = 0; j < NUM_STRINGS; ++j) + { + if (strstr(langtexts[i][j], "%R")) + { len = strlen(langtexts[i][j]); strscpy(tmp, langtexts[i][j], sizeof(tmp)); - if (Config.UseStrictPrivMsg) { + if (Config.UseStrictPrivMsg) strnrepl(tmp, sizeof(tmp), "%R", "/"); - } else { + else strnrepl(tmp, sizeof(tmp), "%R", "/msg "); - } newstr = sstrdup(tmp); delete [] langtexts[i][j]; langtexts[i][j] = newstr; @@ -187,18 +201,18 @@ void lang_init() load_lang(LANG_HUN, "hun"); load_lang(LANG_PL, "pl"); - for (i = 0; i < NUM_LANGS; i++) { - if (langtexts[langorder[i]] != NULL) { + for (i = 0; i < NUM_LANGS; ++i) + { + if (langtexts[langorder[i]] != NULL) + { langnames[langorder[i]] = langtexts[langorder[i]][LANG_NAME]; langlist[n++] = langorder[i]; - for (j = 0; j < NUM_STRINGS; j++) { - if (!langtexts[langorder[i]][j]) { - langtexts[langorder[i]][j] = - langtexts[DEF_LANGUAGE][j]; - } - if (!langtexts[langorder[i]][j]) { + for (j = 0; j < NUM_STRINGS; ++j) + { + if (!langtexts[langorder[i]][j]) + langtexts[langorder[i]][j] = langtexts[DEF_LANGUAGE][j]; + if (!langtexts[langorder[i]][j]) langtexts[langorder[i]][j] = langtexts[LANG_EN_US][j]; - } } } } @@ -212,7 +226,8 @@ void lang_init() if (!langtexts[DEF_LANGUAGE]) fatal("Unable to load default language"); - for (i = 0; i < NUM_LANGS; i++) { + for (i = 0; i < NUM_LANGS; ++i) + { if (!langtexts[i]) langtexts[i] = langtexts[DEF_LANGUAGE]; } @@ -230,44 +245,47 @@ void lang_init() * greater than BUFSIZE. */ -int strftime_lang(char *buf, int size, User * u, int format, struct tm *tm) +int strftime_lang(char *buf, int size, User *u, int format, struct tm *tm) { int language = u && u->Account() ? u->Account()->language : Config.NSDefLanguage; char tmpbuf[BUFSIZE], buf2[BUFSIZE]; char *s; int i, ret; - if (!tm) { + if (!tm) return 0; - } strscpy(tmpbuf, langtexts[language][format], sizeof(tmpbuf)); - if ((s = langtexts[language][STRFTIME_DAYS_SHORT]) != NULL) { - for (i = 0; i < tm->tm_wday; i++) + if ((s = langtexts[language][STRFTIME_DAYS_SHORT])) + { + for (i = 0; i < tm->tm_wday; ++i) s += strcspn(s, "\n") + 1; i = strcspn(s, "\n"); strncpy(buf2, s, i); buf2[i] = 0; strnrepl(tmpbuf, sizeof(tmpbuf), "%a", buf2); } - if ((s = langtexts[language][STRFTIME_DAYS_LONG]) != NULL) { - for (i = 0; i < tm->tm_wday; i++) + if ((s = langtexts[language][STRFTIME_DAYS_LONG])) + { + for (i = 0; i < tm->tm_wday; ++i) s += strcspn(s, "\n") + 1; i = strcspn(s, "\n"); strncpy(buf2, s, i); buf2[i] = 0; strnrepl(tmpbuf, sizeof(tmpbuf), "%A", buf2); } - if ((s = langtexts[language][STRFTIME_MONTHS_SHORT]) != NULL) { - for (i = 0; i < tm->tm_mon; i++) + if ((s = langtexts[language][STRFTIME_MONTHS_SHORT])) + { + for (i = 0; i < tm->tm_mon; ++i) s += strcspn(s, "\n") + 1; i = strcspn(s, "\n"); strncpy(buf2, s, i); buf2[i] = 0; strnrepl(tmpbuf, sizeof(tmpbuf), "%b", buf2); } - if ((s = langtexts[language][STRFTIME_MONTHS_LONG]) != NULL) { - for (i = 0; i < tm->tm_mon; i++) + if ((s = langtexts[language][STRFTIME_MONTHS_LONG])) + { + for (i = 0; i < tm->tm_mon; ++i) s += strcspn(s, "\n") + 1; i = strcspn(s, "\n"); strncpy(buf2, s, i); @@ -285,13 +303,12 @@ int strftime_lang(char *buf, int size, User * u, int format, struct tm *tm) /* Send a syntax-error message to the user. */ -void syntax_error(char *service, User * u, const char *command, int msgnum) +void syntax_error(char *service, User *u, const char *command, int msgnum) { const char *str; - if (!u) { + if (!u) return; - } str = getstring(u, msgnum); notice_lang(service, u, SYNTAX_ERROR, str); @@ -316,9 +333,7 @@ const char *getstring(NickCore *nc, int index) int langidx = Config.NSDefLanguage; if (nc) - { langidx = nc->language; - } return langtexts[langidx][index]; } diff --git a/src/log.cpp b/src/log.cpp index bf5fd10fb..9ebdb4a6b 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -24,8 +22,8 @@ static int get_logname(char *name, int count, struct tm *tm) char timestamp[32]; time_t t; - - if (!tm) { + if (!tm) + { time(&t); tm = localtime(&t); } @@ -69,7 +67,8 @@ static void checkday() time(&t); tm = *localtime(&t); - if (curday != tm.tm_yday) { + if (curday != tm.tm_yday) + { close_log(); remove_log(); open_log(); @@ -121,21 +120,19 @@ char *log_gettimestamp() time(&t); tm = *localtime(&t); #if HAVE_GETTIMEOFDAY - if (debug) { + if (debug) + { char *s; struct timeval tv; gettimeofday(&tv, NULL); strftime(tbuf, sizeof(tbuf) - 1, "[%b %d %H:%M:%S", &tm); s = tbuf + strlen(tbuf); - s += snprintf(s, sizeof(tbuf) - (s - tbuf), ".%06d", - static_cast<int>(tv.tv_usec)); + s += snprintf(s, sizeof(tbuf) - (s - tbuf), ".%06d", static_cast<int>(tv.tv_usec)); strftime(s, sizeof(tbuf) - (s - tbuf) - 1, " %Y]", &tm); - } else { -#endif - strftime(tbuf, sizeof(tbuf) - 1, "[%b %d %H:%M:%S %Y]", &tm); -#if HAVE_GETTIMEOFDAY } + else #endif + strftime(tbuf, sizeof(tbuf) - 1, "[%b %d %H:%M:%S %Y]", &tm); return tbuf; } @@ -154,9 +151,8 @@ void log_perror(const char *fmt, ...) checkday(); - if (!fmt) { + if (!fmt) return; - } va_start(args, fmt); vsnprintf(str, sizeof(str), fmt, args); @@ -164,12 +160,10 @@ void log_perror(const char *fmt, ...) buf = log_gettimestamp(); - if (logfile) { + if (logfile) fprintf(logfile, "%s %s : %s\n", buf, str, strerror(errno_save)); - } - if (nofork) { + if (nofork) fprintf(stderr, "%s %s : %s\n", buf, str, strerror(errno_save)); - } errno = errno_save; } @@ -187,9 +181,8 @@ void fatal(const char *fmt, ...) checkday(); - if (!fmt) { + if (!fmt) return; - } va_start(args, fmt); vsnprintf(buf2, sizeof(buf2), fmt, args); @@ -223,9 +216,8 @@ void fatal_perror(const char *fmt, ...) checkday(); - if (!fmt) { + if (!fmt) return; - } va_start(args, fmt); vsnprintf(buf2, sizeof(buf2), fmt, args); @@ -234,14 +226,11 @@ void fatal_perror(const char *fmt, ...) buf = log_gettimestamp(); if (logfile) - fprintf(logfile, "%s FATAL: %s: %s\n", buf, buf2, - strerror(errno_save)); + fprintf(logfile, "%s FATAL: %s: %s\n", buf, buf2, strerror(errno_save)); if (nofork) - fprintf(stderr, "%s FATAL: %s: %s\n", buf, buf2, - strerror(errno_save)); + fprintf(stderr, "%s FATAL: %s: %s\n", buf, buf2, strerror(errno_save)); if (UplinkSock) - ircdproto->SendGlobops(NULL, "FATAL ERROR! %s: %s", buf2, - strerror(errno_save)); + ircdproto->SendGlobops(NULL, "FATAL ERROR! %s: %s", buf2, strerror(errno_save)); /* one of the many places this needs to be called from */ ModuleRunTimeDirCleanUp(); @@ -267,15 +256,13 @@ Alog::~Alog() tbuf = log_gettimestamp(); - if (logfile) { + if (logfile) fprintf(logfile, "%s %s\n", tbuf, buf.str().c_str()); - } if (nofork) std::cout << tbuf << " " << buf.str() << std::endl; else if (Level == LOG_TERMINAL) // XXX dont use this yet unless you know we're at terminal and not daemonized std::cout << buf.str() << std::endl; - if (Config.LogChannel && LogChan && !debug && findchan(Config.LogChannel)) { + if (Config.LogChannel && LogChan && !debug && findchan(Config.LogChannel)) ircdproto->SendPrivmsg(Global, Config.LogChannel, "%s", buf.str().c_str()); - } errno = errno_save; } diff --git a/src/mail.cpp b/src/mail.cpp index 9e1c60c6b..c7c8ebda7 100644 --- a/src/mail.cpp +++ b/src/mail.cpp @@ -14,9 +14,7 @@ void MailThread::Run() FILE *pipe = popen(Config.SendMailPath, "w"); if (!pipe) - { return; - } fprintf(pipe, "From: %s\n", Config.SendFrom); if (Config.DontQuoteAddresses) @@ -26,7 +24,7 @@ void MailThread::Run() fprintf(pipe, "Subject: %s\n", Subject.c_str()); fprintf(pipe, "%s", Message.c_str()); fprintf(pipe, "\n.\n"); - + pclose(pipe); Success = true; @@ -36,9 +34,9 @@ bool Mail(User *u, NickRequest *nr, const std::string &service, const std::strin { if (!u || !nr || subject.empty() || service.empty() || message.empty()) return false; - + time_t t = time(NULL); - + if (!Config.UseMail) notice_lang(service.c_str(), u, MAIL_DISABLED); else if (t - u->lastmail < Config.MailDelay) @@ -59,7 +57,7 @@ bool Mail(User *u, NickCore *nc, const std::string &service, const std::string & { if (!u || !nc || subject.empty() || service.empty() || message.empty()) return false; - + time_t t = time(NULL); if (!Config.UseMail) @@ -82,7 +80,7 @@ bool Mail(NickCore *nc, const std::string &subject, const std::string &message) { if (!Config.UseMail || !nc || !nc->email || subject.empty() || message.empty()) return false; - + nc->lastmail = time(NULL); threadEngine.Start(new MailThread(nc->display, nc->email, subject, message)); @@ -103,14 +101,12 @@ bool MailValidate(const std::string &email) bool has_period = false; char copy[BUFSIZE]; - static char specials[] = { - '(', ')', '<', '>', '@', ',', ';', ':', '\\', '\"', '[', ']', ' ' - }; + static char specials[] = {'(', ')', '<', '>', '@', ',', ';', ':', '\\', '\"', '[', ']', ' '}; if (email.empty()) return false; strlcpy(copy, email.c_str(), sizeof(copy)); - + char *domain = strchr(copy, '@'); if (!domain) return false; @@ -119,28 +115,28 @@ bool MailValidate(const std::string &email) /* Don't accept NULL copy or domain. */ if (!*copy || !*domain) return false; - + /* Check for forbidden characters in the name */ - for (unsigned int i = 0; i < strlen(copy); i++) + for (unsigned int i = 0; i < strlen(copy); ++i) { if (copy[i] <= 31 || copy[i] >= 127) return false; - for (unsigned int j = 0; j < 13; j++) + for (unsigned int j = 0; j < 13; ++j) if (copy[i] == specials[j]) return false; } /* Check for forbidden characters in the domain */ - for (unsigned int i = 0; i < strlen(domain); i++) + for (unsigned int i = 0; i < strlen(domain); ++i) { if (domain[i] <= 31 || domain[i] >= 127) return false; - for (unsigned int j = 0; j < 13; j++) + for (unsigned int j = 0; j < 13; ++j) if (domain[i] == specials[j]) return false; if (domain[i] == '.') { - if (i == 0 || i == strlen(domain) - 1) + if (!i || i == strlen(domain) - 1) return false; has_period = true; } @@ -148,4 +144,3 @@ bool MailValidate(const std::string &email) return has_period; } - diff --git a/src/main.cpp b/src/main.cpp index 70c7f9e7e..cb63060ea 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -21,8 +21,6 @@ * 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" @@ -36,27 +34,26 @@ # include <sys/resource.h> #endif - /******** Global variables! ********/ /* Command-line options: (note that configuration variables are in config.c) */ -std::string services_dir; /* -dir dirname */ +std::string services_dir; /* -dir dirname */ std::string services_bin; /* Binary as specified by the user */ std::string orig_cwd; /* Original current working directory */ -std::string log_filename = "services.log"; /* -log filename */ -int debug = 0; /* -debug */ -int readonly = 0; /* -readonly */ -bool LogChan = false; /* -logchan */ -int nofork = 0; /* -nofork */ -int forceload = 0; /* -forceload */ -int nothird = 0; /* -nothrid */ -int noexpire = 0; /* -noexpire */ -int protocoldebug = 0; /* -protocoldebug */ +std::string log_filename = "services.log"; /* -log filename */ +int debug = 0; /* -debug */ +int readonly = 0; /* -readonly */ +bool LogChan = false; /* -logchan */ +int nofork = 0; /* -nofork */ +int forceload = 0; /* -forceload */ +int nothird = 0; /* -nothrid */ +int noexpire = 0; /* -noexpire */ +int protocoldebug = 0; /* -protocoldebug */ std::string binary_dir; /* Used to store base path for Anope */ #ifdef _WIN32 -#include <process.h> -#define execve _execve +# include <process.h> +# define execve _execve #endif /* Set to 1 if we are to quit */ @@ -80,8 +77,7 @@ char **my_av, **my_envp; /* Moved here from version.h */ const char version_number[] = VERSION_STRING; const char version_number_dotted[] = VERSION_STRING_DOTTED; -const char version_build[] = - "build #" BUILD ", compiled " __DATE__ " " __TIME__; +const char version_build[] = "build #" BUILD ", compiled " __DATE__ " " __TIME__; /* the space is needed cause if you build with nothing it will complain */ /******** Local variables! ********/ @@ -144,10 +140,8 @@ class UplinkSocket : public Socket extern void expire_all() { if (noexpire || readonly) - { // Definitely *do not* want. return; - } FOREACH_MOD(I_OnPreDatabaseExpire, OnPreDatabaseExpire()); @@ -166,7 +160,7 @@ void save_databases() { if (readonly) return; - + EventReturn MOD_RESULT; FOREACH_RESULT(I_OnSaveDatabase, OnSaveDatabase()); Alog(LOG_DEBUG) << "Saving FFF databases"; @@ -177,7 +171,8 @@ void save_databases() /* Restarts services */ void do_restart_services() { - if (!readonly) { + if (!readonly) + { expire_all(); save_databases(); } @@ -188,11 +183,9 @@ void do_restart_services() if (!quitmsg) quitmsg = "Restarting"; /* Send a quit for all of our bots */ - for (botinfo_map::const_iterator it = BotListByNick.begin(); it != BotListByNick.end(); ++it) - { + for (botinfo_map::const_iterator it = BotListByNick.begin(), it_end = BotListByNick.end(); it != it_end; ++it) /* Don't use quitmsg here, it may contain information you don't want people to see */ ircdproto->SendQuit(it->second, "Restarting"); - } ircdproto->SendSquit(Config.ServerName, quitmsg); /* Process to send the last bits of information before disconnecting */ socketEngine.Process(); @@ -203,7 +196,8 @@ void do_restart_services() ModuleManager::UnloadAll(true); chdir(binary_dir.c_str()); execve(services_bin.c_str(), my_av, my_envp); - if (!readonly) { + if (!readonly) + { open_log(); log_perror("Restart failed"); close_log(); @@ -228,18 +222,14 @@ static void services_shutdown() if (started && UplinkSock) { /* Send a quit for all of our bots */ - for (botinfo_map::const_iterator it = BotListByNick.begin(); it != BotListByNick.end(); ++it) - { + for (botinfo_map::const_iterator it = BotListByNick.begin(), it_end = BotListByNick.end(); it != it_end; ++it) /* Don't use quitmsg here, it may contain information you don't want people to see */ ircdproto->SendQuit(it->second, "Shutting down"); - } ircdproto->SendSquit(Config.ServerName, quitmsg); while (!UserListByNick.empty()) - { delete UserListByNick.begin()->second; - } } /* Process to send the last bits of information before disconnecting */ socketEngine.Process(); @@ -284,7 +274,8 @@ void sighandler(int signum) FOREACH_MOD(I_OnReload, OnReload(true)); return; - } else + } + else #endif if (signum == SIGTERM) { @@ -316,7 +307,6 @@ void sighandler(int signum) } } - /* Should we send the signum here as well? -GD */ FOREACH_MOD(I_OnSignal, OnSignal(quitmsg)); @@ -328,13 +318,9 @@ void sighandler(int signum) else { if (isatty(2)) - { fprintf(stderr, "%s\n", quitmsg); - } else - { Alog() << quitmsg; - } exit(1); } @@ -390,7 +376,7 @@ static bool Connect() { /* Connect to the remote server */ int servernum = 1; - for (std::list<Uplink *>::iterator curr_uplink = Config.Uplinks.begin(); curr_uplink != Config.Uplinks.end(); ++curr_uplink, ++servernum) + for (std::list<Uplink *>::iterator curr_uplink = Config.Uplinks.begin(), end_uplink = Config.Uplinks.end(); curr_uplink != end_uplink; ++curr_uplink, ++servernum) { uplink_server = *curr_uplink; @@ -407,7 +393,7 @@ static bool Connect() { new UplinkSocket(uplink_server->host, uplink_server->port, Config.LocalHost ? Config.LocalHost : "", uplink_server->ipv6); } - catch (SocketException& ex) + catch (const SocketException &ex) { Alog() << "Unable to connect to server" << servernum << " (" << uplink_server->host << ":" << uplink_server->port << "), " << ex.GetReason(); continue; @@ -443,12 +429,11 @@ int main(int ac, char **av, char **envp) #ifndef _WIN32 /* If we're root, issue a warning now */ - if ((getuid() == 0) && (getgid() == 0)) { - fprintf(stderr, - "WARNING: You are currently running Anope as the root superuser. Anope does not\n"); - fprintf(stderr, - " require root privileges to run, and it is discouraged that you run Anope\n"); - fprintf(stderr, " as the root superuser.\n"); + if (!getuid() && !getgid()) + { + fprintf(stderr, "WARNING: You are currently running Anope as the root superuser. Anope does not\n"); + fprintf(stderr, " require root privileges to run, and it is discouraged that you run Anope\n"); + fprintf(stderr, " as the root superuser.\n"); } #endif @@ -467,9 +452,9 @@ int main(int ac, char **av, char **envp) ModuleRunTimeDirCleanUp(); /* General initialization first */ - if ((i = init_primary(ac, av)) != 0) + if ((i = init_primary(ac, av))) return i; - + Alog(LOG_TERMINAL) << "Anope " << version_number << ", " << version_build; #ifdef _WIN32 Alog(LOG_TERMINAL) << "Using configuration file " << services_dir << "\\" << services_conf; @@ -478,7 +463,7 @@ int main(int ac, char **av, char **envp) #endif /* Initialization stuff. */ - if ((i = init_secondary(ac, av)) != 0) + if ((i = init_secondary(ac, av))) return i; /* If the first connect fails give up, don't sit endlessly trying to reconnect */ @@ -495,16 +480,12 @@ int main(int ac, char **av, char **envp) { rlimit rl; if (getrlimit(RLIMIT_CORE, &rl) == -1) - { Alog() << "Failed to getrlimit()!"; - } else { rl.rlim_cur = rl.rlim_max; if (setrlimit(RLIMIT_CORE, &rl) == -1) - { Alog() << "setrlimit() failed, cannot increase coredump size"; - } } } #endif @@ -553,10 +534,8 @@ int main(int ac, char **av, char **envp) } if (quitting) - { /* Disconnect and exit */ services_shutdown(); - } else { FOREACH_MOD(I_OnServerDisconnect, OnServerDisconnect()); @@ -584,4 +563,3 @@ int main(int ac, char **av, char **envp) return 0; } - diff --git a/src/memory.cpp b/src/memory.cpp index 4343bf5e6..1fb1d2b21 100644 --- a/src/memory.cpp +++ b/src/memory.cpp @@ -7,17 +7,15 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" /* smalloc, scalloc, srealloc, sstrdup: - * Versions of the memory allocation functions which will cause the - * program to terminate with an "Out of memory" error if the memory - * cannot be allocated. (Hence, the return value from these functions - * is never NULL.) + * Versions of the memory allocation functions which will cause the + * program to terminate with an "Out of memory" error if the memory + * cannot be allocated. (Hence, the return value from these functions + * is never NULL.) */ /*************************************************************************/ @@ -31,9 +29,8 @@ void *smalloc(long size) { void *buf; - if (!size) { + if (!size) size = 1; - } buf = malloc(size); if (!buf) abort(); @@ -52,9 +49,8 @@ void *scalloc(long elsize, long els) { void *buf; - if (!elsize || !els) { + if (!elsize || !els) elsize = els = 1; - } buf = calloc(elsize, els); if (!buf) abort(); @@ -73,9 +69,8 @@ void *srealloc(void *oldptr, long newsize) { void *buf; - if (!newsize) { + if (!newsize) newsize = 1; - } buf = realloc(oldptr, newsize); if (!buf) abort(); @@ -93,12 +88,15 @@ void *srealloc(void *oldptr, long newsize) char *sstrdup(const char *src) { char *ret = NULL; - if (src) { + if (src) + { ret = new char[strlen(src) + 1]; if (!ret) abort(); strcpy(ret, src); - } else { + } + else + { Alog() << "sstrdup() called with NULL-arg"; abort(); } diff --git a/src/memoserv.cpp b/src/memoserv.cpp index 505b4ed18..5ceca0c7a 100644 --- a/src/memoserv.cpp +++ b/src/memoserv.cpp @@ -1,15 +1,13 @@ /* MemoServ functions. -* -* (C) 2003-2010 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. -* -* -*/ + * + * (C) 2003-2010 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 "modules.h" @@ -23,7 +21,8 @@ static bool SendMemoMail(NickCore *nc, Memo *m); /*************************************************************************/ -void moduleAddMemoServCmds() { +void moduleAddMemoServCmds() +{ ModuleManager::LoadModuleList(Config.MemoServCoreModules); } @@ -55,7 +54,7 @@ void memoserv(User *u, const std::string &buf) { if (!u || buf.empty()) return; - + if (buf.find("\1PING ", 0, 6) != std::string::npos && buf[buf.length() - 1] == '\1') { std::string command = buf; @@ -64,9 +63,7 @@ void memoserv(User *u, const std::string &buf) ircdproto->SendCTCP(MemoServ, u->nick.c_str(), "%s", command.c_str()); } else - { mod_run_cmd(MemoServ, u, buf); - } } /*************************************************************************/ @@ -78,7 +75,7 @@ void memoserv(User *u, const std::string &buf) * @param u User Struct * @return void */ -void check_memos(User * u) +void check_memos(User *u) { NickCore *nc; unsigned i, newcnt = 0; @@ -89,33 +86,33 @@ void check_memos(User * u) return; } - if (!(nc = u->Account()) || !u->IsRecognized() || - !(nc->HasFlag(NI_MEMO_SIGNON))) { + if (!(nc = u->Account()) || !u->IsRecognized() || !(nc->HasFlag(NI_MEMO_SIGNON))) return; - } - for (i = 0; i < nc->memos.memos.size(); i++) { + for (i = 0; i < nc->memos.memos.size(); ++i) + { if (nc->memos.memos[i]->HasFlag(MF_UNREAD)) - newcnt++; + ++newcnt; } - if (newcnt > 0) { - notice_lang(Config.s_MemoServ, u, - newcnt == 1 ? MEMO_HAVE_NEW_MEMO : MEMO_HAVE_NEW_MEMOS, - newcnt); - if (newcnt == 1 && (nc->memos.memos[i - 1]->HasFlag(MF_UNREAD))) { + if (newcnt > 0) + { + notice_lang(Config.s_MemoServ, u, newcnt == 1 ? MEMO_HAVE_NEW_MEMO : MEMO_HAVE_NEW_MEMOS, newcnt); + if (newcnt == 1 && (nc->memos.memos[i - 1]->HasFlag(MF_UNREAD))) notice_lang(Config.s_MemoServ, u, MEMO_TYPE_READ_LAST, Config.s_MemoServ); - } else if (newcnt == 1) { - for (i = 0; i < nc->memos.memos.size(); i++) { + else if (newcnt == 1) + { + for (i = 0; i < nc->memos.memos.size(); ++i) + { if (nc->memos.memos[i]->HasFlag(MF_UNREAD)) break; } - notice_lang(Config.s_MemoServ, u, MEMO_TYPE_READ_NUM, Config.s_MemoServ, - nc->memos.memos[i]->number); - } else { - notice_lang(Config.s_MemoServ, u, MEMO_TYPE_LIST_NEW, Config.s_MemoServ); + notice_lang(Config.s_MemoServ, u, MEMO_TYPE_READ_NUM, Config.s_MemoServ, nc->memos.memos[i]->number); } + else + notice_lang(Config.s_MemoServ, u, MEMO_TYPE_LIST_NEW, Config.s_MemoServ); } - if (nc->memos.memomax > 0 && nc->memos.memos.size() >= nc->memos.memomax) { + if (nc->memos.memomax > 0 && nc->memos.memos.size() >= nc->memos.memomax) + { if (nc->memos.memos.size() > nc->memos.memomax) notice_lang(Config.s_MemoServ, u, MEMO_OVER_LIMIT, nc->memos.memomax); else @@ -137,37 +134,52 @@ void check_memos(User * u) */ MemoInfo *getmemoinfo(const char *name, int *ischan, int *isforbid) { - if (*name == '#') { + if (*name == '#') + { ChannelInfo *ci; if (ischan) *ischan = 1; ci = cs_findchan(name); - if (ci) { - if (!(ci->HasFlag(CI_FORBIDDEN))) { + if (ci) + { + if (!ci->HasFlag(CI_FORBIDDEN)) + { *isforbid = 0; return &ci->memos; - } else { + } + else + { *isforbid = 1; return NULL; } - } else { + } + else + { *isforbid = 0; return NULL; } - } else { + } + else + { NickAlias *na; if (ischan) *ischan = 0; na = findnick(name); - if (na) { - if (!na->HasFlag(NS_FORBIDDEN)) { + if (na) + { + if (!na->HasFlag(NS_FORBIDDEN)) + { *isforbid = 0; return &na->nc->memos; - } else { + } + else + { *isforbid = 1; return NULL; } - } else { + } + else + { *isforbid = 0; return NULL; } @@ -182,13 +194,13 @@ MemoInfo *getmemoinfo(const char *name, int *ischan, int *isforbid) * @param name Target of the memo * @param text Memo Text * @param z type see info - * 0 - reply to user - * 1 - silent - * 2 - silent with no delay timer - * 3 - reply to user and request read receipt + * 0 - reply to user + * 1 - silent + * 2 - silent with no delay timer + * 3 - reply to user and request read receipt * @return void */ -void memo_send(User * u, const char *name, const char *text, int z) +void memo_send(User *u, const char *name, const char *text, int z) { int ischan; int isforbid; @@ -198,51 +210,52 @@ void memo_send(User * u, const char *name, const char *text, int z) char *source = u->Account()->display; int is_servoper = u->Account() && u->Account()->IsServicesOper(); - if (readonly) { + if (readonly) notice_lang(Config.s_MemoServ, u, MEMO_SEND_DISABLED); - } else if (!text) { - if (z == 0) + else if (!text) + { + if (!z) syntax_error(Config.s_MemoServ, u, "SEND", MEMO_SEND_SYNTAX); if (z == 3) syntax_error(Config.s_MemoServ, u, "RSEND", MEMO_RSEND_SYNTAX); - - } else if (!u->IsIdentified() && !u->IsRecognized()) { - if (z == 0 || z == 3) + } + else if (!u->IsIdentified() && !u->IsRecognized()) + { + if (!z || z == 3) notice_lang(Config.s_MemoServ, u, NICK_IDENTIFY_REQUIRED, Config.s_NickServ); - - } else if (!(mi = getmemoinfo(name, &ischan, &isforbid))) { - if (z == 0 || z == 3) { - if (isforbid) { - notice_lang(Config.s_MemoServ, u, - ischan ? CHAN_X_FORBIDDEN : - NICK_X_FORBIDDEN, name); - } else { - notice_lang(Config.s_MemoServ, u, - ischan ? CHAN_X_NOT_REGISTERED : - NICK_X_NOT_REGISTERED, name); - } + } + else if (!(mi = getmemoinfo(name, &ischan, &isforbid))) + { + if (!z || z == 3) + { + if (isforbid) + notice_lang(Config.s_MemoServ, u, ischan ? CHAN_X_FORBIDDEN : NICK_X_FORBIDDEN, name); + else + notice_lang(Config.s_MemoServ, u, ischan ? CHAN_X_NOT_REGISTERED : NICK_X_NOT_REGISTERED, name); } - } else if (z != 2 && Config.MSSendDelay > 0 && - u && u->lastmemosend + Config.MSSendDelay > now) { + } + else if (z != 2 && Config.MSSendDelay > 0 && u && u->lastmemosend + Config.MSSendDelay > now) + { u->lastmemosend = now; - if (z == 0) + if (!z) notice_lang(Config.s_MemoServ, u, MEMO_SEND_PLEASE_WAIT, Config.MSSendDelay); if (z == 3) - notice_lang(Config.s_MemoServ, u, MEMO_RSEND_PLEASE_WAIT, - Config.MSSendDelay); - - } else if (mi->memomax == 0 && !is_servoper) { - if (z == 0 || z == 3) + notice_lang(Config.s_MemoServ, u, MEMO_RSEND_PLEASE_WAIT, Config.MSSendDelay); + } + else if (!mi->memomax && !is_servoper) + { + if (!z || z == 3) notice_lang(Config.s_MemoServ, u, MEMO_X_GETS_NO_MEMOS, name); - - } else if (mi->memomax > 0 && mi->memos.size() >= mi->memomax - && !is_servoper) { - if (z == 0 || z == 3) + } + else if (mi->memomax > 0 && mi->memos.size() >= mi->memomax && !is_servoper) + { + if (!z || z == 3) notice_lang(Config.s_MemoServ, u, MEMO_X_HAS_TOO_MANY_MEMOS, name); - - } else { + } + else + { u->lastmemosend = now; m = new Memo; mi->memos.push_back(m); @@ -252,10 +265,8 @@ void memo_send(User * u, const char *name, const char *text, int z) m->number = mi->memos[mi->memos.size() - 2]->number + 1; if (m->number < 1) { - for (unsigned i = 0; i < mi->memos.size(); i++) - { + for (unsigned i = 0; i < mi->memos.size(); ++i) mi->memos[i]->number = i + 1; - } } } else @@ -264,68 +275,63 @@ void memo_send(User * u, const char *name, const char *text, int z) m->text = sstrdup(text); m->SetFlag(MF_UNREAD); /* Set notify sent flag - DrStein */ - if (z == 2) { + if (z == 2) m->SetFlag(MF_NOTIFYS); - } /* Set receipt request flag */ if (z == 3) m->SetFlag(MF_RECEIPT); - if (z == 0 || z == 3) + if (!z || z == 3) notice_lang(Config.s_MemoServ, u, MEMO_SENT, name); - if (!ischan) { + if (!ischan) + { NickCore *nc = (findnick(name))->nc; FOREACH_MOD(I_OnMemoSend, OnMemoSend(u, nc, m)); - if (Config.MSNotifyAll) { - if ((nc->HasFlag(NI_MEMO_RECEIVE)) - && get_ignore(name) == NULL) { - - for (std::list<NickAlias *>::iterator it = nc->aliases.begin(); it != nc->aliases.end(); ++it) + if (Config.MSNotifyAll) + { + if (nc->HasFlag(NI_MEMO_RECEIVE) && !get_ignore(name)) + { + for (std::list<NickAlias *>::iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end; ++it) { NickAlias *na = *it; User *user = finduser(na->nick); if (user && user->IsIdentified()) - notice_lang(Config.s_MemoServ, user, - MEMO_NEW_MEMO_ARRIVED, source, - Config.s_MemoServ, m->number); + notice_lang(Config.s_MemoServ, user, MEMO_NEW_MEMO_ARRIVED, source, Config.s_MemoServ, m->number); } - } else { - if ((u = finduser(name)) && u->IsIdentified() - && (nc->HasFlag(NI_MEMO_RECEIVE))) - notice_lang(Config.s_MemoServ, u, MEMO_NEW_MEMO_ARRIVED, - source, Config.s_MemoServ, m->number); - } /* if (flags & MEMO_RECEIVE) */ + } + else + { + if ((u = finduser(name)) && u->IsIdentified() && nc->HasFlag(NI_MEMO_RECEIVE)) + notice_lang(Config.s_MemoServ, u, MEMO_NEW_MEMO_ARRIVED, source, Config.s_MemoServ, m->number); + } /* if (flags & MEMO_RECEIVE) */ } /* if (MSNotifyAll) */ /* let's get out the mail if set in the nickcore - certus */ if (nc->HasFlag(NI_MEMO_MAIL)) SendMemoMail(nc, m); - } else { + } + else + { Channel *c; FOREACH_MOD(I_OnMemoSend, OnMemoSend(u, cs_findchan(name), m)); if (Config.MSNotifyAll && (c = findchan(name))) { - for (CUserList::iterator it = c->users.begin(); it != c->users.end(); ++it) + for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ++it) { UserContainer *cu = *it; - if (check_access(cu->user, c->ci, CA_MEMO)) { - if (cu->user->Account() - && (cu->user->Account()->HasFlag(NI_MEMO_RECEIVE)) - && get_ignore(cu->user->nick.c_str()) == NULL) { - notice_lang(Config.s_MemoServ, cu->user, - MEMO_NEW_X_MEMO_ARRIVED, - c->ci->name.c_str(), Config.s_MemoServ, - c->ci->name.c_str(), m->number); - } + if (check_access(cu->user, c->ci, CA_MEMO)) + { + if (cu->user->Account() && cu->user->Account()->HasFlag(NI_MEMO_RECEIVE) && !get_ignore(cu->user->nick.c_str())) + notice_lang(Config.s_MemoServ, cu->user, MEMO_NEW_X_MEMO_ARRIVED, c->ci->name.c_str(), Config.s_MemoServ, c->ci->name.c_str(), m->number); } } - } /* MSNotifyAll */ - } /* if (!ischan) */ - } /* if command is valid */ + } /* MSNotifyAll */ + } /* if (!ischan) */ + } /* if command is valid */ } /*************************************************************************/ @@ -335,23 +341,26 @@ void memo_send(User * u, const char *name, const char *text, int z) * @param num Memo number to delete * @return int 1 if the memo was found, else 0. */ -int delmemo(MemoInfo * mi, int num) +int delmemo(MemoInfo *mi, int num) { unsigned i; - if (mi->memos.empty()) return 0; + if (mi->memos.empty()) + return 0; - for (i = 0; i < mi->memos.size(); i++) { + for (i = 0; i < mi->memos.size(); ++i) + { if (mi->memos[i]->number == num) break; } - if (i < mi->memos.size()) { - delete [] mi->memos[i]->text; /* Deallocate memo text memory */ - delete mi->memos[i]; /* Deallocate the memo itself */ + if (i < mi->memos.size()) + { + delete [] mi->memos[i]->text; /* Deallocate memo text memory */ + delete mi->memos[i]; /* Deallocate the memo itself */ mi->memos.erase(mi->memos.begin() + i); /* Remove the memo pointer from the vector */ return 1; - } else { - return 0; } + else + return 0; } /*************************************************************************/ @@ -369,7 +378,7 @@ static bool SendMemoMail(NickCore *nc, Memo *m) /* Send receipt notification to sender. */ -void rsend_notify(User * u, Memo * m, const char *chan) +void rsend_notify(User *u, Memo *m, const char *chan) { NickAlias *na; NickCore *nc; @@ -377,29 +386,29 @@ void rsend_notify(User * u, Memo * m, const char *chan) const char *fmt; /* Only send receipt if memos are allowed */ - if ((!readonly)) + if (!readonly) { - /* Get nick alias for sender */ na = findnick(m->sender); - if (!na) { + if (!na) return; - } /* Get nick core for sender */ nc = na->nc; - if (!nc) { + if (!nc) return; - } /* Text of the memo varies if the recepient was a nick or channel */ - if (chan) { + if (chan) + { fmt = getstring(na, MEMO_RSEND_CHAN_MEMO_TEXT); snprintf(text, sizeof(text), fmt, chan); - } else { + } + else + { fmt = getstring(na, MEMO_RSEND_NICK_MEMO_TEXT); snprintf(text, sizeof(text), "%s", fmt); } @@ -409,8 +418,7 @@ void rsend_notify(User * u, Memo * m, const char *chan) /* Notify recepient of the memo that a notification has been sent to the sender */ - notice_lang(Config.s_MemoServ, u, MEMO_RSEND_USER_NOTIFICATION, - nc->display); + notice_lang(Config.s_MemoServ, u, MEMO_RSEND_USER_NOTIFICATION, nc->display); } /* Remove receipt flag from the original memo */ diff --git a/src/messages.cpp b/src/messages.cpp index 81c64b1fb..8ecd038cf 100644 --- a/src/messages.cpp +++ b/src/messages.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -31,7 +29,7 @@ int m_away(const char *source, const char *msg) u = finduser(source); - if (u && msg == 0) /* un-away */ + if (u && !msg) /* un-away */ check_memos(u); return MOD_CONT; } @@ -62,9 +60,8 @@ int m_time(const char *source, int ac, const char **av) struct tm *tm; char buf[64]; - if (!source) { + if (!source) return MOD_CONT; - } time(&t); tm = localtime(&t); @@ -80,22 +77,23 @@ int m_motd(const char *source) FILE *f; char buf[BUFSIZE]; - if (!source) { + if (!source) return MOD_CONT; - } f = fopen(Config.MOTDFilename, "r"); - if (f) { + if (f) + { ircdproto->SendNumeric(Config.ServerName, 375, source, ":- %s Message of the Day", Config.ServerName); - while (fgets(buf, sizeof(buf), f)) { + while (fgets(buf, sizeof(buf), f)) + { buf[strlen(buf) - 1] = 0; ircdproto->SendNumeric(Config.ServerName, 372, source, ":- %s", buf); } fclose(f); ircdproto->SendNumeric(Config.ServerName, 376, source, ":End of /MOTD command."); - } else { - ircdproto->SendNumeric(Config.ServerName, 422, source, ":- MOTD file not found! Please contact your IRC administrator."); } + else + ircdproto->SendNumeric(Config.ServerName, 422, source, ":- MOTD file not found! Please contact your IRC administrator."); return MOD_CONT; } @@ -107,9 +105,7 @@ int m_privmsg(const std::string &source, const std::string &receiver, const std: time_t starttime, stoptime; /* When processing started and finished */ if (source.empty() || receiver.empty() || message.empty()) - { return MOD_CONT; - } User *u = finduser(source); @@ -119,9 +115,7 @@ int m_privmsg(const std::string &source, const std::string &receiver, const std: BotInfo *bi = findbot(receiver); if (bi) - { ircdproto->SendMessage(bi, source.c_str(), "%s", getstring(USER_RECORD_NOT_FOUND)); - } return MOD_CONT; } @@ -133,9 +127,7 @@ int m_privmsg(const std::string &source, const std::string &receiver, const std: { /* Some paranoia checks */ if (!ci->HasFlag(CI_FORBIDDEN) && ci->c && ci->bi) - { botchanmsgs(u, ci, message); - } } } else @@ -166,8 +158,7 @@ int m_privmsg(const std::string &source, const std::string &receiver, const std: else if (Config.UseStrictPrivMsg) { Alog(LOG_DEBUG) << "Ignored PRIVMSG without @ from " << source; - notice_lang(receiver, u, INVALID_TARGET, receiver.c_str(), receiver.c_str(), - Config.ServerName, receiver.c_str()); + notice_lang(receiver, u, INVALID_TARGET, receiver.c_str(), receiver.c_str(), Config.ServerName, receiver.c_str()); return MOD_CONT; } @@ -228,53 +219,54 @@ int m_stats(const char *source, int ac, const char **av) if (ac < 1) return MOD_CONT; - switch (*av[0]) { - case 'l': - u = finduser(source); - - if (u && is_oper(u)) { + switch (*av[0]) + { + case 'l': + u = finduser(source); - ircdproto->SendNumeric(Config.ServerName, 211, source, "Server SendBuf SentBytes SentMsgs RecvBuf RecvBytes RecvMsgs ConnTime"); - ircdproto->SendNumeric(Config.ServerName, 211, source, "%s %d %d %d %d %d %d %ld", uplink_server->host, UplinkSock->WriteBufferLen(), TotalWritten, -1, UplinkSock->ReadBufferLen(), TotalRead, -1, time(NULL) - start_time); - } + if (u && is_oper(u)) + { + ircdproto->SendNumeric(Config.ServerName, 211, source, "Server SendBuf SentBytes SentMsgs RecvBuf RecvBytes RecvMsgs ConnTime"); + ircdproto->SendNumeric(Config.ServerName, 211, source, "%s %d %d %d %d %d %d %ld", uplink_server->host, UplinkSock->WriteBufferLen(), TotalWritten, -1, UplinkSock->ReadBufferLen(), TotalRead, -1, time(NULL) - start_time); + } - ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); - break; - case 'o': - case 'O': -/* Check whether the user is an operator */ - u = finduser(source); - if (u && !is_oper(u) && Config.HideStatsO) { ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); - } else { - std::list<std::pair<std::string, std::string> >::iterator it; - - for (it = Config.Opers.begin(); it != Config.Opers.end(); ++it) + break; + case 'o': + case 'O': + /* Check whether the user is an operator */ + u = finduser(source); + if (u && !is_oper(u) && Config.HideStatsO) + ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); + else { - std::string nick = it->first, type = it->second; + std::list<std::pair<ci::string, ci::string> >::iterator it, it_end; - NickCore *nc = findcore(nick); - if (nc) - ircdproto->SendNumeric(Config.ServerName, 243, source, "O * * %s %s 0", nick.c_str(), type.c_str()); - } + for (it = Config.Opers.begin(), it_end = Config.Opers.end(); it != it_end; ++it) + { + ci::string nick = it->first, type = it->second; - ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); - } + NickCore *nc = findcore(nick); + if (nc) + ircdproto->SendNumeric(Config.ServerName, 243, source, "O * * %s %s 0", nick.c_str(), type.c_str()); + } - break; + ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); + } + + break; - case 'u':{ + case 'u': + { int uptime = time(NULL) - start_time; - ircdproto->SendNumeric(Config.ServerName, 242, source, ":Services up %d day%s, %02d:%02d:%02d", uptime / 86400, uptime / 86400 == 1 ? "" : "s", - (uptime / 3600) % 24, (uptime / 60) % 60, uptime % 60); + ircdproto->SendNumeric(Config.ServerName, 242, source, ":Services up %d day%s, %02d:%02d:%02d", uptime / 86400, uptime / 86400 == 1 ? "" : "s", (uptime / 3600) % 24, (uptime / 60) % 60, uptime % 60); ircdproto->SendNumeric(Config.ServerName, 250, source, ":Current users: %d (%d ops); maximum %d", usercnt, opcnt, maxusercnt); ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); break; - } /* case 'u' */ + } /* case 'u' */ - default: - ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); - break; + default: + ircdproto->SendNumeric(Config.ServerName, 219, source, "%c :End of /STATS report.", *av[0] ? *av[0] : '*'); } return MOD_CONT; } @@ -288,7 +280,6 @@ int m_version(const char *source, int ac, const char **av) return MOD_CONT; } - /*************************************************************************/ int m_whois(const char *source, const char *who) @@ -316,9 +307,7 @@ int m_whois(const char *source, const char *who) ircdproto->SendNumeric(Config.ServerName, 318, source, "%s :End of /WHOIS list.", who); } else - { ircdproto->SendNumeric(Config.ServerName, 401, source, "%s :No such service.", who); - } } return MOD_CONT; } @@ -330,4 +319,3 @@ void moduleAddMsgs() Anope::AddMessage("TIME", m_time); Anope::AddMessage("VERSION", m_version); } - diff --git a/src/misc.cpp b/src/misc.cpp index 51ff5e97c..a653571e2 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -8,8 +8,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -19,7 +17,8 @@ /* Cheaper than isspace() or isblank() */ #define issp(c) ((c) == 32) -struct arc4_stream { +struct arc4_stream +{ uint8 i; uint8 j; uint8 s[256]; @@ -35,43 +34,39 @@ bool IsFile(const std::string &filename) { struct stat fileinfo; if (!stat(filename.c_str(), &fileinfo)) - { return true; - } return false; } /** * toupper: Like the ANSI functions, but make sure we return an - * int instead of a (signed) char. + * int instead of a (signed) char. * @param c Char * @return int */ int toupper(char c) { - if (islower(c)) { + if (islower(c)) return static_cast<int>(c) - ('a' - 'A'); - } else { + else return static_cast<int>(c); - } } /*************************************************************************/ /** * tolower: Like the ANSI functions, but make sure we return an - * int instead of a (signed) char. + * int instead of a (signed) char. * @param c Char * @return int */ int tolower(char c) { - if (isupper(c)) { + if (isupper(c)) return static_cast<int>(c) + ('a' - 'A'); - } else { + else return static_cast<int>(c); - } } /*************************************************************************/ @@ -85,7 +80,8 @@ void binary_to_hex(unsigned char *bin, char *hex, int length) static const char trans[] = "0123456789ABCDEF"; int i; - for (i = 0; i < length; i++) { + for (i = 0; i < length; ++i) + { hex[i << 1] = trans[bin[i] >> 4]; hex[(i << 1) + 1] = trans[bin[i] & 0xf]; } @@ -108,9 +104,8 @@ char *strscpy(char *d, const char *s, size_t len) { char *d_orig = d; - if (!len) { + if (!len) return d; - } while (--len && (*d++ = *s++)); *d = '\0'; return d_orig; @@ -130,13 +125,17 @@ const char *stristr(const char *s1, const char *s2) { register const char *s = s1, *d = s2; - while (*s1) { - if (tolower(*s1) == tolower(*d)) { - s1++; - d++; - if (*d == 0) + while (*s1) + { + if (tolower(*s1) == tolower(*d)) + { + ++s1; + ++d; + if (!*d) return s; - } else { + } + else + { s = ++s1; d = s2; } @@ -148,9 +147,9 @@ const char *stristr(const char *s1, const char *s2) /** * strnrepl: Replace occurrences of `old' with `new' in string `s'. Stop - * replacing if a replacement would cause the string to exceed - * `size' bytes (including the null terminator). Return the - * string. + * replacing if a replacement would cause the string to exceed + * `size' bytes (including the null terminator). Return the + * string. * @param s String * @param size size of s * @param old character to replace @@ -166,15 +165,17 @@ char *strnrepl(char *s, int32 size, const char *old, const char *newstr) int32 newlen = strlen(newstr); int32 diff = newlen - oldlen; - while (left >= oldlen) { - if (strncmp(ptr, old, oldlen) != 0) { - left--; - ptr++; + while (left >= oldlen) + { + if (strncmp(ptr, old, oldlen)) + { + --left; + ++ptr; continue; } if (diff > avail) break; - if (diff != 0) + if (diff) memmove(ptr + oldlen + diff, ptr + oldlen, left + 1 - oldlen); strncpy(ptr, newstr, newlen); ptr += newlen; @@ -187,8 +188,8 @@ char *strnrepl(char *s, int32 size, const char *old, const char *newstr) /** * merge_args: Take an argument count and argument vector and merge them - * into a single string in which each argument is separated by - * a space. + * into a single string in which each argument is separated by + * a space. * @param int Number of Args * @param argv Array * @return string of the merged array @@ -200,9 +201,8 @@ const char *merge_args(int argc, const char **argv) char *t; t = s; - for (i = 0; i < argc; i++) - t += snprintf(t, sizeof(s) - (t - s), "%s%s", *argv++, - (i < argc - 1) ? " " : ""); + for (i = 0; i < argc; ++i) + t += snprintf(t, sizeof(s) - (t - s), "%s%s", *argv++, i < argc - 1 ? " " : ""); return s; } @@ -216,9 +216,8 @@ const char *merge_args(int argc, char **argv) char *t; t = s; - for (i = 0; i < argc; i++) - t += snprintf(t, sizeof(s) - (t - s), "%s%s", *argv++, - (i < argc - 1) ? " " : ""); + for (i = 0; i < argc; ++i) + t += snprintf(t, sizeof(s) - (t - s), "%s%s", *argv++, i < argc - 1 ? " " : ""); return s; } @@ -240,10 +239,8 @@ NumberList::NumberList(const std::string &list, bool descending) : desc(descendi if (t == std::string::npos) { unsigned num = strtol(token.c_str(), &error, 10); - if (*error == '\0') - { + if (!*error) numbers.insert(num); - } else { if (!this->InvalidRange(list)) @@ -258,12 +255,10 @@ NumberList::NumberList(const std::string &list, bool descending) : desc(descendi char *error2; unsigned num1 = strtol(token.substr(0, t).c_str(), &error, 10); unsigned num2 = strtol(token.substr(t + 1).c_str(), &error2, 10); - if (*error == '\0' && *error2 == '\0') + if (!*error && !*error2) { for (unsigned i = num1; i <= num2; ++i) - { numbers.insert(i); - } } else { @@ -285,19 +280,15 @@ void NumberList::Process() { if (this->desc) { - for (std::set<unsigned>::reverse_iterator it = numbers.rbegin(); it != numbers.rend(); ++it) - { + for (std::set<unsigned>::reverse_iterator it = numbers.rbegin(), it_end = numbers.rend(); it != it_end; ++it) this->HandleNumber(*it); - } } else { - for (std::set<unsigned>::iterator it = numbers.begin(); it != numbers.end(); ++it) - { + for (std::set<unsigned>::iterator it = numbers.begin(), it_end = numbers.end(); it != it_end; ++it) this->HandleNumber(*it); - } } - + delete this; } @@ -312,12 +303,12 @@ bool NumberList::InvalidRange(const std::string &) /** * dotime: Return the number of seconds corresponding to the given time - * string. If the given string does not represent a valid time, - * return -1. + * string. If the given string does not represent a valid time, + * return -1. * - * A time string is either a plain integer (representing a number - * of seconds), or an integer followed by one of these characters: - * "s" (seconds), "m" (minutes), "h" (hours), or "d" (days). + * A time string is either a plain integer (representing a number + * of seconds), or an integer followed by one of these characters: + * "s" (seconds), "m" (minutes), "h" (hours), or "d" (days). * @param s String to convert * @return time_t */ @@ -325,31 +316,32 @@ time_t dotime(const char *s) { int amount; - if (!s || !*s) { + if (!s || !*s) return -1; - } amount = strtol(s, const_cast<char **>(&s), 10); - if (*s) { - switch (*s) { - case 's': - return amount; - case 'm': - return amount * 60; - case 'h': - return amount * 3600; - case 'd': - return amount * 86400; - case 'w': - return amount * 86400 * 7; - case 'y': - return amount * 86400 * 365; - default: - return -1; + if (*s) + { + switch (*s) + { + case 's': + return amount; + case 'm': + return amount * 60; + case 'h': + return amount * 3600; + case 'd': + return amount * 86400; + case 'w': + return amount * 86400 * 7; + case 'y': + return amount * 86400 * 365; + default: + return -1; } - } else { - return amount; } + else + return amount; } /*************************************************************************/ @@ -378,42 +370,27 @@ const char *duration(NickCore *nc, char *buf, int bufsize, time_t seconds) seconds -= (hours * 3600); minutes = seconds / 60; - if (!days && !hours && !minutes) { - snprintf(buf, bufsize, - getstring(nc, - (seconds <= - 1 ? DURATION_SECOND : DURATION_SECONDS)), - seconds); - } else { + if (!days && !hours && !minutes) + snprintf(buf, bufsize, getstring(nc, seconds <= 1 ? DURATION_SECOND : DURATION_SECONDS), seconds); + else + { end = buf; - if (days) { - snprintf(buf2, sizeof(buf2), - getstring(nc, - (days == 1 ? DURATION_DAY : DURATION_DAYS)), - days); + if (days) + { + snprintf(buf2, sizeof(buf2), getstring(nc, days == 1 ? DURATION_DAY : DURATION_DAYS), days); end += snprintf(end, bufsize - (end - buf), "%s", buf2); need_comma = 1; } - if (hours) { - snprintf(buf2, sizeof(buf2), - getstring(nc, - (hours == - 1 ? DURATION_HOUR : DURATION_HOURS)), - hours); - end += - snprintf(end, bufsize - (end - buf), "%s%s", - (need_comma ? comma : ""), buf2); + if (hours) + { + snprintf(buf2, sizeof(buf2), getstring(nc, hours == 1 ? DURATION_HOUR : DURATION_HOURS), hours); + end += snprintf(end, bufsize - (end - buf), "%s%s", need_comma ? comma : "", buf2); need_comma = 1; } - if (minutes) { - snprintf(buf2, sizeof(buf2), - getstring(nc, - (minutes == - 1 ? DURATION_MINUTE : DURATION_MINUTES)), - minutes); - end += - snprintf(end, bufsize - (end - buf), "%s%s", - (need_comma ? comma : ""), buf2); + if (minutes) + { + snprintf(buf2, sizeof(buf2), getstring(nc, minutes == 1 ? DURATION_MINUTE : DURATION_MINUTES), minutes); + end += snprintf(end, bufsize - (end - buf), "%s%s", need_comma ? comma : "", buf2); need_comma = 1; } } @@ -435,42 +412,32 @@ const char *expire_left(NickCore *nc, char *buf, int len, time_t expires) { time_t now = time(NULL); - if (!expires) { + if (!expires) strlcpy(buf, getstring(nc, NO_EXPIRE), len); - } else if (expires <= now) { + else if (expires <= now) strlcpy(buf, getstring(nc, EXPIRES_SOON), len); - } else { + else + { time_t diff = expires - now + 59; - if (diff >= 86400) { + if (diff >= 86400) + { int days = diff / 86400; - snprintf(buf, len, - getstring(nc, (days == 1) ? EXPIRES_1D : EXPIRES_D), - days); - } else { - if (diff <= 3600) { + snprintf(buf, len, getstring(nc, days == 1 ? EXPIRES_1D : EXPIRES_D), days); + } + else + { + if (diff <= 3600) + { int minutes = diff / 60; - snprintf(buf, len, - getstring(nc, - (minutes == - 1) ? EXPIRES_1M : EXPIRES_M), minutes); - } else { + snprintf(buf, len, getstring(nc, minutes == 1 ? EXPIRES_1M : EXPIRES_M), minutes); + } + else + { int hours = diff / 3600, minutes; - diff -= (hours * 3600); + diff -= hours * 3600; minutes = diff / 60; - snprintf(buf, len, - getstring(nc, - ((hours == 1 - && minutes == - 1) ? EXPIRES_1H1M : ((hours == 1 - && minutes != - 1) ? EXPIRES_1HM - : ((hours != 1 - && minutes == - 1) ? - EXPIRES_H1M : - EXPIRES_HM)))), - hours, minutes); + snprintf(buf, len, getstring(nc, hours == 1 && minutes == 1 ? EXPIRES_1H1M : (hours == 1 && minutes != 1 ? EXPIRES_1HM : (hours != 1 && minutes == 1 ? EXPIRES_H1M : EXPIRES_HM))), hours, minutes); } } } @@ -496,73 +463,67 @@ int doValidHost(const char *host, int type) int len = 0; int sec_len = 0; int dots = 1; - if (type != 1 && type != 2) { + if (type != 1 && type != 2) return 0; - } - if (!host) { + if (!host) return 0; - } len = strlen(host); - if (len > Config.HostLen) { + if (len > Config.HostLen) return 0; - } - switch (type) { - case 1: - for (idx = 0; idx < len; idx++) { - if (isdigit(host[idx])) { - if (sec_len < 3) { - sec_len++; - } else { - return 0; - } - } else { - if (idx == 0) { - return 0; - } /* cant start with a non-digit */ - if (host[idx] != '.') { - return 0; - } /* only . is a valid non-digit */ - if (sec_len > 3) { - return 0; - } /* sections cant be more than 3 digits */ - sec_len = 0; - dots++; - } - } - if (dots != 4) { - return 0; - } - break; - case 2: - dots = 0; - for (idx = 0; idx < len; idx++) { - if (!isalnum(host[idx])) { - if (idx == 0) { - return 0; + switch (type) + { + case 1: + for (idx = 0; idx < len; ++idx) + { + if (isdigit(host[idx])) + { + if (sec_len < 3) + ++sec_len; + else + return 0; } - if ((host[idx] != '.') && (host[idx] != '-')) { - return 0; + else + { + if (!idx) + return 0; /* cant start with a non-digit */ + if (host[idx] != '.') + return 0; /* only . is a valid non-digit */ + if (sec_len > 3) + return 0; /* sections cant be more than 3 digits */ + sec_len = 0; + ++dots; } - if (host[idx] == '.') { - dots++; + } + if (dots != 4) + return 0; + break; + case 2: + dots = 0; + for (idx = 0; idx < len; ++idx) + { + if (!isalnum(host[idx])) + { + if (!idx) + return 0; + if (host[idx] != '.' && host[idx] != '-') + return 0; + if (host[idx] == '.') + ++dots; } } - } - if (host[len - 1] == '.') { - return 0; - } - /** - * Ultimate3 dosnt like a non-dotted hosts at all, nor does unreal, - * so just dont allow them. - **/ - if (dots == 0) { - return 0; - } + if (host[len - 1] == '.') + return 0; + /** + * Ultimate3 dosnt like a non-dotted hosts at all, nor does unreal, + * so just dont allow them. + */ + if (!dots) + return 0; - break; + break; } return 1; } @@ -578,13 +539,13 @@ int doValidHost(const char *host, int type) int isValidHost(const char *host, int type) { int status = 0; - if (type == 3) { - if (!(status = doValidHost(host, 1))) { + if (type == 3) + { + if (!(status = doValidHost(host, 1))) status = doValidHost(host, 2); - } - } else { - status = doValidHost(host, type); } + else + status = doValidHost(host, type); return status; } @@ -597,15 +558,12 @@ int isValidHost(const char *host, int type) */ int isvalidchar(const char c) { - if (((c >= 'A') && (c <= 'Z')) || - ((c >= 'a') && (c <= 'z')) || - ((c >= '0') && (c <= '9')) || (c == '.') || (c == '-')) + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-') return 1; else return 0; } - /*************************************************************************/ /** @@ -619,19 +577,18 @@ char *myStrGetToken(const char *str, const char dilim, int token_number) { int len, idx, counter = 0, start_pos = 0; char *substring = NULL; - if (!str) { + if (!str) return NULL; - } len = strlen(str); - for (idx = 0; idx <= len; idx++) { - if ((str[idx] == dilim) || (idx == len)) { - if (counter == token_number) { + for (idx = 0; idx <= len; ++idx) + { + if (str[idx] == dilim || idx == len) + { + if (counter == token_number) substring = myStrSubString(str, start_pos, idx); - counter++; - } else { + else start_pos = idx + 1; - counter++; - } + ++counter; } } return substring; @@ -646,27 +603,27 @@ char *myStrGetToken(const char *str, const char dilim, int token_number) * @param token_number the token number * @return token */ -char *myStrGetOnlyToken(const char *str, const char dilim, - int token_number) +char *myStrGetOnlyToken(const char *str, const char dilim, int token_number) { int len, idx, counter = 0, start_pos = 0; char *substring = NULL; - if (!str) { + if (!str) return NULL; - } len = strlen(str); - for (idx = 0; idx <= len; idx++) { - if (str[idx] == dilim) { - if (counter == token_number) { + for (idx = 0; idx <= len; ++idx) + { + if (str[idx] == dilim) + { + if (counter == token_number) + { if (str[idx] == '\r') substring = myStrSubString(str, start_pos, idx - 1); else substring = myStrSubString(str, start_pos, idx); - counter++; - } else { - start_pos = idx + 1; - counter++; } + else + start_pos = idx + 1; + ++counter; } } return substring; @@ -681,25 +638,23 @@ char *myStrGetOnlyToken(const char *str, const char dilim, * @param token_number the token number * @return token */ -char *myStrGetTokenRemainder(const char *str, const char dilim, - int token_number) +char *myStrGetTokenRemainder(const char *str, const char dilim, int token_number) { int len, idx, counter = 0, start_pos = 0; char *substring = NULL; - if (!str) { + if (!str) return NULL; - } len = strlen(str); - for (idx = 0; idx <= len; idx++) { - if ((str[idx] == dilim) || (idx == len)) { - if (counter == token_number) { + for (idx = 0; idx <= len; ++idx) + { + if (str[idx] == dilim || idx == len) + { + if (counter == token_number) substring = myStrSubString(str, start_pos, len); - counter++; - } else { + else start_pos = idx + 1; - counter++; - } + ++counter; } } return substring; @@ -718,15 +673,14 @@ char *myStrSubString(const char *src, int start, int end) { char *substring = NULL; int len, idx; - if (!src) { + if (!src) return NULL; - } len = strlen(src); - if (((start >= 0) && (end <= len)) && (end > start)) { + if (start >= 0 && end <= len && end > start) + { substring = new char[(end - start) + 1]; - for (idx = 0; idx <= end - start; idx++) { + for (idx = 0; idx <= end - start; ++idx) substring[idx] = src[start + idx]; - } substring[end - start] = '\0'; } return substring; @@ -744,28 +698,28 @@ void doCleanBuffer(char *str) char *in, *out; char ch; - if (!str) { + if (!str) return; - } in = str; out = str; while (issp(ch = *in++)); - if (ch != '\0') - for (;;) { + if (ch) + for (;;) + { *out++ = ch; ch = *in++; - if (ch == '\0') + if (!ch) break; if (!issp(ch)) continue; while (issp(ch = *in++)); - if (ch == '\0') + if (!ch) break; *out++ = ' '; } - *out = ch; /* == '\0' */ + *out = ch; /* == '\0' */ } /*************************************************************************/ @@ -780,7 +734,8 @@ void EnforceQlinedNick(const std::string &nick, const char *killer) { User *u2; - if ((u2 = finduser(nick))) { + if ((u2 = finduser(nick))) + { Alog() << "Killed Q-lined nick: " << u2->GetMask(); kill_user(killer, u2->nick.c_str(), "This nick is reserved for Services. Please use a non Q-Lined nick."); } @@ -799,45 +754,46 @@ int nickIsServices(const char *tempnick, int bot) int found = 0; char *s, *nick; - if (!tempnick) { + if (!tempnick) return found; - } nick = sstrdup(tempnick); s = strchr(nick, '@'); - if (s) { + if (s) + { *s++ = 0; - if (stricmp(s, Config.ServerName) != 0) { + if (stricmp(s, Config.ServerName)) + { delete [] nick; return found; } } - if (Config.s_NickServ && (stricmp(nick, Config.s_NickServ) == 0)) - found++; - else if (Config.s_ChanServ && (stricmp(nick, Config.s_ChanServ) == 0)) - found++; - else if (Config.s_HostServ && (stricmp(nick, Config.s_HostServ) == 0)) - found++; - else if (Config.s_MemoServ && (stricmp(nick, Config.s_MemoServ) == 0)) - found++; - else if (Config.s_BotServ && (stricmp(nick, Config.s_BotServ) == 0)) - found++; - else if (Config.s_OperServ && (stricmp(nick, Config.s_OperServ) == 0)) - found++; - else if (Config.s_GlobalNoticer && (stricmp(nick, Config.s_GlobalNoticer) == 0)) - found++; + if (Config.s_NickServ && !stricmp(nick, Config.s_NickServ)) + ++found; + else if (Config.s_ChanServ && !stricmp(nick, Config.s_ChanServ)) + ++found; + else if (Config.s_HostServ && !stricmp(nick, Config.s_HostServ)) + ++found; + else if (Config.s_MemoServ && !stricmp(nick, Config.s_MemoServ)) + ++found; + else if (Config.s_BotServ && !stricmp(nick, Config.s_BotServ)) + ++found; + else if (Config.s_OperServ && !stricmp(nick, Config.s_OperServ)) + ++found; + else if (Config.s_GlobalNoticer && !stricmp(nick, Config.s_GlobalNoticer)) + ++found; else if (Config.s_BotServ && bot) { - for (botinfo_map::const_iterator it = BotListByNick.begin(); it != BotListByNick.end(); ++it) + for (botinfo_map::const_iterator it = BotListByNick.begin(), it_end = BotListByNick.end(); it != it_end; ++it) { BotInfo *bi = it->second; - + ci::string ci_bi_nick(bi->nick.c_str()); if (ci_bi_nick == nick) { - found++; + ++found; break; } } @@ -858,7 +814,7 @@ int nickIsServices(const char *tempnick, int bot) static void arc4_init() { int n; - for (n = 0; n < 256; n++) + for (n = 0; n < 256; ++n) rs.s[n] = n; rs.i = 0; rs.j = 0; @@ -877,11 +833,12 @@ static void arc4_addrandom(void *dat, int datlen) int n; uint8 si; - rs.i--; - for (n = 0; n < 256; n++) { - rs.i = (rs.i + 1); + --rs.i; + for (n = 0; n < 256; ++n) + { + rs.i = rs.i + 1; si = rs.s[rs.i]; - rs.j = (rs.j + si + (static_cast<unsigned char *>(dat))[n % datlen]); + rs.j = rs.j + si + (static_cast<unsigned char *>(dat))[n % datlen]; rs.s[rs.i] = rs.s[rs.j]; rs.s[rs.j] = si; } @@ -900,11 +857,11 @@ void rand_init() #endif struct { #ifndef _WIN32 - struct timeval nowt; /* time */ - char rnd[32]; /* /dev/urandom */ + struct timeval nowt; /* time */ + char rnd[32]; /* /dev/urandom */ #else - MEMORYSTATUS mstat; /* memory status */ - struct _timeb nowt; /* time */ + MEMORYSTATUS mstat; /* memory status */ + struct _timeb nowt; /* time */ #endif } rdat; @@ -916,7 +873,8 @@ void rand_init() gettimeofday(&rdat.nowt, NULL); /* unix/bsd: /dev/urandom */ fd = open("/dev/urandom", O_RDONLY); - if (fd) { + if (fd) + { n = read(fd, &rdat.rnd, sizeof(rdat.rnd)); close(fd); } @@ -954,13 +912,13 @@ unsigned char getrandom8() { unsigned char si, sj; - rs.i = (rs.i + 1); + rs.i = rs.i + 1; si = rs.s[rs.i]; - rs.j = (rs.j + si); + rs.j = rs.j + si; sj = rs.s[rs.j]; rs.s[rs.i] = sj; rs.s[rs.j] = si; - return (rs.s[(si + sj) & 0xff]); + return rs.s[(si + sj) & 0xff]; } /*************************************************************************/ @@ -1006,14 +964,15 @@ uint32 getrandom32() int myNumToken(const char *str, const char dilim) { int len, idx, counter = 0, start_pos = 0; - if (!str) { + if (!str) return 0; - } len = strlen(str); - for (idx = 0; idx <= len; idx++) { - if ((str[idx] == dilim) || (idx == len)) { + for (idx = 0; idx <= len; ++idx) + { + if (str[idx] == dilim || idx == len) + { start_pos = idx + 1; - counter++; + ++counter; } } return counter; @@ -1038,16 +997,15 @@ char *host_resolve(char *host) hentp = gethostbyname(host); - if (hentp) { + if (hentp) + { memcpy(&ip, hentp->h_addr, sizeof(hentp->h_length)); addr.s_addr = ip; ntoa(addr, ipbuf, sizeof(ipbuf)); ipreturn = sstrdup(ipbuf); Alog(LOG_DEBUG) << "resolved " << host << " to " << ipbuf; - return ipreturn; - } else { - return ipreturn; } + return ipreturn; } /*************************************************************************/ @@ -1088,7 +1046,7 @@ std::vector<std::string> BuildStringVector(const std::string &src) while (tokens.GetToken(token)) Ret.push_back(token); - + return Ret; } @@ -1106,7 +1064,8 @@ char *str_signed(unsigned char *str) char *nstr; nstr = reinterpret_cast<char *>(str); - while (*str) { + while (*str) + { *nstr = static_cast<char>(*str); str++; nstr++; @@ -1122,9 +1081,8 @@ char *str_signed(unsigned char *str) char *stripModePrefix(const char *str) { - if (str && ((*str == '+') || (*str == '-'))) { + if (str && (*str == '+' || *str == '-')) return sstrdup(str + 1); - } return NULL; } @@ -1133,8 +1091,7 @@ char *stripModePrefix(const char *str) void ntoa(struct in_addr addr, char *ipaddr, int len) { unsigned char *bytes = reinterpret_cast<unsigned char *>(&addr.s_addr); - snprintf(ipaddr, len, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2], - bytes[3]); + snprintf(ipaddr, len, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2], bytes[3]); } /* @@ -1149,12 +1106,12 @@ void ntoa(struct in_addr addr, char *ipaddr, int len) * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. +* notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products -* derived from this software without specific prior written permission. +* derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED `AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY @@ -1175,26 +1132,28 @@ size_t strlcat(char *dst, const char *src, size_t siz) const char *s = src; size_t n = siz, dlen; - while (n-- != 0 && *d != '\0') - d++; + while (n-- && *d) + ++d; dlen = d - dst; n = siz - dlen; - if (n == 0) - return (dlen + strlen(s)); + if (!n) + return dlen + strlen(s); - while (*s != '\0') { - if (n != 1) { + while (*s) + { + if (n != 1) + { *d++ = *s; - n--; + --n; } - s++; + ++s; } *d = '\0'; - return dlen + (s - src); /* count does not include NUL */ + return dlen + (s - src); /* count does not include NUL */ } #endif @@ -1206,28 +1165,28 @@ size_t strlcpy(char *dst, const char *src, size_t siz) size_t n = siz; /* Copy as many bytes as will fit */ - if (n != 0 && --n != 0) { - do { - if ((*d++ = *s++) == 0) + if (n && --n) + { + do + { + if (!(*d++ = *s++)) break; } - while (--n != 0); + while (--n); } /* Not enough room in dst, add NUL and traverse rest of src */ - if (n == 0) { - if (siz != 0) - *d = '\0'; /* NUL-terminate dst */ + if (!n) + { + if (siz) + *d = '\0'; /* NUL-terminate dst */ while (*s++); } - return s - src - 1; /* count does not include NUL */ + return s - src - 1; /* count does not include NUL */ } #endif - - - #ifdef _WIN32 char *GetWindowsVersion() { @@ -1242,126 +1201,119 @@ char *GetWindowsVersion() ZeroMemory(&si, sizeof(SYSTEM_INFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) & osvi))) { + if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi))) + { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - if (!GetVersionEx((OSVERSIONINFO *) & osvi)) { + if (!GetVersionEx((OSVERSIONINFO *)&osvi)) return sstrdup(""); - } } GetSystemInfo(&si); /* Determine CPU type 32 or 64 */ - if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 ) { - cputype = sstrdup(" 64-bit"); - } else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL ) { - cputype = sstrdup(" 32-bit"); - } else if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64 ) { - cputype = sstrdup(" Itanium 64-bit"); - } else { - cputype = sstrdup(" "); - } + if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) + cputype = sstrdup(" 64-bit"); + else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) + cputype = sstrdup(" 32-bit"); + else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) + cputype = sstrdup(" Itanium 64-bit"); + else + cputype = sstrdup(" "); - switch (osvi.dwPlatformId) { + switch (osvi.dwPlatformId) + { /* test for the Windows NT product family. */ - case VER_PLATFORM_WIN32_NT: - /* Windows Vista or Windows Server 2008 */ - if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) { - if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { - extra = sstrdup("Enterprise Edition"); - } else if (osvi.wSuiteMask & VER_SUITE_DATACENTER) { - extra = sstrdup("Datacenter Edition"); - } else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) { - extra = sstrdup("Home Premium/Basic"); - } else { - extra = sstrdup(" "); + case VER_PLATFORM_WIN32_NT: + /* Windows Vista or Windows Server 2008 */ + if (osvi.dwMajorVersion == 6 && !osvi.dwMinorVersion) + { + if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) + extra = sstrdup("Enterprise Edition"); + else if (osvi.wSuiteMask & VER_SUITE_DATACENTER) + extra = sstrdup("Datacenter Edition"); + else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) + extra = sstrdup("Home Premium/Basic"); + else + extra = sstrdup(" "); + if (osvi.wProductType & VER_NT_WORKSTATION) + snprintf(buf, sizeof(buf), "Microsoft Windows Vista %s%s", cputype, extra); + else + snprintf(buf, sizeof(buf), "Microsoft Windows Server 2008 %s%s", cputype, extra); + delete [] extra; } - if (osvi.wProductType & VER_NT_WORKSTATION) { - snprintf(buf, sizeof(buf), "Microsoft Windows Vista %s%s", - cputype, extra); - } else { - snprintf(buf, sizeof(buf), "Microsoft Windows Server 2008 %s%s", - cputype, extra); - } - delete [] extra; - } - /* Windows 2003 or Windows XP Pro 64 */ - if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { - if (osvi.wSuiteMask & VER_SUITE_DATACENTER) { - extra = sstrdup("Datacenter Edition"); - } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { - extra = sstrdup("Enterprise Edition"); + /* Windows 2003 or Windows XP Pro 64 */ + if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) + { + if (osvi.wSuiteMask & VER_SUITE_DATACENTER) + extra = sstrdup("Datacenter Edition"); + else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) + extra = sstrdup("Enterprise Edition"); #ifdef VER_SUITE_COMPUTE_SERVER - } else if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER) { - extra = sstrdup("Compute Cluster Edition"); + else if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER) + extra = sstrdup("Compute Cluster Edition"); #endif - } else if (osvi.wSuiteMask == VER_SUITE_BLADE) { - extra = sstrdup("Web Edition"); - } else { - extra = sstrdup("Standard Edition"); + else if (osvi.wSuiteMask == VER_SUITE_BLADE) + extra = sstrdup("Web Edition"); + else + extra = sstrdup("Standard Edition"); + if (osvi.wProductType & VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) + snprintf(buf, sizeof(buf), "Windows XP Professional x64 Edition %s", extra); + else + snprintf(buf, sizeof(buf), "Microsoft Windows Server 2003 Family %s%s", cputype, extra); + delete [] extra; } - if ( osvi.wProductType & VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { - snprintf(buf, sizeof(buf), "Windows XP Professional x64 Edition %s", - extra); - } else { - snprintf(buf, sizeof(buf), - "Microsoft Windows Server 2003 Family %s%s", cputype, extra); - } - delete [] extra; - } - if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) { - if (osvi.wSuiteMask & VER_SUITE_EMBEDDEDNT) { - extra = sstrdup("Embedded"); - } else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) { - extra = sstrdup("Home Edition"); - } else { - extra = sstrdup(" "); + if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) + { + if (osvi.wSuiteMask & VER_SUITE_EMBEDDEDNT) + extra = sstrdup("Embedded"); + else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) + extra = sstrdup("Home Edition"); + else + extra = sstrdup(" "); + snprintf(buf, sizeof(buf), "Microsoft Windows XP %s", extra); + delete [] extra; } - snprintf(buf, sizeof(buf), "Microsoft Windows XP %s", extra); - delete [] extra; - } - if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { - if (osvi.wSuiteMask & VER_SUITE_DATACENTER) { - extra = sstrdup("Datacenter Server"); - } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { - extra = sstrdup("Advanced Server"); - } else { - extra = sstrdup("Server"); + if (osvi.dwMajorVersion == 5 && !osvi.dwMinorVersion) + { + if (osvi.wSuiteMask & VER_SUITE_DATACENTER) + extra = sstrdup("Datacenter Server"); + else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) + extra = sstrdup("Advanced Server"); + else + extra = sstrdup("Server"); + snprintf(buf, sizeof(buf), "Microsoft Windows 2000 %s", extra); + delete [] extra; } - snprintf(buf, sizeof(buf), "Microsoft Windows 2000 %s", extra); - delete [] extra; - } - if (osvi.dwMajorVersion <= 4) { - if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) { - extra = sstrdup("Server 4.0, Enterprise Edition"); - } else { - extra = sstrdup("Server 4.0"); + if (osvi.dwMajorVersion <= 4) + { + if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) + extra = sstrdup("Server 4.0, Enterprise Edition"); + else + extra = sstrdup("Server 4.0"); + snprintf(buf, sizeof(buf), "Microsoft Windows NT %s", extra); + delete [] extra; } - snprintf(buf, sizeof(buf), "Microsoft Windows NT %s", extra); - delete [] extra; - } - case VER_PLATFORM_WIN32_WINDOWS: - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { - if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') { - extra = sstrdup("OSR2"); - } else { - extra = sstrdup(" "); + break; + case VER_PLATFORM_WIN32_WINDOWS: + if (osvi.dwMajorVersion == 4 && !osvi.dwMinorVersion) + { + if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') + extra = sstrdup("OSR2"); + else + extra = sstrdup(" "); + snprintf(buf, sizeof(buf), "Microsoft Windows 95 %s", extra); + delete [] extra; } - snprintf(buf, sizeof(buf), "Microsoft Windows 95 %s", extra); - delete [] extra; - } - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { - if (osvi.szCSDVersion[1] == 'A') { - extra = sstrdup("SE"); - } else { - extra = sstrdup(" "); + if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) + { + if (osvi.szCSDVersion[1] == 'A') + extra = sstrdup("SE"); + else + extra = sstrdup(" "); + snprintf(buf, sizeof(buf), "Microsoft Windows 98 %s", extra); + delete [] extra; } - snprintf(buf, sizeof(buf), "Microsoft Windows 98 %s", extra); - delete [] extra; - } - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { - snprintf(buf, sizeof(buf), - "Microsoft Windows Millennium Edition"); - } + if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) + snprintf(buf, sizeof(buf), "Microsoft Windows Millennium Edition"); } delete [] cputype; return sstrdup(buf); @@ -1375,32 +1327,31 @@ int SupportedWindowsVersion() ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) & osvi))) { + if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi))) + { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - if (!GetVersionEx((OSVERSIONINFO *) & osvi)) { + if (!GetVersionEx((OSVERSIONINFO *)&osvi)) return 0; - } } - switch (osvi.dwPlatformId) { + switch (osvi.dwPlatformId) + { /* test for the Windows NT product family. */ - case VER_PLATFORM_WIN32_NT: - /* win nt4 */ - if (osvi.dwMajorVersion <= 4) { - return 0; - } - /* the rest */ - return 1; + case VER_PLATFORM_WIN32_NT: + /* win nt4 */ + if (osvi.dwMajorVersion <= 4) + return 0; + /* the rest */ + return 1; /* win95 win98 winME */ - case VER_PLATFORM_WIN32_WINDOWS: - return 0; + case VER_PLATFORM_WIN32_WINDOWS: + return 0; } return 0; } #endif - /*************************************************************************/ /* This 2 functions were originally found in Bahamut */ @@ -1411,10 +1362,10 @@ int SupportedWindowsVersion() */ uint32 cidr_to_netmask(uint16 cidr) { - if (cidr == 0) + if (!cidr) return 0; - return (0xFFFFFFFF - (1 << (32 - cidr)) + 1); + return 0xFFFFFFFF - (1 << (32 - cidr)) + 1; } /** @@ -1426,10 +1377,10 @@ uint16 netmask_to_cidr(uint32 mask) { int tmp = 0; - while (!(mask & (1 << tmp)) && (tmp < 32)) - tmp++; + while (!(mask & (1 << tmp)) && tmp < 32) + ++tmp; - return (32 - tmp); + return 32 - tmp; } /*************************************************************************/ @@ -1441,10 +1392,11 @@ uint16 netmask_to_cidr(uint32 mask) */ int str_is_wildcard(const char *str) { - while (*str) { - if ((*str == '*') || (*str == '?')) + while (*str) + { + if (*str == '*' || *str == '?') return 1; - str++; + ++str; } return 0; @@ -1457,10 +1409,11 @@ int str_is_wildcard(const char *str) */ int str_is_pure_wildcard(const char *str) { - while (*str) { + while (*str) + { if (*str != '*') return 0; - str++; + ++str; } return 1; @@ -1480,14 +1433,14 @@ uint32 str_is_ip(char *str) char *s = str; uint32 ip; - for (i = 0; i < 4; i++) { + for (i = 0; i < 4; ++i) + { octets[i] = strtol(s, &s, 10); /* Bail out if the octet is invalid or wrongly terminated */ - if ((octets[i] < 0) || (octets[i] > 255) - || ((i < 3) && (*s != '.'))) + if (octets[i] < 0 || octets[i] > 255 || (i < 3 && *s != '.')) return 0; if (i < 3) - s++; + ++s; } /* Fill the IP - the dirty way */ @@ -1510,7 +1463,7 @@ uint32 str_is_ip(char *str) * @param host Displayed host * @return 1 for IP/CIDR, 0 for anything else */ -int str_is_cidr(char *str, uint32 * ip, uint32 * mask, char **host) +int str_is_cidr(char *str, uint32 *ip, uint32 *mask, char **host) { int i; int octets[4] = { -1, -1, -1, -1 }; @@ -1518,14 +1471,14 @@ int str_is_cidr(char *str, uint32 * ip, uint32 * mask, char **host) char buf[512]; uint16 cidr; - for (i = 0; i < 4; i++) { + for (i = 0; i < 4; ++i) + { octets[i] = strtol(s, &s, 10); /* Bail out if the octet is invalid or wrongly terminated */ - if ((octets[i] < 0) || (octets[i] > 255) - || ((i < 3) && (*s != '.'))) + if (octets[i] < 0 || octets[i] > 255 || (i < 3 && *s != '.')) return 0; if (i < 3) - s++; + ++s; } /* Fill the IP - the dirty way */ @@ -1534,17 +1487,18 @@ int str_is_cidr(char *str, uint32 * ip, uint32 * mask, char **host) *ip += octets[1] * 65536; *ip += octets[0] * 16777216; - if (*s == '/') { - s++; + if (*s == '/') + { + ++s; /* There's a CIDR mask here! */ cidr = strtol(s, &s, 10); /* Bail out if the CIDR is invalid or the string isn't done yet */ - if ((cidr > 32) || (*s)) + if (cidr > 32 || *s) return 0; - } else { + } + else /* No CIDR mask here - use 32 so the whole ip will be matched */ cidr = 32; - } *mask = cidr_to_netmask(cidr); /* Apply the mask to avoid 255.255.255.255/8 bans */ @@ -1557,15 +1511,11 @@ int str_is_cidr(char *str, uint32 * ip, uint32 * mask, char **host) octets[3] = (*ip & 0x000000FF); if (cidr == 32) - snprintf(buf, 512, "%d.%d.%d.%d", octets[0], octets[1], octets[2], - octets[3]); + snprintf(buf, 512, "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]); else - snprintf(buf, 512, "%d.%d.%d.%d/%d", octets[0], octets[1], - octets[2], octets[3], cidr); + snprintf(buf, 512, "%d.%d.%d.%d/%d", octets[0], octets[1], octets[2], octets[3], cidr); *host = sstrdup(buf); return 1; } - -/* EOF */ diff --git a/src/modes.cpp b/src/modes.cpp index 935d1e1b3..dce375488 100644 --- a/src/modes.cpp +++ b/src/modes.cpp @@ -4,8 +4,6 @@ * Copyright (C) 2008-2010 Anope Team <team@anope.org> * * Please read COPYING and README for further details. - * - * */ #include "services.h" @@ -51,15 +49,15 @@ void SetDefaultMLock() spacesepstream sep(Config.MLock); sep.GetToken(modes); - for (unsigned i = 0; i < modes.size(); ++i) + for (unsigned i = 0, end_mode = modes.size(); i < end_mode; ++i) { - if (modes[i] == '+') - ptr = &DefMLockOn; - else if (modes[i] == '-') - ptr = &DefMLockOff; - else - { - if (!ptr) + if (modes[i] == '+') + ptr = &DefMLockOn; + else if (modes[i] == '-') + ptr = &DefMLockOff; + else + { + if (!ptr) continue; ChannelMode *cm = ModeManager::FindChannelModeByChar(modes[i]); @@ -71,9 +69,7 @@ void SetDefaultMLock() if (ptr == &DefMLockOn && cm->Type == MODE_PARAM) { if (sep.GetToken(param)) - { DefMLockParams.insert(std::make_pair(cm->Name, param)); - } else { Alog() << "Warning: Got default mlock mode " << cm->ModeChar << " with no param?"; @@ -86,14 +82,12 @@ void SetDefaultMLock() /* Set Bot Modes */ BotModes.clear(); - for (unsigned i = 0; i < Config.BotModes.size(); ++i) + for (unsigned i = 0, end_mode = Config.BotModes.size(); i < end_mode; ++i) { ChannelMode *cm = ModeManager::FindChannelModeByChar(Config.BotModes[i]); if (cm && cm->Type == MODE_STATUS && std::find(BotModes.begin(), BotModes.end(), cm) == BotModes.end()) - { BotModes.push_back(dynamic_cast<ChannelModeStatus *>(cm)); - } } } @@ -274,8 +268,7 @@ void ChannelModeBan::AddMask(Channel *chan, const char *mask) /* Check whether it matches a botserv bot after adding internally * and parsing it through cidr support. ~ Viper */ - if (Config.s_BotServ && Config.BSSmartJoin && chan->ci && chan->ci->bi - && chan->users.size() >= Config.BSMinUsers) + if (Config.s_BotServ && Config.BSSmartJoin && chan->ci && chan->ci->bi && chan->users.size() >= Config.BSMinUsers) { BotInfo *bi = chan->ci->bi; @@ -300,7 +293,7 @@ void ChannelModeBan::DelMask(Channel *chan, const char *mask) Entry *ban; /* Sanity check as it seems some IRCD will just send -b without a mask */ - if (!mask || !chan->bans || (chan->bans->count == 0)) + if (!mask || !chan->bans || !chan->bans->count) return; ban = elist_find_mask(chan->bans, mask); @@ -351,7 +344,7 @@ void ChannelModeExcept::DelMask(Channel *chan, const char *mask) Entry *exception; /* Sanity check as it seems some IRCD will just send -e without a mask */ - if (!mask || !chan->excepts || (chan->excepts->count == 0)) + if (!mask || !chan->excepts || !chan->excepts->count) return; exception = elist_find_mask(chan->excepts, mask); @@ -399,7 +392,7 @@ void ChannelModeInvite::DelMask(Channel *chan, const char *mask) Entry *invite; /* Sanity check as it seems some IRCD will just send -I without a mask */ - if (!mask || !chan->invites || (chan->invites->count == 0)) + if (!mask || !chan->invites || !chan->invites->count) return; invite = elist_find_mask(chan->invites, mask); @@ -416,24 +409,20 @@ void StackerInfo::AddMode(void *Mode, bool Set, const std::string &Param) ChannelMode *cm = NULL; UserMode *um = NULL; std::list<std::pair<void *, std::string> > *list, *otherlist; - std::list<std::pair<void *, std::string > >::iterator it; + std::list<std::pair<void *, std::string > >::iterator it, it_end; bool IsParam = false; if (Type == ST_CHANNEL) { cm = static_cast<ChannelMode *>(Mode); if (cm->Type == MODE_PARAM) - { IsParam = true; - } } else if (Type == ST_USER) { um = static_cast<UserMode *>(Mode); if (um->Type == MODE_PARAM) - { IsParam = true; - } } if (Set) { @@ -447,7 +436,7 @@ void StackerInfo::AddMode(void *Mode, bool Set, const std::string &Param) } /* Loop through the list and find if this mode is already on here */ - for (it = list->begin(); it != list->end(); ++it) + for (it = list->begin(), it_end = list->end(); it != it_end; ++it) { /* The param must match too (can have multiple status or list modes), but * if it is a param mode it can match no matter what the param is @@ -460,7 +449,7 @@ void StackerInfo::AddMode(void *Mode, bool Set, const std::string &Param) } } /* If the mode is on the other list, remove it from there (eg, we dont want +o-o Adam Adam) */ - for (it = otherlist->begin(); it != otherlist->end(); ++it) + for (it = otherlist->begin(), it_end = otherlist->end(); it != it_end; ++it) { /* The param must match too (can have multiple status or list modes), but * if it is a param mode it can match no matter what the param is @@ -486,7 +475,7 @@ void StackerInfo::AddMode(void *Mode, bool Set, const std::string &Param) */ StackerInfo *ModeManager::GetInfo(void *Item) { - for (std::list<std::pair<void *, StackerInfo *> >::const_iterator it = StackerObjects.begin(); it != StackerObjects.end(); ++it) + for (std::list<std::pair<void *, StackerInfo *> >::const_iterator it = StackerObjects.begin(), it_end = StackerObjects.end(); it != it_end; ++it) { const std::pair<void *, StackerInfo *> &PItem = *it; if (PItem.first == Item) @@ -505,14 +494,14 @@ StackerInfo *ModeManager::GetInfo(void *Item) std::list<std::string> ModeManager::BuildModeStrings(StackerInfo *info) { std::list<std::string> ret; - std::list<std::pair<void *, std::string> >::iterator it; + std::list<std::pair<void *, std::string> >::iterator it, it_end; std::string buf, parambuf; ChannelMode *cm = NULL; UserMode *um = NULL; unsigned NModes = 0; buf = "+"; - for (it = info->AddModes.begin(); it != info->AddModes.end(); ++it) + for (it = info->AddModes.begin(), it_end = info->AddModes.end(); it != it_end; ++it) { if (++NModes > ircd->maxmodes) { @@ -541,7 +530,7 @@ std::list<std::string> ModeManager::BuildModeStrings(StackerInfo *info) buf.erase(buf.length() - 1); buf += "-"; - for (it = info->DelModes.begin(); it != info->DelModes.end(); ++it) + for (it = info->DelModes.begin(), it_end = info->DelModes.end(); it != it_end; ++it) { if (++NModes > ircd->maxmodes) { @@ -679,9 +668,7 @@ ChannelMode *ModeManager::FindChannelModeByChar(char Mode) std::map<char, ChannelMode *>::iterator it = ModeManager::ChannelModesByChar.find(Mode); if (it != ModeManager::ChannelModesByChar.end()) - { return it->second; - } return NULL; } @@ -695,9 +682,7 @@ UserMode *ModeManager::FindUserModeByChar(char Mode) std::map<char, UserMode *>::iterator it = ModeManager::UserModesByChar.find(Mode); if (it != ModeManager::UserModesByChar.end()) - { return it->second; - } return NULL; } @@ -711,9 +696,7 @@ ChannelMode *ModeManager::FindChannelModeByName(ChannelModeName Name) std::map<ChannelModeName, ChannelMode *>::iterator it = ModeManager::ChannelModesByName.find(Name); if (it != ModeManager::ChannelModesByName.end()) - { return it->second; - } return NULL; } @@ -727,9 +710,7 @@ UserMode *ModeManager::FindUserModeByName(UserModeName Name) std::map<UserModeName, UserMode *>::iterator it = ModeManager::UserModesByName.find(Name); if (it != ModeManager::UserModesByName.end()) - { return it->second; - } return NULL; } @@ -740,11 +721,11 @@ UserMode *ModeManager::FindUserModeByName(UserModeName Name) */ char ModeManager::GetStatusChar(char Value) { - std::map<char, ChannelMode *>::iterator it; + std::map<char, ChannelMode *>::iterator it, it_end; ChannelMode *cm; ChannelModeStatus *cms; - for (it = ModeManager::ChannelModesByChar.begin(); it != ModeManager::ChannelModesByChar.end(); ++it) + for (it = ModeManager::ChannelModesByChar.begin(), it_end = ModeManager::ChannelModesByChar.end(); it != it_end; ++it) { cm = it->second; if (cm->Type == MODE_STATUS) @@ -752,9 +733,7 @@ char ModeManager::GetStatusChar(char Value) cms = dynamic_cast<ChannelModeStatus *>(cm); if (Value == cms->Symbol) - { return it->first; - } } } @@ -839,7 +818,7 @@ void ModeManager::ProcessModes() { if (!StackerObjects.empty()) { - for (std::list<std::pair<void *, StackerInfo *> >::const_iterator it = StackerObjects.begin(); it != StackerObjects.end(); ++it) + for (std::list<std::pair<void *, StackerInfo *> >::const_iterator it = StackerObjects.begin(), it_end = StackerObjects.end(); it != it_end; ++it) { StackerInfo *s = it->second; User *u = NULL; @@ -853,7 +832,7 @@ void ModeManager::ProcessModes() else throw CoreException("ModeManager::ProcessModes got invalid Stacker Info type"); - for (std::list<std::string>::iterator lit = ModeStrings.begin(); lit != ModeStrings.end(); ++lit) + for (std::list<std::string>::iterator lit = ModeStrings.begin(), lit_end = ModeStrings.end(); lit != lit_end; ++lit) { if (c) ircdproto->SendMode(s->bi, c, lit->c_str()); @@ -865,4 +844,3 @@ void ModeManager::ProcessModes() StackerObjects.clear(); } } - diff --git a/src/module.cpp b/src/module.cpp index b30e2b6a7..df50b63d1 100644 --- a/src/module.cpp +++ b/src/module.cpp @@ -4,29 +4,26 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. - * - * */ + #include "modules.h" #include "language.h" #include "version.h" Module::Module(const std::string &mname, const std::string &creator) { - this->name = mname; /* Our name */ + this->name = mname; /* Our name */ this->type = THIRD; this->handle = NULL; this->permanent = false; - for (int i = 0; i < NUM_LANGS; i++) - { + for (int i = 0; i < NUM_LANGS; ++i) this->lang[i].argc = 0; - } if (FindModule(this->name)) throw CoreException("Module already exists!"); - + this->created = time(NULL); Modules.push_back(this); @@ -36,7 +33,7 @@ Module::~Module() { int i = 0; - for (i = 0; i < NUM_LANGS; i++) + for (i = 0; i < NUM_LANGS; ++i) this->DeleteLanguage(i); remove(this->filename.c_str()); @@ -49,7 +46,7 @@ Module::~Module() **/ if (HostServ) { - for (std::map<ci::string, Command *>::iterator it = HostServ->Commands.begin(); it != HostServ->Commands.end();) + for (std::map<ci::string, Command *>::iterator it = HostServ->Commands.begin(), it_end = HostServ->Commands.end(); it != it_end; ) { Command *c = it->second; ++it; @@ -61,7 +58,7 @@ Module::~Module() if (BotServ) { - for (std::map<ci::string, Command *>::iterator it = BotServ->Commands.begin(); it != BotServ->Commands.end();) + for (std::map<ci::string, Command *>::iterator it = BotServ->Commands.begin(), it_end = BotServ->Commands.end(); it != it_end; ) { Command *c = it->second; ++it; @@ -73,7 +70,7 @@ Module::~Module() if (MemoServ) { - for (std::map<ci::string, Command *>::iterator it = MemoServ->Commands.begin(); it != MemoServ->Commands.end();) + for (std::map<ci::string, Command *>::iterator it = MemoServ->Commands.begin(), it_end = MemoServ->Commands.end(); it != it_end; ) { Command *c = it->second; ++it; @@ -85,7 +82,7 @@ Module::~Module() if (NickServ) { - for (std::map<ci::string, Command *>::iterator it = NickServ->Commands.begin(); it != NickServ->Commands.end();) + for (std::map<ci::string, Command *>::iterator it = NickServ->Commands.begin(), it_end = NickServ->Commands.end(); it != it_end; ) { Command *c = it->second; ++it; @@ -94,10 +91,10 @@ Module::~Module() this->DelCommand(NickServ, c); } } - + if (ChanServ) { - for (std::map<ci::string, Command *>::iterator it = ChanServ->Commands.begin(); it != ChanServ->Commands.end();) + for (std::map<ci::string, Command *>::iterator it = ChanServ->Commands.begin(), it_end = ChanServ->Commands.end(); it != it_end; ) { Command *c = it->second; ++it; @@ -109,7 +106,7 @@ Module::~Module() if (OperServ) { - for (std::map<ci::string, Command *>::iterator it = OperServ->Commands.begin(); it != OperServ->Commands.end();) + for (std::map<ci::string, Command *>::iterator it = OperServ->Commands.begin(), it_end = OperServ->Commands.end(); it != it_end; ) { Command *c = it->second; ++it; @@ -119,7 +116,7 @@ Module::~Module() } } - for (std::deque<Module *>::iterator it = Modules.begin(); it != Modules.end(); ++it) + for (std::deque<Module *>::iterator it = Modules.begin(), it_end = Modules.end(); it != it_end; ++it) { if (*it == this) { diff --git a/src/modulemanager.cpp b/src/modulemanager.cpp index b11ad2829..2d65ab4c9 100644 --- a/src/modulemanager.cpp +++ b/src/modulemanager.cpp @@ -4,9 +4,8 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. - * - * */ + #include "modules.h" #include "language.h" #include "version.h" @@ -16,7 +15,17 @@ std::vector<Module *> ModuleManager::EventHandlers[I_END]; void ModuleManager::LoadModuleList(std::list<std::string> &ModuleList) { - for (std::list<std::string>::iterator it = ModuleList.begin(); it != ModuleList.end(); ++it) + for (std::list<std::string>::iterator it = ModuleList.begin(), it_end = ModuleList.end(); it != it_end; ++it) + { + Module *m = FindModule(*it); + if (!m) + ModuleManager::LoadModule(*it, NULL); + } +} + +void ModuleManager::LoadModuleList(std::list<ci::string> &ModuleList) +{ + for (std::list<ci::string>::iterator it = ModuleList.begin(), it_end = ModuleList.end(); it != it_end; ++it) { Module *m = FindModule(*it); if (!m) @@ -47,7 +56,7 @@ static int moduleCopyFile(const char *name, const char *output) strlcat(input, name, sizeof(input)); strlcat(input, MODULE_EXT, sizeof(input)); - if ((source = fopen(input, "rb")) == NULL) + if (!(source = fopen(input, "rb"))) return MOD_ERR_NOEXIST; #ifndef _WIN32 @@ -61,19 +70,16 @@ static int moduleCopyFile(const char *name, const char *output) Alog(LOG_DEBUG) << "Runtime module location: " << output; #ifndef _WIN32 - if ((target = fdopen(srcfp, "w")) == NULL) { + if (!(target = fdopen(srcfp, "w"))) #else - if ((target = fopen(output, "wb")) == NULL) { + if (!(target = fopen(output, "wb"))) #endif return MOD_ERR_FILE_IO; - } - while ((ch = fgetc(source)) != EOF) { + while ((ch = fgetc(source)) != EOF) fputc(ch, target); - } fclose(source); - if (fclose(target) != 0) { + if (fclose(target)) return MOD_ERR_FILE_IO; - } return MOD_ERR_OK; } @@ -81,12 +87,10 @@ static bool IsOneOfModuleTypeLoaded(MODType mt) { int pmods = 0; - for (std::deque<Module *>::iterator it = Modules.begin(); it != Modules.end(); ++it) + for (std::deque<Module *>::iterator it = Modules.begin(), it_end = Modules.end(); it != it_end; ++it) { if ((*it)->type == mt) - { ++pmods; - } } /* @@ -104,10 +108,10 @@ static bool IsOneOfModuleTypeLoaded(MODType mt) * This function will take a pointer from either dlsym or GetProcAddress and cast it in * a way that won't cause C++ warnings/errors to come up. */ -template <class TYPE> -TYPE function_cast(ano_module_t symbol) +template <class TYPE> TYPE function_cast(ano_module_t symbol) { - union { + union + { ano_module_t symbol; TYPE function; } cast; @@ -115,7 +119,7 @@ TYPE function_cast(ano_module_t symbol) return cast.function; } -int ModuleManager::LoadModule(const std::string &modname, User * u) +int ModuleManager::LoadModule(const std::string &modname, User *u) { const char *err; Module *(*func)(const std::string &, const std::string &); @@ -154,7 +158,7 @@ int ModuleManager::LoadModule(const std::string &modname, User * u) ano_modclearerr(); ano_module_t handle = dlopen(pbuf.c_str(), RTLD_LAZY); - if (handle == NULL && (err = dlerror()) != NULL) + if (!handle && (err = dlerror())) { Alog() << err; return MOD_ERR_NOLOAD; @@ -162,7 +166,7 @@ int ModuleManager::LoadModule(const std::string &modname, User * u) ano_modclearerr(); func = function_cast<Module *(*)(const std::string &, const std::string &)>(dlsym(handle, "AnopeInit")); - if (func == NULL && (err = dlerror()) != NULL) + if (!func && (err = dlerror())) { Alog() << "No init function found, not an Anope module"; dlclose(handle); @@ -170,9 +174,7 @@ int ModuleManager::LoadModule(const std::string &modname, User * u) } if (!func) - { throw CoreException("Couldn't find constructor, yet moderror wasn't set?"); - } /* Create module. */ std::string nick; @@ -187,7 +189,7 @@ int ModuleManager::LoadModule(const std::string &modname, User * u) { m = func(modname, nick); } - catch (ModuleException &ex) + catch (const ModuleException &ex) { Alog() << "Error while loading " << modname << ": " << ex.GetReason(); return MOD_STOP; @@ -210,18 +212,11 @@ int ModuleManager::LoadModule(const std::string &modname, User * u) return MOD_STOP; } else if (v.GetBuild() < VERSION_BUILD) - { Alog() << "Module " << modname << " is compiled against an older revision of Anope " << v.GetBuild() << ", this is " << VERSION_BUILD; - } else if (v.GetBuild() > VERSION_BUILD) - { Alog() << "Module " << modname << " is compiled against a newer revision of Anope " << v.GetBuild() << ", this is " << VERSION_BUILD; - } else if (v.GetBuild() == VERSION_BUILD) - { Alog(LOG_DEBUG) << "Module " << modname << " compiled against current version of Anope " << v.GetBuild(); - } - if (m->type == PROTOCOL && IsOneOfModuleTypeLoaded(PROTOCOL)) { @@ -246,6 +241,16 @@ int ModuleManager::LoadModule(const std::string &modname, User * u) return MOD_ERR_OK; } +int ModuleManager::LoadModule(const char *modname, User *u) +{ + return LoadModule(std::string(modname), u); +} + +int ModuleManager::LoadModule(const ci::string &modname, User *u) +{ + return LoadModule(std::string(modname.c_str()), u); +} + int ModuleManager::UnloadModule(Module *m, User *u) { if (!m || !m->handle) @@ -281,33 +286,29 @@ void ModuleManager::DeleteModule(Module *m) ano_module_t handle; if (!m || !m->handle) /* check m is least possibly valid */ - { return; - } DetachAll(m); handle = m->handle; ano_modclearerr(); destroy_func = function_cast<void (*)(Module *)>(dlsym(m->handle, "AnopeFini")); - if (destroy_func == NULL && (err = dlerror()) != NULL) + if (!destroy_func && (err = dlerror())) { Alog() << "No destroy function found, chancing delete..."; delete m; /* we just have to chance they haven't overwrote the delete operator then... */ } else - { destroy_func(m); /* Let the module delete it self, just in case */ - } if (handle) { - if ((dlclose(handle)) != 0) + if (dlclose(handle)) Alog() << dlerror(); } } -bool ModuleManager::Attach(Implementation i, Module* mod) +bool ModuleManager::Attach(Implementation i, Module *mod) { if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end()) return false; @@ -316,7 +317,7 @@ bool ModuleManager::Attach(Implementation i, Module* mod) return true; } -bool ModuleManager::Detach(Implementation i, Module* mod) +bool ModuleManager::Detach(Implementation i, Module *mod) { std::vector<Module *>::iterator x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod); @@ -327,19 +328,19 @@ bool ModuleManager::Detach(Implementation i, Module* mod) return true; } -void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz) +void ModuleManager::Attach(Implementation *i, Module *mod, size_t sz) { for (size_t n = 0; n < sz; ++n) Attach(i[n], mod); } -void ModuleManager::DetachAll(Module* mod) +void ModuleManager::DetachAll(Module *mod) { for (size_t n = I_BEGIN + 1; n != I_END; ++n) Detach(static_cast<Implementation>(n), mod); } -bool ModuleManager::SetPriority(Module* mod, Priority s) +bool ModuleManager::SetPriority(Module *mod, Priority s) { for (size_t n = I_BEGIN + 1; n != I_END; ++n) SetPriority(mod, static_cast<Implementation>(n), s); @@ -347,7 +348,7 @@ bool ModuleManager::SetPriority(Module* mod, Priority s) return true; } -bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module** modules, size_t sz) +bool ModuleManager::SetPriority(Module *mod, Implementation i, Priority s, Module **modules, size_t sz) { /** To change the priority of a module, we first find its position in the vector, * then we find the position of the other modules in the vector that this module @@ -363,7 +364,7 @@ bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Modul /* Locate our module. This is O(n) but it only occurs on module load so we're * not too bothered about it */ - for (size_t x = 0; x != EventHandlers[i].size(); ++x) + for (size_t x = 0, end = EventHandlers[i].size(); x != end; ++x) { if (EventHandlers[i][x] == mod) { @@ -384,59 +385,58 @@ bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Modul /* Dummy value */ case PRIORITY_DONTCARE: swap = false; - break; + break; /* Module wants to be first, sod everything else */ case PRIORITY_FIRST: swap_pos = 0; - break; + break; /* Module is submissive and wants to be last... awww. */ case PRIORITY_LAST: if (EventHandlers[i].empty()) swap_pos = 0; else swap_pos = EventHandlers[i].size() - 1; - break; + break; /* Place this module after a set of other modules */ case PRIORITY_AFTER: - { - /* Find the latest possible position */ - swap_pos = 0; - swap = false; - for (size_t x = 0; x != EventHandlers[i].size(); ++x) { - for (size_t n = 0; n < sz; ++n) + /* Find the latest possible position */ + swap_pos = 0; + swap = false; + for (size_t x = 0, end = EventHandlers[i].size(); x != end; ++x) { - if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x >= swap_pos) && (source <= swap_pos)) + for (size_t n = 0; n < sz; ++n) { - swap_pos = x; - swap = true; + if (modules[n] && EventHandlers[i][x] == modules[n] && x >= swap_pos && source <= swap_pos) + { + swap_pos = x; + swap = true; + } } } } - } - break; + break; /* Place this module before a set of other modules */ case PRIORITY_BEFORE: - { - swap_pos = EventHandlers[i].size() - 1; - swap = false; - for (size_t x = 0; x != EventHandlers[i].size(); ++x) { - for (size_t n = 0; n < sz; ++n) + swap_pos = EventHandlers[i].size() - 1; + swap = false; + for (size_t x = 0, end = EventHandlers[i].size(); x != end; ++x) { - if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x <= swap_pos) && (source >= swap_pos)) + for (size_t n = 0; n < sz; ++n) { - swap = true; - swap_pos = x; + if (modules[n] && EventHandlers[i][x] == modules[n] && x <= swap_pos && source >= swap_pos) + { + swap = true; + swap_pos = x; + } } } } - } - break; } /* Do we need to swap? */ - if (swap && (swap_pos != source)) + if (swap && swap_pos != source) { /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */ int incrmnt = 1; @@ -446,10 +446,10 @@ bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Modul for (unsigned int j = source; j != swap_pos; j += incrmnt) { - if (( j + incrmnt > EventHandlers[i].size() - 1) || (j + incrmnt < 0)) + if (j + incrmnt > EventHandlers[i].size() - 1 || j + incrmnt < 0) continue; - std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]); + std::swap(EventHandlers[i][j], EventHandlers[i][j + incrmnt]); } } @@ -471,7 +471,7 @@ void ModuleManager::ClearCallBacks(Module *m) */ void ModuleManager::UnloadAll(bool unload_proto) { - for (std::deque<Module *>::iterator it = Modules.begin(); it != Modules.end();) + for (std::deque<Module *>::iterator it = Modules.begin(), it_end = Modules.end(); it != it_end; ) { Module *m = *it++; @@ -482,4 +482,3 @@ void ModuleManager::UnloadAll(bool unload_proto) break; } } - diff --git a/src/modules.cpp b/src/modules.cpp index 0044bcc56..f66bd01a2 100644 --- a/src/modules.cpp +++ b/src/modules.cpp @@ -7,9 +7,8 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ + #include "modules.h" #include "language.h" #include "version.h" @@ -23,24 +22,23 @@ char *ModuleGetErrStr(int status) { const char *module_err_str[] = { "Module, Okay - No Error", /* MOD_ERR_OK */ - "Module Error, Allocating memory", /* MOD_ERR_MEMORY */ - "Module Error, Not enough parameters", /* MOD_ERR_PARAMS */ - "Module Error, Already loaded", /* MOD_ERR_EXISTS */ - "Module Error, File does not exist", /* MOD_ERR_NOEXIST */ + "Module Error, Allocating memory", /* MOD_ERR_MEMORY */ + "Module Error, Not enough parameters", /* MOD_ERR_PARAMS */ + "Module Error, Already loaded", /* MOD_ERR_EXISTS */ + "Module Error, File does not exist", /* MOD_ERR_NOEXIST */ "Module Error, No User", /* MOD_ERR_NOUSER */ - "Module Error, Error during load time or module returned MOD_STOP", /* MOD_ERR_NOLOAD */ - "Module Error, Unable to unload", /* MOD_ERR_NOUNLOAD */ - "Module Error, Incorrect syntax", /* MOD_ERR_SYNTAX */ - "Module Error, Unable to delete", /* MOD_ERR_NODELETE */ - "Module Error, Unknown Error occuried", /* MOD_ERR_UNKOWN */ - "Module Error, File I/O Error", /* MOD_ERR_FILE_IO */ - "Module Error, No Service found for request", /* MOD_ERR_NOSERVICE */ - "Module Error, No module name for request" /* MOD_ERR_NO_MOD_NAME */ + "Module Error, Error during load time or module returned MOD_STOP", /* MOD_ERR_NOLOAD */ + "Module Error, Unable to unload", /* MOD_ERR_NOUNLOAD */ + "Module Error, Incorrect syntax", /* MOD_ERR_SYNTAX */ + "Module Error, Unable to delete", /* MOD_ERR_NODELETE */ + "Module Error, Unknown Error occuried", /* MOD_ERR_UNKOWN */ + "Module Error, File I/O Error", /* MOD_ERR_FILE_IO */ + "Module Error, No Service found for request", /* MOD_ERR_NOSERVICE */ + "Module Error, No module name for request" /* MOD_ERR_NO_MOD_NAME */ }; return const_cast<char *>(module_err_str[status]); } - /************************************************/ /** @@ -79,15 +77,13 @@ void Module::InsertLanguage(int langNumber, int ac, const char **av) Alog(LOG_DEBUG) << this->name << "Adding " << ac << " texts for language " << langNumber; - if (this->lang[langNumber].argc > 0) { + if (this->lang[langNumber].argc > 0) this->DeleteLanguage(langNumber); - } this->lang[langNumber].argc = ac; this->lang[langNumber].argv = new char *[ac]; - for (i = 0; i < ac; i++) { + for (i = 0; i < ac; ++i) this->lang[langNumber].argv[i] = sstrdup(av[i]); - } } /** @@ -97,19 +93,27 @@ void Module::InsertLanguage(int langNumber, int ac, const char **av) */ Module *FindModule(const std::string &name) { - for (std::deque<Module *>::iterator it = Modules.begin(); it != Modules.end(); ++it) + for (std::deque<Module *>::iterator it = Modules.begin(), it_end = Modules.end(); it != it_end; ++it) { Module *m = *it; if (m->name == name) - { return m; - } } return NULL; } +Module *FindModule(const char *name) +{ + return FindModule(std::string(name)); +} + +Module *FindModule(const ci::string &name) +{ + return FindModule(std::string(name.c_str())); +} + /** Add a message to Anope * @param name The message name as sent by the IRCd * @param func A callback function that will be called when this message is received @@ -138,9 +142,7 @@ bool Anope::DelMessage(Message *m) std::multimap<std::string, Message *>::iterator it = MessageMap.find(m->name); if (it == MessageMap.end()) - { return false; - } std::multimap<std::string, Message *>::iterator upper = MessageMap.upper_bound(m->name); @@ -165,7 +167,7 @@ int Module::AddCommand(BotInfo *bi, Command *c) { if (!bi || !c) return MOD_ERR_PARAMS; - + c->module = this; c->service = bi; @@ -177,7 +179,7 @@ int Module::AddCommand(BotInfo *bi, Command *c) delete c; return MOD_ERR_EXISTS; } - + return MOD_ERR_OK; } @@ -191,7 +193,7 @@ int Module::DelCommand(BotInfo *bi, Command *c) { if (!bi || !c) return MOD_ERR_PARAMS; - + if (!bi->Commands.erase(c->name)) return MOD_ERR_NOEXIST; @@ -211,7 +213,7 @@ std::vector<Message *> FindMessage(const std::string &name) if (it == MessageMap.end()) return messages; - + std::multimap<std::string, Message *>::iterator upper = MessageMap.upper_bound(name); for (; it != upper; ++it) @@ -235,29 +237,28 @@ std::vector<Message *> FindMessage(const std::string &name) bool moduleMinVersion(int major, int minor, int patch, int build) { bool ret = false; - if (VERSION_MAJOR > major) { /* Def. new */ + if (VERSION_MAJOR > major) /* Def. new */ ret = true; - } else if (VERSION_MAJOR == major) { /* Might be newer */ - if (minor == -1) { - return true; - } /* They dont care about minor */ - if (VERSION_MINOR > minor) { /* Def. newer */ + else if (VERSION_MAJOR == major) /* Might be newer */ + { + if (minor == -1) + return true; /* They dont care about minor */ + if (VERSION_MINOR > minor) /* Def. newer */ ret = true; - } else if (VERSION_MINOR == minor) { /* Might be newer */ - if (patch == -1) { - return true; - } /* They dont care about patch */ - if (VERSION_PATCH > patch) { + else if (VERSION_MINOR == minor) /* Might be newer */ + { + if (patch == -1) + return true; /* They dont care about patch */ + if (VERSION_PATCH > patch) ret = true; - } else if (VERSION_PATCH == patch) { + else if (VERSION_PATCH == patch) + { #if 0 // XXX - if (build == -1) { - return true; - } /* They dont care about build */ - if (VERSION_BUILD >= build) { + if (build == -1) + return true; /* They dont care about build */ + if (VERSION_BUILD >= build) ret = true; - } #endif } } @@ -265,7 +266,7 @@ bool moduleMinVersion(int major, int minor, int patch, int build) return ret; } -void Module::NoticeLang(const char *source, User * u, int number, ...) +void Module::NoticeLang(const char *source, User *u, int number, ...) { va_list va; char buffer[4096], outbuf[4096]; @@ -274,18 +275,16 @@ void Module::NoticeLang(const char *source, User * u, int number, ...) char *s, *t, *buf; /* Find the users lang, and use it if we can */ - if (u && u->Account()) { + if (u && u->Account()) mlang = u->Account()->language; - } /* If the users lang isnt supported, drop back to English */ - if (this->lang[mlang].argc == 0) - { + if (!this->lang[mlang].argc) mlang = LANG_EN_US; - } /* If the requested lang string exists for the language */ - if (this->lang[mlang].argc > number) { + if (this->lang[mlang].argc > number) + { fmt = this->lang[mlang].argv[number]; buf = sstrdup(fmt); @@ -293,7 +292,8 @@ void Module::NoticeLang(const char *source, User * u, int number, ...) vsnprintf(buffer, 4095, buf, va); va_end(va); s = buffer; - while (*s) { + while (*s) + { t = s; s += strcspn(s, "\n"); if (*s) @@ -302,12 +302,12 @@ void Module::NoticeLang(const char *source, User * u, int number, ...) u->SendMessage(source, "%s", outbuf); } delete [] buf; - } else { - Alog() << this->name << ": INVALID language string call, language: [" << mlang << "], String [" << number << "]"; } + else + Alog() << this->name << ": INVALID language string call, language: [" << mlang << "], String [" << number << "]"; } -const char *Module::GetLangString(User * u, int number) +const char *Module::GetLangString(User *u, int number) { int mlang = Config.NSDefLanguage; @@ -316,17 +316,18 @@ const char *Module::GetLangString(User * u, int number) mlang = u->Account()->language; /* If the users lang isnt supported, drop back to English */ - if (this->lang[mlang].argc == 0) + if (!this->lang[mlang].argc) mlang = LANG_EN_US; /* If the requested lang string exists for the language */ - if (this->lang[mlang].argc > number) { + if (this->lang[mlang].argc > number) return this->lang[mlang].argv[number]; /* Return an empty string otherwise, because we might be used without * the return value being checked. If we would return NULL, bad things * would happen! */ - } else { + else + { Alog() << this->name << ": INVALID language string call, language: [" << mlang << "], String [" << number << "]"; return ""; } @@ -336,7 +337,7 @@ void Module::DeleteLanguage(int langNumber) { if (this->lang[langNumber].argc) { - for (int idx = 0; idx > this->lang[langNumber].argc; idx++) + for (int idx = 0; idx > this->lang[langNumber].argc; ++idx) delete [] this->lang[langNumber].argv[idx]; delete [] this->lang[langNumber].argv; this->lang[langNumber].argc = 0; @@ -362,52 +363,49 @@ void ModuleRunTimeDirCleanUp() Alog(LOG_DEBUG) << "Cleaning out Module run time directory (" << dirbuf << ") - this may take a moment please wait"; - #ifndef _WIN32 - if ((dirp = opendir(dirbuf)) == NULL) + if (!(dirp = opendir(dirbuf))) { Alog(LOG_DEBUG) << "cannot open directory (" << dirbuf << ")"; return; } - while ((dp = readdir(dirp)) != NULL) { - if (dp->d_ino == 0) { + while ((dp = readdir(dirp))) + { + if (!dp->d_ino) continue; - } - if (!stricmp(dp->d_name, ".") || !stricmp(dp->d_name, "..")) { + if (!stricmp(dp->d_name, ".") || !stricmp(dp->d_name, "..")) continue; - } snprintf(filebuf, BUFSIZE, "%s/%s", dirbuf, dp->d_name); unlink(filebuf); } closedir(dirp); #else /* Get the current working directory: */ - if (_getcwd(buffer, _MAX_PATH) == NULL) - { + if (!_getcwd(buffer, _MAX_PATH)) Alog(LOG_DEBUG) << "Unable to set Current working directory"; - } snprintf(szDir, sizeof(szDir), "%s\\%s\\*", buffer, dirbuf); hList = FindFirstFile(szDir, &FileData); - if (hList != INVALID_HANDLE_VALUE) { + if (hList != INVALID_HANDLE_VALUE) + { fFinished = FALSE; - while (!fFinished) { - if (!(FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + while (!fFinished) + { + if (!(FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + { snprintf(filebuf, BUFSIZE, "%s/%s", dirbuf, FileData.cFileName); DeleteFile(filebuf); } - if (!FindNextFile(hList, &FileData)) { - if (GetLastError() == ERROR_NO_MORE_FILES) { + if (!FindNextFile(hList, &FileData)) + { + if (GetLastError() == ERROR_NO_MORE_FILES) fFinished = TRUE; - } } } - } else { - Alog(LOG_DEBUG) << "Invalid File Handle. GetLastError() reports "<< static_cast<int>(GetLastError()); } + else + Alog(LOG_DEBUG) << "Invalid File Handle. GetLastError() reports "<< static_cast<int>(GetLastError()); FindClose(hList); #endif Alog(LOG_DEBUG) << "Module run time directory has been cleaned out"; } - -/* EOF */ diff --git a/src/modules/hs_request.cpp b/src/modules/hs_request.cpp index cc5637bef..574611f09 100644 --- a/src/modules/hs_request.cpp +++ b/src/modules/hs_request.cpp @@ -781,7 +781,7 @@ void req_send_memos(User *u, char *vIdent, char *vHost) { int z = 2; char host[BUFSIZE]; - std::list<std::pair<std::string, std::string> >::iterator it; + std::list<std::pair<ci::string, ci::string> >::iterator it; if (vIdent) snprintf(host, sizeof(host), "%s@%s", vIdent, vHost); @@ -792,7 +792,7 @@ void req_send_memos(User *u, char *vIdent, char *vHost) { for (it = Config.Opers.begin(); it != Config.Opers.end(); ++it) { - std::string nick = it->first; + ci::string nick = it->first; my_memo_lang(u, nick.c_str(), z, LNG_REQUEST_MEMO, host); } } diff --git a/src/nickalias.cpp b/src/nickalias.cpp index a196145b9..8ffbac891 100644 --- a/src/nickalias.cpp +++ b/src/nickalias.cpp @@ -19,7 +19,7 @@ NickRequest::~NickRequest() FOREACH_MOD(I_OnDelNickRequest, OnDelNickRequest(this)); NickRequestList.erase(this->nick); - + if (this->nick) delete [] this->nick; if (this->email) @@ -39,22 +39,22 @@ NickAlias::NickAlias(const std::string &nickname, NickCore *nickcore) nick = last_quit = last_realname = last_usermask = NULL; time_registered = last_seen = 0; - + this->nick = sstrdup(nickname.c_str()); this->nc = nickcore; nc->aliases.push_back(this); NickAliasList[this->nick] = this; - for (std::list<std::pair<std::string, std::string> >::iterator it = Config.Opers.begin(); it != Config.Opers.end(); it++) + for (std::list<std::pair<ci::string, ci::string> >::iterator it = Config.Opers.begin(), it_end = Config.Opers.end(); it != it_end; ++it) { if (nc->ot) break; if (stricmp(it->first.c_str(), this->nick)) continue; - for (std::list<OperType *>::iterator tit = Config.MyOperTypes.begin(); tit != Config.MyOperTypes.end(); tit++) - { + for (std::list<OperType *>::iterator tit = Config.MyOperTypes.begin(), tit_end = Config.MyOperTypes.end(); tit != tit_end; ++tit) + { OperType *ot = *tit; if (ot->GetName() == it->second) @@ -90,9 +90,7 @@ NickAlias::~NickAlias() /* Next: see if our core is still useful. */ std::list<NickAlias *>::iterator it = std::find(this->nc->aliases.begin(), this->nc->aliases.end(), this); if (it != this->nc->aliases.end()) - { nc->aliases.erase(it); - } if (this->nc->aliases.empty()) { delete this->nc; @@ -127,14 +125,10 @@ void NickAlias::Release() if (this->HasFlag(NS_HELD)) { if (ircd->svshold) - { ircdproto->SendSVSHoldDel(this->nick); - } else - { ircdproto->SendQuit(this->nick, NULL); - } - + this->UnsetFlag(NS_HELD); } } @@ -151,9 +145,7 @@ void NickAlias::OnCancel(User *) this->UnsetFlag(NS_COLLIDED); if (ircd->svshold) - { ircdproto->SendSVSHold(this->nick); - } else { std::string uid = (ircd->ts6 ? ts6_uid_retrieve() : ""); @@ -163,4 +155,3 @@ void NickAlias::OnCancel(User *) } } } - diff --git a/src/nickcore.cpp b/src/nickcore.cpp index cf92b0b3d..9d51422c9 100644 --- a/src/nickcore.cpp +++ b/src/nickcore.cpp @@ -21,7 +21,7 @@ NickCore::NickCore(const std::string &coredisplay) for (size_t t = NI_BEGIN + 1; t != NI_END; ++t) if (Config.NSDefFlags.HasFlag(static_cast<NickCoreFlag>(t))) SetFlag(static_cast<NickCoreFlag>(t)); - + NickCoreList[this->display] = this; } @@ -34,7 +34,7 @@ NickCore::~NickCore() /* Clean up this nick core from any users online using it * (ones that /nick but remain unidentified) */ - for (std::list<User *>::iterator it = this->Users.begin(); it != this->Users.end(); ++it) + for (std::list<User *>::iterator it = this->Users.begin(), it_end = this->Users.end(); it != it_end; ++it) { User *user = *it; ircdproto->SendAccountLogout(user, user->Account()); @@ -64,11 +64,11 @@ NickCore::~NickCore() if (this->greet) delete [] this->greet; if (this->url) - delete [] this->url; + delete [] this->url; if (!this->memos.memos.empty()) { - for (unsigned i = 0; i < this->memos.memos.size(); ++i) + for (unsigned i = 0, end = this->memos.memos.size(); i < end; ++i) { if (this->memos.memos[i]->text) delete [] this->memos.memos[i]->text; @@ -78,7 +78,7 @@ NickCore::~NickCore() } } -bool NickCore::HasCommand(const std::string &cmdstr) const +bool NickCore::HasCommand(const ci::string &cmdstr) const { if (!this->ot) { @@ -97,13 +97,11 @@ bool NickCore::IsServicesOper() const return false; } -bool NickCore::HasPriv(const std::string &privstr) const +bool NickCore::HasPriv(const ci::string &privstr) const { if (!this->ot) - { // No opertype. return false; - } return this->ot->HasPriv(privstr); } @@ -123,7 +121,7 @@ std::string NickCore::GetAccess(unsigned entry) bool NickCore::FindAccess(const std::string &entry) { - for (unsigned i = 0; i < access.size(); ++i) + for (unsigned i = 0, end = access.size(); i < end; ++i) if (access[i] == entry) return true; @@ -132,7 +130,7 @@ bool NickCore::FindAccess(const std::string &entry) void NickCore::EraseAccess(const std::string &entry) { - for (unsigned i = 0; i < access.size(); ++i) + for (unsigned i = 0, end = access.size(); i < end; ++i) if (access[i] == entry) { FOREACH_MOD(I_OnNickEraseAccess, OnNickEraseAccess(this, entry)); diff --git a/src/nickserv.cpp b/src/nickserv.cpp index c14de6ae6..8d59ae672 100644 --- a/src/nickserv.cpp +++ b/src/nickserv.cpp @@ -1,4 +1,3 @@ - /* NickServ functions. * * (C) 2003-2010 Anope Team @@ -8,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -28,9 +25,7 @@ NickServCollide::NickServCollide(const std::string &_nick, time_t delay) : Timer /* Erase the current collide and use the new one */ std::map<std::string, NickServCollide *>::iterator nit = NickServCollides.find(nick); if (nit != NickServCollides.end()) - { delete nit->second; - } NickServCollides.insert(std::make_pair(nick, this)); } @@ -47,7 +42,7 @@ void NickServCollide::Tick(time_t ctime) NickAlias *na = findnick(nick); if (!u || !na || u->Account() == na->nc || u->my_signon > this->GetSetTime()) return; - + u->Collide(na); } @@ -56,9 +51,7 @@ NickServRelease::NickServRelease(const std::string &_nick, const std::string &_u /* Erase the current release timer and use the new one */ std::map<std::string, NickServRelease *>::iterator nit = NickServReleases.find(nick); if (nit != NickServReleases.end()) - { delete nit->second; - } NickServReleases.insert(std::make_pair(nick, this)); } @@ -91,11 +84,11 @@ void get_aliases_stats(long *nrec, long *memuse) { long count = 0, mem = 0; - for (nickalias_map::const_iterator it = NickAliasList.begin(); it != NickAliasList.end(); ++it) + for (nickalias_map::const_iterator it = NickAliasList.begin(), it_end = NickAliasList.end(); it != it_end; ++it) { NickAlias *na = it->second; - - count++; + + ++count; mem += sizeof(*na); if (na->nick) mem += strlen(na->nick) + 1; @@ -117,19 +110,19 @@ void get_aliases_stats(long *nrec, long *memuse) void get_core_stats(long *nrec, long *memuse) { long count = 0, mem = 0; - unsigned j; + unsigned j, end; - for (nickcore_map::const_iterator it = NickCoreList.begin(); it != NickCoreList.end(); ++it) + for (nickcore_map::const_iterator it = NickCoreList.begin(), it_end = NickCoreList.end(); it != it_end; ++it) { NickCore *nc = it->second; - count++; + ++count; mem += sizeof(*nc); if (nc->display) mem += strlen(nc->display) + 1; if (!nc->pass.empty()) - mem += (nc->pass.capacity() + (2 * sizeof(size_t)) + (2 * sizeof(void*))); + mem += (nc->pass.capacity() + (2 * sizeof(size_t)) + (2 * sizeof(void *))); if (nc->url) mem += strlen(nc->url) + 1; if (nc->email) @@ -138,11 +131,11 @@ void get_core_stats(long *nrec, long *memuse) mem += strlen(nc->greet) + 1; mem += sizeof(std::string) * nc->access.size(); - for (j = 0; j < nc->access.size(); ++j) + for (j = 0, end = nc->access.size(); j < end; ++j) mem += nc->GetAccess(j).length() + 1; mem += nc->memos.memos.size() * sizeof(Memo); - for (j = 0; j < nc->memos.memos.size(); j++) + for (j = 0, end = nc->memos.memos.size(); j < end; ++j) { if (nc->memos.memos[j]->text) mem += strlen(nc->memos.memos[j]->text) + 1; @@ -172,7 +165,7 @@ void nickserv(User *u, const std::string &buf) { if (!u || buf.empty()) return; - + if (buf.find("\1PING ", 0, 6) != std::string::npos && buf[buf.length() - 1] == '\1') { std::string command = buf; @@ -181,10 +174,7 @@ void nickserv(User *u, const std::string &buf) ircdproto->SendCTCP(NickServ, u->nick.c_str(), "%s", command.c_str()); } else - { mod_run_cmd(NickServ, u, buf); - } - } /*************************************************************************/ @@ -197,7 +187,7 @@ void nickserv(User *u, const std::string &buf) * If the user's nick is not registered, 0 is returned. */ -int validate_user(User * u) +int validate_user(User *u) { NickAlias *na; NickRequest *nr; @@ -281,11 +271,11 @@ void expire_nicks() { time_t now = time(NULL); - for (nickalias_map::const_iterator it = NickAliasList.begin(); it != NickAliasList.end();) + for (nickalias_map::const_iterator it = NickAliasList.begin(), it_end = NickAliasList.end(); it != it_end; ) { NickAlias *na = it->second; ++it; - + User *u = finduser(na->nick); if (u && (na->nc->HasFlag(NI_SECURE) ? u->IsIdentified() : u->IsRecognized())) { @@ -294,16 +284,13 @@ void expire_nicks() continue; } - if (Config.NSExpire && now - na->last_seen >= Config.NSExpire - && !na->HasFlag(NS_FORBIDDEN) && !na->HasFlag(NS_NO_EXPIRE) - && !na->nc->HasFlag(NI_SUSPENDED)) + if (Config.NSExpire && now - na->last_seen >= Config.NSExpire && !na->HasFlag(NS_FORBIDDEN) && !na->HasFlag(NS_NO_EXPIRE) && !na->nc->HasFlag(NI_SUSPENDED)) { EventReturn MOD_RESULT; FOREACH_RESULT(I_OnPreNickExpire, OnPreNickExpire(na)); if (MOD_RESULT == EVENT_STOP) continue; - Alog() << "Expiring nickname " << na->nick << " (group: " << na->nc->display << ") (e-mail: " - << (na->nc->email ? na->nc->email : "none") << ")"; + Alog() << "Expiring nickname " << na->nick << " (group: " << na->nc->display << ") (e-mail: " << (na->nc->email ? na->nc->email : "none") << ")"; FOREACH_MOD(I_OnNickExpire, OnNickExpire(na)); delete na; } @@ -314,10 +301,10 @@ void expire_requests() { time_t now = time(NULL); - for (nickrequest_map::const_iterator it = NickRequestList.begin(); it != NickRequestList.end(); ++it) + for (nickrequest_map::const_iterator it = NickRequestList.begin(), it_end = NickRequestList.end(); it != it_end; ++it) { NickRequest *nr = it->second; - + if (Config.NSRExpire && now - nr->requested >= Config.NSRExpire) { Alog() << "Request for nick " << nr->nick << " expiring"; @@ -398,7 +385,7 @@ NickCore *findcore(const ci::string &nick) */ bool is_on_access(User *u, NickCore *nc) { - unsigned i; + unsigned i, end; char *buf; char *buf2 = NULL; char *buf3 = NULL; @@ -423,7 +410,7 @@ bool is_on_access(User *u, NickCore *nc) } } - for (i = 0; i < nc->access.size(); i++) + for (i = 0, end = nc->access.size(); i < end; ++i) { std::string access = nc->GetAccess(i); if (Anope::Match(buf, access, false) || (buf2 && Anope::Match(buf2, access, false)) || (buf3 && Anope::Match(buf3, access, false))) @@ -432,13 +419,9 @@ bool is_on_access(User *u, NickCore *nc) if (ircd->vhost) { if (u->vhost) - { delete [] buf2; - } if (!u->GetCloakedHost().empty()) - { delete [] buf3; - } } return true; } @@ -460,8 +443,7 @@ bool is_on_access(User *u, NickCore *nc) * it to the first alias in the list. */ - -void change_core_display(NickCore * nc, const char *newdisplay) +void change_core_display(NickCore *nc, const char *newdisplay) { /* Log ... */ FOREACH_MOD(I_OnChangeCoreDisplay, OnChangeCoreDisplay(nc, newdisplay)); @@ -476,7 +458,7 @@ void change_core_display(NickCore * nc, const char *newdisplay) NickCoreList[nc->display] = nc; } -void change_core_display(NickCore * nc) +void change_core_display(NickCore *nc) { NickAlias *na; if (nc->aliases.empty()) @@ -485,17 +467,16 @@ void change_core_display(NickCore * nc) change_core_display(nc,na->nick); } - /*************************************************************************/ /*********************** NickServ command routines ***********************/ /*************************************************************************/ -int do_setmodes(User * u) +int do_setmodes(User *u) { Channel *c; /* Walk users current channels */ - for (UChannelList::iterator it = u->chans.begin(); it != u->chans.end(); ++it) + for (UChannelList::iterator it = u->chans.begin(), it_end = u->chans.end(); it != it_end; ++it) { ChannelContainer *cc = *it; @@ -504,4 +485,3 @@ int do_setmodes(User * u) } return MOD_CONT; } - diff --git a/src/operserv.cpp b/src/operserv.cpp index 8e3a3c90f..1dda039e4 100644 --- a/src/operserv.cpp +++ b/src/operserv.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -54,9 +52,7 @@ void operserv(User *u, const std::string &buf) ircdproto->SendCTCP(OperServ, u->nick.c_str(), "%s", command.c_str()); } else - { mod_run_cmd(OperServ, u, buf); - } } bool SetDefConParam(ChannelModeName Name, std::string &buf) @@ -84,9 +80,7 @@ void UnsetDefConParam(ChannelModeName Name) std::map<ChannelModeName, std::string>::iterator it = DefConModesOnParams.find(Name); if (it != DefConModesOnParams.end()) - { DefConModesOnParams.erase(it); - } } /** Check if a certain defcon option is currently in affect @@ -136,17 +130,15 @@ void server_global(Server *s, const std::string &message) if (s->GetLinks()) { - for (std::list<Server *>::const_iterator it = s->GetLinks()->begin(); it != s->GetLinks()->end(); ++it) - { + for (std::list<Server *>::const_iterator it = s->GetLinks()->begin(), it_end = s->GetLinks()->end(); it != it_end; ++it) server_global(*it, message); - } } } void oper_global(char *nick, const char *fmt, ...) { va_list args; - char msg[2048]; /* largest valid message is 512, this should cover any global */ + char msg[2048]; /* largest valid message is 512, this should cover any global */ va_start(args, fmt); vsnprintf(msg, sizeof(msg), fmt, args); @@ -191,17 +183,11 @@ ci::string XLine::GetUser() const size_t user_t = Mask.find('!'), host_t = Mask.find('@'); if (user_t == ci::string::npos) - { return Mask.substr(0, host_t); - } else if (host_t != ci::string::npos) - { return Mask.substr((user_t != ci::string::npos ? user_t + 1 : 0), host_t); - } else - { return ""; - } } ci::string XLine::GetHost() const @@ -209,13 +195,9 @@ ci::string XLine::GetHost() const size_t host_t = Mask.find('@'); if (host_t == ci::string::npos) - { return Mask; - } else - { return Mask.substr(host_t + 1); - } } /** Constructor @@ -251,9 +233,7 @@ void XLineManager::UnregisterXLineManager(XLineManager *xlm) std::list<XLineManager *>::iterator it = std::find(XLineManagers.begin(), XLineManagers.end(), xlm); if (it != XLineManagers.end()) - { XLineManagers.erase(it); - } } /* Check a user against all known XLineManagers @@ -264,7 +244,7 @@ std::pair<XLineManager *, XLine *> XLineManager::CheckAll(User *u) { std::pair<XLineManager *, XLine *> ret(NULL, NULL); - for (std::list<XLineManager *>::iterator it = XLineManagers.begin(); it != XLineManagers.end(); ++it) + for (std::list<XLineManager *>::iterator it = XLineManagers.begin(), it_end = XLineManagers.end(); it != it_end; ++it) { XLineManager *xlm = *it; @@ -332,7 +312,7 @@ XLine *XLineManager::GetEntry(unsigned index) const { if (index >= XLines.size()) return NULL; - + return XLines[index]; } @@ -340,10 +320,8 @@ XLine *XLineManager::GetEntry(unsigned index) const */ void XLineManager::Clear() { - for (std::deque<XLine *>::iterator it = XLines.begin(); it != XLines.end(); ++it) - { + for (std::deque<XLine *>::iterator it = XLines.begin(), it_end = XLines.end(); it != it_end; ++it) delete *it; - } XLines.clear(); } @@ -380,14 +358,14 @@ std::pair<int, XLine *> XLineManager::CanAdd(const ci::string &mask, time_t expi { std::pair<int, XLine *> ret(0, NULL); - for (unsigned i = 0; i < GetCount(); ++i) + for (unsigned i = 0, end = GetCount(); i < end; ++i) { XLine *x = GetEntry(i); ret.second = x; if (x->Mask == mask) { - if (x->Expires == 0 || x->Expires >= expires) + if (!x->Expires || x->Expires >= expires) { ret.first = 1; break; @@ -400,12 +378,12 @@ std::pair<int, XLine *> XLineManager::CanAdd(const ci::string &mask, time_t expi break; } } - else if (Anope::Match(mask, x->Mask) && (x->Expires == 0 || x->Expires >= expires)) + else if (Anope::Match(mask, x->Mask) && (!x->Expires || x->Expires >= expires)) { ret.first = 3; break; } - else if (Anope::Match(x->Mask, mask) && (expires == 0 || x->Expires <= expires)) + else if (Anope::Match(x->Mask, mask) && (!expires || x->Expires <= expires)) { this->DelXLine(x); --i; @@ -421,14 +399,12 @@ std::pair<int, XLine *> XLineManager::CanAdd(const ci::string &mask, time_t expi */ XLine *XLineManager::HasEntry(const ci::string &mask) const { - for (unsigned i = 0; i < XLines.size(); ++i) + for (unsigned i = 0, end = XLines.size(); i < end; ++i) { XLine *x = XLines[i]; if (x->Mask == mask) - { return x; - } } return NULL; @@ -442,7 +418,7 @@ XLine *XLineManager::Check(User *u) { const time_t now = time(NULL); - for (std::deque<XLine *>::iterator it = XLines.begin(); it != XLines.end(); ++it) + for (std::deque<XLine *>::iterator it = XLines.begin(), it_end = XLines.end(); it != it_end; ++it) { XLine *x = *it; @@ -461,7 +437,7 @@ XLine *XLineManager::Check(User *u) if (!x->GetUser().empty() && !Anope::Match(u->GetIdent().c_str(), x->GetUser())) continue; - if (x->GetHost().empty() || ((u->hostip && Anope::Match(u->hostip, x->GetHost())) || Anope::Match(u->host, x->GetHost()) || (!u->chost.empty() && Anope::Match(u->chost.c_str(), x->GetHost())) || (u->vhost && Anope::Match(u->vhost, x->GetHost())))) + if (x->GetHost().empty() || (u->hostip && Anope::Match(u->hostip, x->GetHost())) || Anope::Match(u->host, x->GetHost()) || (!u->chost.empty() && Anope::Match(u->chost.c_str(), x->GetHost())) || (u->vhost && Anope::Match(u->vhost, x->GetHost()))) { OnMatch(u, x); return x; @@ -528,7 +504,7 @@ XLine *SGLineManager::Add(BotInfo *bi, User *u, const ci::string &mask, time_t e std::string realreason = reason; if (u && Config.AddAkiller) realreason = "[" + u->nick + "]" + reason; - + XLine *x = new XLine(mask, u ? u->nick.c_str() : "", expires, realreason); EventReturn MOD_RESULT; @@ -538,12 +514,12 @@ XLine *SGLineManager::Add(BotInfo *bi, User *u, const ci::string &mask, time_t e delete x; return NULL; } - + this->AddXLine(x); if (Config.AkillOnAdd) ircdproto->SendAkill(x); - + return x; } @@ -584,7 +560,7 @@ XLine *SNLineManager::Add(BotInfo *bi, User *u, const ci::string &mask, time_t e else if (canAdd.first == 3) notice_lang(bi->nick.c_str(), u, OPER_SNLINE_ALREADY_COVERED, mask.c_str(), canAdd.second->Mask.c_str()); } - + return canAdd.second; } @@ -604,15 +580,13 @@ XLine *SNLineManager::Add(BotInfo *bi, User *u, const ci::string &mask, time_t e { std::string rreason = "G-Lined: " + reason; - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end();) + for (user_map::const_iterator it = UserListByNick.begin(), it_end = UserListByNick.end(); it != it_end; ) { User *user = it->second; ++it; if (!is_oper(user) && Anope::Match(user->realname, x->Mask)) - { kill_user(Config.ServerName, user->nick, rreason.c_str()); - } } } @@ -688,13 +662,13 @@ XLine *SQLineManager::Add(BotInfo *bi, User *u, const ci::string &mask, time_t e if (mask[0] == '#') { - for (channel_map::const_iterator cit = ChannelList.begin(); cit != ChannelList.end(); ++cit) + for (channel_map::const_iterator cit = ChannelList.begin(), cit_end = ChannelList.end(); cit != cit_end; ++cit) { Channel *c = cit->second; if (!Anope::Match(c->name.c_str(), mask)) continue; - for (CUserList::iterator it = c->users.begin(); it != c->users.end();) + for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ) { UserContainer *uc = *it; ++it; @@ -707,15 +681,13 @@ XLine *SQLineManager::Add(BotInfo *bi, User *u, const ci::string &mask, time_t e } else { - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end();) + for (user_map::const_iterator it = UserListByNick.begin(), it_end = UserListByNick.end(); it != it_end; ) { User *user = it->second; ++it; if (!is_oper(user) && Anope::Match(user->nick.c_str(), x->Mask)) - { kill_user(Config.ServerName, user->nick, rreason.c_str()); - } } } } @@ -749,14 +721,12 @@ bool SQLineManager::Check(Channel *c) { if (ircd->chansqline && SQLine) { - for (std::deque<XLine *>::const_iterator it = SGLine->GetList().begin(); it != SGLine->GetList().end(); ++it) + for (std::deque<XLine *>::const_iterator it = SGLine->GetList().begin(), it_end = SGLine->GetList().end(); it != it_end; ++it) { XLine *x = *it; if (Anope::Match(c->name.c_str(), x->Mask)) - { return true; - } } } @@ -825,4 +795,3 @@ void SZLineManager::OnExpire(XLine *x) if (Config.WallSZLineExpire) ircdproto->SendGlobops(OperServ, "SZLINE on \2%s\2 has expired", x->Mask.c_str()); } - diff --git a/src/opertype.cpp b/src/opertype.cpp index 0ee6d000f..968163003 100644 --- a/src/opertype.cpp +++ b/src/opertype.cpp @@ -3,9 +3,6 @@ * Copyright (C) 2008-2010 Anope Team <team@anope.org> * * Please read COPYING and README for further details. - * - * - * */ #include "services.h" @@ -14,56 +11,48 @@ OperType::OperType(const ci::string &nname) : name(nname) { } -bool OperType::HasCommand(const std::string &cmdstr) const +bool OperType::HasCommand(const ci::string &cmdstr) const { - for (std::list<std::string>::const_iterator it = this->commands.begin(); it != this->commands.end(); ++it) + for (std::list<ci::string>::const_iterator it = this->commands.begin(), it_end = this->commands.end(); it != it_end; ++it) { if (Anope::Match(cmdstr, *it)) - { return true; - } } - for (std::set<OperType *>::const_iterator iit = this->inheritances.begin(); iit != this->inheritances.end(); ++iit) + for (std::set<OperType *>::const_iterator iit = this->inheritances.begin(), iit_end = this->inheritances.end(); iit != iit_end; ++iit) { OperType *ot = *iit; if (ot->HasCommand(cmdstr)) - { return true; - } } return false; } -bool OperType::HasPriv(const std::string &privstr) const +bool OperType::HasPriv(const ci::string &privstr) const { - for (std::list<std::string>::const_iterator it = this->privs.begin(); it != this->privs.end(); ++it) + for (std::list<ci::string>::const_iterator it = this->privs.begin(), it_end = this->privs.end(); it != it_end; ++it) { if (Anope::Match(privstr, *it)) - { return true; - } } - for (std::set<OperType *>::const_iterator iit = this->inheritances.begin(); iit != this->inheritances.end(); ++iit) + for (std::set<OperType *>::const_iterator iit = this->inheritances.begin(), iit_end = this->inheritances.end(); iit != iit_end; ++iit) { OperType *ot = *iit; if (ot->HasPriv(privstr)) - { return true; - } } return false; } -void OperType::AddCommand(const std::string &cmdstr) +void OperType::AddCommand(const ci::string &cmdstr) { this->commands.push_back(cmdstr); } -void OperType::AddPriv(const std::string &privstr) +void OperType::AddPriv(const ci::string &privstr) { this->privs.push_back(privstr); } @@ -77,4 +66,3 @@ void OperType::Inherits(OperType *ot) { this->inheritances.insert(ot); } - diff --git a/src/process.cpp b/src/process.cpp index 7a015c64b..a240a0008 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -40,42 +38,52 @@ void add_ignore(const char *nick, time_t delta) return; now = time(NULL); /* If it s an existing user, we ignore the hostmask. */ - if ((u = finduser(nick))) { + if ((u = finduser(nick))) + { snprintf(tmp, sizeof(tmp), "*!*@%s", u->host); mask = sstrdup(tmp); + } /* Determine whether we get a nick or a mask. */ - } else if ((host = const_cast<char *>(strchr(nick, '@')))) { + else if ((host = const_cast<char *>(strchr(nick, '@')))) + { /* Check whether we have a nick too.. */ - if ((user = const_cast<char *>(strchr(nick, '!')))) { + if ((user = const_cast<char *>(strchr(nick, '!')))) + { /* this should never happen */ if (user > host) return; mask = sstrdup(nick); - } else { + } + else + { /* We have user@host. Add nick wildcard. */ - snprintf(tmp, sizeof(tmp), "*!%s", nick); + snprintf(tmp, sizeof(tmp), "*!%s", nick); mask = sstrdup(tmp); } + } /* We only got a nick.. */ - } else { + else { snprintf(tmp, sizeof(tmp), "%s!*@*", nick); mask = sstrdup(tmp); } /* Check if we already got an identical entry. */ for (ign = ignore; ign; ign = ign->next) - if (stricmp(ign->mask, mask) == 0) + if (!stricmp(ign->mask, mask)) break; /* Found one.. */ - if (ign) { - if (delta == 0) + if (ign) + { + if (!delta) ign->time = 0; else if (ign->time < now + delta) ign->time = now + delta; + } /* Create new entry.. */ - } else { + else + { ign = new IgnoreData; ign->mask = mask; - ign->time = (delta == 0 ? 0 : now + delta); + ign->time = !delta ? 0 : now + delta; ign->prev = NULL; ign->next = ignore; if (ignore) @@ -109,34 +117,40 @@ IgnoreData *get_ignore(const char *nick) now = time(NULL); u = finduser(nick); /* If we find a real user, match his mask against the ignorelist. */ - if (u) { + if (u) + { /* Opers are not ignored, even if a matching entry may be present. */ if (is_oper(u)) return NULL; for (ign = ignore; ign; ign = ign->next) if (match_usermask(ign->mask, u)) break; - } else { + } + else + { /* We didn't get a user.. generate a valid mask. */ - if ((host = const_cast<char *>(strchr(nick, '@')))) { - if ((user = const_cast<char *>(strchr(nick, '!')))) { + if ((host = const_cast<char *>(strchr(nick, '@')))) + { + if ((user = const_cast<char *>(strchr(nick, '!')))) + { /* this should never happen */ if (user > host) return NULL; snprintf(tmp, sizeof(tmp), "%s", nick); - } else { + } + else /* We have user@host. Add nick wildcard. */ snprintf(tmp, sizeof(tmp), "*!%s", nick); - } + } /* We only got a nick.. */ - } else + else snprintf(tmp, sizeof(tmp), "%s!*@*", nick); for (ign = ignore; ign; ign = ign->next) if (Anope::Match(tmp, ign->mask, false)) break; } /* Check whether the entry has timed out */ - if (ign && ign->time != 0 && ign->time <= now) + if (ign && ign->time != 0 && ign->time <= now) { Alog(LOG_DEBUG) << "Expiring ignore entry " << ign->mask; if (ign->prev) @@ -154,7 +168,6 @@ IgnoreData *get_ignore(const char *nick) return ign; } - /*************************************************************************/ /** @@ -171,25 +184,28 @@ int delete_ignore(const char *nick) if (!nick) return 0; /* If it s an existing user, we ignore the hostmask. */ - if ((u = finduser(nick))) { + if ((u = finduser(nick))) snprintf(tmp, sizeof(tmp), "*!*@%s", u->host); /* Determine whether we get a nick or a mask. */ - } else if ((host = const_cast<char *>(strchr(nick, '@')))) { + else if ((host = const_cast<char *>(strchr(nick, '@')))) + { /* Check whether we have a nick too.. */ - if ((user = const_cast<char *>(strchr(nick, '!')))) { + if ((user = const_cast<char *>(strchr(nick, '!')))) + { /* this should never happen */ if (user > host) return 0; snprintf(tmp, sizeof(tmp), "%s", nick); - } else { - /* We have user@host. Add nick wildcard. */ - snprintf(tmp, sizeof(tmp), "*!%s", nick); } + else + /* We have user@host. Add nick wildcard. */ + snprintf(tmp, sizeof(tmp), "*!%s", nick); + } /* We only got a nick.. */ - } else + else snprintf(tmp, sizeof(tmp), "%s!*@*", nick); for (ign = ignore; ign; ign = ign->next) - if (stricmp(ign->mask, tmp) == 0) + if (!stricmp(ign->mask, tmp)) break; /* No matching ignore found. */ if (!ign) @@ -208,8 +224,6 @@ int delete_ignore(const char *nick) return 1; } - - /*************************************************************************/ /** @@ -222,25 +236,25 @@ int clear_ignores() int i = 0; if (!ignore) return 0; - for (ign = ignore; ign; ign = next) { + for (ign = ignore; ign; ign = next) + { next = ign->next; Alog(LOG_DEBUG) << "Deleting ignore entry " << ign->mask; delete [] ign->mask; delete ign; - i++; + ++i; } ignore = NULL; return i; } - /*************************************************************************/ /* split_buf: Split a buffer into arguments and store the arguments in an - * argument vector pointed to by argv (which will be malloc'd - * as necessary); return the argument count. If colon_special - * is non-zero, then treat a parameter with a leading ':' as - * the last parameter of the line, per the IRC RFC. Destroys - * the buffer by side effect. + * argument vector pointed to by argv (which will be malloc'd + * as necessary); return the argument count. If colon_special + * is non-zero, then treat a parameter with a leading ':' as + * the last parameter of the line, per the IRC RFC. Destroys + * the buffer by side effect. */ int split_buf(char *buf, const char ***argv, int colon_special) { @@ -250,23 +264,29 @@ int split_buf(char *buf, const char ***argv, int colon_special) *argv = static_cast<const char **>(scalloc(sizeof(const char *) * argvsize, 1)); argc = 0; - while (*buf) { - if (argc == argvsize) { + while (*buf) + { + if (argc == argvsize) + { argvsize += 8; *argv = static_cast<const char **>(srealloc(*argv, sizeof(const char *) * argvsize)); } - if (*buf == ':') { + if (*buf == ':') + { (*argv)[argc++] = buf + 1; buf = const_cast<char *>(""); // XXX: unsafe cast. - } else { + } + else + { s = strpbrk(buf, " "); - if (s) { + if (s) + { *s++ = 0; while (*s == ' ') - s++; - } else { - s = buf + strlen(buf); + ++s; } + else + s = buf + strlen(buf); (*argv)[argc++] = buf; buf = s; } @@ -277,23 +297,18 @@ int split_buf(char *buf, const char ***argv, int colon_special) /*************************************************************************/ /* process: Main processing routine. Takes the string in inbuf (global - * variable) and does something appropriate with it. */ + * variable) and does something appropriate with it. */ void process(const std::string &buffer) { int retVal = 0; - char source[64]; - char cmd[64]; - char buf[512]; /* Longest legal IRC command line */ + char source[64] = ""; + char cmd[64] = ""; + char buf[512] = ""; /* Longest legal IRC command line */ char *s; - int ac; /* Parameters for the command */ + int ac; /* Parameters for the command */ const char **av; - /* zero out the buffers before we do much else */ - *buf = '\0'; - *source = '\0'; - *cmd = '\0'; - /* If debugging, log the buffer */ Alog(LOG_DEBUG) << "Received: " << buffer; @@ -304,7 +319,8 @@ void process(const std::string &buffer) doCleanBuffer(buf); /* Split the buffer into pieces. */ - if (*buf == ':') { + if (*buf == ':') + { s = strpbrk(buf, " "); if (!s) return; @@ -312,16 +328,18 @@ void process(const std::string &buffer) while (isspace(*++s)); strscpy(source, buf + 1, sizeof(source)); memmove(buf, s, strlen(s) + 1); - } else { - *source = 0; } + else + *source = 0; if (!*buf) return; s = strpbrk(buf, " "); - if (s) { + if (s) + { *s = 0; while (isspace(*++s)); - } else + } + else s = buf + strlen(buf); strscpy(cmd, buf, sizeof(cmd)); ac = split_buf(s, &av, 1); @@ -335,7 +353,7 @@ void process(const std::string &buffer) if (ac) { int i; - for (i = 0; i < ac; i++) + for (i = 0; i < ac; ++i) Alog() << "av[" << i << "] = " << av[i]; } else @@ -349,7 +367,7 @@ void process(const std::string &buffer) { retVal = MOD_CONT; - for (std::vector<Message *>::iterator it = messages.begin(); retVal == MOD_CONT && it != messages.end(); ++it) + for (std::vector<Message *>::iterator it = messages.begin(), it_end = messages.end(); retVal == MOD_CONT && it != it_end; ++it) { Message *m = *it; diff --git a/src/regchannel.cpp b/src/regchannel.cpp index 8ee823e33..9e28b5cb0 100644 --- a/src/regchannel.cpp +++ b/src/regchannel.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -56,7 +54,7 @@ ChannelInfo::ChannelInfo(const std::string &chname) last_used = time_registered = time(NULL); this->ttb = new int16[2 * TTB_SIZE]; - for (int i = 0; i < TTB_SIZE; i++) + for (int i = 0; i < TTB_SIZE; ++i) this->ttb[i] = 0; reset_levels(this); @@ -68,14 +66,14 @@ ChannelInfo::ChannelInfo(const std::string &chname) */ ChannelInfo::~ChannelInfo() { - unsigned i; + unsigned i, end; FOREACH_MOD(I_OnDelChan, OnDelChan(this)); Alog(LOG_DEBUG) << "Deleting channel " << this->name; if (this->bi) - this->bi->chancount--; + --this->bi->chancount; if (this->c) { @@ -109,7 +107,7 @@ ChannelInfo::~ChannelInfo() if (!this->memos.memos.empty()) { - for (i = 0; i < this->memos.memos.size(); ++i) + for (i = 0, end = this->memos.memos.size(); i < end; ++i) { if (this->memos.memos[i]->text) delete [] this->memos.memos[i]->text; @@ -122,7 +120,7 @@ ChannelInfo::~ChannelInfo() delete [] this->ttb; if (this->founder) - this->founder->channelcount--; + --this->founder->channelcount; } /** Add an entry to the channel access list @@ -170,8 +168,7 @@ ChanAccess *ChannelInfo::GetAccess(unsigned index) * @param level Optional channel access level to compare the access entries to * @return A ChanAccess struct corresponding to the NickCore, or NULL if not found * - * Retrieves an entry from the access list that matches the given NickCore, optionally also matching a -certain level. + * Retrieves an entry from the access list that matches the given NickCore, optionally also matching a certain level. */ ChanAccess *ChannelInfo::GetAccess(NickCore *nc, int16 level) @@ -179,7 +176,7 @@ ChanAccess *ChannelInfo::GetAccess(NickCore *nc, int16 level) if (access.empty()) return NULL; - for (unsigned i = 0; i < access.size(); i++) + for (unsigned i = 0, end = access.size(); i < end; ++i) if (access[i]->nc == nc && (level ? access[i]->level == level : true)) return access[i]; @@ -216,9 +213,7 @@ void ChannelInfo::EraseAccess(unsigned index) void ChannelInfo::ClearAccess() { while (!access.empty()) - { EraseAccess(0); - } } /** Add an akick entry to the channel by NickCore @@ -296,7 +291,7 @@ void ChannelInfo::EraseAkick(unsigned index) { if (akick.empty() || index > akick.size()) return; - + delete akick[index]; akick.erase(akick.begin() + index); } @@ -306,9 +301,7 @@ void ChannelInfo::EraseAkick(unsigned index) void ChannelInfo::ClearAkick() { while (!akick.empty()) - { EraseAkick(0); - } } /** Add a badword to the badword list @@ -323,7 +316,7 @@ BadWord *ChannelInfo::AddBadWord(const std::string &word, BadWordType type) bw->type = type; badwords.push_back(bw); - + FOREACH_MOD(I_OnBadWordAdd, OnBadWordAdd(this, bw)); return bw; @@ -356,7 +349,7 @@ void ChannelInfo::EraseBadWord(unsigned index) { if (badwords.empty() || index >= badwords.size()) return; - + delete badwords[index]; badwords.erase(badwords.begin() + index); } @@ -366,9 +359,7 @@ void ChannelInfo::EraseBadWord(unsigned index) void ChannelInfo::ClearBadWords() { while (!badwords.empty()) - { EraseBadWord(0); - } } /** Loads MLocked modes from extensible. This is used from database loading because Anope doesn't know what modes exist @@ -377,21 +368,19 @@ void ChannelInfo::ClearBadWords() void ChannelInfo::LoadMLock() { std::vector<std::string> modenames; - + if (this->GetExtRegular("db_mlock_modes_on", modenames)) { - for (std::vector<std::string>::iterator it = modenames.begin(); it != modenames.end(); ++it) + for (std::vector<std::string>::iterator it = modenames.begin(), it_end = modenames.end(); it != it_end; ++it) { - for (std::list<Mode *>::iterator mit = ModeManager::Modes.begin(); mit != ModeManager::Modes.end(); ++mit) + for (std::list<Mode *>::iterator mit = ModeManager::Modes.begin(), mit_end = ModeManager::Modes.end(); mit != mit_end; ++mit) { if ((*mit)->Class == MC_CHANNEL) { ChannelMode *cm = dynamic_cast<ChannelMode *>(*mit); if (cm->NameAsString == *it) - { this->SetMLock(cm->Name, true); - } } } } @@ -401,18 +390,16 @@ void ChannelInfo::LoadMLock() if (this->GetExtRegular("db_mlock_modes_off", modenames)) { - for (std::vector<std::string>::iterator it = modenames.begin(); it != modenames.end(); ++it) + for (std::vector<std::string>::iterator it = modenames.begin(), it_end = modenames.end(); it != it_end; ++it) { - for (std::list<Mode *>::iterator mit = ModeManager::Modes.begin(); mit != ModeManager::Modes.end(); ++mit) + for (std::list<Mode *>::iterator mit = ModeManager::Modes.begin(), mit_end = ModeManager::Modes.end(); mit != mit_end; ++mit) { if ((*mit)->Class == MC_CHANNEL) { ChannelMode *cm = dynamic_cast<ChannelMode *>(*mit); if (cm->NameAsString == *it) - { this->SetMLock(cm->Name, false); - } } } } @@ -424,18 +411,16 @@ void ChannelInfo::LoadMLock() if (this->GetExtRegular("db_mlp", params)) { - for (std::vector<std::pair<std::string, std::string> >::iterator it = params.begin(); it != params.end(); ++it) + for (std::vector<std::pair<std::string, std::string> >::iterator it = params.begin(), it_end = params.end(); it != it_end; ++it) { - for (std::list<Mode *>::iterator mit = ModeManager::Modes.begin(); mit != ModeManager::Modes.end(); ++mit) + for (std::list<Mode *>::iterator mit = ModeManager::Modes.begin(), mit_end = ModeManager::Modes.end(); mit != mit_end; ++mit) { if ((*mit)->Class == MC_CHANNEL) { ChannelMode *cm = dynamic_cast<ChannelMode *>(*mit); if (cm->NameAsString == it->first) - { this->SetMLock(cm->Name, true, it->second); - } } } } @@ -479,19 +464,15 @@ bool ChannelInfo::SetMLock(ChannelModeName Name, bool status, const std::string std::map<ChannelModeName, std::string>::iterator it = Params.find(Name); if (it != Params.end()) - { Params.erase(it); - } if (status) mlock_on.SetFlag(Name); else mlock_off.SetFlag(Name); - + if (status && !param.empty()) - { Params.insert(std::make_pair(Name, param)); - } return true; } @@ -509,12 +490,10 @@ bool ChannelInfo::RemoveMLock(ChannelModeName Name) mlock_on.UnsetFlag(Name); mlock_off.UnsetFlag(Name); - + std::map<ChannelModeName, std::string>::iterator it = Params.find(Name); if (it != Params.end()) - { Params.erase(it); - } return true; } @@ -567,9 +546,7 @@ const bool ChannelInfo::HasParam(ChannelModeName Name) std::map<ChannelModeName, std::string>::iterator it = Params.find(Name); if (it != Params.end()) - { return true; - } return false; } @@ -603,10 +580,10 @@ bool ChannelInfo::CheckKick(User *user) * as this will likely lead to kick/rejoin floods. ~ Viper */ if (user->server->IsULined()) return false; - + if (!do_kick && user->IsProtected()) return false; - + if (ircd->chansqline && SQLineManager::Check(this->c)) do_kick = true; @@ -628,13 +605,11 @@ bool ChannelInfo::CheckKick(User *user) if (!do_kick) { - for (unsigned j = 0; j < this->GetAkickCount(); ++j) + for (unsigned j = 0, end = this->GetAkickCount(); j < end; ++j) { autokick = this->GetAkick(j); - if ((autokick->HasFlag(AK_ISNICK) && autokick->nc == nc) - || (!autokick->HasFlag(AK_ISNICK) - && match_usermask(autokick->mask.c_str(), user))) + if ((autokick->HasFlag(AK_ISNICK) && autokick->nc == nc) || (!autokick->HasFlag(AK_ISNICK) && match_usermask(autokick->mask.c_str(), user))) { Alog(LOG_DEBUG_2) << user->nick << " matched akick " << (autokick->HasFlag(AK_ISNICK) ? autokick->nc->display : autokick->mask); autokick->last_used = time(NULL); @@ -649,7 +624,6 @@ bool ChannelInfo::CheckKick(User *user) } } - if (!do_kick && check_access(user, this, CA_NOJOIN)) { get_idealban(this, user, mask, sizeof(mask)); @@ -688,4 +662,3 @@ bool ChannelInfo::CheckKick(User *user) return true; } - diff --git a/src/send.cpp b/src/send.cpp index 4209e2a1b..430c7f919 100644 --- a/src/send.cpp +++ b/src/send.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -55,7 +53,6 @@ void send_cmd(const char *source, const char *fmt, ...) va_end(args); } - /* * Copypasta version that accepts std::string source. */ @@ -104,18 +101,17 @@ void send_cmd(const std::string &source, const char *fmt, ...) void notice_server(char *source, Server * s, const char *fmt, ...) { va_list args; - char buf[BUFSIZE]; - *buf = '\0'; + char buf[BUFSIZE] = ""; - if (fmt) { + if (fmt) + { va_start(args, fmt); vsnprintf(buf, BUFSIZE - 1, fmt, args); - if (Config.NSDefFlags.HasFlag(NI_MSG)) { + if (Config.NSDefFlags.HasFlag(NI_MSG)) ircdproto->SendGlobalPrivmsg(findbot(source), s, buf); - } else { + else ircdproto->SendGlobalNotice(findbot(source), s, buf); - } va_end(args); } } @@ -132,17 +128,17 @@ void notice_server(char *source, Server * s, const char *fmt, ...) void notice_list(char *source, char *dest, char **text) { User *u = finduser(dest); - while (*text) { + while (*text) + { /* Have to kludge around an ircII bug here: if a notice includes * no text, it is ignored, so we replace blank lines by lines * with a single space. */ - if (**text) { + if (**text) u->SendMessage(source, "%s", *text); - } else { + else u->SendMessage(source, " "); - } - text++; + ++text; } } @@ -159,13 +155,12 @@ void notice_list(char *source, char *dest, char **text) void notice_lang(const std::string &source, User * dest, int message, ...) { va_list args; - char buf[4096]; /* because messages can be really big */ + char buf[4096]; /* because messages can be really big */ char *s, *t; const char *fmt; - if (!dest || !message) { + if (!dest || !message) return; - } va_start(args, message); fmt = getstring(dest, message); @@ -174,7 +169,8 @@ void notice_lang(const std::string &source, User * dest, int message, ...) memset(buf, 0, 4096); vsnprintf(buf, sizeof(buf), fmt, args); s = buf; - while (*s) { + while (*s) + { t = s; s += strcspn(s, "\n"); if (*s) @@ -204,9 +200,8 @@ void notice_help(const char *source, User * dest, int message, ...) char *s, *t; const char *fmt; - if (!dest || !message) { + if (!dest || !message) return; - } va_start(args, message); fmt = getstring(dest, message); if (!fmt) @@ -218,7 +213,8 @@ void notice_help(const char *source, User * dest, int message, ...) strnrepl(buf2, sizeof(buf2), "%S", "\1\1"); vsnprintf(buf, sizeof(buf), buf2, args); s = buf; - while (*s) { + while (*s) + { t = s; s += strcspn(s, "\n"); if (*s) diff --git a/src/servers.cpp b/src/servers.cpp index 88b326f47..f226deb1a 100644 --- a/src/servers.cpp +++ b/src/servers.cpp @@ -7,9 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * $Id$ - * */ #include "services.h" @@ -70,7 +67,7 @@ Server::Server(Server *uplink, const std::string &name, unsigned int hops, const /* Add this server to our uplinks leaf list */ if (UplinkServer) UplinkServer->AddLink(this); - + if (Me && UplinkServer && Me == UplinkServer) { /* Bring in our pseudo-clients */ @@ -78,10 +75,8 @@ Server::Server(Server *uplink, const std::string &name, unsigned int hops, const /* And some IRCds needs Global joined in the logchan */ if (LogChan && ircd->join2msg) - { /* XXX might desync */ ircdproto->SendJoin(Global, Config.LogChannel, time(NULL)); - } } } @@ -95,7 +90,7 @@ Server::~Server() { time_t t = time(NULL); - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end();) + for (user_map::const_iterator it = UserListByNick.begin(), it_end = UserListByNick.end(); it != it_end; ) { User *u = it->second; ++it; @@ -112,9 +107,7 @@ Server::~Server() } if (Config.LimitSessions && !u->server->IsULined()) - { del_session(u->host); - } delete u; } @@ -125,10 +118,8 @@ Server::~Server() if (Links) { - for (std::list<Server *>::iterator it = Links->begin(); it != Links->end(); ++it) - { + for (std::list<Server *>::iterator it = Links->begin(), it_end = Links->end(); it != it_end; ++it) delete *it; - } } delete Links; @@ -146,7 +137,7 @@ void Server::Delete(const std::string &reason) /** Get the name for this server * @return The name */ -const std::string& Server::GetName() const +const std::string &Server::GetName() const { return Name; } @@ -162,7 +153,7 @@ unsigned int Server::GetHops() const /** Set the server description * @param desc The new description */ -void Server::SetDescription(const std::string& desc) +void Server::SetDescription(const std::string &desc) { Description = desc; } @@ -170,7 +161,7 @@ void Server::SetDescription(const std::string& desc) /** Get the server description * @return The server description */ -const std::string& Server::GetDescription() const +const std::string &Server::GetDescription() const { return Description; } @@ -178,7 +169,7 @@ const std::string& Server::GetDescription() const /** Get the server numeric/SID * @return The numeric/SID */ -const std::string& Server::GetSID() const +const std::string &Server::GetSID() const { return SID; } @@ -186,7 +177,7 @@ const std::string& Server::GetSID() const /** Get the list of links this server has, or NULL if it has none * @return A list of servers */ -const std::list<Server*>* Server::GetLinks() const +const std::list<Server*> *Server::GetLinks() const { return Links; } @@ -194,7 +185,7 @@ const std::list<Server*>* Server::GetLinks() const /** Get the uplink server for this server, if this is our uplink will be Me * @return The servers uplink */ -Server* Server::GetUplink() const +Server *Server::GetUplink() const { return UplinkServer; } @@ -208,15 +199,11 @@ void Server::AddLink(Server *s) * connect to the server which introduces itself and has us as the uplink, which calls this */ if (!UplinkServer) - { UplinkServer = s; - } else { if (!Links) - { Links = new std::list<Server *>(); - } Links->push_back(s); } @@ -231,8 +218,8 @@ void Server::DelLink(Server *s) { if (!Links) throw CoreException("Server::DelLink called on " + GetName() + " for " + s->GetName() + " but we have no links?"); - - for (std::list<Server *>::iterator it = Links->begin(); it != Links->end(); ++it) + + for (std::list<Server *>::iterator it = Links->begin(), it_end = Links->end(); it != it_end; ++it) { if (*it == s) { @@ -257,15 +244,13 @@ void Server::Sync(bool SyncLinks) { if (IsSynced()) return; - + UnsetFlag(SERVER_SYNCING); if (SyncLinks && Links) { - for (std::list<Server *>::iterator it = Links->begin(); it != Links->end(); ++it) - { + for (std::list<Server *>::iterator it = Links->begin(), it_end = Links->end(); it != it_end; ++it) (*it)->Sync(true); - } } if (this == Me->GetUplink()) @@ -310,16 +295,16 @@ bool Server::IsULined() const * @param s The server list to search for this server on, defaults to our Uplink * @return The server */ -Server* Server::Find(const std::string &name, Server *s) +Server *Server::Find(const std::string &name, Server *s) { if (!s) s = Me->GetUplink(); if (s->GetName() == name || s->GetSID() == name) return s; - + if (s->GetLinks()) { - for (std::list<Server *>::const_iterator it = s->GetLinks()->begin(); it != s->GetLinks()->end(); ++it) + for (std::list<Server *>::const_iterator it = s->GetLinks()->begin(), it_end = s->GetLinks()->end(); it != it_end; ++it) { Server *serv = *it; @@ -353,7 +338,7 @@ void do_server(const std::string &source, const std::string &servername, unsigne Alog(LOG_DEBUG) << "Server introduced (" << servername << ")" << " from " << source; Server *s = NULL; - + if (!source.empty()) { s = Server::Find(source); @@ -442,7 +427,7 @@ void CapabParse(int ac, const char **av) } /* Apply MLock now that we know what modes exist (capab is parsed after modes are added to Anope) */ - for (registered_channel_map::iterator it = RegisteredChannelList.begin(); it != RegisteredChannelList.end(); ++it) + for (registered_channel_map::iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; ++it) { ChannelInfo *ci = it->second; @@ -455,7 +440,7 @@ void CapabParse(int ac, const char **av) /* TS6 UID generator common code. * * Derived from atheme-services, uid.c (hg 2954:116d46894b4c). - * -nenolod + * -nenolod */ static bool ts6_uid_initted = false; static char ts6_new_uid[10]; @@ -477,7 +462,7 @@ static void ts6_uid_increment(unsigned int slot) else { if (ts6_new_uid[slot] == 'Z') - for (slot = 3; slot < 9; slot++) + for (slot = 3; slot < 9; ++slot) ts6_new_uid[slot] = 'A'; else ++ts6_new_uid[slot]; @@ -489,7 +474,7 @@ static void ts6_uid_increment(unsigned int slot) */ const char *ts6_uid_retrieve() { - if (ircd->ts6 == 0) + if (!ircd->ts6) { Alog(LOG_DEBUG) << "ts6_uid_retrieve(): TS6 not supported on this ircd"; return ""; @@ -508,7 +493,7 @@ const char *ts6_uid_retrieve() /*******************************************************************/ /* - * TS6 generator code, provided by DukePyrolator + * TS6 SID generator code, provided by DukePyrolator */ static bool ts6_sid_initted = false; @@ -581,5 +566,3 @@ const char *ts6_sid_retrieve() /* not reached */ return ""; } - -/* EOF */ diff --git a/src/sessions.cpp b/src/sessions.cpp index e0c20e185..9c8ec7163 100644 --- a/src/sessions.cpp +++ b/src/sessions.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -64,7 +62,7 @@ void get_session_stats(long *nrec, long *memuse) { long mem = sizeof(Session) * SessionList.size(); - for (session_map::const_iterator it = SessionList.begin(); it != SessionList.end(); ++it) + for (session_map::const_iterator it = SessionList.begin(), it_end = SessionList.end(); it != it_end; ++it) { Session *session = it->second; @@ -81,7 +79,8 @@ void get_exception_stats(long *nrec, long *memuse) int i; mem = sizeof(Exception) * nexceptions; - for (i = 0; i < nexceptions; i++) { + for (i = 0; i < nexceptions; ++i) + { mem += strlen(exceptions[i].mask) + 1; mem += strlen(exceptions[i].reason) + 1; } @@ -115,12 +114,14 @@ int add_session(const char *nick, const char *host, char *hostip) session = findsession(host); - if (session) { + if (session) + { exception = find_hostip_exception(host, hostip); sessionlimit = exception ? exception->limit : Config.DefSessionLimit; - if (sessionlimit != 0 && session->count >= sessionlimit) { + if (sessionlimit != 0 && session->count >= sessionlimit) + { if (Config.SessionLimitExceeded) ircdproto->SendMessage(OperServ, nick, Config.SessionLimitExceeded, host); if (Config.SessionLimitDetailsLoc) @@ -133,11 +134,12 @@ int add_session(const char *nick, const char *host, char *hostip) * read users.c), so we must increment this here no matter what because it will either be * decremented in do_kill or in do_quit - Adam */ - session->count++; + ++session->count; kill_user(Config.s_OperServ, nick, "Session limit exceeded"); - session->hits++; - if (Config.MaxSessionKill && session->hits >= Config.MaxSessionKill) { + ++session->hits; + if (Config.MaxSessionKill && session->hits >= Config.MaxSessionKill) + { char akillmask[BUFSIZE]; snprintf(akillmask, sizeof(akillmask), "*@%s", host); XLine *x = new XLine(ci::string("*@") + host, Config.s_OperServ, time(NULL) + Config.SessionAutoKillExpiry, "Session limit exceeded"); @@ -146,8 +148,10 @@ int add_session(const char *nick, const char *host, char *hostip) ircdproto->SendGlobops(OperServ, "Added a temporary AKILL for \2%s\2 due to excessive connections", akillmask); } return 0; - } else { - session->count++; + } + else + { + ++session->count; return 1; } } @@ -164,12 +168,14 @@ int add_session(const char *nick, const char *host, char *hostip) void del_session(const char *host) { - if (!Config.LimitSessions) { + if (!Config.LimitSessions) + { Alog(LOG_DEBUG) << "del_session called when LimitSessions is disabled"; return; } - if (!host || !*host) { + if (!host || !*host) + { Alog(LOG_DEBUG) << "del_session called with NULL values"; return; } @@ -178,8 +184,9 @@ void del_session(const char *host) Session *session = findsession(host); - if (!session) { - if (debug) + if (!session) + { + if (debug) { ircdproto->SendGlobops(OperServ, "WARNING: Tried to delete non-existant session: \2%s", host); Alog(LOG_DEBUG) << "session: Tried to delete non-existant session: " << host; @@ -187,8 +194,9 @@ void del_session(const char *host) return; } - if (session->count > 1) { - session->count--; + if (session->count > 1) + { + --session->count; return; } @@ -202,7 +210,6 @@ void del_session(const char *host) Alog(LOG_DEBUG_2) << "del_session() done"; } - /*************************************************************************/ /********************** Internal Exception Functions *********************/ /*************************************************************************/ @@ -212,21 +219,19 @@ void expire_exceptions() int i; time_t now = time(NULL); - for (i = 0; i < nexceptions; i++) { - if (exceptions[i].expires == 0 || exceptions[i].expires > now) + for (i = 0; i < nexceptions; ++i) + { + if (!exceptions[i].expires || exceptions[i].expires > now) continue; if (Config.WallExceptionExpire) - ircdproto->SendGlobops(OperServ, - "Session limit exception for %s has expired.", - exceptions[i].mask); + ircdproto->SendGlobops(OperServ, "Session limit exception for %s has expired.", exceptions[i].mask); delete [] exceptions[i].mask; delete [] exceptions[i].reason; delete [] exceptions[i].who; - nexceptions--; - memmove(exceptions + i, exceptions + i + 1, - sizeof(Exception) * (nexceptions - i)); + --nexceptions; + memmove(exceptions + i, exceptions + i + 1, sizeof(Exception) * (nexceptions - i)); exceptions = static_cast<Exception *>(srealloc(exceptions, sizeof(Exception) * nexceptions)); - i--; + --i; } } @@ -235,11 +240,9 @@ Exception *find_host_exception(const char *host) { int i; - for (i = 0; i < nexceptions; i++) { - if ((Anope::Match(host, exceptions[i].mask, false))) { + for (i = 0; i < nexceptions; ++i) + if ((Anope::Match(host, exceptions[i].mask, false))) return &exceptions[i]; - } - } return NULL; } @@ -250,41 +253,37 @@ Exception *find_hostip_exception(const char *host, const char *hostip) { int i; - for (i = 0; i < nexceptions; i++) { - if ((Anope::Match(host, exceptions[i].mask, false)) - || ((ircd->nickip && hostip) - && (Anope::Match(hostip, exceptions[i].mask, false)))) { + for (i = 0; i < nexceptions; ++i) + if (Anope::Match(host, exceptions[i].mask, false) || ((ircd->nickip && hostip) && Anope::Match(hostip, exceptions[i].mask, false))) return &exceptions[i]; - } - } return NULL; } - /*************************************************************************/ /************************ Exception Manipulation *************************/ /*************************************************************************/ -int exception_add(User * u, const char *mask, const int limit, - const char *reason, const char *who, - const time_t expires) +int exception_add(User *u, const char *mask, const int limit, const char *reason, const char *who, const time_t expires) { int i; /* Check if an exception already exists for this mask */ - for (i = 0; i < nexceptions; i++) { - if (!stricmp(mask, exceptions[i].mask)) { - if (exceptions[i].limit != limit) { + for (i = 0; i < nexceptions; ++i) + { + if (!stricmp(mask, exceptions[i].mask)) + { + if (exceptions[i].limit != limit) + { exceptions[i].limit = limit; if (u) - notice_lang(Config.s_OperServ, u, OPER_EXCEPTION_CHANGED, - mask, exceptions[i].limit); + notice_lang(Config.s_OperServ, u, OPER_EXCEPTION_CHANGED, mask, exceptions[i].limit); return -2; - } else { + } + else + { if (u) - notice_lang(Config.s_OperServ, u, OPER_EXCEPTION_EXISTS, - mask); + notice_lang(Config.s_OperServ, u, OPER_EXCEPTION_EXISTS, mask); return -1; } } diff --git a/src/sockets.cpp b/src/sockets.cpp index 861cd26d8..db51d7b03 100644 --- a/src/sockets.cpp +++ b/src/sockets.cpp @@ -25,7 +25,7 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi { if (!IPv6 && (TargetHost.find(':') != std::string::npos || BindHost.find(':') != std::string::npos)) IPv6 = true; - + Sock = socket(IPv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0); addrinfo hints; @@ -41,7 +41,7 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi sockaddr_in6 bindaddr6; int Bound = -1; - if (getaddrinfo(BindHost.c_str(), NULL, &hints, &bindar) == 0) + if (!getaddrinfo(BindHost.c_str(), NULL, &hints, &bindar)) { if (IPv6) memcpy(&bindaddr6, bindar->ai_addr, bindar->ai_addrlen); @@ -59,28 +59,20 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi bindaddr6.sin6_family = AF_INET6; if (inet_pton(AF_INET6, BindHost.c_str(), &bindaddr6.sin6_addr) < 1) - { throw SocketException("Invalid bind host"); - } if (bind(Sock, reinterpret_cast<sockaddr *>(&bindaddr6), sizeof(bindaddr6)) == -1) - { throw SocketException("Unable to bind to address"); - } } else { bindaddr.sin_family = AF_INET; if (inet_pton(bindaddr.sin_family, BindHost.c_str(), &bindaddr.sin_addr) < 1) - { throw SocketException("Invalid bind host"); - } if (bind(Sock, reinterpret_cast<sockaddr *>(&bindaddr), sizeof(bindaddr)) == -1) - { throw SocketException("Unable to bind to address"); - } } } } @@ -88,7 +80,7 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi addrinfo *conar; sockaddr_in conaddr; sockaddr_in6 conaddr6; - if (getaddrinfo(TargetHost.c_str(), NULL, &hints, &conar) == 0) + if (!getaddrinfo(TargetHost.c_str(), NULL, &hints, &conar)) { if (IPv6) memcpy(&conaddr6, conar->ai_addr, conar->ai_addrlen); @@ -102,16 +94,12 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi if (IPv6) { if (inet_pton(AF_INET6, TargetHost.c_str(), &conaddr6.sin6_addr) < 1) - { throw SocketException("Invalid server address"); - } } else { if (inet_pton(AF_INET, TargetHost.c_str(), &conaddr.sin_addr) < 1) - { throw SocketException("Invalid server address"); - } } } @@ -121,9 +109,7 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi conaddr6.sin6_port = htons(Port); if (connect(Sock, reinterpret_cast<sockaddr *>(&conaddr6), sizeof(conaddr6)) < 0) - { throw SocketException("Error connecting to server"); - } } else { @@ -131,9 +117,7 @@ Socket::Socket(const std::string &nTargetHost, int nPort, const std::string &nBi conaddr.sin_port = htons(Port); if (connect(Sock, reinterpret_cast<sockaddr *>(&conaddr), sizeof(conaddr)) < 0) - { throw SocketException("Error connecting to server"); - } } socketEngine.AddSocket(this); @@ -193,9 +177,7 @@ bool Socket::ProcessRead() RecvLen = RecvInternal(buffer, sizeof(buffer) - 1); if (RecvLen <= 0) - { return false; - } TotalRead += RecvLen; std::string sbuffer = extrabuf; @@ -208,7 +190,7 @@ bool Socket::ProcessRead() TrimBuf(extrabuf); sbuffer = sbuffer.substr(0, lastnewline); } - + sepstream stream(sbuffer, '\n'); std::string buf; @@ -217,12 +199,8 @@ bool Socket::ProcessRead() TrimBuf(buf); if (!buf.empty()) - { if (!Read(buf)) - { return false; - } - } } return true; @@ -235,9 +213,7 @@ bool Socket::ProcessWrite() { int Written = SendInternal(WriteBuffer); if (Written == -1) - { return false; - } TotalWritten += Written; WriteBuffer.clear(); @@ -310,9 +286,7 @@ SocketEngine::SocketEngine() #ifdef _WIN32 WSADATA wsa; if (WSAStartup(MAKEWORD(2, 0), &wsa)) - { Alog() << "Failed to initialize WinSock library"; - } #endif } @@ -377,9 +351,7 @@ void SocketEngine::Process() int sresult = select(MaxFD + 1, &rfdset, &wfdset, &efdset, &tval); if (sresult == -1) - { Alog() << "SocketEngine::Process error, " << GetError(); - } else if (sresult) { for (std::set<Socket *>::iterator it = Sockets.begin(); it != Sockets.end(); ++it) @@ -456,4 +428,3 @@ const std::string SocketEngine::GetError() const return "Socket engine caught unknown error"; } } - diff --git a/src/threadengine.cpp b/src/threadengine.cpp index ea652e1f2..36a73d324 100644 --- a/src/threadengine.cpp +++ b/src/threadengine.cpp @@ -34,4 +34,3 @@ bool Thread::GetExitState() const void Thread::Run() { } - diff --git a/src/threadengine_pthread.cpp b/src/threadengine_pthread.cpp index 9d9bf160d..a85af583e 100644 --- a/src/threadengine_pthread.cpp +++ b/src/threadengine_pthread.cpp @@ -11,9 +11,7 @@ static void *entry_point(void *parameter) Thread *thread = static_cast<Thread *>(parameter); thread->Run(); if (!thread->GetExitState()) - { thread->Join(); - } delete thread; pthread_exit(0); } @@ -23,9 +21,7 @@ static void *entry_point(void *parameter) ThreadEngine::ThreadEngine() { if (pthread_attr_init(&threadengine_attr)) - { throw CoreException("ThreadEngine: Error calling pthread_attr_init"); - } } /** Threadengines destructor @@ -110,4 +106,3 @@ void Condition::Wait() { pthread_cond_wait(&cond, &mutex); } - diff --git a/src/threadengine_win32.cpp b/src/threadengine_win32.cpp index 5ee2f4596..54db9529a 100644 --- a/src/threadengine_win32.cpp +++ b/src/threadengine_win32.cpp @@ -8,9 +8,7 @@ static DWORD WINAPI entry_point(void *parameter) Thread *thread = static_cast<Thread *>(parameter); thread->Run(); if (!thread->GetExitState()) - { thread->Join(); - } delete thread; return 0; } @@ -106,4 +104,3 @@ void Condition::Wait() WaitForSingleObject(cond, INFINITE); EnterCriticalSection(&mutex); } - diff --git a/src/timers.cpp b/src/timers.cpp index 718cbe82f..e4a2ef04b 100644 --- a/src/timers.cpp +++ b/src/timers.cpp @@ -5,9 +5,7 @@ * * Please read COPYING and README for furhter details. * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - * - * + * Based on the original code of Services by Andy Church. */ #include "services.h" @@ -91,11 +89,9 @@ void TimerManager::AddTimer(Timer *T) void TimerManager::DelTimer(Timer *T) { std::vector<Timer *>::iterator i = std::find(Timers.begin(), Timers.end(), T); - + if (i != Timers.end()) - { Timers.erase(i); - } } /** Tick all pending timers @@ -108,7 +104,7 @@ void TimerManager::TickTimers(time_t ctime) Timer *t = Timers.front(); t->Tick(ctime); - + if (t->GetRepeat()) { t->SetTimer(ctime + t->GetSecs()); diff --git a/src/users.cpp b/src/users.cpp index a1890f6c5..7678f17c9 100644 --- a/src/users.cpp +++ b/src/users.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #include "services.h" @@ -51,7 +49,7 @@ User::User(const std::string &snick, const std::string &suid) this->nc = NULL; - usercnt++; + ++usercnt; if (usercnt > maxusercnt) { @@ -68,9 +66,7 @@ void User::SetNewNick(const std::string &newnick) { /* Sanity check to make sure we don't segfault */ if (newnick.empty()) - { throw "User::SetNewNick() got a bad argument"; - } Alog(LOG_DEBUG) << this->nick << " changed nick to " << newnick; @@ -141,7 +137,6 @@ const std::string &User::GetUID() const return this->uid; } - void User::SetVIdent(const std::string &sident) { this->vident = sident; @@ -210,25 +205,21 @@ User::~User() { const char *srealname = normalizeBuffer(this->realname); - Alog() << "LOGUSERS: " << this->GetMask() << (ircd->vhost ? " => " : " ") - << (ircd->vhost ? this->GetDisplayedHost() : "") - << " (" << srealname << ") left the network (" << this->server->GetName() << ")."; + Alog() << "LOGUSERS: " << this->GetMask() << (ircd->vhost ? " => " : " ") << (ircd->vhost ? this->GetDisplayedHost() : "") << " (" << srealname << ") left the network (" << this->server->GetName() << ")."; delete [] srealname; } FOREACH_MOD(I_OnUserLogoff, OnUserLogoff(this)); - usercnt--; + --usercnt; if (is_oper(this)) - opcnt--; + --opcnt; while (!this->chans.empty()) - { this->chans.front()->chan->DeleteUser(this); - } - + UserListByNick.erase(this->nick.c_str()); if (!this->uid.empty()) UserListByUID.erase(this->uid); @@ -255,8 +246,7 @@ User::~User() void User::SendMessage(const std::string &source, const char *fmt, ...) { va_list args; - char buf[BUFSIZE]; - *buf = '\0'; + char buf[BUFSIZE] = ""; if (fmt) { @@ -276,15 +266,10 @@ void User::SendMessage(const std::string &source, const std::string &msg) * - The user is not registered and NSDefMsg is enabled * - The user is registered and has set /ns set msg on */ - if (Config.UsePrivmsg && - ((!this->nc && Config.NSDefFlags.HasFlag(NI_MSG)) || (this->nc && this->nc->HasFlag(NI_MSG)))) - { + if (Config.UsePrivmsg && ((!this->nc && Config.NSDefFlags.HasFlag(NI_MSG)) || (this->nc && this->nc->HasFlag(NI_MSG)))) ircdproto->SendPrivmsg(findbot(source), this->nick.c_str(), "%s", msg.c_str()); - } else - { ircdproto->SendNotice(findbot(source), this->nick.c_str(), "%s", msg.c_str()); - } } /** Collides a nick. @@ -357,16 +342,13 @@ void User::Collide(NickAlias *na) char randbuf[17]; snprintf(randbuf, sizeof(randbuf), "%d", getrandom16()); guestnick = std::string(Config.NSGuestNickPrefix) + std::string(randbuf); - } - while (finduser(guestnick)); + } while (finduser(guestnick)); notice_lang(Config.s_NickServ, this, FORCENICKCHANGE_CHANGING, guestnick.c_str()); ircdproto->SendForceNickChange(this, guestnick.c_str(), time(NULL)); } else - { kill_user(Config.s_NickServ, this->nick, "Services nickname-enforcer kill"); - } } /** Check if the user should become identified because @@ -421,7 +403,6 @@ void User::AutoID(const std::string &account) } } - /** Login the user to a NickCore * @param core The account the user is useing */ @@ -440,9 +421,7 @@ void User::Logout() std::list<User *>::iterator it = std::find(this->nc->Users.begin(), this->nc->Users.end(), this); if (it != this->nc->Users.end()) - { this->nc->Users.erase(it); - } nc = NULL; } @@ -466,9 +445,7 @@ const bool User::IsIdentified(bool CheckNick) const NickAlias *na = findnick(this->nc->display); if (na && na->nc == this->nc) - { return true; - } return false; } @@ -487,9 +464,7 @@ const bool User::IsRecognized(bool CheckSecure) const NickAlias *na = findnick(this->nick); if (!na || !na->nc->HasFlag(NI_SECURE)) - { return false; - } } return OnAccess; @@ -537,9 +512,7 @@ void User::SetModeInternal(UserMode *um, const std::string &Param) modes.SetFlag(um->Name); if (!Param.empty()) - { Params.insert(std::make_pair(um->Name, Param)); - } FOREACH_MOD(I_OnUserModeSet, OnUserModeSet(this, um->Name)); } @@ -555,9 +528,7 @@ void User::RemoveModeInternal(UserMode *um) modes.UnsetFlag(um->Name); std::map<UserModeName, std::string>::iterator it = Params.find(um->Name); if (it != Params.end()) - { Params.erase(it); - } FOREACH_MOD(I_OnUserModeUnset, OnUserModeUnset(this, um->Name)); } @@ -643,7 +614,7 @@ void User::SetModes(BotInfo *bi, const char *umodes, ...) spacesepstream sep(buf); sep.GetToken(modebuf); - for (unsigned i = 0; i < modebuf.size(); ++i) + for (unsigned i = 0, end = modebuf.size(); i < end; ++i) { UserMode *um; @@ -671,9 +642,7 @@ void User::SetModes(BotInfo *bi, const char *umodes, ...) this->SetMode(bi, um); } else - { this->RemoveMode(bi, um); - } } } @@ -685,7 +654,7 @@ void User::SetModes(BotInfo *bi, const char *umodes, ...) */ ChannelContainer *User::FindChannel(Channel *c) { - for (UChannelList::iterator it = this->chans.begin(); it != this->chans.end(); ++it) + for (UChannelList::iterator it = this->chans.begin(), it_end = this->chans.end(); it != it_end; ++it) if ((*it)->chan == c) return *it; return NULL; @@ -708,7 +677,7 @@ void get_user_stats(long *nusers, long *memuse) { long count = 0, mem = 0; - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) + for (user_map::const_iterator it = UserListByNick.begin(), it_end = UserListByNick.end(); it != it_end; ++it) { User *user = it->second; @@ -762,19 +731,21 @@ User *finduser(const ci::string &nick) /* Handle a server NICK command. */ -User *do_nick(const char *source, const char *nick, const char *username, const char *host, - const char *server, const char *realname, time_t ts, - uint32 ip, const char *vhost, const char *uid) +User *do_nick(const char *source, const char *nick, const char *username, const char *host, const char *server, const char *realname, time_t ts, uint32 ip, const char *vhost, const char *uid) { User *user = NULL; - if (!*source) { + if (!*source) + { char ipbuf[16]; struct in_addr addr; - if (ircd->nickvhost) { - if (vhost) { - if (!strcmp(vhost, "*")) { + if (ircd->nickvhost) + { + if (vhost) + { + if (!strcmp(vhost, "*")) + { vhost = NULL; Alog(LOG_DEBUG) << "new user with no vhost in NICK command: " << nick; } @@ -784,7 +755,8 @@ User *do_nick(const char *source, const char *nick, const char *username, const /* This is a new user; create a User structure for it. */ Alog(LOG_DEBUG) << "new user: " << nick; - if (ircd->nickip) { + if (ircd->nickip) + { addr.s_addr = htonl(ip); ntoa(addr, ipbuf, sizeof(ipbuf)); } @@ -810,11 +782,8 @@ User *do_nick(const char *source, const char *nick, const char *username, const /** * End of ugly swap **/ - Alog() << "LOGUSERS: " << nick << " (" << username << "@" << host - << (ircd->nickvhost && vhost ? " => " : "") - << (ircd->nickvhost && vhost ? vhost : "") << ") (" << logrealname << ") " - << (ircd->nickip ? "[" : "") << (ircd->nickip ? ipbuf : "") << (ircd->nickip ? "]" : "") - << " connected to the network (" << serv->GetName() << ")."; + Alog() << "LOGUSERS: " << nick << " (" << username << "@" << host << (ircd->nickvhost && vhost ? " => " : "") << (ircd->nickvhost && vhost ? vhost : "") << ") (" << logrealname << ") " + << (ircd->nickip ? "[" : "") << (ircd->nickip ? ipbuf : "") << (ircd->nickip ? "]" : "") << " connected to the network (" << serv->GetName() << ")."; delete [] logrealname; } @@ -831,11 +800,10 @@ User *do_nick(const char *source, const char *nick, const char *username, const user->SetVIdent(username); /* We now store the user's ip in the user_ struct, * because we will use it in serveral places -- DrStein */ - if (ircd->nickip) { + if (ircd->nickip) user->hostip = sstrdup(ipbuf); - } else { + else user->hostip = NULL; - } EventReturn MOD_RESULT; FOREACH_RESULT(I_OnPreUserConnect, OnPreUserConnect(user)); @@ -858,7 +826,8 @@ User *do_nick(const char *source, const char *nick, const char *username, const /* An old user changing nicks. */ user = finduser(source); - if (!user) { + if (!user) + { Alog() << "user: NICK from nonexistent nick " << source; return NULL; } @@ -868,8 +837,7 @@ User *do_nick(const char *source, const char *nick, const char *username, const if (Config.LogUsers) { const char *logrealname = normalizeBuffer(user->realname); - Alog() << "LOGUSERS: " << user->nick << " (" << user->GetIdent() << "@" << user->host - << (ircd->vhost ? " => " : "") << (ircd->vhost ? user->GetDisplayedHost() : "") << ") (" + Alog() << "LOGUSERS: " << user->nick << " (" << user->GetIdent() << "@" << user->host << (ircd->vhost ? " => " : "") << (ircd->vhost ? user->GetDisplayedHost() : "") << ") (" << logrealname << ") " << "changed nick to " << nick << " (" << user->server->GetName() << ")."; if (logrealname) delete [] logrealname; @@ -877,11 +845,9 @@ User *do_nick(const char *source, const char *nick, const char *username, const user->timestamp = ts; - if (stricmp(nick, user->nick.c_str()) == 0) - { + if (!stricmp(nick, user->nick.c_str())) /* No need to redo things */ user->SetNewNick(nick); - } else { /* Update this only if nicks aren't the same */ @@ -938,7 +904,8 @@ void do_umode(const char *source, int ac, const char **av) User *user; user = finduser(av[0]); - if (!user) { + if (!user) + { Alog() << "user: MODE "<< av[1] << " for nonexistent nick "<< av[0] << ":" << merge_args(ac, av); return; } @@ -958,13 +925,14 @@ void do_quit(const char *source, int ac, const char **av) NickAlias *na; user = finduser(source); - if (!user) { + if (!user) + { Alog() << "user: QUIT from nonexistent user " << source << ":" << merge_args(ac, av); return; } Alog(LOG_DEBUG) << source << " quits"; - if ((na = findnick(user->nick)) && !na->HasFlag(NS_FORBIDDEN) - && !na->nc->HasFlag(NI_SUSPENDED) && (user->IsRecognized() || user->IsIdentified(true))) { + if ((na = findnick(user->nick)) && !na->HasFlag(NS_FORBIDDEN) && !na->nc->HasFlag(NI_SUSPENDED) && (user->IsRecognized() || user->IsIdentified(true))) + { na->last_seen = time(NULL); if (na->last_quit) delete [] na->last_quit; @@ -1002,9 +970,8 @@ void do_kill(const std::string &nick, const std::string &msg) delete [] na->last_quit; na->last_quit = !msg.empty() ? sstrdup(msg.c_str()) : NULL; } - if (Config.LimitSessions && !user->server->IsULined()) { + if (Config.LimitSessions && !user->server->IsULined()) del_session(user->host); - } delete user; } @@ -1050,7 +1017,6 @@ int is_excepted_mask(ChannelInfo * ci, const char *mask) return 0; } - /*************************************************************************/ /* Does the user's usermask match the given mask (either nick!user@host or @@ -1063,35 +1029,32 @@ int match_usermask(const char *mask, User * user) char *nick, *username, *host; int result; - if (!mask || !*mask) { + if (!mask || !*mask) return 0; - } mask2 = sstrdup(mask); - if (strchr(mask2, '!')) { + if (strchr(mask2, '!')) + { nick = strtok(mask2, "!"); username = strtok(NULL, "@"); - } else { + } + else + { nick = NULL; username = strtok(mask2, "@"); } host = strtok(NULL, ""); - if (!username || !host) { + if (!username || !host) + { delete [] mask2; return 0; } - if (nick) { - result = Anope::Match(user->nick, nick, false) - && Anope::Match(user->GetIdent().c_str(), username, false) - && (Anope::Match(user->host, host, false) - || Anope::Match(user->GetDisplayedHost().c_str(), host, false)); - } else { - result = Anope::Match(user->GetIdent().c_str(), username, false) - && (Anope::Match(user->host, host, false) - || Anope::Match(user->GetDisplayedHost().c_str(), host, false)); - } + if (nick) + result = Anope::Match(user->nick, nick, false) && Anope::Match(user->GetIdent().c_str(), username, false) && (Anope::Match(user->host, host, false) || Anope::Match(user->GetDisplayedHost().c_str(), host, false)); + else + result = Anope::Match(user->GetIdent().c_str(), username, false) && (Anope::Match(user->host, host, false) || Anope::Match(user->GetDisplayedHost().c_str(), host, false)); delete [] mask2; return result; @@ -1108,7 +1071,7 @@ int match_usermask(const char *mask, User * user) * when done with. */ -char *create_mask(User * u) +char *create_mask(User *u) { char *mask, *s, *end; std::string mident = u->GetIdent(); @@ -1128,10 +1091,8 @@ char *create_mask(User * u) // XXX: someone needs to rewrite this godawful kitten murdering pile of crap. if (strspn(mhost.c_str(), "0123456789.") == mhost.length() && (s = strchr(const_cast<char *>(mhost.c_str()), '.')) // XXX - Potentially unsafe cast - && (s = strchr(s + 1, '.')) - && (s = strchr(s + 1, '.')) - && (!strchr(s + 1, '.'))) - { /* IP addr */ + && (s = strchr(s + 1, '.')) && (s = strchr(s + 1, '.')) && (!strchr(s + 1, '.'))) + { /* IP addr */ s = sstrdup(mhost.c_str()); *strrchr(s, '.') = 0; @@ -1140,14 +1101,15 @@ char *create_mask(User * u) } else { - if ((s = strchr(const_cast<char *>(mhost.c_str()), '.')) && strchr(s + 1, '.')) { + if ((s = strchr(const_cast<char *>(mhost.c_str()), '.')) && strchr(s + 1, '.')) + { s = sstrdup(strchr(mhost.c_str(), '.') - 1); *s = '*'; strcpy(end, s); delete [] s; - } else { - strcpy(end, mhost.c_str()); } + else + strcpy(end, mhost.c_str()); } return mask; } @@ -1168,7 +1130,7 @@ void UserSetInternalModes(User *user, int ac, const char **av) Alog(LOG_DEBUG) << "Changing user modes for " << user->nick << " to " << merge_args(ac, av); - for (; *modes; modes++) + for (; *modes; ++modes) { UserMode *um; @@ -1232,4 +1194,3 @@ void UserSetInternalModes(User *user, int ac, const char **av) } } } - diff --git a/src/wildcard.cpp b/src/wildcard.cpp index 1106a9cd6..42f0812f7 100644 --- a/src/wildcard.cpp +++ b/src/wildcard.cpp @@ -6,7 +6,7 @@ static bool match_internal(const unsigned char *str, const unsigned char *mask, unsigned char *string = const_cast<unsigned char *>(str); // XXX: unsafe cast unsigned char *wild = const_cast<unsigned char *>(mask); // XXX: unsafe cast - while ((*string) && (*wild != '*')) + while (*string && *wild != '*') { if (case_sensitive) { @@ -28,12 +28,10 @@ static bool match_internal(const unsigned char *str, const unsigned char *mask, if (*wild == '*') { if (!*++wild) - { return 1; - } mp = wild; - cp = string+1; + cp = string + 1; } else { @@ -41,8 +39,8 @@ static bool match_internal(const unsigned char *str, const unsigned char *mask, { if (*wild == *string || *wild == '?') { - wild++; - string++; + ++wild; + ++string; } else { @@ -54,8 +52,8 @@ static bool match_internal(const unsigned char *str, const unsigned char *mask, { if (tolower(*wild) == tolower(*string) || *wild == '?') { - wild++; - string++; + ++wild; + ++string; } else { @@ -68,9 +66,7 @@ static bool match_internal(const unsigned char *str, const unsigned char *mask, } while (*wild == '*') - { - wild++; - } + ++wild; return !*wild; } diff --git a/src/win32_memory.cpp b/src/win32_memory.cpp index dc4cd4a89..903be83e6 100644 --- a/src/win32_memory.cpp +++ b/src/win32_memory.cpp @@ -28,9 +28,9 @@ * when it comes to memory usage between dlls and exes. */ -void * ::operator new(size_t iSize) +void *::operator new(size_t iSize) { - void *ptr = HeapAlloc(GetProcessHeap(), 0, iSize); /* zero memory for unix compatibility */ + void *ptr = HeapAlloc(GetProcessHeap(), 0, iSize); /* zero memory for unix compatibility */ /* This is the correct behaviour according to C++ standards for out of memory, * not returning null -- Brain */ @@ -46,7 +46,8 @@ void ::operator delete(void *ptr) HeapFree(GetProcessHeap(), 0, ptr); } -void * operator new[](size_t iSize) { +void *operator new[](size_t iSize) +{ void *ptr = HeapAlloc(GetProcessHeap(), 0, iSize); /* Why were we initializing the memory to zeros here? This is just a waste of cpu! */ if (!ptr) throw std::bad_alloc(); diff --git a/src/windows.cpp b/src/windows.cpp index 75bd9f7d1..6568e860e 100644 --- a/src/windows.cpp +++ b/src/windows.cpp @@ -7,8 +7,6 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * */ #ifdef WIN32 @@ -24,7 +22,6 @@ const char *dlerror() return errbuf; } - /** This is inet_pton, but it works on Windows * @param af The protocol type, AF_INET or AF_INET6 * @param src The address @@ -37,7 +34,7 @@ int inet_pton(int af, const char *src, void *dst) sockaddr_storage sa; sockaddr_in *sin = reinterpret_cast<sockaddr_in *>(&sa); sockaddr_in6 *sin6 = reinterpret_cast<sockaddr_in6 *>(&sa); - + switch (af) { case AF_INET: @@ -49,8 +46,8 @@ int inet_pton(int af, const char *src, void *dst) default: return -1; } - - if (WSAStringToAddress((LPSTR) src, af, NULL, reinterpret_cast<LPSOCKADDR>(&sa), &address_length) == 0) + + if (!WSAStringToAddress((LPSTR) src, af, NULL, reinterpret_cast<LPSOCKADDR>(&sa), &address_length)) { switch (af) { @@ -63,10 +60,10 @@ int inet_pton(int af, const char *src, void *dst) } return 1; } - + return 0; } - + /** This is inet_ntop, but it works on Windows * @param af The protocol type, AF_INET or AF_INET6 * @param src Network address structure @@ -81,9 +78,9 @@ const char *inet_ntop(int af, const void *src, char *dst, size_t size) sockaddr_storage sa; sockaddr_in *sin = reinterpret_cast<sockaddr_in *>(&sa); sockaddr_in6 *sin6 = reinterpret_cast<sockaddr_in6 *>(&sa); - + memset(&sa, 0, sizeof(sa)); - + switch (af) { case AF_INET: @@ -99,10 +96,10 @@ const char *inet_ntop(int af, const void *src, char *dst, size_t size) default: return NULL; } - - if (WSAAddressToString(reinterpret_cast<LPSOCKADDR>(&sa), address_length, NULL, dst, &string_length) == 0) + + if (!WSAAddressToString(reinterpret_cast<LPSOCKADDR>(&sa), address_length, NULL, dst, &string_length)) return dst; - + return NULL; } |