1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
44 #include "connection.h"
54 #define nspace __gnu_cxx
59 int LogLevel = DEFAULT;
60 char ServerName[MAXBUF];
62 char ServerDesc[MAXBUF];
63 char AdminName[MAXBUF];
64 char AdminEmail[MAXBUF];
65 char AdminNick[MAXBUF];
67 char restartpass[MAXBUF];
71 char PrefixQuit[MAXBUF];
72 char DieValue[MAXBUF];
74 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
75 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
77 time_t startup_time = time(NULL);
78 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
79 time_t nb_start = time(NULL);
81 extern vector<Module*> modules;
82 std::vector<std::string> module_names;
83 extern vector<ircd_module*> factory;
84 std::vector<int> fd_reap;
92 template<> struct nspace::hash<in_addr>
94 size_t operator()(const struct in_addr &a) const
97 memcpy(&q,&a,sizeof(size_t));
102 template<> struct nspace::hash<string>
104 size_t operator()(const string &s) const
107 static struct hash<const char *> strhash;
119 bool operator()(const string& s1, const string& s2) const
121 char a[MAXBUF],b[MAXBUF];
122 strcpy(a,s1.c_str());
123 strcpy(b,s2.c_str());
124 return (strcasecmp(a,b) == 0);
129 struct InAddr_HashComp
132 bool operator()(const in_addr &s1, const in_addr &s2) const
137 memcpy(&q,&s1,sizeof(size_t));
138 memcpy(&p,&s2,sizeof(size_t));
146 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
147 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
148 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
149 typedef std::deque<command_t> command_table;
155 user_hash clientlist;
158 command_table cmdlist;
165 struct linger linger = { 0 };
166 char bannerBuffer[MAXBUF];
167 int boundPortCount = 0;
168 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
169 int defaultRoute = 0;
173 long MyKey = C.GenKey();
177 int has_channel(userrec *u, chanrec *c);
178 int usercount(chanrec *c);
179 int usercount_i(chanrec *c);
180 void update_stats_l(int fd,int data_out);
181 char* Passwd(userrec *user);
182 bool IsDenied(userrec *user);
183 void AddWhoWas(userrec* u);
185 std::stringstream config_f(stringstream::in | stringstream::out);
187 void safedelete(userrec *p)
191 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
192 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
198 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
202 void safedelete(chanrec *p)
208 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
212 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
217 void tidystring(char* str)
219 // strips out double spaces before a : parameter
222 bool go_again = true;
229 while ((str[0] == ' ') && (strlen(str)>0))
236 bool noparse = false;
239 while (a < strlen(str))
241 if ((a<strlen(str)-1) && (noparse==false))
243 if ((str[a] == ' ') && (str[a+1] == ' '))
245 log(DEBUG,"Tidied extra space out of string: %s",str);
253 if ((str[a] == ' ') && (str[a+1] == ':'))
259 temp[t++] = str[a++];
262 strncpy(str,temp,MAXBUF);
266 /* chop a string down to 512 characters and preserve linefeed (irc max
273 log(DEBUG,"ERROR! Null string passed to chop()!");
277 FOREACH_MOD OnServerRaw(temp,false);
278 const char* str2 = temp.c_str();
279 sprintf(str,"%s",str2);
282 if (strlen(str) >= 512)
291 std::string getservername()
296 std::string getserverdesc()
301 std::string getnetworkname()
306 std::string getadminname()
311 std::string getadminemail()
316 std::string getadminnick()
321 void log(int level,char *text, ...)
323 char textbuffer[MAXBUF];
326 struct tm * timeinfo;
327 if (level < LogLevel)
331 timeinfo = localtime (&rawtime);
336 va_start (argsPtr, text);
337 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
339 strcpy(b,asctime(timeinfo));
340 b[strlen(b)-1] = ':';
341 fprintf(log_file,"%s %s\n",b,textbuffer);
344 // nofork enabled? display it on terminal too
345 printf("%s %s\n",b,textbuffer);
350 void readfile(file_cache &F, const char* fname)
353 char linebuf[MAXBUF];
355 log(DEBUG,"readfile: loading %s",fname);
357 file = fopen(fname,"r");
362 fgets(linebuf,sizeof(linebuf),file);
363 linebuf[strlen(linebuf)-1]='\0';
364 if (!strcmp(linebuf,""))
370 F.push_back(linebuf);
377 log(DEBUG,"readfile: failed to load file: %s",fname);
379 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
382 void ReadConfig(void)
384 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
387 LoadConf(CONFIG_FILE,&config_f);
389 ConfValue("server","name",0,ServerName,&config_f);
390 ConfValue("server","description",0,ServerDesc,&config_f);
391 ConfValue("server","network",0,Network,&config_f);
392 ConfValue("admin","name",0,AdminName,&config_f);
393 ConfValue("admin","email",0,AdminEmail,&config_f);
394 ConfValue("admin","nick",0,AdminNick,&config_f);
395 ConfValue("files","motd",0,motd,&config_f);
396 ConfValue("files","rules",0,rules,&config_f);
397 ConfValue("power","diepass",0,diepass,&config_f);
398 ConfValue("power","pause",0,pauseval,&config_f);
399 ConfValue("power","restartpass",0,restartpass,&config_f);
400 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
401 ConfValue("die","value",0,DieValue,&config_f);
402 ConfValue("options","loglevel",0,dbg,&config_f);
403 ConfValue("options","netbuffersize",0,NB,&config_f);
404 NetBufferSize = atoi(NB);
405 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
407 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
408 NetBufferSize = 10240;
410 if (!strcmp(dbg,"debug"))
412 if (!strcmp(dbg,"verbose"))
414 if (!strcmp(dbg,"default"))
416 if (!strcmp(dbg,"sparse"))
418 if (!strcmp(dbg,"none"))
421 log(DEBUG,"Reading message of the day");
422 readfile(RULES,rules);
423 log(DEBUG,"Reading connect classes");
425 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
428 ConfValue("connect","allow",i,Value,&config_f);
429 ConfValue("connect","timeout",i,timeout,&config_f);
430 ConfValue("connect","flood",i,flood,&config_f);
431 if (strcmp(Value,""))
433 strcpy(c.host,Value);
436 ConfValue("connect","password",i,Value,&config_f);
437 strcpy(c.pass,Value);
438 c.registration_timeout = 90; // default is 2 minutes
439 c.flood = atoi(flood);
442 c.registration_timeout = atoi(timeout);
444 Classes.push_back(c);
445 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
449 ConfValue("connect","deny",i,Value,&config_f);
450 strcpy(c.host,Value);
452 Classes.push_back(c);
453 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
462 log(DEBUG,"Blocking: %d",s);
463 flags = fcntl(s, F_GETFL, 0);
464 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
467 void NonBlocking(int s)
470 log(DEBUG,"NonBlocking: %d",s);
471 flags = fcntl(s, F_GETFL, 0);
472 //fcntl(s, F_SETFL, O_NONBLOCK);
473 fcntl(s, F_SETFL, flags | O_NONBLOCK);
477 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
479 struct hostent *hostPtr = NULL;
482 memset (resolvedHost, '\0',MAXBUF);
483 if(unresolvedHost == NULL)
485 if ((inet_aton(unresolvedHost,&addr)) == 0)
487 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
489 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
491 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
495 /* write formatted text to a socket, in same format as printf */
497 void Write(int sock,char *text, ...)
501 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
504 char textbuffer[MAXBUF];
508 va_start (argsPtr, text);
509 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
511 sprintf(tb,"%s\r\n",textbuffer);
515 write(sock,tb,strlen(tb));
516 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
520 /* write a server formatted numeric response to a single socket */
522 void WriteServ(int sock, char* text, ...)
526 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
529 char textbuffer[MAXBUF],tb[MAXBUF];
531 va_start (argsPtr, text);
533 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
535 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
539 write(sock,tb,strlen(tb));
540 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
544 /* write text from an originating user to originating user */
546 void WriteFrom(int sock, userrec *user,char* text, ...)
548 if ((!text) || (!user))
550 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
553 char textbuffer[MAXBUF],tb[MAXBUF];
555 va_start (argsPtr, text);
557 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
559 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
563 write(sock,tb,strlen(tb));
564 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
568 /* write text to an destination user from a source user (e.g. user privmsg) */
570 void WriteTo(userrec *source, userrec *dest,char *data, ...)
572 if ((!dest) || (!data))
574 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
577 char textbuffer[MAXBUF],tb[MAXBUF];
579 va_start (argsPtr, data);
580 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
584 // if no source given send it from the server.
587 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
591 WriteFrom(dest->fd,source,"%s",textbuffer);
595 /* write formatted text from a source user to all users on a channel
596 * including the sender (NOT for privmsg, notice etc!) */
598 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
600 if ((!Ptr) || (!user) || (!text))
602 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
605 char textbuffer[MAXBUF];
607 va_start (argsPtr, text);
608 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
610 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
612 if (has_channel(i->second,Ptr))
614 WriteTo(user,i->second,"%s",textbuffer);
619 /* write formatted text from a source user to all users on a channel
620 * including the sender (NOT for privmsg, notice etc!) doesnt send to
621 * users on remote servers */
623 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
625 if ((!Ptr) || (!text))
627 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
630 char textbuffer[MAXBUF];
632 va_start (argsPtr, text);
633 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
635 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
637 if (has_channel(i->second,Ptr))
639 if (i->second->fd != -1)
643 WriteServ(i->second->fd,"%s",textbuffer);
647 WriteTo(user,i->second,"%s",textbuffer);
655 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
657 if ((!Ptr) || (!user) || (!text))
659 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
662 char textbuffer[MAXBUF];
664 va_start (argsPtr, text);
665 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
667 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
671 if (has_channel(i->second,Ptr))
673 WriteServ(i->second->fd,"%s",textbuffer);
680 /* write formatted text from a source user to all users on a channel except
681 * for the sender (for privmsg etc) */
683 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
685 if ((!Ptr) || (!user) || (!text))
687 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
690 char textbuffer[MAXBUF];
692 va_start (argsPtr, text);
693 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
696 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
700 if (has_channel(i->second,Ptr) && (user != i->second))
702 WriteTo(user,i->second,"%s",textbuffer);
708 int c_count(userrec* u)
711 for (int i =0; i != MAXCHANS; i++)
712 if (u->chans[i].channel != NULL)
718 /* return 0 or 1 depending if users u and u2 share one or more common channels
719 * (used by QUIT, NICK etc which arent channel specific notices) */
721 int common_channels(userrec *u, userrec *u2)
728 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
731 for (int i = 0; i != MAXCHANS; i++)
733 for (z = 0; z != MAXCHANS; z++)
735 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
737 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
739 if ((c_count(u)) && (c_count(u2)))
750 /* write a formatted string to all users who share at least one common
751 * channel, including the source user e.g. for use in NICK */
753 void WriteCommon(userrec *u, char* text, ...)
757 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
761 if (u->registered != 7) {
762 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
766 char textbuffer[MAXBUF];
768 va_start (argsPtr, text);
769 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
772 WriteFrom(u->fd,u,"%s",textbuffer);
774 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
778 if (common_channels(u,i->second) && (i->second != u))
780 WriteFrom(i->second->fd,u,"%s",textbuffer);
786 /* write a formatted string to all users who share at least one common
787 * channel, NOT including the source user e.g. for use in QUIT */
789 void WriteCommonExcept(userrec *u, char* text, ...)
793 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
797 if (u->registered != 7) {
798 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
802 char textbuffer[MAXBUF];
804 va_start (argsPtr, text);
805 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
808 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
812 if ((common_channels(u,i->second)) && (u != i->second))
814 WriteFrom(i->second->fd,u,"%s",textbuffer);
820 void WriteOpers(char* text, ...)
824 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
828 char textbuffer[MAXBUF];
830 va_start (argsPtr, text);
831 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
834 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
838 if (strchr(i->second->modes,'o'))
840 if (strchr(i->second->modes,'s'))
842 // send server notices to all with +s
843 // (TODO: needs SNOMASKs)
844 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
851 // returns TRUE of any users on channel C occupy server 'servername'.
853 bool ChanAnyOnThisServer(chanrec *c,char* servername)
855 log(DEBUG,"ChanAnyOnThisServer");
856 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
858 if (has_channel(i->second,c))
860 if (!strcasecmp(i->second->server,servername))
869 // returns true if user 'u' shares any common channels with any users on server 'servername'
871 bool CommonOnThisServer(userrec* u,const char* servername)
873 log(DEBUG,"ChanAnyOnThisServer");
874 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
876 if ((common_channels(u,i->second)) && (u != i->second))
878 if (!strcasecmp(i->second->server,servername))
888 void NetSendToCommon(userrec* u, chanrec* c, char* s)
891 snprintf(buffer,MAXBUF,"%s",s);
893 for (int j = 0; j < 32; j++)
897 for (int k = 0; k < me[j]->connectors.size(); k++)
899 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
901 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
909 void NetSendToAll(char* s)
912 snprintf(buffer,MAXBUF,"%s",s);
914 for (int j = 0; j < 32; j++)
918 for (int k = 0; k < me[j]->connectors.size(); k++)
920 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
927 void NetSendToOne(char* target,char* s)
930 snprintf(buffer,MAXBUF,"%s",s);
932 for (int j = 0; j < 32; j++)
936 for (int k = 0; k < me[j]->connectors.size(); k++)
938 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
940 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
947 void NetSendToAllExcept(char* target,char* s)
950 snprintf(buffer,MAXBUF,"%s",s);
952 for (int j = 0; j < 32; j++)
956 for (int k = 0; k < me[j]->connectors.size(); k++)
958 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
960 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
968 bool hasumode(userrec* user, char mode)
972 return (strchr(user->modes,mode)>0);
977 void WriteMode(const char* modes, int flags, const char* text, ...)
979 if ((!text) || (!modes) || (!flags))
981 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
985 char textbuffer[MAXBUF];
987 va_start (argsPtr, text);
988 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
991 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
995 bool send_to_user = false;
1000 for (int n = 0; n < strlen(modes); n++)
1002 if (!hasumode(i->second,modes[n]))
1004 send_to_user = false;
1009 else if (flags == WM_OR)
1011 send_to_user = false;
1012 for (int n = 0; n < strlen(modes); n++)
1014 if (hasumode(i->second,modes[n]))
1016 send_to_user = true;
1024 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1030 void ChangeName(userrec* user, const char* gecos)
1032 strncpy(user->fullname,gecos,MAXBUF);
1034 // TODO: replace these with functions:
1035 // NetSendToAll - to all
1036 // NetSendToCommon - to all that hold users sharing a common channel with another user
1037 // NetSendToOne - to one server
1038 // NetSendToAllExcept - send to all but one
1039 // all by servername
1041 char buffer[MAXBUF];
1042 snprintf(buffer,MAXBUF,"a %s :%s",user->nick,gecos);
1043 NetSendToAll(buffer);
1046 void ChangeDisplayedHost(userrec* user, const char* host)
1048 strncpy(user->dhost,host,160);
1049 char buffer[MAXBUF];
1050 snprintf(buffer,MAXBUF,"b %s :%s",user->nick,host);
1051 NetSendToAll(buffer);
1054 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1056 if ((!text) || (!source))
1058 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1063 char textbuffer[MAXBUF];
1065 va_start (argsPtr, text);
1066 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1069 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1073 if (strchr(i->second->modes,'w'))
1075 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
1082 char buffer[MAXBUF];
1083 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1084 NetSendToAll(buffer);
1088 /* convert a string to lowercase. Note following special circumstances
1089 * taken from RFC 1459. Many "official" server branches still hold to this
1090 * rule so i will too;
1092 * Because of IRC's scandanavian origin, the characters {}| are
1093 * considered to be the lower case equivalents of the characters []\,
1094 * respectively. This is a critical issue when determining the
1095 * equivalence of two nicknames.
1098 void strlower(char *n)
1104 for (int i = 0; i != strlen(n); i++)
1106 n[i] = tolower(n[i]);
1116 /* verify that a user's ident and nickname is valid */
1118 int isident(const char* n)
1130 for (int i = 0; i != strlen(n); i++)
1132 if ((n[i] < 33) || (n[i] > 125))
1136 /* can't occur ANYWHERE in an Ident! */
1137 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1146 int isnick(const char* n)
1158 if (strlen(n) > NICKMAX-1)
1162 for (int i = 0; i != strlen(n); i++)
1164 if ((n[i] < 33) || (n[i] > 125))
1168 /* can't occur ANYWHERE in a nickname! */
1169 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1173 /* can't occur as the first char of a nickname... */
1174 if ((strchr("0123456789",n[i])) && (!i))
1182 /* Find a user record by nickname and return a pointer to it */
1184 userrec* Find(string nick)
1186 user_hash::iterator iter = clientlist.find(nick);
1188 if (iter == clientlist.end())
1189 /* Couldn't find it */
1192 return iter->second;
1195 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1197 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1201 if (i->second->fd == fd)
1203 i->second->bytes_out+=data_out;
1204 i->second->cmds_out++;
1211 /* find a channel record by channel name and return a pointer to it */
1213 chanrec* FindChan(const char* chan)
1217 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1221 chan_hash::iterator iter = chanlist.find(chan);
1223 if (iter == chanlist.end())
1224 /* Couldn't find it */
1227 return iter->second;
1231 void purge_empty_chans(void)
1233 int go_again = 1, purge = 0;
1238 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1241 if (!usercount(i->second))
1243 /* kill the record */
1244 if (i != chanlist.end())
1246 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1256 log(DEBUG,"skipped purge for %s",i->second->name);
1261 log(DEBUG,"completed channel purge, killed %d",purge);
1264 /* returns the status character for a given user on a channel, e.g. @ for op,
1265 * % for halfop etc. If the user has several modes set, the highest mode
1266 * the user has must be returned. */
1268 char* cmode(userrec *user, chanrec *chan)
1270 if ((!user) || (!chan))
1272 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1277 for (int i = 0; i != MAXCHANS; i++)
1279 if ((user->chans[i].channel == chan) && (chan != NULL))
1281 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1285 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1289 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1298 char scratch[MAXBUF];
1299 char sparam[MAXBUF];
1301 char* chanmodes(chanrec *chan)
1305 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1312 if (chan->noexternal)
1314 strncat(scratch,"n",MAXMODES);
1316 if (chan->topiclock)
1318 strncat(scratch,"t",MAXMODES);
1320 if (strcmp(chan->key,""))
1322 strncat(scratch,"k",MAXMODES);
1326 strncat(scratch,"l",MAXMODES);
1328 if (chan->inviteonly)
1330 strncat(scratch,"i",MAXMODES);
1332 if (chan->moderated)
1334 strncat(scratch,"m",MAXMODES);
1338 strncat(scratch,"s",MAXMODES);
1340 if (chan->c_private)
1342 strncat(scratch,"p",MAXMODES);
1344 if (strcmp(chan->key,""))
1346 strncat(sparam,chan->key,MAXBUF);
1351 sprintf(foo," %d",chan->limit);
1352 strncat(sparam,foo,MAXBUF);
1354 if (strlen(chan->custom_modes))
1356 strncat(scratch,chan->custom_modes,MAXMODES);
1357 for (int z = 0; z < strlen(chan->custom_modes); z++)
1359 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1362 strncat(sparam," ",MAXBUF);
1363 strncat(sparam,extparam.c_str(),MAXBUF);
1367 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1368 strncat(scratch,sparam,MAXMODES);
1372 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1373 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1374 * highest mode the user has must be returned. */
1376 int cstatus(userrec *user, chanrec *chan)
1378 if ((!chan) || (!user))
1380 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1384 for (int i = 0; i != MAXCHANS; i++)
1386 if ((user->chans[i].channel == chan) && (chan != NULL))
1388 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1392 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1396 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1398 return STATUS_VOICE;
1400 return STATUS_NORMAL;
1406 /* compile a userlist of a channel into a string, each nick seperated by
1407 * spaces and op, voice etc status shown as @ and + */
1409 void userlist(userrec *user,chanrec *c)
1411 if ((!c) || (!user))
1413 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1417 sprintf(list,"353 %s = %s :", user->nick, c->name);
1418 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1420 if (has_channel(i->second,c))
1422 if (isnick(i->second->nick))
1424 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1426 /* user is +i, and source not on the channel, does not show
1427 * nick in NAMES list */
1430 strcat(list,cmode(i->second,c));
1431 strcat(list,i->second->nick);
1433 if (strlen(list)>(480-NICKMAX))
1435 /* list overflowed into
1436 * multiple numerics */
1437 WriteServ(user->fd,list);
1438 sprintf(list,"353 %s = %s :", user->nick, c->name);
1443 /* if whats left in the list isnt empty, send it */
1444 if (list[strlen(list)-1] != ':')
1446 WriteServ(user->fd,list);
1450 /* return a count of the users on a specific channel accounting for
1451 * invisible users who won't increase the count. e.g. for /LIST */
1453 int usercount_i(chanrec *c)
1460 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1465 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1469 if (has_channel(i->second,c))
1471 if (isnick(i->second->nick))
1473 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1475 /* user is +i, and source not on the channel, does not show
1476 * nick in NAMES list */
1484 log(DEBUG,"usercount_i: %s %d",c->name,count);
1489 int usercount(chanrec *c)
1496 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1501 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1505 if (has_channel(i->second,c))
1507 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1514 log(DEBUG,"usercount: %s %d",c->name,count);
1519 /* add a channel to a user, creating the record for it if needed and linking
1520 * it to the user record */
1522 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1524 if ((!user) || (!cn))
1526 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1535 strncpy(cname,cn,MAXBUF);
1537 // we MUST declare this wherever we use FOREACH_RESULT
1540 if (strlen(cname) > CHANMAX-1)
1542 cname[CHANMAX-1] = '\0';
1545 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1547 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1549 return NULL; // already on the channel!
1553 if (!FindChan(cname))
1555 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1560 /* create a new one */
1561 log(DEBUG,"add_channel: creating: %s",cname);
1563 chanlist[cname] = new chanrec();
1565 strcpy(chanlist[cname]->name, cname);
1566 chanlist[cname]->topiclock = 1;
1567 chanlist[cname]->noexternal = 1;
1568 chanlist[cname]->created = time(NULL);
1569 strcpy(chanlist[cname]->topic, "");
1570 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1571 chanlist[cname]->topicset = 0;
1572 Ptr = chanlist[cname];
1573 log(DEBUG,"add_channel: created: %s",cname);
1574 /* set created to 2 to indicate user
1575 * is the first in the channel
1576 * and should be given ops */
1582 /* channel exists, just fish out a pointer to its struct */
1583 Ptr = FindChan(cname);
1586 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1588 // the override flag allows us to bypass channel modes
1589 // and bans (used by servers)
1592 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1597 if (strcmp(Ptr->key,""))
1599 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1602 log(DEBUG,"add_channel: no key given in JOIN");
1603 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1608 log(DEBUG,"key at %p is %s",key,key);
1609 if (strcasecmp(key,Ptr->key))
1611 log(DEBUG,"add_channel: bad key given in JOIN");
1612 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1617 log(DEBUG,"add_channel: no key");
1619 if (Ptr->inviteonly)
1621 log(DEBUG,"add_channel: channel is +i");
1622 if (user->IsInvited(Ptr->name))
1624 /* user was invited to channel */
1625 /* there may be an optional channel NOTICE here */
1629 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1633 log(DEBUG,"add_channel: channel is not +i");
1637 if (usercount(Ptr) == Ptr->limit)
1639 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1644 log(DEBUG,"add_channel: about to walk banlist");
1646 /* check user against the channel banlist */
1649 if (Ptr->bans.size())
1651 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1653 if (match(user->GetFullHost(),i->data))
1655 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1662 log(DEBUG,"add_channel: bans checked");
1665 if ((Ptr) && (user))
1667 user->RemoveInvite(Ptr->name);
1670 log(DEBUG,"add_channel: invites removed");
1675 log(DEBUG,"Overridden checks");
1683 log(DEBUG,"Passed channel checks");
1685 for (int i =0; i != MAXCHANS; i++)
1687 log(DEBUG,"Check location %d",i);
1688 if (user->chans[i].channel == NULL)
1690 log(DEBUG,"Adding into their channel list at location %d",i);
1694 /* first user in is given ops */
1695 user->chans[i].uc_modes = UCMODE_OP;
1699 user->chans[i].uc_modes = 0;
1701 user->chans[i].channel = Ptr;
1702 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1704 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1706 // use the stamdard J token with no privilages.
1707 char buffer[MAXBUF];
1708 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1709 NetSendToAll(buffer);
1712 log(DEBUG,"Sent JOIN to client");
1716 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1717 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1720 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1721 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1722 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1723 FOREACH_MOD OnUserJoin(user,Ptr);
1727 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1728 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1732 /* remove a channel from a users record, and remove the record from memory
1733 * if the channel has become empty */
1735 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1737 if ((!user) || (!cname))
1739 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1746 if ((!cname) || (!user))
1751 Ptr = FindChan(cname);
1758 FOREACH_MOD OnUserPart(user,Ptr);
1759 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1761 for (int i =0; i != MAXCHANS; i++)
1763 /* zap it from the channel list of the user */
1764 if (user->chans[i].channel == Ptr)
1768 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1772 char buffer[MAXBUF];
1773 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1774 NetSendToAll(buffer);
1783 char buffer[MAXBUF];
1784 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1785 NetSendToAll(buffer);
1788 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1790 user->chans[i].uc_modes = 0;
1791 user->chans[i].channel = NULL;
1792 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1797 /* if there are no users left on the channel */
1798 if (!usercount(Ptr))
1800 chan_hash::iterator iter = chanlist.find(Ptr->name);
1802 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1804 /* kill the record */
1805 if (iter != chanlist.end())
1807 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1808 delete iter->second;
1809 chanlist.erase(iter);
1815 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1817 if ((!src) || (!user) || (!Ptr) || (!reason))
1819 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1826 if ((!Ptr) || (!user) || (!src))
1831 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1833 if (!has_channel(user,Ptr))
1835 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1838 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1840 if (cstatus(src,Ptr) == STATUS_HOP)
1842 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1846 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1852 for (int i =0; i != MAXCHANS; i++)
1854 /* zap it from the channel list of the user */
1855 if (user->chans[i].channel)
1856 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1858 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1859 user->chans[i].uc_modes = 0;
1860 user->chans[i].channel = NULL;
1861 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1866 /* if there are no users left on the channel */
1867 if (!usercount(Ptr))
1869 chan_hash::iterator iter = chanlist.find(Ptr->name);
1871 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1873 /* kill the record */
1874 if (iter != chanlist.end())
1876 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1877 delete iter->second;
1878 chanlist.erase(iter);
1884 /* returns 1 if user u has channel c in their record, 0 if not */
1886 int has_channel(userrec *u, chanrec *c)
1890 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1893 for (int i =0; i != MAXCHANS; i++)
1895 if (u->chans[i].channel == c)
1903 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1908 if ((!user) || (!dest) || (!chan))
1910 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1913 if (status < STATUS_OP)
1915 log(DEBUG,"%s cant give ops to %s because they nave status %d and needs %d",user->nick,dest,status,STATUS_OP);
1916 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1923 log(DEFAULT,"the target nickname given to give_ops was invalid");
1924 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1930 log(DEFAULT,"the target nickname given to give_ops couldnt be found");
1931 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1936 for (int i = 0; i != MAXCHANS; i++)
1938 if ((d->chans[i].channel != NULL) && (chan != NULL))
1939 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1941 if (d->chans[i].uc_modes & UCMODE_OP)
1943 /* mode already set on user, dont allow multiple */
1944 log(DEFAULT,"The target user given to give_ops was already opped on the channel");
1947 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1948 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1952 log(DEFAULT,"The target channel given to give_ops was not in the users mode list");
1958 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1963 if ((!user) || (!dest) || (!chan))
1965 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1968 if (status != STATUS_OP)
1970 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1978 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1983 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1988 for (int i = 0; i != MAXCHANS; i++)
1990 if ((d->chans[i].channel != NULL) && (chan != NULL))
1991 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1993 if (d->chans[i].uc_modes & UCMODE_HOP)
1995 /* mode already set on user, dont allow multiple */
1998 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1999 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
2008 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
2013 if ((!user) || (!dest) || (!chan))
2015 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
2018 if (status < STATUS_HOP)
2020 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2028 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2033 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2038 for (int i = 0; i != MAXCHANS; i++)
2040 if ((d->chans[i].channel != NULL) && (chan != NULL))
2041 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2043 if (d->chans[i].uc_modes & UCMODE_VOICE)
2045 /* mode already set on user, dont allow multiple */
2048 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
2049 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
2058 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
2063 if ((!user) || (!dest) || (!chan))
2065 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
2068 if (status < STATUS_OP)
2070 log(DEBUG,"%s cant give ops to %s because they have status %d and needs %d",user->nick,dest,status,STATUS_OP);
2071 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2079 log(DEBUG,"take_ops was given an invalid target nickname of %s",dest);
2080 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2085 log(DEBUG,"take_ops couldnt resolve the target nickname: %s",dest);
2086 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2091 for (int i = 0; i != MAXCHANS; i++)
2093 if ((d->chans[i].channel != NULL) && (chan != NULL))
2094 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2096 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
2098 /* mode already set on user, dont allow multiple */
2101 d->chans[i].uc_modes ^= UCMODE_OP;
2102 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
2106 log(DEBUG,"take_ops couldnt locate the target channel in the target users list");
2112 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
2117 if ((!user) || (!dest) || (!chan))
2119 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
2122 if (status != STATUS_OP)
2124 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2132 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2137 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2142 for (int i = 0; i != MAXCHANS; i++)
2144 if ((d->chans[i].channel != NULL) && (chan != NULL))
2145 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2147 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
2149 /* mode already set on user, dont allow multiple */
2152 d->chans[i].uc_modes ^= UCMODE_HOP;
2153 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
2162 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
2167 if ((!user) || (!dest) || (!chan))
2169 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
2172 if (status < STATUS_HOP)
2174 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2182 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2187 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2192 for (int i = 0; i != MAXCHANS; i++)
2194 if ((d->chans[i].channel != NULL) && (chan != NULL))
2195 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2197 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
2199 /* mode already set on user, dont allow multiple */
2202 d->chans[i].uc_modes ^= UCMODE_VOICE;
2203 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
2212 void TidyBan(char *ban)
2215 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
2219 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
2223 char* pos_of_pling = strchr(temp,'!');
2224 char* pos_of_at = strchr(temp,'@');
2226 pos_of_pling[0] = '\0';
2227 pos_of_at[0] = '\0';
2231 strncpy(NICK,temp,NICKMAX);
2232 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
2233 strncpy(HOST,pos_of_at,160);
2235 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
2238 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
2240 if ((!user) || (!dest) || (!chan)) {
2241 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
2246 if ((!user) || (!dest) || (!chan))
2248 if (strchr(dest,'!')==0)
2250 if (strchr(dest,'@')==0)
2252 for (int i = 0; i < strlen(dest); i++)
2255 for (int i = 0; i < strlen(dest); i++)
2259 for (int i = 0; i < strlen(dest); i++)
2265 for (int i = 0; i < strlen(dest); i++)
2270 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2273 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2275 if (!strcasecmp(i->data,dest))
2277 // dont allow a user to set the same ban twice
2282 b.set_time = time(NULL);
2283 strncpy(b.data,dest,MAXBUF);
2284 strncpy(b.set_by,user->nick,NICKMAX);
2285 chan->bans.push_back(b);
2289 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2291 if ((!user) || (!dest) || (!chan)) {
2292 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2296 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2297 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2299 if (!strcasecmp(i->data,dest))
2301 chan->bans.erase(i);
2308 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode, bool silent, bool local)
2311 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2315 char modelist[MAXBUF];
2316 char outlist[MAXBUF];
2317 char outstr[MAXBUF];
2318 char outpars[32][MAXBUF];
2324 bool k_set = false, l_set = false;
2331 log(DEBUG,"process_modes: start: parameters=%d",pcnt);
2333 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2334 /* parameters[2] onwards are parameters for
2335 * modes that require them :) */
2336 strcpy(outlist,"+");
2339 log(DEBUG,"process_modes: modelist: %s",modelist);
2341 for (ptr = 0; ptr < strlen(modelist); ptr++)
2346 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2347 char modechar = modelist[ptr];
2348 switch (modelist[ptr])
2353 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2355 outlist[strlen(outlist)-1] = '-';
2359 strcat(outlist,"-");
2369 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2371 outlist[strlen(outlist)-1] = '+';
2375 strcat(outlist,"+");
2383 if ((param >= pcnt)) break;
2384 log(DEBUG,"Enough parameters left");
2387 log(DEBUG,"calling give_ops");
2388 r = give_ops(user,parameters[param++],chan,status);
2392 log(DEBUG,"calling take_ops");
2393 r = take_ops(user,parameters[param++],chan,status);
2397 strcat(outlist,"o");
2398 strcpy(outpars[pc++],parameters[param-1]);
2403 if ((param >= pcnt)) break;
2406 r = give_hops(user,parameters[param++],chan,status);
2410 r = take_hops(user,parameters[param++],chan,status);
2414 strcat(outlist,"h");
2415 strcpy(outpars[pc++],parameters[param-1]);
2421 if ((param >= pcnt)) break;
2424 r = give_voice(user,parameters[param++],chan,status);
2428 r = take_voice(user,parameters[param++],chan,status);
2432 strcat(outlist,"v");
2433 strcpy(outpars[pc++],parameters[param-1]);
2438 if ((param >= pcnt)) break;
2441 r = add_ban(user,parameters[param++],chan,status);
2445 r = take_ban(user,parameters[param++],chan,status);
2449 strcat(outlist,"b");
2450 strcpy(outpars[pc++],parameters[param-1]);
2456 if ((param >= pcnt))
2464 if (!strcmp(chan->key,""))
2466 strcat(outlist,"k");
2468 strcpy(key,parameters[param++]);
2469 if (strlen(key)>32) {
2472 strcpy(outpars[pc++],key);
2473 strcpy(chan->key,key);
2479 /* checks on -k are case sensitive and only accurate to the
2480 first 32 characters */
2482 strcpy(key,parameters[param++]);
2483 if (strlen(key)>32) {
2486 /* only allow -k if correct key given */
2487 if (!strcmp(chan->key,key))
2489 strcat(outlist,"k");
2490 strcpy(chan->key,"");
2491 strcpy(outpars[pc++],key);
2501 strcat(outlist,"l");
2506 if ((param >= pcnt)) break;
2512 bool invalid = false;
2513 for (int i = 0; i < strlen(parameters[param]); i++)
2515 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2520 if (atoi(parameters[param]) < 1)
2528 chan->limit = atoi(parameters[param]);
2531 strcat(outlist,"l");
2532 strcpy(outpars[pc++],parameters[param++]);
2539 if (chan->inviteonly != mdir)
2541 strcat(outlist,"i");
2543 chan->inviteonly = mdir;
2547 if (chan->topiclock != mdir)
2549 strcat(outlist,"t");
2551 chan->topiclock = mdir;
2555 if (chan->noexternal != mdir)
2557 strcat(outlist,"n");
2559 chan->noexternal = mdir;
2563 if (chan->moderated != mdir)
2565 strcat(outlist,"m");
2567 chan->moderated = mdir;
2571 if (chan->secret != mdir)
2573 strcat(outlist,"s");
2574 if (chan->c_private)
2576 chan->c_private = 0;
2579 strcat(outlist,"-p+");
2583 strcat(outlist,"+p-");
2587 chan->secret = mdir;
2591 if (chan->c_private != mdir)
2593 strcat(outlist,"p");
2599 strcat(outlist,"-s+");
2603 strcat(outlist,"+s-");
2607 chan->c_private = mdir;
2611 log(DEBUG,"Preprocessing custom mode %c",modechar);
2614 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2616 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2619 if (ModeDefined(modechar,MT_CHANNEL))
2621 log(DEBUG,"A module has claimed this mode");
2624 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2626 p.push_back(parameters[param]);
2628 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2630 p.push_back(parameters[param]);
2633 bool handled = false;
2636 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2637 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2638 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2644 for (int i = 0; i <= MODCOUNT; i++)
2648 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2650 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2651 char app[] = {modechar, 0};
2654 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2656 strcat(outlist, app);
2658 else if (!strchr(outlist,modechar))
2660 strcat(outlist, app);
2663 chan->SetCustomMode(modechar,mdir);
2664 // include parameters in output if mode has them
2665 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2667 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2668 strcpy(outpars[pc++],parameters[param++]);
2670 // break, because only one module can handle the mode.
2682 /* this ensures only the *valid* modes are sent out onto the network */
2683 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2685 outlist[strlen(outlist)-1] = '\0';
2687 if (strcmp(outlist,""))
2689 strcpy(outstr,outlist);
2690 for (ptr = 0; ptr < pc; ptr++)
2693 strcat(outstr,outpars[ptr]);
2697 log(DEBUG,"Local mode change");
2698 WriteChannelLocal(chan, user, "MODE %s %s",chan->name,outstr);
2706 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2707 // M token for a usermode must go to all servers
2708 char buffer[MAXBUF];
2709 snprintf(buffer,MAXBUF,"M %s %s",chan->name, outstr);
2710 NetSendToAll(buffer);
2718 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2719 // M token for a usermode must go to all servers
2720 char buffer[MAXBUF];
2721 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick,chan->name, outstr);
2722 NetSendToAll(buffer);
2729 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2731 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2733 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2734 // RFC1459 specified modes
2735 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2737 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2741 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2742 if ((strchr(sourcemodes,'o')) && (!adding))
2744 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2747 else if (umode == 'o')
2749 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2753 // process any module-defined modes that need oper
2754 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2756 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2760 if (ModeDefined(umode,MT_CLIENT))
2762 // process any module-defined modes that don't need oper
2763 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2764 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2766 // no, this mode needs oper, and this user 'aint got what it takes!
2772 // anything else - return false.
2773 log(DEBUG,"umode %c not known by any ruleset",umode);
2777 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2784 strncpy(s2->nick,ServerName,NICKMAX);
2785 strcpy(s2->modes,"o");
2792 if (ModeDefined(umode,MT_CLIENT))
2794 for (int i = 0; i <= MODCOUNT; i++)
2796 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2798 log(DEBUG,"Module claims umode %c",umode);
2802 log(DEBUG,"No module claims umode %c",umode);
2812 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2822 void handle_mode(char **parameters, int pcnt, userrec *user)
2828 char outpars[MAXBUF];
2830 dest = Find(parameters[0]);
2837 if ((dest) && (pcnt == 1))
2839 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2843 if ((dest) && (pcnt > 1))
2845 char dmodes[MAXBUF];
2846 strncpy(dmodes,dest->modes,MAXBUF);
2847 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2852 if (strchr(user->modes,'o'))
2863 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2867 strcpy(outpars,"+");
2870 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2873 for (int i = 0; i < strlen(parameters[1]); i++)
2875 if (parameters[1][i] == '+')
2879 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2881 outpars[strlen(outpars)-1] = '+';
2885 strcat(outpars,"+");
2891 if (parameters[1][i] == '-')
2895 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2897 outpars[strlen(outpars)-1] = '-';
2901 strcat(outpars,"-");
2909 if (strchr(user->modes,'o'))
2915 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2924 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2926 char umode = parameters[1][i];
2927 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2929 dmodes[strlen(dmodes)+1]='\0';
2930 dmodes[strlen(dmodes)] = parameters[1][i];
2931 outpars[strlen(outpars)+1]='\0';
2932 outpars[strlen(outpars)] = parameters[1][i];
2938 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2940 char umode = parameters[1][i];
2941 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2947 outpars[strlen(outpars)+1]='\0';
2948 outpars[strlen(outpars)] = parameters[1][i];
2951 for (q = 0; q < strlen(dmodes); q++)
2953 if (dmodes[q] != parameters[1][i])
2960 strcpy(dmodes,temp);
2967 if (strlen(outpars))
2973 while (i < strlen (outpars))
2975 b[z++] = outpars[i++];
2977 if (i<strlen(outpars)-1)
2979 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2981 // someones playing silly buggers and trying
2982 // to put a +- or -+ into the line...
2986 if (i == strlen(outpars)-1)
2988 if ((outpars[i] == '-') || (outpars[i] == '+'))
2996 if ((b[z] == '-') || (b[z] == '+'))
2999 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3002 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3004 // M token for a usermode must go to all servers
3005 char buffer[MAXBUF];
3006 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3007 NetSendToAll(buffer);
3009 if (strlen(dmodes)>MAXMODES)
3011 dmodes[MAXMODES-1] = '\0';
3013 log(DEBUG,"Stripped mode line");
3014 log(DEBUG,"Line dest is now %s",dmodes);
3015 strncpy(dest->modes,dmodes,MAXMODES);
3022 Ptr = FindChan(parameters[0]);
3027 /* just /modes #channel */
3028 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
3029 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
3035 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
3038 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
3040 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
3042 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
3047 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3049 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
3053 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,false);
3057 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3064 void server_mode(char **parameters, int pcnt, userrec *user)
3070 char outpars[MAXBUF];
3072 dest = Find(parameters[0]);
3074 // fix: ChroNiCk found this - we cant use this as debug if its null!
3077 log(DEBUG,"server_mode on %s",dest->nick);
3080 if ((dest) && (pcnt > 1))
3082 log(DEBUG,"params > 1");
3084 char dmodes[MAXBUF];
3085 strncpy(dmodes,dest->modes,MAXBUF);
3087 strcpy(outpars,"+");
3090 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3093 for (int i = 0; i < strlen(parameters[1]); i++)
3095 if (parameters[1][i] == '+')
3099 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3101 outpars[strlen(outpars)-1] = '+';
3105 strcat(outpars,"+");
3111 if (parameters[1][i] == '-')
3115 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3117 outpars[strlen(outpars)-1] = '-';
3121 strcat(outpars,"-");
3128 log(DEBUG,"begin mode processing entry");
3134 log(DEBUG,"umode %c being added",parameters[1][i]);
3135 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3137 char umode = parameters[1][i];
3138 log(DEBUG,"umode %c is an allowed umode",umode);
3139 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3141 dmodes[strlen(dmodes)+1]='\0';
3142 dmodes[strlen(dmodes)] = parameters[1][i];
3143 outpars[strlen(outpars)+1]='\0';
3144 outpars[strlen(outpars)] = parameters[1][i];
3150 // can only remove a mode they already have
3151 log(DEBUG,"umode %c being removed",parameters[1][i]);
3152 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3154 char umode = parameters[1][i];
3155 log(DEBUG,"umode %c is an allowed umode",umode);
3156 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3162 outpars[strlen(outpars)+1]='\0';
3163 outpars[strlen(outpars)] = parameters[1][i];
3166 for (q = 0; q < strlen(dmodes); q++)
3168 if (dmodes[q] != parameters[1][i])
3175 strcpy(dmodes,temp);
3182 if (strlen(outpars))
3188 while (i < strlen (outpars))
3190 b[z++] = outpars[i++];
3192 if (i<strlen(outpars)-1)
3194 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3196 // someones playing silly buggers and trying
3197 // to put a +- or -+ into the line...
3201 if (i == strlen(outpars)-1)
3203 if ((outpars[i] == '-') || (outpars[i] == '+'))
3211 if ((b[z] == '-') || (b[z] == '+'))
3214 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3217 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3219 // M token for a usermode must go to all servers
3220 char buffer[MAXBUF];
3221 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3222 NetSendToAll(buffer);
3224 if (strlen(dmodes)>MAXMODES)
3226 dmodes[MAXMODES-1] = '\0';
3228 log(DEBUG,"Stripped mode line");
3229 log(DEBUG,"Line dest is now %s",dmodes);
3230 strncpy(dest->modes,dmodes,MAXMODES);
3237 Ptr = FindChan(parameters[0]);
3240 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true,false,false);
3244 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3250 void merge_mode(char **parameters, int pcnt)
3256 char outpars[MAXBUF];
3258 dest = Find(parameters[0]);
3260 // fix: ChroNiCk found this - we cant use this as debug if its null!
3263 log(DEBUG,"merge_mode on %s",dest->nick);
3266 if ((dest) && (pcnt > 1))
3268 log(DEBUG,"params > 1");
3270 char dmodes[MAXBUF];
3271 strncpy(dmodes,dest->modes,MAXBUF);
3273 strcpy(outpars,"+");
3276 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3279 for (int i = 0; i < strlen(parameters[1]); i++)
3281 if (parameters[1][i] == '+')
3285 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3287 outpars[strlen(outpars)-1] = '+';
3291 strcat(outpars,"+");
3297 if (parameters[1][i] == '-')
3301 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3303 outpars[strlen(outpars)-1] = '-';
3307 strcat(outpars,"-");
3314 log(DEBUG,"begin mode processing entry");
3320 log(DEBUG,"umode %c being added",parameters[1][i]);
3321 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],"o",true)))
3323 char umode = parameters[1][i];
3324 log(DEBUG,"umode %c is an allowed umode",umode);
3325 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3327 dmodes[strlen(dmodes)+1]='\0';
3328 dmodes[strlen(dmodes)] = parameters[1][i];
3329 outpars[strlen(outpars)+1]='\0';
3330 outpars[strlen(outpars)] = parameters[1][i];
3336 // can only remove a mode they already have
3337 log(DEBUG,"umode %c being removed",parameters[1][i]);
3338 if ((allowed_umode(parameters[1][i],"o",false)) && (strchr(dmodes,parameters[1][i])))
3340 char umode = parameters[1][i];
3341 log(DEBUG,"umode %c is an allowed umode",umode);
3342 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3348 outpars[strlen(outpars)+1]='\0';
3349 outpars[strlen(outpars)] = parameters[1][i];
3352 for (q = 0; q < strlen(dmodes); q++)
3354 if (dmodes[q] != parameters[1][i])
3361 strcpy(dmodes,temp);
3368 if (strlen(outpars))
3374 while (i < strlen (outpars))
3376 b[z++] = outpars[i++];
3378 if (i<strlen(outpars)-1)
3380 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3382 // someones playing silly buggers and trying
3383 // to put a +- or -+ into the line...
3387 if (i == strlen(outpars)-1)
3389 if ((outpars[i] == '-') || (outpars[i] == '+'))
3397 if ((b[z] == '-') || (b[z] == '+'))
3400 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3403 if (strlen(dmodes)>MAXMODES)
3405 dmodes[MAXMODES-1] = '\0';
3407 log(DEBUG,"Stripped mode line");
3408 log(DEBUG,"Line dest is now %s",dmodes);
3409 strncpy(dest->modes,dmodes,MAXMODES);
3416 Ptr = FindChan(parameters[0]);
3420 strncpy(s2.nick,ServerName,NICKMAX);
3421 strcpy(s2.modes,"o");
3423 process_modes(parameters,&s2,Ptr,STATUS_OP,pcnt,true,true,false);
3428 void merge_mode2(char **parameters, int pcnt, userrec* user)
3434 char outpars[MAXBUF];
3436 dest = Find(parameters[0]);
3438 // fix: ChroNiCk found this - we cant use this as debug if its null!
3441 log(DEBUG,"merge_mode on %s",dest->nick);
3444 if ((dest) && (pcnt > 1))
3446 log(DEBUG,"params > 1");
3448 char dmodes[MAXBUF];
3449 strncpy(dmodes,dest->modes,MAXBUF);
3451 strcpy(outpars,"+");
3454 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3457 for (int i = 0; i < strlen(parameters[1]); i++)
3459 if (parameters[1][i] == '+')
3463 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3465 outpars[strlen(outpars)-1] = '+';
3469 strcat(outpars,"+");
3475 if (parameters[1][i] == '-')
3479 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3481 outpars[strlen(outpars)-1] = '-';
3485 strcat(outpars,"-");
3492 log(DEBUG,"begin mode processing entry");
3498 log(DEBUG,"umode %c being added",parameters[1][i]);
3499 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3501 char umode = parameters[1][i];
3502 log(DEBUG,"umode %c is an allowed umode",umode);
3503 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3505 dmodes[strlen(dmodes)+1]='\0';
3506 dmodes[strlen(dmodes)] = parameters[1][i];
3507 outpars[strlen(outpars)+1]='\0';
3508 outpars[strlen(outpars)] = parameters[1][i];
3514 // can only remove a mode they already have
3515 log(DEBUG,"umode %c being removed",parameters[1][i]);
3516 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3518 char umode = parameters[1][i];
3519 log(DEBUG,"umode %c is an allowed umode",umode);
3520 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3526 outpars[strlen(outpars)+1]='\0';
3527 outpars[strlen(outpars)] = parameters[1][i];
3530 for (q = 0; q < strlen(dmodes); q++)
3532 if (dmodes[q] != parameters[1][i])
3539 strcpy(dmodes,temp);
3546 if (strlen(outpars))
3552 while (i < strlen (outpars))
3554 b[z++] = outpars[i++];
3556 if (i<strlen(outpars)-1)
3558 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3560 // someones playing silly buggers and trying
3561 // to put a +- or -+ into the line...
3565 if (i == strlen(outpars)-1)
3567 if ((outpars[i] == '-') || (outpars[i] == '+'))
3575 if ((b[z] == '-') || (b[z] == '+'))
3578 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3581 WriteTo(user,dest,"MODE :%s",b);
3583 if (strlen(dmodes)>MAXMODES)
3585 dmodes[MAXMODES-1] = '\0';
3587 log(DEBUG,"Stripped mode line");
3588 log(DEBUG,"Line dest is now %s",dmodes);
3589 strncpy(dest->modes,dmodes,MAXMODES);
3596 Ptr = FindChan(parameters[0]);
3599 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3604 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,true);
3610 /* This function pokes and hacks at a parameter list like the following:
3612 * PART #winbot, #darkgalaxy :m00!
3614 * to turn it into a series of individual calls like this:
3616 * PART #winbot :m00!
3617 * PART #darkgalaxy :m00!
3619 * The seperate calls are sent to a callback function provided by the caller
3620 * (the caller will usually call itself recursively). The callback function
3621 * must be a command handler. Calling this function on a line with no list causes
3622 * no action to be taken. You must provide a starting and ending parameter number
3623 * where the range of the list can be found, useful if you have a terminating
3624 * parameter as above which is actually not part of the list, or parameters
3625 * before the actual list as well. This code is used by many functions which
3626 * can function as "one to list" (see the RFC) */
3628 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
3633 char blog[32][MAXBUF];
3634 char blog2[32][MAXBUF];
3635 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
3636 char keystr[MAXBUF];
3639 for (int i = 0; i <32; i++)
3642 for (int i = 0; i <32; i++)
3643 strcpy(blog2[i],"");
3646 for (int i = 0; i <10; i++)
3650 parameters[i] = moo;
3655 if (pcnt > 1) /* we have a key to copy */
3657 strcpy(keystr,parameters[1]);
3661 if (!parameters[start])
3665 if (!strchr(parameters[start],','))
3670 for (int i = start; i <= end; i++)
3674 strcat(plist,parameters[i]);
3682 for (int i = 0; i < t; i++)
3684 if (plist[i] == ',')
3687 strcpy(blog[j++],param);
3691 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3696 strcpy(blog[j++],param);
3699 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3704 if ((joins) && (keystr))
3706 if (strchr(keystr,','))
3710 t2 = strlen(keystr);
3711 for (int i = 0; i < t2; i++)
3713 if (keystr[i] == ',')
3716 strcpy(blog2[j++],param);
3720 strcpy(blog2[j++],param);
3725 for (j = 0; j < total; j++)
3731 for (q = end; q < pcnt-1; q++)
3733 if (parameters[q+1])
3735 pars[q-end+1] = parameters[q+1];
3738 if ((joins) && (parameters[1]))
3749 /* repeatedly call the function with the hacked parameter list */
3750 if ((joins) && (pcnt > 1))
3754 // pars[1] already set up and containing key from blog2[j]
3759 pars[1] = parameters[1];
3765 fn(pars,pcnt-(end-start),u);
3773 void handle_join(char **parameters, int pcnt, userrec *user)
3778 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3780 if (parameters[0][0] == '#')
3782 Ptr = add_channel(user,parameters[0],parameters[1],false);
3787 void handle_part(char **parameters, int pcnt, userrec *user)
3793 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3795 del_channel(user,parameters[0],parameters[1],false);
3799 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3801 del_channel(user,parameters[0],NULL,false);
3805 void handle_kick(char **parameters, int pcnt, userrec *user)
3807 chanrec* Ptr = FindChan(parameters[0]);
3808 userrec* u = Find(parameters[1]);
3812 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3816 if (!has_channel(u,Ptr))
3818 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3822 char reason[MAXBUF];
3826 strncpy(reason,parameters[2],MAXBUF);
3827 if (strlen(reason)>MAXKICK)
3829 reason[MAXKICK-1] = '\0';
3832 kick_channel(user,u,Ptr,reason);
3836 strcpy(reason,user->nick);
3837 kick_channel(user,u,Ptr,reason);
3840 // this must be propogated so that channel membership is kept in step network-wide
3842 char buffer[MAXBUF];
3843 snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
3844 NetSendToAll(buffer);
3848 void handle_die(char **parameters, int pcnt, userrec *user)
3850 log(DEBUG,"die: %s",user->nick);
3851 if (!strcmp(parameters[0],diepass))
3853 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3859 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3863 void handle_restart(char **parameters, int pcnt, userrec *user)
3865 log(DEBUG,"restart: %s",user->nick);
3866 if (!strcmp(parameters[0],restartpass))
3868 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3871 /* Will finish this later when i can be arsed :) */
3875 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3880 void kill_link(userrec *user,const char* r)
3882 user_hash::iterator iter = clientlist.find(user->nick);
3884 char reason[MAXBUF];
3886 strncpy(reason,r,MAXBUF);
3888 if (strlen(reason)>MAXQUIT)
3890 reason[MAXQUIT-1] = '\0';
3893 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3894 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3895 log(DEBUG,"closing fd %d",user->fd);
3897 /* bugfix, cant close() a nonblocking socket (sux!) */
3898 if (user->registered == 7) {
3899 FOREACH_MOD OnUserQuit(user);
3900 WriteCommonExcept(user,"QUIT :%s",reason);
3902 // Q token must go to ALL servers!!!
3903 char buffer[MAXBUF];
3904 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
3905 NetSendToAll(buffer);
3908 /* push the socket on a stack of sockets due to be closed at the next opportunity
3909 * 'Client exited' is an exception to this as it means the client side has already
3910 * closed the socket, we don't need to do it.
3912 fd_reap.push_back(user->fd);
3914 bool do_purge = false;
3916 if (user->registered == 7) {
3917 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3921 if (iter != clientlist.end())
3923 log(DEBUG,"deleting user hash value %d",iter->second);
3924 if ((iter->second) && (user->registered == 7)) {
3925 delete iter->second;
3927 clientlist.erase(iter);
3930 if (user->registered == 7) {
3931 purge_empty_chans();
3936 void handle_kill(char **parameters, int pcnt, userrec *user)
3938 userrec *u = Find(parameters[0]);
3939 char killreason[MAXBUF];
3941 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3944 if (strcmp(ServerName,u->server))
3947 WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3948 sprintf(killreason,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
3949 WriteCommonExcept(u,"QUIT :%s",killreason);
3950 // K token must go to ALL servers!!!
3951 char buffer[MAXBUF];
3952 snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
3953 NetSendToAll(buffer);
3955 user_hash::iterator iter = clientlist.find(u->nick);
3956 if (iter != clientlist.end())
3958 log(DEBUG,"deleting user hash value %d",iter->second);
3959 if ((iter->second) && (user->registered == 7)) {
3960 delete iter->second;
3962 clientlist.erase(iter);
3964 purge_empty_chans();
3969 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3970 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3971 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3972 kill_link(u,killreason);
3977 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3981 void handle_summon(char **parameters, int pcnt, userrec *user)
3983 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3986 void handle_users(char **parameters, int pcnt, userrec *user)
3988 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3992 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3994 char* Passwd(userrec *user)
3996 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3998 if (match(user->host,i->host) && (i->type == CC_ALLOW))
4006 bool IsDenied(userrec *user)
4008 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4010 if (match(user->host,i->host) && (i->type == CC_DENY))
4020 void handle_pass(char **parameters, int pcnt, userrec *user)
4022 // Check to make sure they havnt registered -- Fix by FCS
4023 if (user->registered == 7)
4025 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4028 if (!strcasecmp(parameters[0],Passwd(user)))
4030 user->haspassed = true;
4034 void handle_invite(char **parameters, int pcnt, userrec *user)
4036 userrec* u = Find(parameters[0]);
4037 chanrec* c = FindChan(parameters[1]);
4043 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
4049 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
4058 if (cstatus(user,c) < STATUS_HOP)
4060 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
4064 if (has_channel(u,c))
4066 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
4069 if (!has_channel(user,c))
4071 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
4074 u->InviteTo(c->name);
4075 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
4076 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
4078 // i token must go to ALL servers!!!
4079 char buffer[MAXBUF];
4080 snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
4081 NetSendToAll(buffer);
4084 void handle_topic(char **parameters, int pcnt, userrec *user)
4090 if (strlen(parameters[0]) <= CHANMAX)
4092 Ptr = FindChan(parameters[0]);
4097 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
4098 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
4102 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
4107 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4114 if (strlen(parameters[0]) <= CHANMAX)
4116 Ptr = FindChan(parameters[0]);
4119 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
4121 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
4126 strncpy(topic,parameters[1],MAXBUF);
4127 if (strlen(topic)>MAXTOPIC)
4129 topic[MAXTOPIC-1] = '\0';
4132 strcpy(Ptr->topic,topic);
4133 strcpy(Ptr->setby,user->nick);
4134 Ptr->topicset = time(NULL);
4135 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
4137 // t token must go to ALL servers!!!
4138 char buffer[MAXBUF];
4139 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
4140 NetSendToAll(buffer);
4144 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4150 /* sends out an error notice to all connected clients (not to be used
4153 void send_error(char *s)
4155 log(DEBUG,"send_error: %s",s);
4156 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4158 if (isnick(i->second->nick))
4160 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
4164 // fix - unregistered connections receive ERROR, not NOTICE
4165 Write(i->second->fd,"ERROR :%s",s);
4170 void Error(int status)
4172 signal (SIGALRM, SIG_IGN);
4173 signal (SIGPIPE, SIG_IGN);
4174 signal (SIGTERM, SIG_IGN);
4175 signal (SIGABRT, SIG_IGN);
4176 signal (SIGSEGV, SIG_IGN);
4177 signal (SIGURG, SIG_IGN);
4178 signal (SIGKILL, SIG_IGN);
4179 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
4180 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
4185 int main (int argc, char *argv[])
4188 log(DEBUG,"*** InspIRCd starting up!");
4189 if (!FileExists(CONFIG_FILE))
4191 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
4192 log(DEBUG,"main: no config");
4193 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
4197 if (!strcmp(argv[1],"-nofork")) {
4201 if (InspIRCd() == ERROR)
4203 log(DEBUG,"main: daemon function bailed");
4204 printf("ERROR: could not initialise. Shutting down.\n");
4211 template<typename T> inline string ConvToStr(const T &in)
4214 if (!(tmp << in)) return string();
4218 /* re-allocates a nick in the user_hash after they change nicknames,
4219 * returns a pointer to the new user as it may have moved */
4221 userrec* ReHashNick(char* Old, char* New)
4223 user_hash::iterator newnick;
4224 user_hash::iterator oldnick = clientlist.find(Old);
4226 log(DEBUG,"ReHashNick: %s %s",Old,New);
4228 if (!strcasecmp(Old,New))
4230 log(DEBUG,"old nick is new nick, skipping");
4231 return oldnick->second;
4234 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
4236 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
4238 clientlist[New] = new userrec();
4239 clientlist[New] = oldnick->second;
4240 /*delete oldnick->second; */
4241 clientlist.erase(oldnick);
4243 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
4245 return clientlist[New];
4248 /* adds or updates an entry in the whowas list */
4249 void AddWhoWas(userrec* u)
4251 user_hash::iterator iter = whowas.find(u->nick);
4252 userrec *a = new userrec();
4253 strcpy(a->nick,u->nick);
4254 strcpy(a->ident,u->ident);
4255 strcpy(a->dhost,u->dhost);
4256 strcpy(a->host,u->host);
4257 strcpy(a->fullname,u->fullname);
4258 strcpy(a->server,u->server);
4259 a->signon = u->signon;
4261 /* MAX_WHOWAS: max number of /WHOWAS items
4262 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
4263 * can be replaced by a newer one
4266 if (iter == whowas.end())
4268 if (whowas.size() == WHOWAS_MAX)
4270 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
4272 // 3600 seconds in an hour ;)
4273 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
4277 log(DEBUG,"added WHOWAS entry, purged an old record");
4284 log(DEBUG,"added fresh WHOWAS entry");
4285 whowas[a->nick] = a;
4290 log(DEBUG,"updated WHOWAS entry");
4291 delete iter->second;
4297 /* add a client connection to the sockets list */
4298 void AddClient(int socket, char* host, int port, bool iscached)
4302 char resolved[MAXBUF];
4305 user_hash::iterator iter;
4307 tempnick = ConvToStr(socket) + "-unknown";
4308 sprintf(tn2,"%d-unknown",socket);
4310 iter = clientlist.find(tempnick);
4312 if (iter != clientlist.end()) return;
4315 * It is OK to access the value here this way since we know
4316 * it exists, we just created it above.
4318 * At NO other time should you access a value in a map or a
4319 * hash_map this way.
4321 clientlist[tempnick] = new userrec();
4323 NonBlocking(socket);
4324 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
4326 clientlist[tempnick]->fd = socket;
4327 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
4328 strncpy(clientlist[tempnick]->host, host,160);
4329 strncpy(clientlist[tempnick]->dhost, host,160);
4330 strncpy(clientlist[tempnick]->server, ServerName,256);
4331 strncpy(clientlist[tempnick]->ident, "unknown",9);
4332 clientlist[tempnick]->registered = 0;
4333 clientlist[tempnick]->signon = time(NULL);
4334 clientlist[tempnick]->nping = time(NULL)+240;
4335 clientlist[tempnick]->lastping = 1;
4336 clientlist[tempnick]->port = port;
4340 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
4344 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
4347 // set the registration timeout for this user
4348 unsigned long class_regtimeout = 90;
4349 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4351 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4353 class_regtimeout = (unsigned long)i->registration_timeout;
4358 int class_flood = 0;
4359 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4361 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4363 class_flood = i->flood;
4368 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
4369 clientlist[tempnick]->flood = class_flood;
4371 for (int i = 0; i < MAXCHANS; i++)
4373 clientlist[tempnick]->chans[i].channel = NULL;
4374 clientlist[tempnick]->chans[i].uc_modes = 0;
4377 if (clientlist.size() == MAXCLIENTS)
4378 kill_link(clientlist[tempnick],"No more connections allowed in this class");
4381 void handle_names(char **parameters, int pcnt, userrec *user)
4385 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
4387 c = FindChan(parameters[0]);
4390 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
4392 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
4396 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4400 void handle_privmsg(char **parameters, int pcnt, userrec *user)
4405 user->idle_lastmsg = time(NULL);
4407 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
4409 if (parameters[0][0] == '#')
4411 chan = FindChan(parameters[0]);
4414 if ((chan->noexternal) && (!has_channel(user,chan)))
4416 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4419 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4421 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4427 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4432 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
4434 // if any users of this channel are on remote servers, broadcast the packet
4435 char buffer[MAXBUF];
4436 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
4437 NetSendToCommon(user,chan,buffer);
4441 /* no such nick/channel */
4442 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4447 dest = Find(parameters[0]);
4450 if (strcmp(dest->awaymsg,""))
4452 /* auto respond with aweh msg */
4453 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
4458 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
4465 if (!strcmp(dest->server,user->server))
4467 // direct write, same server
4468 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
4472 char buffer[MAXBUF];
4473 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
4474 NetSendToOne(dest->server,buffer);
4479 /* no such nick/channel */
4480 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4484 void handle_notice(char **parameters, int pcnt, userrec *user)
4489 user->idle_lastmsg = time(NULL);
4491 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
4493 if (parameters[0][0] == '#')
4495 chan = FindChan(parameters[0]);
4498 if ((chan->noexternal) && (!has_channel(user,chan)))
4500 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4503 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4505 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4511 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4516 ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
4518 // if any users of this channel are on remote servers, broadcast the packet
4519 char buffer[MAXBUF];
4520 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
4521 NetSendToCommon(user,chan,buffer);
4525 /* no such nick/channel */
4526 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4531 dest = Find(parameters[0]);
4536 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
4541 if (!strcmp(dest->server,user->server))
4543 // direct write, same server
4544 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
4548 char buffer[MAXBUF];
4549 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
4550 NetSendToOne(dest->server,buffer);
4555 /* no such nick/channel */
4556 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4562 char* chlist(userrec *user)
4567 log(DEBUG,"chlist: %s",user->nick);
4573 for (int i = 0; i != MAXCHANS; i++)
4575 if (user->chans[i].channel != NULL)
4577 if (user->chans[i].channel->name)
4579 strcpy(cmp,user->chans[i].channel->name);
4581 if (!strstr(lst,cmp))
4583 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
4585 strcat(lst,cmode(user,user->chans[i].channel));
4586 strcat(lst,user->chans[i].channel->name);
4595 lst[strlen(lst)-1] = '\0'; // chop trailing space
4600 void handle_info(char **parameters, int pcnt, userrec *user)
4602 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
4603 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
4604 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
4605 FOREACH_MOD OnInfo(user);
4606 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
4609 void handle_time(char **parameters, int pcnt, userrec *user)
4612 struct tm * timeinfo;
4615 timeinfo = localtime ( &rawtime );
4616 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
4620 void handle_whois(char **parameters, int pcnt, userrec *user)
4625 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
4627 dest = Find(parameters[0]);
4630 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
4631 if (dest->registered == 7)
4633 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
4634 if ((user == dest) || (strchr(user->modes,'o')))
4636 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
4638 if (strcmp(chlist(dest),""))
4640 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
4642 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
4643 if (strcmp(dest->awaymsg,""))
4645 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
4647 if (strchr(dest->modes,'o'))
4649 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
4651 FOREACH_MOD OnWhois(user,dest);
4652 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
4653 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
4655 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
4659 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4664 /* no such nick/channel */
4665 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4669 void send_network_quit(const char* nick, const char* reason)
4671 char buffer[MAXBUF];
4672 snprintf(buffer,MAXBUF,"Q %s :%s",nick,reason);
4673 NetSendToAll(buffer);
4676 void handle_quit(char **parameters, int pcnt, userrec *user)
4678 user_hash::iterator iter = clientlist.find(user->nick);
4681 if (user->registered == 7)
4683 /* theres more to do here, but for now just close the socket */
4686 if (parameters[0][0] == ':')
4690 reason = parameters[0];
4692 if (strlen(reason)>MAXQUIT)
4694 reason[MAXQUIT-1] = '\0';
4697 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
4698 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
4699 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
4701 char buffer[MAXBUF];
4702 snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
4703 NetSendToAll(buffer);
4707 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
4708 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
4709 WriteCommonExcept(user,"QUIT :Client exited");
4711 char buffer[MAXBUF];
4712 snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
4713 NetSendToAll(buffer);
4715 FOREACH_MOD OnUserQuit(user);
4719 /* push the socket on a stack of sockets due to be closed at the next opportunity */
4720 fd_reap.push_back(user->fd);
4722 if (iter != clientlist.end())
4724 clientlist.erase(iter);
4725 log(DEBUG,"deleting user hash value %d",iter->second);
4726 //if ((user) && (user->registered == 7)) {
4731 if (user->registered == 7) {
4732 purge_empty_chans();
4736 void handle_who(char **parameters, int pcnt, userrec *user)
4738 chanrec* Ptr = NULL;
4740 /* theres more to do here, but for now just close the socket */
4743 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
4745 if (user->chans[0].channel)
4747 Ptr = user->chans[0].channel;
4748 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4750 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4752 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4758 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4762 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
4766 if (parameters[0][0] == '#')
4768 Ptr = FindChan(parameters[0]);
4771 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4773 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
4775 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4778 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4782 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4787 userrec* u = Find(parameters[0]);
4788 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, u->nick, u->ident, u->dhost, u->server, u->nick, u->fullname);
4793 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4795 Ptr = user->chans[0].channel;
4796 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4798 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4800 if (strchr(i->second->modes,'o'))
4802 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4806 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4812 void handle_wallops(char **parameters, int pcnt, userrec *user)
4814 WriteWallOps(user,false,"%s",parameters[0]);
4817 void handle_list(char **parameters, int pcnt, userrec *user)
4821 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4822 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4824 if ((!i->second->c_private) && (!i->second->secret))
4826 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4829 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4833 void handle_rehash(char **parameters, int pcnt, userrec *user)
4835 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4837 FOREACH_MOD OnRehash();
4838 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4844 return clientlist.size();
4848 int usercount_invisible(void)
4852 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4854 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4859 int usercount_opers(void)
4863 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4865 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4870 int usercount_unknown(void)
4874 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4876 if ((i->second->fd) && (i->second->registered != 7))
4882 long chancount(void)
4884 return chanlist.size();
4887 long count_servs(void)
4890 //for (int j = 0; j < 255; j++)
4892 // if (servers[j] != NULL)
4898 long servercount(void)
4900 return count_servs()+1;
4906 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4908 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
4914 void handle_lusers(char **parameters, int pcnt, userrec *user)
4916 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4917 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4918 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4919 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4920 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
4923 void handle_admin(char **parameters, int pcnt, userrec *user)
4925 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4926 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4927 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4928 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4931 void ShowMOTD(userrec *user)
4935 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4938 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4939 for (int i = 0; i != MOTD.size(); i++)
4941 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4943 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4946 void ShowRULES(userrec *user)
4950 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4953 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4954 for (int i = 0; i != RULES.size(); i++)
4956 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4958 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4961 /* shows the message of the day, and any other on-logon stuff */
4962 void ConnectUser(userrec *user)
4964 user->registered = 7;
4965 user->idle_lastmsg = time(NULL);
4966 log(DEBUG,"ConnectUser: %s",user->nick);
4968 if (strcmp(Passwd(user),"") && (!user->haspassed))
4970 kill_link(user,"Invalid password");
4975 kill_link(user,"Unauthorised connection");
4979 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4980 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4981 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4982 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4983 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4984 WriteServ(user->fd,"005 %s :MAP KNOCK SAFELIST HCN MAXCHANNELS=20 MAXBANS=60 NICKLEN=30 TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 :are supported by this server",user->nick);
4985 WriteServ(user->fd,"005 %s :WALLCHOPS WATCH=128 SILENCE=5 MODES=13 CHANTYPES=# PREFIX=(ohv)@%c+ CHANMODES=ohvbeqa,kfL,l,psmntirRcOAQKVHGCuzN NETWORK=%s :are supported by this server",user->nick,'%',Network);
4987 FOREACH_MOD OnUserConnect(user);
4988 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4990 char buffer[MAXBUF];
4991 snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,ServerName,user->fullname);
4992 NetSendToAll(buffer);
4995 void handle_version(char **parameters, int pcnt, userrec *user)
4997 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Revision$ $Date$",ServerName,SYSTEM);
5000 void handle_ping(char **parameters, int pcnt, userrec *user)
5002 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
5005 void handle_pong(char **parameters, int pcnt, userrec *user)
5007 // set the user as alive so they survive to next ping
5011 void handle_motd(char **parameters, int pcnt, userrec *user)
5016 void handle_rules(char **parameters, int pcnt, userrec *user)
5021 void handle_user(char **parameters, int pcnt, userrec *user)
5023 if (user->registered < 3)
5025 if (isident(parameters[0]) == 0) {
5026 // This kinda Sucks, According to the RFC thou, its either this,
5027 // or "You have already registered" :p -- Craig
5028 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
5031 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
5032 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
5033 strncat(user->ident,parameters[0],IDENTMAX);
5034 strncpy(user->fullname,parameters[3],128);
5035 user->registered = (user->registered | 1);
5040 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
5043 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
5044 if (user->registered == 3)
5046 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5051 void handle_userhost(char **parameters, int pcnt, userrec *user)
5053 char Return[MAXBUF],junk[MAXBUF];
5054 sprintf(Return,"302 %s :",user->nick);
5055 for (int i = 0; i < pcnt; i++)
5057 userrec *u = Find(parameters[i]);
5060 if (strchr(u->modes,'o'))
5062 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
5063 strcat(Return,junk);
5067 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
5068 strcat(Return,junk);
5072 WriteServ(user->fd,Return);
5076 void handle_ison(char **parameters, int pcnt, userrec *user)
5078 char Return[MAXBUF];
5079 sprintf(Return,"303 %s :",user->nick);
5080 for (int i = 0; i < pcnt; i++)
5082 userrec *u = Find(parameters[i]);
5085 strcat(Return,u->nick);
5089 WriteServ(user->fd,Return);
5093 void handle_away(char **parameters, int pcnt, userrec *user)
5097 strcpy(user->awaymsg,parameters[0]);
5098 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
5102 strcpy(user->awaymsg,"");
5103 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
5107 void handle_whowas(char **parameters, int pcnt, userrec* user)
5109 user_hash::iterator i = whowas.find(parameters[0]);
5111 if (i == whowas.end())
5113 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
5114 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5118 time_t rawtime = i->second->signon;
5122 timeinfo = localtime(&rawtime);
5123 strcpy(b,asctime(timeinfo));
5124 b[strlen(b)-1] = '\0';
5126 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
5127 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
5128 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5133 void handle_trace(char **parameters, int pcnt, userrec *user)
5135 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5139 if (isnick(i->second->nick))
5141 if (strchr(i->second->modes,'o'))
5143 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
5147 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
5152 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
5158 void handle_modules(char **parameters, int pcnt, userrec *user)
5160 for (int i = 0; i < module_names.size(); i++)
5162 Version V = modules[i]->GetVersion();
5163 char modulename[MAXBUF];
5164 strncpy(modulename,module_names[i].c_str(),256);
5165 WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,CleanFilename(modulename));
5169 // calls a handler function for a command
5171 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
5173 for (int i = 0; i < cmdlist.size(); i++)
5175 if (!strcasecmp(cmdlist[i].command,commandname))
5177 if (cmdlist[i].handler_function)
5179 if (pcnt>=cmdlist[i].min_params)
5181 if (strchr(user->modes,cmdlist[i].flags_needed))
5183 cmdlist[i].handler_function(parameters,pcnt,user);
5191 void handle_stats(char **parameters, int pcnt, userrec *user)
5197 if (strlen(parameters[0])>1)
5199 /* make the stats query 1 character long */
5200 parameters[0][1] = '\0';
5203 /* stats m (list number of times each command has been used, plus bytecount) */
5204 if (!strcasecmp(parameters[0],"m"))
5206 for (int i = 0; i < cmdlist.size(); i++)
5208 if (cmdlist[i].handler_function)
5210 if (cmdlist[i].use_count)
5212 /* RPL_STATSCOMMANDS */
5213 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
5220 /* stats z (debug and memory info) */
5221 if (!strcasecmp(parameters[0],"z"))
5223 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
5224 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
5225 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
5226 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
5227 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
5228 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
5229 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
5230 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
5234 if (!strcasecmp(parameters[0],"o"))
5236 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5238 char LoginName[MAXBUF];
5239 char HostName[MAXBUF];
5240 char OperType[MAXBUF];
5241 ConfValue("oper","name",i,LoginName,&config_f);
5242 ConfValue("oper","host",i,HostName,&config_f);
5243 ConfValue("oper","type",i,OperType,&config_f);
5244 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
5248 /* stats l (show user I/O stats) */
5249 if (!strcasecmp(parameters[0],"l"))
5251 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
5252 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5254 if (isnick(i->second->nick))
5256 WriteServ(user->fd,"211 %s :%s:%d %s %d %d %d %d",user->nick,ServerName,i->second->port,i->second->nick,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
5260 WriteServ(user->fd,"211 %s :%s:%d (unknown@%d) %d %d %d %d",user->nick,ServerName,i->second->port,i->second->fd,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
5266 /* stats u (show server uptime) */
5267 if (!strcasecmp(parameters[0],"u"))
5269 time_t current_time = 0;
5270 current_time = time(NULL);
5271 time_t server_uptime = current_time - startup_time;
5273 stime = gmtime(&server_uptime);
5274 /* i dont know who the hell would have an ircd running for over a year nonstop, but
5275 * Craig suggested this, and it seemed a good idea so in it went */
5276 if (stime->tm_year > 70)
5278 WriteServ(user->fd,"242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick,(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
5282 WriteServ(user->fd,"242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick,stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
5286 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
5287 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
5291 void handle_connect(char **parameters, int pcnt, userrec *user)
5293 char Link_ServerName[1024];
5294 char Link_IPAddr[1024];
5295 char Link_Port[1024];
5296 char Link_Pass[1024];
5300 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5304 ConfValue("link","name",i,Link_ServerName,&config_f);
5305 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5306 ConfValue("link","port",i,Link_Port,&config_f);
5307 ConfValue("link","sendpass",i,Link_Pass,&config_f);
5308 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5309 LinkPort = atoi(Link_Port);
5310 if (match(Link_ServerName,parameters[0])) {
5318 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
5322 // TODO: Perform a check here to stop a server being linked twice!
5324 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
5326 if (me[defaultRoute])
5328 me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName);
5333 WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
5337 void handle_squit(char **parameters, int pcnt, userrec *user)
5339 // send out an squit across the mesh and then clear the server list (for local squit)
5342 char islast(serverrec* s)
5345 /*for (int j = 0; j < 255; j++)
5347 if (servers[j] != NULL)
5351 if (servers[j] == s)
5359 long map_count(serverrec* s)
5362 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
5364 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s->name))) c++;
5369 void handle_links(char **parameters, int pcnt, userrec *user)
5371 WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
5372 for (int j = 0; j < 255; j++)
5374 // if (servers[j] != NULL)
5376 // WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,servers[j]->name,ServerName,servers[j]->description);
5379 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
5382 void handle_map(char **parameters, int pcnt, userrec *user)
5385 snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
5386 while (strlen(line) < 50)
5388 WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)usercnt())*100));
5389 for (int j = 0; j < 255; j++)
5391 // if (servers[j] != NULL)
5393 // snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(servers[j]),servers[j]->name);
5394 // while (strlen(line) < 50)
5395 // strcat(line," ");
5396 // WriteServ(user->fd,"%s%d (%.2f%%)",line,map_count(servers[j]),(float)(((float)map_count(servers[j])/(float)usercnt())*100));
5399 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
5403 void handle_oper(char **parameters, int pcnt, userrec *user)
5405 char LoginName[MAXBUF];
5406 char Password[MAXBUF];
5407 char OperType[MAXBUF];
5408 char TypeName[MAXBUF];
5409 char Hostname[MAXBUF];
5412 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5414 ConfValue("oper","name",i,LoginName,&config_f);
5415 ConfValue("oper","password",i,Password,&config_f);
5416 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
5418 /* correct oper credentials */
5419 ConfValue("oper","type",i,OperType,&config_f);
5420 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
5421 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
5422 WriteServ(user->fd,"MODE %s :+o",user->nick);
5423 for (j =0; j < ConfValueEnum("type",&config_f); j++)
5425 ConfValue("type","name",j,TypeName,&config_f);
5426 if (!strcmp(TypeName,OperType))
5428 /* found this oper's opertype */
5429 ConfValue("type","host",j,Hostname,&config_f);
5430 strncpy(user->dhost,Hostname,256);
5433 if (!strchr(user->modes,'o'))
5435 strcat(user->modes,"o");
5437 FOREACH_MOD OnOper(user);
5442 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
5443 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
5446 void handle_nick(char **parameters, int pcnt, userrec *user)
5450 log(DEBUG,"not enough params for handle_nick");
5455 log(DEBUG,"invalid parameter passed to handle_nick");
5458 if (!strlen(parameters[0]))
5460 log(DEBUG,"zero length new nick passed to handle_nick");
5465 log(DEBUG,"invalid user passed to handle_nick");
5470 log(DEBUG,"invalid old nick passed to handle_nick");
5473 if (!strcasecmp(user->nick,parameters[0]))
5475 log(DEBUG,"old nick is new nick, skipping");
5480 if (strlen(parameters[0]) > 1)
5482 if (parameters[0][0] == ':')
5487 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
5489 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
5493 if (isnick(parameters[0]) == 0)
5495 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
5499 if (user->registered == 7)
5501 WriteCommon(user,"NICK %s",parameters[0]);
5503 // Q token must go to ALL servers!!!
5504 char buffer[MAXBUF];
5505 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
5506 NetSendToAll(buffer);
5510 /* change the nick of the user in the users_hash */
5511 user = ReHashNick(user->nick, parameters[0]);
5512 /* actually change the nick within the record */
5514 if (!user->nick) return;
5516 strncpy(user->nick, parameters[0],NICKMAX);
5518 log(DEBUG,"new nick set: %s",user->nick);
5520 if (user->registered < 3)
5521 user->registered = (user->registered | 2);
5522 if (user->registered == 3)
5524 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5527 log(DEBUG,"exit nickchange: %s",user->nick);
5530 void force_nickchange(userrec* user,const char* newnick)
5539 strncpy(nick,newnick,MAXBUF);
5541 if (user->registered == 7)
5545 handle_nick(pars,1,user);
5551 int process_parameters(char **command_p,char *parameters)
5556 q = strlen(parameters);
5559 /* no parameters, command_p invalid! */
5562 if (parameters[0] == ':')
5564 command_p[0] = parameters+1;
5569 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
5571 /* only one parameter */
5572 command_p[0] = parameters;
5573 if (parameters[0] == ':')
5575 if (strchr(parameters,' ') != NULL)
5583 command_p[j++] = parameters;
5584 for (int i = 0; i <= q; i++)
5586 if (parameters[i] == ' ')
5588 command_p[j++] = parameters+i+1;
5589 parameters[i] = '\0';
5590 if (command_p[j-1][0] == ':')
5592 *command_p[j-1]++; /* remove dodgy ":" */
5594 /* parameter like this marks end of the sequence */
5598 return j; /* returns total number of items in the list */
5601 void process_command(userrec *user, char* cmd)
5605 char *command_p[127];
5606 char p[MAXBUF], temp[MAXBUF];
5607 int i, j, items, cmd_found;
5609 for (int i = 0; i < 127; i++)
5610 command_p[i] = NULL;
5620 if (!strcmp(cmd,""))
5625 int total_params = 0;
5628 for (int q = 0; q < strlen(cmd)-1; q++)
5630 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
5633 // found a 'trailing', we dont count them after this.
5641 // another phidjit bug...
5642 if (total_params > 126)
5644 kill_link(user,"Protocol violation (1)");
5650 std::string tmp = cmd;
5651 for (int i = 0; i <= MODCOUNT; i++)
5653 std::string oldtmp = tmp;
5654 modules[i]->OnServerRaw(tmp,true);
5657 log(DEBUG,"A Module changed the input string!");
5658 log(DEBUG,"New string: %s",tmp.c_str());
5659 log(DEBUG,"Old string: %s",oldtmp.c_str());
5663 strncpy(cmd,tmp.c_str(),MAXBUF);
5666 if (!strchr(cmd,' '))
5668 /* no parameters, lets skip the formalities and not chop up
5670 log(DEBUG,"About to preprocess command with no params");
5672 command_p[0] = NULL;
5674 for (int i = 0; i <= strlen(cmd); i++)
5676 cmd[i] = toupper(cmd[i]);
5678 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
5685 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
5686 for (int i = 0; i < strlen(temp); i++)
5688 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
5694 /* split the full string into a command plus parameters */
5698 if (strchr(cmd,' '))
5700 for (int i = 0; i <= strlen(cmd); i++)
5702 /* capitalise the command ONLY, leave params intact */
5703 cmd[i] = toupper(cmd[i]);
5704 /* are we nearly there yet?! :P */
5708 parameters = cmd+i+1;
5716 for (int i = 0; i <= strlen(cmd); i++)
5718 cmd[i] = toupper(cmd[i]);
5725 if (strlen(command)>MAXCOMMAND)
5727 kill_link(user,"Protocol violation (2)");
5731 for (int x = 0; x < strlen(command); x++)
5733 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
5735 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
5737 if (strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
5739 kill_link(user,"Protocol violation (3)");
5746 for (int i = 0; i != cmdlist.size(); i++)
5748 if (strcmp(cmdlist[i].command,""))
5750 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
5752 log(DEBUG,"Found matching command");
5756 if (strcmp(parameters,""))
5758 items = process_parameters(command_p,parameters);
5763 command_p[0] = NULL;
5769 command_p[0] = NULL;
5774 log(DEBUG,"Processing command");
5776 /* activity resets the ping pending timer */
5777 user->nping = time(NULL) + 120;
5778 if ((items) < cmdlist[i].min_params)
5780 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
5781 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
5784 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
5786 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
5787 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
5791 /* if the command isnt USER, PASS, or NICK, and nick is empty,
5793 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
5795 if ((!isnick(user->nick)) || (user->registered != 7))
5797 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5798 WriteServ(user->fd,"451 %s :You have not registered",command);
5802 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
5804 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
5805 if (cmdlist[i].handler_function)
5807 /* ikky /stats counters */
5812 user->bytes_in += strlen(temp);
5815 cmdlist[i].use_count++;
5816 cmdlist[i].total_bytes+=strlen(temp);
5819 /* WARNING: nothing may come after the
5820 * command handler call, as the handler
5821 * may free the user structure! */
5823 cmdlist[i].handler_function(command_p,items,user);
5829 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5830 WriteServ(user->fd,"451 %s :You have not registered",command);
5838 if ((!cmd_found) && (user))
5840 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
5841 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
5846 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
5849 /* create the command and push it onto the table */
5850 strcpy(comm.command,cmd);
5851 comm.handler_function = f;
5852 comm.flags_needed = flags;
5853 comm.min_params = minparams;
5855 comm.total_bytes = 0;
5856 cmdlist.push_back(comm);
5857 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
5860 void SetupCommandTable(void)
5862 createcommand("USER",handle_user,0,4);
5863 createcommand("NICK",handle_nick,0,1);
5864 createcommand("QUIT",handle_quit,0,0);
5865 createcommand("VERSION",handle_version,0,0);
5866 createcommand("PING",handle_ping,0,1);
5867 createcommand("PONG",handle_pong,0,1);
5868 createcommand("ADMIN",handle_admin,0,0);
5869 createcommand("PRIVMSG",handle_privmsg,0,2);
5870 createcommand("INFO",handle_info,0,0);
5871 createcommand("TIME",handle_time,0,0);
5872 createcommand("WHOIS",handle_whois,0,1);
5873 createcommand("WALLOPS",handle_wallops,'o',1);
5874 createcommand("NOTICE",handle_notice,0,2);
5875 createcommand("JOIN",handle_join,0,1);
5876 createcommand("NAMES",handle_names,0,1);
5877 createcommand("PART",handle_part,0,1);
5878 createcommand("KICK",handle_kick,0,2);
5879 createcommand("MODE",handle_mode,0,1);
5880 createcommand("TOPIC",handle_topic,0,1);
5881 createcommand("WHO",handle_who,0,1);
5882 createcommand("MOTD",handle_motd,0,0);
5883 createcommand("RULES",handle_rules,0,0);
5884 createcommand("OPER",handle_oper,0,2);
5885 createcommand("LIST",handle_list,0,0);
5886 createcommand("DIE",handle_die,'o',1);
5887 createcommand("RESTART",handle_restart,'o',1);
5888 createcommand("KILL",handle_kill,'o',2);
5889 createcommand("REHASH",handle_rehash,'o',0);
5890 createcommand("LUSERS",handle_lusers,0,0);
5891 createcommand("STATS",handle_stats,0,1);
5892 createcommand("USERHOST",handle_userhost,0,1);
5893 createcommand("AWAY",handle_away,0,0);
5894 createcommand("ISON",handle_ison,0,0);
5895 createcommand("SUMMON",handle_summon,0,0);
5896 createcommand("USERS",handle_users,0,0);
5897 createcommand("INVITE",handle_invite,0,2);
5898 createcommand("PASS",handle_pass,0,1);
5899 createcommand("TRACE",handle_trace,'o',0);
5900 createcommand("WHOWAS",handle_whowas,0,1);
5901 createcommand("CONNECT",handle_connect,'o',1);
5902 createcommand("SQUIT",handle_squit,'o',1);
5903 createcommand("MODULES",handle_modules,'o',0);
5904 createcommand("LINKS",handle_links,0,0);
5905 createcommand("MAP",handle_map,0,0);
5908 void process_buffer(const char* cmdbuf,userrec *user)
5912 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5919 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5922 if (!strcmp(cmdbuf,""))
5926 strncpy(cmd,cmdbuf,MAXBUF);
5927 if (!strcmp(cmd,""))
5931 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5933 cmd[strlen(cmd)-1] = '\0';
5935 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5937 cmd[strlen(cmd)-1] = '\0';
5939 if (!strcmp(cmd,""))
5943 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5945 if ((user) && (cmd))
5947 process_command(user,cmd);
5951 void DoSync(serverrec* serv, char* udp_host)
5954 // send start of sync marker: Y <timestamp>
5955 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
5956 // except the ones its receiving it from.
5957 snprintf(data,MAXBUF,"Y %d",time(NULL));
5958 serv->SendPacket(data,udp_host);
5959 // send users and channels
5960 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
5962 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->server,u->second->fullname);
5963 serv->SendPacket(data,udp_host);
5964 if (strcmp(chlist(u->second),""))
5966 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
5967 serv->SendPacket(data,udp_host);
5970 // send channel modes, topics etc...
5971 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
5973 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
5974 serv->SendPacket(data,udp_host);
5975 if (strcmp(c->second->topic,""))
5977 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
5978 serv->SendPacket(data,udp_host);
5980 // send current banlist
5982 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
5984 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
5985 serv->SendPacket(data,udp_host);
5988 // send end of sync marker: E <timestamp>
5989 snprintf(data,MAXBUF,"F %d",time(NULL));
5990 serv->SendPacket(data,udp_host);
5991 // ircd sends its serverlist after the end of sync here
5995 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
5997 char* src = strtok(params," ");
5998 char* dest = strtok(NULL," :");
5999 char* text = strtok(NULL,"\r\n");
6002 userrec* user = Find(src);
6005 userrec* dst = Find(dest);
6009 WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
6013 chanrec* d = FindChan(dest);
6016 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
6024 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6026 char* src = strtok(params," ");
6027 char* dest = strtok(NULL," :");
6028 char* text = strtok(NULL,"\r\n");
6031 userrec* user = Find(src);
6034 userrec* dst = Find(dest);
6038 WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
6042 chanrec* d = FindChan(dest);
6045 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
6052 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6054 char* nick = strtok(params," ");
6055 char* from = strtok(NULL," ");
6056 char* channel = strtok(NULL," ");
6057 userrec* u = Find(nick);
6058 userrec* user = Find(from);
6059 chanrec* c = FindChan(channel);
6060 if ((c) && (u) && (user))
6062 u->InviteTo(c->name);
6063 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
6067 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6069 char* setby = strtok(params," ");
6070 char* channel = strtok(NULL," :");
6071 char* topic = strtok(NULL,"\r\n");
6073 userrec* u = Find(setby);
6074 chanrec* c = FindChan(channel);
6077 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
6078 strncpy(c->topic,topic,MAXTOPIC);
6079 strncpy(c->setby,u->nick,NICKMAX);
6084 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6086 char* tm = strtok(params," ");
6087 char* setby = strtok(NULL," ");
6088 char* channel = strtok(NULL," :");
6089 char* topic = strtok(NULL,"\r\n");
6091 time_t TS = atoi(tm);
6092 chanrec* c = FindChan(channel);
6095 // in the case of topics and TS, the *NEWER*
6096 if (TS <= c->topicset)
6098 WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
6099 strncpy(c->topic,topic,MAXTOPIC);
6100 strncpy(c->setby,setby,NICKMAX);
6105 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6108 char original[MAXBUF],target[MAXBUF];
6109 strncpy(original,params,MAXBUF);
6111 char* parameter = strtok(params," ");
6112 strncpy(target,parameter,MAXBUF);
6115 pars[index++] = parameter;
6116 parameter = strtok(NULL," ");
6118 merge_mode(pars,index);
6119 if (FindChan(target))
6121 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
6125 WriteTo(NULL,Find(target),"MODE %s",original);
6129 // m is modes set by users only (not servers) valid targets are channels or users.
6131 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6133 // m blah #chatspike +b *!test@*4
6135 char original[MAXBUF];
6136 strncpy(original,params,MAXBUF);
6138 if (!strchr(params,' '))
6140 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
6146 char* src = strtok(params," ");
6147 userrec* user = Find(src);
6151 log(DEBUG,"Found user: %s",user->nick);
6152 char* parameter = strtok(NULL," ");
6155 pars[index++] = parameter;
6156 parameter = strtok(NULL," ");
6159 log(DEBUG,"Calling merge_mode2");
6160 merge_mode2(pars,index,user);
6165 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6167 char* nick = strtok(params," ");
6168 char* channel = strtok(NULL," :");
6169 char* reason = strtok(NULL,"\r\n");
6170 userrec* user = Find(nick);
6174 if (strcmp(reason,""))
6176 del_channel(user,channel,reason,true);
6180 del_channel(user,channel,NULL,true);
6185 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6187 char* src = strtok(params," ");
6188 char* nick = strtok(NULL," :");
6189 char* reason = strtok(NULL,"\r\n");
6190 char kreason[MAXBUF];
6193 userrec* u = Find(nick);
6194 userrec* user = Find(src);
6198 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
6199 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
6200 snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
6201 kill_link(u,kreason);
6205 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6207 char* nick = strtok(params," :");
6208 char* reason = strtok(NULL,"\r\n");
6211 userrec* user = Find(nick);
6215 if (strlen(reason)>MAXQUIT)
6217 reason[MAXQUIT-1] = '\0';
6221 WriteCommonExcept(user,"QUIT :%s",reason);
6223 user_hash::iterator iter = clientlist.find(user->nick);
6225 if (iter != clientlist.end())
6227 log(DEBUG,"deleting user hash value %d",iter->second);
6228 if ((iter->second) && (user->registered == 7)) {
6229 delete iter->second;
6231 clientlist.erase(iter);
6234 purge_empty_chans();
6238 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6240 char* oldnick = strtok(params," ");
6241 char* newnick = strtok(NULL," ");
6243 userrec* user = Find(oldnick);
6247 WriteCommon(user,"NICK %s",newnick);
6248 user = ReHashNick(user->nick, newnick);
6250 if (!user->nick) return;
6251 strncpy(user->nick, newnick,NICKMAX);
6252 log(DEBUG,"new nick set: %s",user->nick);
6256 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6257 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6259 char* src = strtok(params," ");
6260 char* dest = strtok(NULL," ");
6261 char* channel = strtok(NULL," :");
6262 char* reason = strtok(NULL,"\r\n");
6264 userrec* s = Find(src);
6265 userrec* d = Find(dest);
6266 chanrec* c = FindChan(channel);
6267 if ((s) && (d) && (c))
6269 kick_channel(s,d,c,reason);
6273 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6275 char* who = strtok(params," :");
6276 char* text = strtok(NULL,"\r\n");
6278 userrec* s = Find(who);
6281 WriteWallOps(s,true,text);
6286 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6288 char* tm = strtok(params," ");
6289 char* nick = strtok(NULL," ");
6290 char* host = strtok(NULL," ");
6291 char* dhost = strtok(NULL," ");
6292 char* ident = strtok(NULL," ");
6293 char* modes = strtok(NULL," ");
6294 char* server = strtok(NULL," :");
6295 char* gecos = strtok(NULL,"\r\n");
6298 time_t TS = atoi(tm);
6299 user_hash::iterator iter = clientlist.find(nick);
6300 if (iter != clientlist.end())
6303 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
6304 if (TS >= iter->second->age)
6307 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
6308 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
6309 // client on remote server is older than the local user, kill the local user
6310 kill_link(iter->second,str);
6313 clientlist[nick] = new userrec();
6314 // remote users have an fd of -1. This is so that our Write abstraction
6315 // routines know to route any messages to this record away to whatever server
6317 clientlist[nick]->fd = -1;
6318 strncpy(clientlist[nick]->nick, nick,NICKMAX);
6319 strncpy(clientlist[nick]->host, host,160);
6320 strncpy(clientlist[nick]->dhost, dhost,160);
6321 strncpy(clientlist[nick]->server, server,256);
6322 strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for '~'
6323 strncpy(clientlist[nick]->fullname, gecos,128);
6324 clientlist[nick]->signon = TS;
6325 clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
6326 clientlist[nick]->lastping = 1;
6327 clientlist[nick]->port = 0; // so is this...
6328 clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
6329 clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
6330 for (int i = 0; i < MAXCHANS; i++)
6332 clientlist[nick]->chans[i].channel = NULL;
6333 clientlist[nick]->chans[i].uc_modes = 0;
6337 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6339 long tdiff = time(NULL) - atoi(params);
6341 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
6344 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6346 char* nick = strtok(params," :");
6347 char* gecos = strtok(NULL,"\r\n");
6349 userrec* user = Find(nick);
6352 strncpy(user->fullname,gecos,MAXBUF);
6355 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6357 char* nick = strtok(params," :");
6358 char* host = strtok(NULL,"\r\n");
6360 userrec* user = Find(nick);
6363 strncpy(user->dhost,host,160);
6367 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6370 // The J token currently has no timestamp - this needs looking at
6371 // because it will allow splitriding.
6372 char* nick = strtok(params," ");
6373 char* channel = strtok(NULL," ");
6374 userrec* user = Find(nick);
6377 if ((user != NULL) && (strcmp(channel,"")))
6379 char privilage = '\0';
6380 if (channel[0] != '#')
6382 privilage = channel[0];
6385 add_channel(user,channel,"",true);
6387 // now work out the privilages they should have on each channel
6388 // and send the appropriate servermodes.
6389 for (int i = 0; i != MAXCHANS; i++)
6391 if (user->chans[i].channel)
6393 if (!strcasecmp(user->chans[i].channel->name,channel))
6395 if (privilage == '@')
6397 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
6398 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
6400 if (privilage == '%')
6402 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
6403 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
6405 if (privilage == '+')
6407 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
6408 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
6415 channel = strtok(NULL," ");
6419 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6426 nb_start = time(NULL);
6427 WriteOpers("Server %s is starting netburst.",source->name);
6432 reply->SendPacket("!",udp_host);
6442 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
6443 // introduce remote client
6445 handle_N(token,params,source,reply,udp_host);
6447 // a <NICK> :<GECOS>
6448 // change GECOS (SETNAME)
6450 handle_a(token,params,source,reply,udp_host);
6453 // change displayed host (SETHOST)
6455 handle_b(token,params,source,reply,udp_host);
6457 // t <NICK> <CHANNEL> :<TOPIC>
6458 // change a channel topic
6460 handle_t(token,params,source,reply,udp_host);
6462 // i <NICK> <CHANNEL>
6463 // invite a user to a channel
6465 handle_i(token,params,source,reply,udp_host);
6467 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6468 // kick a user from a channel
6470 handle_k(token,params,source,reply,udp_host);
6472 // n <NICK> <NEWNICK>
6473 // change nickname of client -- a server should only be able to
6474 // change the nicknames of clients that reside on it unless
6477 handle_n(token,params,source,reply,udp_host);
6479 // J <NICK> <CHANLIST>
6480 // Join user to channel list, merge channel permissions
6482 handle_J(token,params,source,reply,udp_host);
6484 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
6485 // change channel topic (netburst only)
6487 handle_T(token,params,source,reply,udp_host);
6489 // M <TARGET> <MODES> [MODE-PARAMETERS]
6490 // Server setting modes on an object
6492 handle_M(token,params,source,reply,udp_host);
6494 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
6495 // User setting modes on an object
6497 handle_m(token,params,source,reply,udp_host);
6499 // P <SOURCE> <TARGET> :<TEXT>
6500 // Send a private/channel message
6502 handle_P(token,params,source,reply,udp_host);
6504 // V <SOURCE> <TARGET> :<TEXT>
6505 // Send a private/channel notice
6507 handle_V(token,params,source,reply,udp_host);
6509 // L <SOURCE> <CHANNEL> :<REASON>
6510 // User parting a channel
6512 handle_L(token,params,source,reply,udp_host);
6514 // Q <SOURCE> :<REASON>
6517 handle_Q(token,params,source,reply,udp_host);
6519 // K <SOURCE> <DEST> :<REASON>
6522 handle_K(token,params,source,reply,udp_host);
6524 // @ <SOURCE> :<TEXT>
6527 handle_AT(token,params,source,reply,udp_host);
6532 WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
6533 handle_F(token,params,source,reply,udp_host);
6536 WriteOpers("Sending my netburst to %s",udp_host);
6537 DoSync(source,udp_host);
6538 WriteOpers("Send of netburst to %s completed",udp_host);
6543 WriteOpers("WARNING! Unknown datagram type '%c'",token);
6549 void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
6551 char response[10240];
6552 char token = udp_msg[0];
6553 char* params = udp_msg + 2;
6554 char finalparam[1024];
6555 strcpy(finalparam," :xxxx");
6556 if (strstr(params," :")) {
6557 strncpy(finalparam,strstr(params," :"),1024);
6560 // S test.chatspike.net password :ChatSpike InspIRCd test server
6561 char* servername = strtok(params," ");
6562 char* password = strtok(NULL," ");
6563 char* serverdesc = finalparam+2;
6564 WriteOpers("CONNECT from %s (%s)",servername,udp_host);
6566 for (int j = 0; j < serv->connectors.size(); j++)
6568 if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
6570 serv->connectors[j].SetServerName(servername);
6575 char Link_ServerName[1024];
6576 char Link_IPAddr[1024];
6577 char Link_Port[1024];
6578 char Link_Pass[1024];
6579 char Link_SendPass[1024];
6582 // search for a corresponding <link> block in the config files
6583 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6585 ConfValue("link","name",i,Link_ServerName,&config_f);
6586 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6587 ConfValue("link","port",i,Link_Port,&config_f);
6588 ConfValue("link","recvpass",i,Link_Pass,&config_f);
6589 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6590 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6591 LinkPort = atoi(Link_Port);
6592 if (!strcasecmp(Link_ServerName,servername))
6594 // we have a matching link line -
6595 // send a 'diminutive' server message back...
6596 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
6597 serv->SendPacket(response,servername);
6601 char buffer[MAXBUF];
6602 sprintf(buffer,"E :Access is denied (no matching link block)");
6603 serv->SendPacket(buffer,udp_host);
6604 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6609 // S test.chatspike.net password :ChatSpike InspIRCd test server
6610 char* servername = strtok(params," ");
6611 char* password = strtok(NULL," ");
6612 char* serverdesc = finalparam+2;
6614 // TODO: we should do a check here to ensure that this server is one we recently initiated a
6615 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
6616 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
6617 // a connect, so put out an oper alert!
6622 // for now, just accept all, we'll fix that later.
6623 WriteOpers("%s accepted our link credentials ",servername);
6625 char Link_ServerName[1024];
6626 char Link_IPAddr[1024];
6627 char Link_Port[1024];
6628 char Link_Pass[1024];
6629 char Link_SendPass[1024];
6632 // search for a corresponding <link> block in the config files
6633 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6635 ConfValue("link","name",i,Link_ServerName,&config_f);
6636 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6637 ConfValue("link","port",i,Link_Port,&config_f);
6638 ConfValue("link","recvpass",i,Link_Pass,&config_f);
6639 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6640 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6641 LinkPort = atoi(Link_Port);
6642 if (!strcasecmp(Link_ServerName,servername))
6644 // matching link at this end too, we're all done!
6645 // at this point we must begin key exchange and insert this
6646 // server into our 'active' table.
6647 for (int j = 0; j < 32; j++)
6651 for (int k = 0; k < me[j]->connectors.size(); k++)
6653 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
6655 char buffer[MAXBUF];
6656 sprintf(buffer,"X 0");
6657 serv->SendPacket(buffer,udp_host);
6658 DoSync(serv,udp_host);
6663 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
6668 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
6671 char buffer[MAXBUF];
6672 sprintf(buffer,"E :Access is denied (no matching link block)");
6673 serv->SendPacket(buffer,udp_host);
6674 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6679 char* error_message = finalparam+2;
6680 WriteOpers("ERROR from %s: %s",udp_host,error_message);
6681 // remove this server from any lists
6686 serverrec* source_server = NULL;
6688 for (int j = 0; j < 32; j++)
6692 for (int x = 0; x < me[j]->connectors.size(); x++)
6694 log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
6695 if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
6697 log(DEBUG,"match! process restricted stuff here");
6698 // found a valid ircd_connector.
6699 // TODO: Fix this so it only lets servers in that are in the
6700 // STATE_CONNECTED state!!!
6701 process_restricted_commands(token,params,me[j],serv,udp_host);
6708 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
6712 int reap_counter = 0;
6716 struct sockaddr_in client, server;
6717 char addrs[MAXBUF][255];
6718 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
6720 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
6721 int selectResult = 0, selectResult2 = 0;
6722 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
6723 char resolvedHost[MAXBUF];
6727 log_file = fopen("ircd.log","a+");
6730 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
6734 log(DEBUG,"InspIRCd: startup: begin");
6738 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
6740 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
6742 SetupCommandTable();
6743 log(DEBUG,"InspIRCd: startup: default command table set up");
6746 if (strcmp(DieValue,""))
6748 printf("WARNING: %s\n\n",DieValue);
6751 log(DEBUG,"InspIRCd: startup: read config");
6753 int count2 = 0, count3 = 0;
6755 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
6757 ConfValue("bind","port",count,configToken,&config_f);
6758 ConfValue("bind","address",count,Addr,&config_f);
6759 ConfValue("bind","type",count,Type,&config_f);
6760 if (!strcmp(Type,"servers"))
6762 char Default[MAXBUF];
6763 strcpy(Default,"no");
6764 ConfValue("bind","default",count,Default,&config_f);
6765 if (strchr(Default,'y'))
6767 defaultRoute = count3;
6768 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
6770 me[count3] = new serverrec(ServerName,100L,false);
6771 me[count3]->CreateListener(Addr,atoi(configToken));
6776 ports[count2] = atoi(configToken);
6777 strcpy(addrs[count2],Addr);
6780 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
6783 UDPportCount = count3;
6785 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
6787 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
6791 /* BugFix By Craig! :p */
6793 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
6795 char modfile[MAXBUF];
6796 ConfValue("module","name",count2,configToken,&config_f);
6797 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
6798 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
6799 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
6800 /* If The File Doesnt exist, Trying to load it
6801 * Will Segfault the IRCd.. So, check to see if
6802 * it Exists, Before Proceeding. */
6803 if (FileExists(modfile))
6805 factory[count] = new ircd_module(modfile);
6806 if (factory[count]->LastError())
6808 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
6809 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
6812 if (factory[count]->factory)
6814 modules[count] = factory[count]->factory->CreateModule();
6815 /* save the module and the module's classfactory, if
6816 * this isnt done, random crashes can occur :/ */
6817 module_names.push_back(modfile);
6821 log(DEBUG,"Unable to load %s",modfile);
6822 sprintf("Unable to load %s\nExiting...\n",modfile);
6825 /* Increase the Count */
6830 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
6831 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
6834 MODCOUNT = count - 1;
6835 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
6837 printf("\nInspIRCd is now running!\n");
6839 startup_time = time(NULL);
6843 log(VERBOSE,"Not forking as -nofork was specified");
6847 if (DaemonSeed() == ERROR)
6849 log(DEBUG,"InspIRCd: startup: can't daemonise");
6850 printf("ERROR: could not go into daemon mode. Shutting down.\n");
6856 /* setup select call */
6857 FD_ZERO(&selectFds);
6858 log(DEBUG,"InspIRCd: startup: zero selects");
6859 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
6861 for (count = 0; count < portCount; count++)
6863 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
6865 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
6868 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
6870 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
6872 else /* well we at least bound to one socket so we'll continue */
6878 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
6880 /* if we didn't bind to anything then abort */
6881 if (boundPortCount == 0)
6883 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
6888 length = sizeof (client);
6889 char udp_msg[MAXBUF], udp_host[MAXBUF];
6891 /* main loop, this never returns */
6899 user_hash::iterator count2 = clientlist.begin();
6901 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
6902 // them in a list, then reap the list every second or so.
6903 if (reap_counter>5000)
6905 if (fd_reap.size() > 0)
6907 for( int n = 0; n < fd_reap.size(); n++)
6909 Blocking(fd_reap[n]);
6911 NonBlocking(fd_reap[n]);
6919 FD_ZERO(&serverfds);
6922 for (int x = 0; x != UDPportCount; x++)
6924 FD_SET(me[x]->fd, &serverfds);
6930 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
6933 for (int x = 0; x != UDPportCount; x++)
6935 if (FD_ISSET (me[x]->fd, &serverfds))
6937 char remotehost[MAXBUF];
6938 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
6939 strncpy (remotehost,(char *) inet_ntoa (client.sin_addr),MAXBUF);
6940 // add to this connections ircd_connector vector
6941 me[x]->AddIncoming(incomingSockfd,remotehost);
6946 for (int x = 0; x != UDPportCount; x++)
6948 std::deque<std::string> msgs;
6950 if (me[x]->RecvPacket(msgs, udp_host))
6952 for (int ctr = 0; ctr < msgs.size(); ctr++)
6954 char udp_msg[MAXBUF];
6955 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
6956 if (strlen(udp_msg)<1)
6958 log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
6961 FOREACH_MOD OnPacketReceive(udp_msg);
6962 handle_link_packet(udp_msg, udp_host, me[x]);
6969 while (count2 != clientlist.end())
6972 tval.tv_usec = tval.tv_sec = 0;
6974 int total_in_this_set = 0;
6976 user_hash::iterator xcount = count2;
6977 user_hash::iterator endingiter = count2;
6979 if (!count2->second) break;
6982 if (count2->second->fd != 0)
6984 // assemble up to 64 sockets into an fd_set
6985 // to implement a pooling mechanism.
6987 // This should be up to 64x faster than the
6988 // old implementation.
6989 while (total_in_this_set < 64)
6991 if (count2 != clientlist.end())
6993 // we don't check the state of remote users.
6994 if (count2->second->fd > 0)
6996 FD_SET (count2->second->fd, &sfd);
6998 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
6999 // their connection class.
7000 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
7002 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
7003 kill_link(count2->second,"Registration timeout");
7006 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
7008 if ((!count2->second->lastping) && (count2->second->registered == 7))
7010 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
7011 kill_link(count2->second,"Ping timeout");
7014 Write(count2->second->fd,"PING :%s",ServerName);
7015 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
7016 count2->second->lastping = 0;
7017 count2->second->nping = time(NULL)+120;
7021 total_in_this_set++;
7026 endingiter = count2;
7027 count2 = xcount; // roll back to where we were
7033 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
7035 // now loop through all of the items in this pool if any are waiting
7036 //if (selectResult2 > 0)
7037 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
7040 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
7042 log(DEBUG,"Reading fd %d",count2a->second->fd);
7043 memset(data, 0, 10240);
7044 result = read(count2a->second->fd, data, 10240);
7048 log(DEBUG,"Read %d characters from socket",result);
7049 userrec* current = count2a->second;
7050 int currfd = current->fd;
7051 char* l = strtok(data,"\n");
7056 if ((floodlines > current->flood) && (current->flood != 0))
7058 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7059 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7060 kill_link(current,"Excess flood");
7063 char sanitized[NetBufferSize];
7064 memset(sanitized, 0, NetBufferSize);
7066 for (int pt = 0; pt < strlen(l); pt++)
7070 sanitized[ptt++] = l[pt];
7073 sanitized[ptt] = '\0';
7074 if (strlen(sanitized))
7078 // we're gonna re-scan to check if the nick is gone, after every
7079 // command - if it has, we're gonna bail
7080 bool find_again = false;
7081 process_buffer(sanitized,current);
7083 // look for the user's record in case it's changed
7084 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
7086 if (c2->second->fd == currfd)
7088 // found again, update pointer
7089 current == c2->second;
7098 l = strtok(NULL,"\n");
7103 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
7105 log(DEBUG,"killing: %s",count2a->second->nick);
7106 kill_link(count2a->second,strerror(errno));
7110 // result EAGAIN means nothing read
7111 if (result == EAGAIN)
7119 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
7120 kill_link(count2a->second,"Client exited");
7121 // must bail here? kill_link removes the hash, corrupting the iterator
7122 log(DEBUG,"Bailing from client exit");
7126 else if (result > 0)
7131 for (int q = 0; q < total_in_this_set; q++)
7133 // there is no iterator += operator :(
7134 //if (count2 != clientlist.end())
7141 // set up select call
7142 for (count = 0; count < boundPortCount; count++)
7144 FD_SET (openSockfd[count], &selectFds);
7149 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
7151 /* select is reporting a waiting socket. Poll them all to find out which */
7152 if (selectResult > 0)
7154 char target[MAXBUF], resolved[MAXBUF];
7155 for (count = 0; count < boundPortCount; count++)
7157 if (FD_ISSET (openSockfd[count], &selectFds))
7159 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
7161 address_cache::iterator iter = IP.find(client.sin_addr);
7162 bool iscached = false;
7163 if (iter == IP.end())
7165 /* ip isn't in cache, add it */
7166 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
7167 if(CleanAndResolve(resolved, target) != TRUE)
7169 strncpy(resolved,target,MAXBUF);
7171 /* hostname now in 'target' */
7172 IP[client.sin_addr] = new string(resolved);
7173 /* hostname in cache */
7177 /* found ip (cached) */
7178 strncpy(resolved, iter->second->c_str(), MAXBUF);
7182 if (incomingSockfd < 0)
7184 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
7185 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
7189 AddClient(incomingSockfd, resolved, ports[count], iscached);
7190 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
7197 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
7200 close (incomingSockfd);