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
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::vector<long> auth_cookies;
186 std::stringstream config_f(stringstream::in | stringstream::out);
188 void safedelete(userrec *p)
192 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
193 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
199 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
203 void safedelete(chanrec *p)
209 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
213 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
218 void tidystring(char* str)
220 // strips out double spaces before a : parameter
223 bool go_again = true;
230 while ((str[0] == ' ') && (strlen(str)>0))
237 bool noparse = false;
240 while (a < strlen(str))
242 if ((a<strlen(str)-1) && (noparse==false))
244 if ((str[a] == ' ') && (str[a+1] == ' '))
246 log(DEBUG,"Tidied extra space out of string: %s",str);
254 if ((str[a] == ' ') && (str[a+1] == ':'))
260 temp[t++] = str[a++];
263 strncpy(str,temp,MAXBUF);
267 /* chop a string down to 512 characters and preserve linefeed (irc max
274 log(DEBUG,"ERROR! Null string passed to chop()!");
278 FOREACH_MOD OnServerRaw(temp,false);
279 const char* str2 = temp.c_str();
280 sprintf(str,"%s",str2);
283 if (strlen(str) >= 512)
292 std::string getservername()
297 std::string getserverdesc()
302 std::string getnetworkname()
307 std::string getadminname()
312 std::string getadminemail()
317 std::string getadminnick()
322 void log(int level,char *text, ...)
324 char textbuffer[MAXBUF];
327 struct tm * timeinfo;
328 if (level < LogLevel)
332 timeinfo = localtime (&rawtime);
337 va_start (argsPtr, text);
338 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
340 strcpy(b,asctime(timeinfo));
341 b[strlen(b)-1] = ':';
342 fprintf(log_file,"%s %s\n",b,textbuffer);
345 // nofork enabled? display it on terminal too
346 printf("%s %s\n",b,textbuffer);
351 void readfile(file_cache &F, const char* fname)
354 char linebuf[MAXBUF];
356 log(DEBUG,"readfile: loading %s",fname);
358 file = fopen(fname,"r");
363 fgets(linebuf,sizeof(linebuf),file);
364 linebuf[strlen(linebuf)-1]='\0';
365 if (!strcmp(linebuf,""))
371 F.push_back(linebuf);
378 log(DEBUG,"readfile: failed to load file: %s",fname);
380 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
383 void ReadConfig(void)
385 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
388 LoadConf(CONFIG_FILE,&config_f);
390 ConfValue("server","name",0,ServerName,&config_f);
391 ConfValue("server","description",0,ServerDesc,&config_f);
392 ConfValue("server","network",0,Network,&config_f);
393 ConfValue("admin","name",0,AdminName,&config_f);
394 ConfValue("admin","email",0,AdminEmail,&config_f);
395 ConfValue("admin","nick",0,AdminNick,&config_f);
396 ConfValue("files","motd",0,motd,&config_f);
397 ConfValue("files","rules",0,rules,&config_f);
398 ConfValue("power","diepass",0,diepass,&config_f);
399 ConfValue("power","pause",0,pauseval,&config_f);
400 ConfValue("power","restartpass",0,restartpass,&config_f);
401 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
402 ConfValue("die","value",0,DieValue,&config_f);
403 ConfValue("options","loglevel",0,dbg,&config_f);
404 ConfValue("options","netbuffersize",0,NB,&config_f);
405 NetBufferSize = atoi(NB);
406 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
408 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
409 NetBufferSize = 10240;
411 if (!strcmp(dbg,"debug"))
413 if (!strcmp(dbg,"verbose"))
415 if (!strcmp(dbg,"default"))
417 if (!strcmp(dbg,"sparse"))
419 if (!strcmp(dbg,"none"))
422 log(DEBUG,"Reading message of the day");
423 readfile(RULES,rules);
424 log(DEBUG,"Reading connect classes");
426 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
429 ConfValue("connect","allow",i,Value,&config_f);
430 ConfValue("connect","timeout",i,timeout,&config_f);
431 ConfValue("connect","flood",i,flood,&config_f);
432 if (strcmp(Value,""))
434 strcpy(c.host,Value);
437 ConfValue("connect","password",i,Value,&config_f);
438 strcpy(c.pass,Value);
439 c.registration_timeout = 90; // default is 2 minutes
440 c.flood = atoi(flood);
443 c.registration_timeout = atoi(timeout);
445 Classes.push_back(c);
446 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
450 ConfValue("connect","deny",i,Value,&config_f);
451 strcpy(c.host,Value);
453 Classes.push_back(c);
454 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
463 log(DEBUG,"Blocking: %d",s);
464 flags = fcntl(s, F_GETFL, 0);
465 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
468 void NonBlocking(int s)
471 log(DEBUG,"NonBlocking: %d",s);
472 flags = fcntl(s, F_GETFL, 0);
473 //fcntl(s, F_SETFL, O_NONBLOCK);
474 fcntl(s, F_SETFL, flags | O_NONBLOCK);
478 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
480 struct hostent *hostPtr = NULL;
483 memset (resolvedHost, '\0',MAXBUF);
484 if(unresolvedHost == NULL)
486 if ((inet_aton(unresolvedHost,&addr)) == 0)
488 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
490 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
492 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
496 /* write formatted text to a socket, in same format as printf */
498 void Write(int sock,char *text, ...)
502 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
505 char textbuffer[MAXBUF];
509 va_start (argsPtr, text);
510 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
512 sprintf(tb,"%s\r\n",textbuffer);
516 write(sock,tb,strlen(tb));
517 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
521 /* write a server formatted numeric response to a single socket */
523 void WriteServ(int sock, char* text, ...)
527 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
530 char textbuffer[MAXBUF],tb[MAXBUF];
532 va_start (argsPtr, text);
534 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
536 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
540 write(sock,tb,strlen(tb));
541 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
545 /* write text from an originating user to originating user */
547 void WriteFrom(int sock, userrec *user,char* text, ...)
549 if ((!text) || (!user))
551 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
554 char textbuffer[MAXBUF],tb[MAXBUF];
556 va_start (argsPtr, text);
558 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
560 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
564 write(sock,tb,strlen(tb));
565 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
569 /* write text to an destination user from a source user (e.g. user privmsg) */
571 void WriteTo(userrec *source, userrec *dest,char *data, ...)
573 if ((!dest) || (!data))
575 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
578 char textbuffer[MAXBUF],tb[MAXBUF];
580 va_start (argsPtr, data);
581 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
585 // if no source given send it from the server.
588 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
592 WriteFrom(dest->fd,source,"%s",textbuffer);
596 /* write formatted text from a source user to all users on a channel
597 * including the sender (NOT for privmsg, notice etc!) */
599 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
601 if ((!Ptr) || (!user) || (!text))
603 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
606 char textbuffer[MAXBUF];
608 va_start (argsPtr, text);
609 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
611 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
613 if (has_channel(i->second,Ptr))
615 WriteTo(user,i->second,"%s",textbuffer);
620 /* write formatted text from a source user to all users on a channel
621 * including the sender (NOT for privmsg, notice etc!) doesnt send to
622 * users on remote servers */
624 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
626 if ((!Ptr) || (!text))
628 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
631 char textbuffer[MAXBUF];
633 va_start (argsPtr, text);
634 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
636 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
638 if (has_channel(i->second,Ptr))
640 if (i->second->fd != -1)
644 WriteServ(i->second->fd,"%s",textbuffer);
648 WriteTo(user,i->second,"%s",textbuffer);
656 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
658 if ((!Ptr) || (!user) || (!text))
660 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
663 char textbuffer[MAXBUF];
665 va_start (argsPtr, text);
666 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
668 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
672 if (has_channel(i->second,Ptr))
674 WriteServ(i->second->fd,"%s",textbuffer);
681 /* write formatted text from a source user to all users on a channel except
682 * for the sender (for privmsg etc) */
684 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
686 if ((!Ptr) || (!user) || (!text))
688 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
691 char textbuffer[MAXBUF];
693 va_start (argsPtr, text);
694 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
697 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
701 if (has_channel(i->second,Ptr) && (user != i->second))
703 WriteTo(user,i->second,"%s",textbuffer);
709 int c_count(userrec* u)
712 for (int i =0; i != MAXCHANS; i++)
713 if (u->chans[i].channel != NULL)
719 /* return 0 or 1 depending if users u and u2 share one or more common channels
720 * (used by QUIT, NICK etc which arent channel specific notices) */
722 int common_channels(userrec *u, userrec *u2)
729 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
732 for (int i = 0; i != MAXCHANS; i++)
734 for (z = 0; z != MAXCHANS; z++)
736 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
738 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
740 if ((c_count(u)) && (c_count(u2)))
751 /* write a formatted string to all users who share at least one common
752 * channel, including the source user e.g. for use in NICK */
754 void WriteCommon(userrec *u, char* text, ...)
758 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
762 if (u->registered != 7) {
763 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
767 char textbuffer[MAXBUF];
769 va_start (argsPtr, text);
770 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
773 WriteFrom(u->fd,u,"%s",textbuffer);
775 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
779 if (common_channels(u,i->second) && (i->second != u))
781 WriteFrom(i->second->fd,u,"%s",textbuffer);
787 /* write a formatted string to all users who share at least one common
788 * channel, NOT including the source user e.g. for use in QUIT */
790 void WriteCommonExcept(userrec *u, char* text, ...)
794 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
798 if (u->registered != 7) {
799 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
803 char textbuffer[MAXBUF];
805 va_start (argsPtr, text);
806 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
809 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
813 if ((common_channels(u,i->second)) && (u != i->second))
815 WriteFrom(i->second->fd,u,"%s",textbuffer);
821 void WriteOpers(char* text, ...)
825 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
829 char textbuffer[MAXBUF];
831 va_start (argsPtr, text);
832 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
835 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
839 if (strchr(i->second->modes,'o'))
841 if (strchr(i->second->modes,'s'))
843 // send server notices to all with +s
844 // (TODO: needs SNOMASKs)
845 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
852 // returns TRUE of any users on channel C occupy server 'servername'.
854 bool ChanAnyOnThisServer(chanrec *c,char* servername)
856 log(DEBUG,"ChanAnyOnThisServer");
857 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
859 if (has_channel(i->second,c))
861 if (!strcasecmp(i->second->server,servername))
870 // returns true if user 'u' shares any common channels with any users on server 'servername'
872 bool CommonOnThisServer(userrec* u,const char* servername)
874 log(DEBUG,"ChanAnyOnThisServer");
875 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
877 if ((common_channels(u,i->second)) && (u != i->second))
879 if (!strcasecmp(i->second->server,servername))
881 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
890 void NetSendToCommon(userrec* u, char* s)
893 snprintf(buffer,MAXBUF,"%s",s);
895 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
897 for (int j = 0; j < 32; j++)
901 for (int k = 0; k < me[j]->connectors.size(); k++)
903 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
905 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
913 void NetSendToAll(char* s)
916 snprintf(buffer,MAXBUF,"%s",s);
918 log(DEBUG,"NetSendToAll: '%s'",s);
920 for (int j = 0; j < 32; j++)
924 for (int k = 0; k < me[j]->connectors.size(); k++)
926 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
933 void NetSendToOne(char* target,char* s)
936 snprintf(buffer,MAXBUF,"%s",s);
938 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
940 for (int j = 0; j < 32; j++)
944 for (int k = 0; k < me[j]->connectors.size(); k++)
946 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
948 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
955 void NetSendToAllExcept(char* target,char* s)
958 snprintf(buffer,MAXBUF,"%s",s);
960 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
962 for (int j = 0; j < 32; j++)
966 for (int k = 0; k < me[j]->connectors.size(); k++)
968 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
970 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
978 bool hasumode(userrec* user, char mode)
982 return (strchr(user->modes,mode)>0);
987 void WriteMode(const char* modes, int flags, const char* text, ...)
989 if ((!text) || (!modes) || (!flags))
991 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
995 char textbuffer[MAXBUF];
997 va_start (argsPtr, text);
998 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1001 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1005 bool send_to_user = false;
1007 if (flags == WM_AND)
1009 send_to_user = true;
1010 for (int n = 0; n < strlen(modes); n++)
1012 if (!hasumode(i->second,modes[n]))
1014 send_to_user = false;
1019 else if (flags == WM_OR)
1021 send_to_user = false;
1022 for (int n = 0; n < strlen(modes); n++)
1024 if (hasumode(i->second,modes[n]))
1026 send_to_user = true;
1034 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1040 void ChangeName(userrec* user, const char* gecos)
1042 strncpy(user->fullname,gecos,MAXBUF);
1044 // TODO: replace these with functions:
1045 // NetSendToAll - to all
1046 // NetSendToCommon - to all that hold users sharing a common channel with another user
1047 // NetSendToOne - to one server
1048 // NetSendToAllExcept - send to all but one
1049 // all by servername
1051 char buffer[MAXBUF];
1052 snprintf(buffer,MAXBUF,"a %s :%s",user->nick,gecos);
1053 NetSendToAll(buffer);
1056 void ChangeDisplayedHost(userrec* user, const char* host)
1058 strncpy(user->dhost,host,160);
1059 char buffer[MAXBUF];
1060 snprintf(buffer,MAXBUF,"b %s :%s",user->nick,host);
1061 NetSendToAll(buffer);
1064 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1066 if ((!text) || (!source))
1068 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1073 char textbuffer[MAXBUF];
1075 va_start (argsPtr, text);
1076 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1079 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1083 if (strchr(i->second->modes,'w'))
1085 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
1092 char buffer[MAXBUF];
1093 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1094 NetSendToAll(buffer);
1098 /* convert a string to lowercase. Note following special circumstances
1099 * taken from RFC 1459. Many "official" server branches still hold to this
1100 * rule so i will too;
1102 * Because of IRC's scandanavian origin, the characters {}| are
1103 * considered to be the lower case equivalents of the characters []\,
1104 * respectively. This is a critical issue when determining the
1105 * equivalence of two nicknames.
1108 void strlower(char *n)
1114 for (int i = 0; i != strlen(n); i++)
1116 n[i] = tolower(n[i]);
1126 /* verify that a user's ident and nickname is valid */
1128 int isident(const char* n)
1140 for (int i = 0; i != strlen(n); i++)
1142 if ((n[i] < 33) || (n[i] > 125))
1146 /* can't occur ANYWHERE in an Ident! */
1147 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1156 int isnick(const char* n)
1168 if (strlen(n) > NICKMAX-1)
1172 for (int i = 0; i != strlen(n); i++)
1174 if ((n[i] < 33) || (n[i] > 125))
1178 /* can't occur ANYWHERE in a nickname! */
1179 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1183 /* can't occur as the first char of a nickname... */
1184 if ((strchr("0123456789",n[i])) && (!i))
1192 /* Find a user record by nickname and return a pointer to it */
1194 userrec* Find(string nick)
1196 user_hash::iterator iter = clientlist.find(nick);
1198 if (iter == clientlist.end())
1199 /* Couldn't find it */
1202 return iter->second;
1205 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1207 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1211 if (i->second->fd == fd)
1213 i->second->bytes_out+=data_out;
1214 i->second->cmds_out++;
1221 /* find a channel record by channel name and return a pointer to it */
1223 chanrec* FindChan(const char* chan)
1227 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1231 chan_hash::iterator iter = chanlist.find(chan);
1233 if (iter == chanlist.end())
1234 /* Couldn't find it */
1237 return iter->second;
1241 void purge_empty_chans(void)
1243 int go_again = 1, purge = 0;
1248 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1251 if (!usercount(i->second))
1253 /* kill the record */
1254 if (i != chanlist.end())
1256 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1266 log(DEBUG,"skipped purge for %s",i->second->name);
1271 log(DEBUG,"completed channel purge, killed %d",purge);
1274 /* returns the status character for a given user on a channel, e.g. @ for op,
1275 * % for halfop etc. If the user has several modes set, the highest mode
1276 * the user has must be returned. */
1278 char* cmode(userrec *user, chanrec *chan)
1280 if ((!user) || (!chan))
1282 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1287 for (int i = 0; i != MAXCHANS; i++)
1289 if ((user->chans[i].channel == chan) && (chan != NULL))
1291 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1295 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1299 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1308 char scratch[MAXBUF];
1309 char sparam[MAXBUF];
1311 char* chanmodes(chanrec *chan)
1315 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1322 if (chan->noexternal)
1324 strncat(scratch,"n",MAXMODES);
1326 if (chan->topiclock)
1328 strncat(scratch,"t",MAXMODES);
1330 if (strcmp(chan->key,""))
1332 strncat(scratch,"k",MAXMODES);
1336 strncat(scratch,"l",MAXMODES);
1338 if (chan->inviteonly)
1340 strncat(scratch,"i",MAXMODES);
1342 if (chan->moderated)
1344 strncat(scratch,"m",MAXMODES);
1348 strncat(scratch,"s",MAXMODES);
1350 if (chan->c_private)
1352 strncat(scratch,"p",MAXMODES);
1354 if (strcmp(chan->key,""))
1356 strncat(sparam,chan->key,MAXBUF);
1361 sprintf(foo," %d",chan->limit);
1362 strncat(sparam,foo,MAXBUF);
1364 if (strlen(chan->custom_modes))
1366 strncat(scratch,chan->custom_modes,MAXMODES);
1367 for (int z = 0; z < strlen(chan->custom_modes); z++)
1369 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1372 strncat(sparam," ",MAXBUF);
1373 strncat(sparam,extparam.c_str(),MAXBUF);
1377 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1378 strncat(scratch,sparam,MAXMODES);
1382 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1383 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1384 * highest mode the user has must be returned. */
1386 int cstatus(userrec *user, chanrec *chan)
1388 if ((!chan) || (!user))
1390 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1394 for (int i = 0; i != MAXCHANS; i++)
1396 if ((user->chans[i].channel == chan) && (chan != NULL))
1398 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1402 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1406 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1408 return STATUS_VOICE;
1410 return STATUS_NORMAL;
1416 /* compile a userlist of a channel into a string, each nick seperated by
1417 * spaces and op, voice etc status shown as @ and + */
1419 void userlist(userrec *user,chanrec *c)
1421 if ((!c) || (!user))
1423 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1427 sprintf(list,"353 %s = %s :", user->nick, c->name);
1428 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1430 if (has_channel(i->second,c))
1432 if (isnick(i->second->nick))
1434 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1436 /* user is +i, and source not on the channel, does not show
1437 * nick in NAMES list */
1440 strcat(list,cmode(i->second,c));
1441 strcat(list,i->second->nick);
1443 if (strlen(list)>(480-NICKMAX))
1445 /* list overflowed into
1446 * multiple numerics */
1447 WriteServ(user->fd,list);
1448 sprintf(list,"353 %s = %s :", user->nick, c->name);
1453 /* if whats left in the list isnt empty, send it */
1454 if (list[strlen(list)-1] != ':')
1456 WriteServ(user->fd,list);
1460 /* return a count of the users on a specific channel accounting for
1461 * invisible users who won't increase the count. e.g. for /LIST */
1463 int usercount_i(chanrec *c)
1470 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1475 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1479 if (has_channel(i->second,c))
1481 if (isnick(i->second->nick))
1483 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1485 /* user is +i, and source not on the channel, does not show
1486 * nick in NAMES list */
1494 log(DEBUG,"usercount_i: %s %d",c->name,count);
1499 int usercount(chanrec *c)
1506 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1511 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1515 if (has_channel(i->second,c))
1517 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1524 log(DEBUG,"usercount: %s %d",c->name,count);
1529 /* add a channel to a user, creating the record for it if needed and linking
1530 * it to the user record */
1532 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1534 if ((!user) || (!cn))
1536 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1545 strncpy(cname,cn,MAXBUF);
1547 // we MUST declare this wherever we use FOREACH_RESULT
1550 if (strlen(cname) > CHANMAX-1)
1552 cname[CHANMAX-1] = '\0';
1555 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1557 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1559 return NULL; // already on the channel!
1563 if (!FindChan(cname))
1565 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1570 /* create a new one */
1571 log(DEBUG,"add_channel: creating: %s",cname);
1573 chanlist[cname] = new chanrec();
1575 strcpy(chanlist[cname]->name, cname);
1576 chanlist[cname]->topiclock = 1;
1577 chanlist[cname]->noexternal = 1;
1578 chanlist[cname]->created = time(NULL);
1579 strcpy(chanlist[cname]->topic, "");
1580 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1581 chanlist[cname]->topicset = 0;
1582 Ptr = chanlist[cname];
1583 log(DEBUG,"add_channel: created: %s",cname);
1584 /* set created to 2 to indicate user
1585 * is the first in the channel
1586 * and should be given ops */
1592 /* channel exists, just fish out a pointer to its struct */
1593 Ptr = FindChan(cname);
1596 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1598 // the override flag allows us to bypass channel modes
1599 // and bans (used by servers)
1602 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1607 if (strcmp(Ptr->key,""))
1609 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1612 log(DEBUG,"add_channel: no key given in JOIN");
1613 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1618 log(DEBUG,"key at %p is %s",key,key);
1619 if (strcasecmp(key,Ptr->key))
1621 log(DEBUG,"add_channel: bad key given in JOIN");
1622 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1627 log(DEBUG,"add_channel: no key");
1629 if (Ptr->inviteonly)
1631 log(DEBUG,"add_channel: channel is +i");
1632 if (user->IsInvited(Ptr->name))
1634 /* user was invited to channel */
1635 /* there may be an optional channel NOTICE here */
1639 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1643 log(DEBUG,"add_channel: channel is not +i");
1647 if (usercount(Ptr) == Ptr->limit)
1649 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1654 log(DEBUG,"add_channel: about to walk banlist");
1656 /* check user against the channel banlist */
1659 if (Ptr->bans.size())
1661 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1663 if (match(user->GetFullHost(),i->data))
1665 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1672 log(DEBUG,"add_channel: bans checked");
1675 if ((Ptr) && (user))
1677 user->RemoveInvite(Ptr->name);
1680 log(DEBUG,"add_channel: invites removed");
1685 log(DEBUG,"Overridden checks");
1693 log(DEBUG,"Passed channel checks");
1695 for (int i =0; i != MAXCHANS; i++)
1697 log(DEBUG,"Check location %d",i);
1698 if (user->chans[i].channel == NULL)
1700 log(DEBUG,"Adding into their channel list at location %d",i);
1704 /* first user in is given ops */
1705 user->chans[i].uc_modes = UCMODE_OP;
1709 user->chans[i].uc_modes = 0;
1711 user->chans[i].channel = Ptr;
1712 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1714 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1716 // use the stamdard J token with no privilages.
1717 char buffer[MAXBUF];
1718 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1719 NetSendToAll(buffer);
1722 log(DEBUG,"Sent JOIN to client");
1726 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1727 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1730 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1731 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1732 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1733 FOREACH_MOD OnUserJoin(user,Ptr);
1737 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1738 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1742 /* remove a channel from a users record, and remove the record from memory
1743 * if the channel has become empty */
1745 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1747 if ((!user) || (!cname))
1749 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1756 if ((!cname) || (!user))
1761 Ptr = FindChan(cname);
1768 FOREACH_MOD OnUserPart(user,Ptr);
1769 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1771 for (int i =0; i != MAXCHANS; i++)
1773 /* zap it from the channel list of the user */
1774 if (user->chans[i].channel == Ptr)
1778 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1782 char buffer[MAXBUF];
1783 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1784 NetSendToAll(buffer);
1793 char buffer[MAXBUF];
1794 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1795 NetSendToAll(buffer);
1798 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1800 user->chans[i].uc_modes = 0;
1801 user->chans[i].channel = NULL;
1802 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1807 /* if there are no users left on the channel */
1808 if (!usercount(Ptr))
1810 chan_hash::iterator iter = chanlist.find(Ptr->name);
1812 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1814 /* kill the record */
1815 if (iter != chanlist.end())
1817 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1818 delete iter->second;
1819 chanlist.erase(iter);
1825 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1827 if ((!src) || (!user) || (!Ptr) || (!reason))
1829 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1836 if ((!Ptr) || (!user) || (!src))
1841 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1843 if (!has_channel(user,Ptr))
1845 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1848 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1850 if (cstatus(src,Ptr) == STATUS_HOP)
1852 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1856 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1862 for (int i =0; i != MAXCHANS; i++)
1864 /* zap it from the channel list of the user */
1865 if (user->chans[i].channel)
1866 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1868 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1869 user->chans[i].uc_modes = 0;
1870 user->chans[i].channel = NULL;
1871 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1876 /* if there are no users left on the channel */
1877 if (!usercount(Ptr))
1879 chan_hash::iterator iter = chanlist.find(Ptr->name);
1881 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1883 /* kill the record */
1884 if (iter != chanlist.end())
1886 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1887 delete iter->second;
1888 chanlist.erase(iter);
1894 /* returns 1 if user u has channel c in their record, 0 if not */
1896 int has_channel(userrec *u, chanrec *c)
1900 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1903 for (int i =0; i != MAXCHANS; i++)
1905 if (u->chans[i].channel == c)
1913 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1918 if ((!user) || (!dest) || (!chan))
1920 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1923 if (status < STATUS_OP)
1925 log(DEBUG,"%s cant give ops to %s because they nave status %d and needs %d",user->nick,dest,status,STATUS_OP);
1926 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1933 log(DEFAULT,"the target nickname given to give_ops was invalid");
1934 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1940 log(DEFAULT,"the target nickname given to give_ops couldnt be found");
1941 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1946 for (int i = 0; i != MAXCHANS; i++)
1948 if ((d->chans[i].channel != NULL) && (chan != NULL))
1949 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1951 if (d->chans[i].uc_modes & UCMODE_OP)
1953 /* mode already set on user, dont allow multiple */
1954 log(DEFAULT,"The target user given to give_ops was already opped on the channel");
1957 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1958 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1962 log(DEFAULT,"The target channel given to give_ops was not in the users mode list");
1968 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1973 if ((!user) || (!dest) || (!chan))
1975 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1978 if (status != STATUS_OP)
1980 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1988 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1993 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1998 for (int i = 0; i != MAXCHANS; i++)
2000 if ((d->chans[i].channel != NULL) && (chan != NULL))
2001 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2003 if (d->chans[i].uc_modes & UCMODE_HOP)
2005 /* mode already set on user, dont allow multiple */
2008 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
2009 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
2018 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
2023 if ((!user) || (!dest) || (!chan))
2025 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
2028 if (status < STATUS_HOP)
2030 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2038 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2043 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2048 for (int i = 0; i != MAXCHANS; i++)
2050 if ((d->chans[i].channel != NULL) && (chan != NULL))
2051 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2053 if (d->chans[i].uc_modes & UCMODE_VOICE)
2055 /* mode already set on user, dont allow multiple */
2058 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
2059 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
2068 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
2073 if ((!user) || (!dest) || (!chan))
2075 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
2078 if (status < STATUS_OP)
2080 log(DEBUG,"%s cant give ops to %s because they have status %d and needs %d",user->nick,dest,status,STATUS_OP);
2081 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2089 log(DEBUG,"take_ops was given an invalid target nickname of %s",dest);
2090 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2095 log(DEBUG,"take_ops couldnt resolve the target nickname: %s",dest);
2096 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2101 for (int i = 0; i != MAXCHANS; i++)
2103 if ((d->chans[i].channel != NULL) && (chan != NULL))
2104 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2106 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
2108 /* mode already set on user, dont allow multiple */
2111 d->chans[i].uc_modes ^= UCMODE_OP;
2112 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
2116 log(DEBUG,"take_ops couldnt locate the target channel in the target users list");
2122 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
2127 if ((!user) || (!dest) || (!chan))
2129 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
2132 if (status != STATUS_OP)
2134 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2142 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2147 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2152 for (int i = 0; i != MAXCHANS; i++)
2154 if ((d->chans[i].channel != NULL) && (chan != NULL))
2155 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2157 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
2159 /* mode already set on user, dont allow multiple */
2162 d->chans[i].uc_modes ^= UCMODE_HOP;
2163 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
2172 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
2177 if ((!user) || (!dest) || (!chan))
2179 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
2182 if (status < STATUS_HOP)
2184 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2192 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2197 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2202 for (int i = 0; i != MAXCHANS; i++)
2204 if ((d->chans[i].channel != NULL) && (chan != NULL))
2205 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2207 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
2209 /* mode already set on user, dont allow multiple */
2212 d->chans[i].uc_modes ^= UCMODE_VOICE;
2213 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
2222 void TidyBan(char *ban)
2225 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
2229 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
2233 char* pos_of_pling = strchr(temp,'!');
2234 char* pos_of_at = strchr(temp,'@');
2236 pos_of_pling[0] = '\0';
2237 pos_of_at[0] = '\0';
2241 strncpy(NICK,temp,NICKMAX);
2242 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
2243 strncpy(HOST,pos_of_at,160);
2245 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
2248 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
2250 if ((!user) || (!dest) || (!chan)) {
2251 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
2256 if ((!user) || (!dest) || (!chan))
2258 if (strchr(dest,'!')==0)
2260 if (strchr(dest,'@')==0)
2262 for (int i = 0; i < strlen(dest); i++)
2265 for (int i = 0; i < strlen(dest); i++)
2269 for (int i = 0; i < strlen(dest); i++)
2275 for (int i = 0; i < strlen(dest); i++)
2280 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2283 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2285 if (!strcasecmp(i->data,dest))
2287 // dont allow a user to set the same ban twice
2292 b.set_time = time(NULL);
2293 strncpy(b.data,dest,MAXBUF);
2294 strncpy(b.set_by,user->nick,NICKMAX);
2295 chan->bans.push_back(b);
2299 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2301 if ((!user) || (!dest) || (!chan)) {
2302 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2306 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2307 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2309 if (!strcasecmp(i->data,dest))
2311 chan->bans.erase(i);
2318 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode, bool silent, bool local)
2321 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2325 char modelist[MAXBUF];
2326 char outlist[MAXBUF];
2327 char outstr[MAXBUF];
2328 char outpars[32][MAXBUF];
2334 bool k_set = false, l_set = false;
2341 log(DEBUG,"process_modes: start: parameters=%d",pcnt);
2343 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2344 /* parameters[2] onwards are parameters for
2345 * modes that require them :) */
2346 strcpy(outlist,"+");
2349 log(DEBUG,"process_modes: modelist: %s",modelist);
2351 for (ptr = 0; ptr < strlen(modelist); ptr++)
2356 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2357 char modechar = modelist[ptr];
2358 switch (modelist[ptr])
2363 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2365 outlist[strlen(outlist)-1] = '-';
2369 strcat(outlist,"-");
2379 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2381 outlist[strlen(outlist)-1] = '+';
2385 strcat(outlist,"+");
2393 if ((param >= pcnt)) break;
2394 log(DEBUG,"Enough parameters left");
2397 log(DEBUG,"calling give_ops");
2398 r = give_ops(user,parameters[param++],chan,status);
2402 log(DEBUG,"calling take_ops");
2403 r = take_ops(user,parameters[param++],chan,status);
2407 strcat(outlist,"o");
2408 strcpy(outpars[pc++],parameters[param-1]);
2413 if ((param >= pcnt)) break;
2416 r = give_hops(user,parameters[param++],chan,status);
2420 r = take_hops(user,parameters[param++],chan,status);
2424 strcat(outlist,"h");
2425 strcpy(outpars[pc++],parameters[param-1]);
2431 if ((param >= pcnt)) break;
2434 r = give_voice(user,parameters[param++],chan,status);
2438 r = take_voice(user,parameters[param++],chan,status);
2442 strcat(outlist,"v");
2443 strcpy(outpars[pc++],parameters[param-1]);
2448 if ((param >= pcnt)) break;
2451 r = add_ban(user,parameters[param++],chan,status);
2455 r = take_ban(user,parameters[param++],chan,status);
2459 strcat(outlist,"b");
2460 strcpy(outpars[pc++],parameters[param-1]);
2466 if ((param >= pcnt))
2474 if (!strcmp(chan->key,""))
2476 strcat(outlist,"k");
2478 strcpy(key,parameters[param++]);
2479 if (strlen(key)>32) {
2482 strcpy(outpars[pc++],key);
2483 strcpy(chan->key,key);
2489 /* checks on -k are case sensitive and only accurate to the
2490 first 32 characters */
2492 strcpy(key,parameters[param++]);
2493 if (strlen(key)>32) {
2496 /* only allow -k if correct key given */
2497 if (!strcmp(chan->key,key))
2499 strcat(outlist,"k");
2500 strcpy(chan->key,"");
2501 strcpy(outpars[pc++],key);
2511 strcat(outlist,"l");
2516 if ((param >= pcnt)) break;
2522 bool invalid = false;
2523 for (int i = 0; i < strlen(parameters[param]); i++)
2525 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2530 if (atoi(parameters[param]) < 1)
2538 chan->limit = atoi(parameters[param]);
2541 strcat(outlist,"l");
2542 strcpy(outpars[pc++],parameters[param++]);
2549 if (chan->inviteonly != mdir)
2551 strcat(outlist,"i");
2553 chan->inviteonly = mdir;
2557 if (chan->topiclock != mdir)
2559 strcat(outlist,"t");
2561 chan->topiclock = mdir;
2565 if (chan->noexternal != mdir)
2567 strcat(outlist,"n");
2569 chan->noexternal = mdir;
2573 if (chan->moderated != mdir)
2575 strcat(outlist,"m");
2577 chan->moderated = mdir;
2581 if (chan->secret != mdir)
2583 strcat(outlist,"s");
2584 if (chan->c_private)
2586 chan->c_private = 0;
2589 strcat(outlist,"-p+");
2593 strcat(outlist,"+p-");
2597 chan->secret = mdir;
2601 if (chan->c_private != mdir)
2603 strcat(outlist,"p");
2609 strcat(outlist,"-s+");
2613 strcat(outlist,"+s-");
2617 chan->c_private = mdir;
2621 log(DEBUG,"Preprocessing custom mode %c",modechar);
2624 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2626 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2629 if (ModeDefined(modechar,MT_CHANNEL))
2631 log(DEBUG,"A module has claimed this mode");
2634 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2636 p.push_back(parameters[param]);
2638 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2640 p.push_back(parameters[param]);
2643 bool handled = false;
2646 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2647 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2648 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2654 for (int i = 0; i <= MODCOUNT; i++)
2658 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2660 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2661 char app[] = {modechar, 0};
2664 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2666 strcat(outlist, app);
2668 else if (!strchr(outlist,modechar))
2670 strcat(outlist, app);
2673 chan->SetCustomMode(modechar,mdir);
2674 // include parameters in output if mode has them
2675 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2677 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2678 strcpy(outpars[pc++],parameters[param++]);
2680 // break, because only one module can handle the mode.
2692 /* this ensures only the *valid* modes are sent out onto the network */
2693 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2695 outlist[strlen(outlist)-1] = '\0';
2697 if (strcmp(outlist,""))
2699 strcpy(outstr,outlist);
2700 for (ptr = 0; ptr < pc; ptr++)
2703 strcat(outstr,outpars[ptr]);
2707 log(DEBUG,"Local mode change");
2708 WriteChannelLocal(chan, user, "MODE %s %s",chan->name,outstr);
2716 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2717 // M token for a usermode must go to all servers
2718 char buffer[MAXBUF];
2719 snprintf(buffer,MAXBUF,"M %s %s",chan->name, outstr);
2720 NetSendToAll(buffer);
2728 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2729 // M token for a usermode must go to all servers
2730 char buffer[MAXBUF];
2731 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick,chan->name, outstr);
2732 NetSendToAll(buffer);
2739 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2741 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2743 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2744 // RFC1459 specified modes
2745 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2747 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2751 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2752 if ((strchr(sourcemodes,'o')) && (!adding))
2754 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2757 else if (umode == 'o')
2759 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2763 // process any module-defined modes that need oper
2764 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2766 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2770 if (ModeDefined(umode,MT_CLIENT))
2772 // process any module-defined modes that don't need oper
2773 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2774 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2776 // no, this mode needs oper, and this user 'aint got what it takes!
2782 // anything else - return false.
2783 log(DEBUG,"umode %c not known by any ruleset",umode);
2787 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2794 strncpy(s2->nick,ServerName,NICKMAX);
2795 strcpy(s2->modes,"o");
2802 if (ModeDefined(umode,MT_CLIENT))
2804 for (int i = 0; i <= MODCOUNT; i++)
2806 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2808 log(DEBUG,"Module claims umode %c",umode);
2812 log(DEBUG,"No module claims umode %c",umode);
2831 void handle_mode(char **parameters, int pcnt, userrec *user)
2837 char outpars[MAXBUF];
2839 dest = Find(parameters[0]);
2846 if ((dest) && (pcnt == 1))
2848 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2852 if ((dest) && (pcnt > 1))
2854 char dmodes[MAXBUF];
2855 strncpy(dmodes,dest->modes,MAXBUF);
2856 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2861 if (strchr(user->modes,'o'))
2872 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2876 strcpy(outpars,"+");
2879 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2882 for (int i = 0; i < strlen(parameters[1]); i++)
2884 if (parameters[1][i] == '+')
2888 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2890 outpars[strlen(outpars)-1] = '+';
2894 strcat(outpars,"+");
2900 if (parameters[1][i] == '-')
2904 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2906 outpars[strlen(outpars)-1] = '-';
2910 strcat(outpars,"-");
2918 if (strchr(user->modes,'o'))
2924 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2933 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2935 char umode = parameters[1][i];
2936 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2938 dmodes[strlen(dmodes)+1]='\0';
2939 dmodes[strlen(dmodes)] = parameters[1][i];
2940 outpars[strlen(outpars)+1]='\0';
2941 outpars[strlen(outpars)] = parameters[1][i];
2947 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2949 char umode = parameters[1][i];
2950 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2956 outpars[strlen(outpars)+1]='\0';
2957 outpars[strlen(outpars)] = parameters[1][i];
2960 for (q = 0; q < strlen(dmodes); q++)
2962 if (dmodes[q] != parameters[1][i])
2969 strcpy(dmodes,temp);
2976 if (strlen(outpars))
2982 while (i < strlen (outpars))
2984 b[z++] = outpars[i++];
2986 if (i<strlen(outpars)-1)
2988 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2990 // someones playing silly buggers and trying
2991 // to put a +- or -+ into the line...
2995 if (i == strlen(outpars)-1)
2997 if ((outpars[i] == '-') || (outpars[i] == '+'))
3005 if ((b[z] == '-') || (b[z] == '+'))
3008 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3011 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3013 // M token for a usermode must go to all servers
3014 char buffer[MAXBUF];
3015 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3016 NetSendToAll(buffer);
3018 if (strlen(dmodes)>MAXMODES)
3020 dmodes[MAXMODES-1] = '\0';
3022 log(DEBUG,"Stripped mode line");
3023 log(DEBUG,"Line dest is now %s",dmodes);
3024 strncpy(dest->modes,dmodes,MAXMODES);
3031 Ptr = FindChan(parameters[0]);
3036 /* just /modes #channel */
3037 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
3038 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
3044 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
3047 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
3049 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
3051 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
3056 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3058 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
3062 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,false);
3066 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3073 void server_mode(char **parameters, int pcnt, userrec *user)
3079 char outpars[MAXBUF];
3081 dest = Find(parameters[0]);
3083 // fix: ChroNiCk found this - we cant use this as debug if its null!
3086 log(DEBUG,"server_mode on %s",dest->nick);
3089 if ((dest) && (pcnt > 1))
3091 log(DEBUG,"params > 1");
3093 char dmodes[MAXBUF];
3094 strncpy(dmodes,dest->modes,MAXBUF);
3096 strcpy(outpars,"+");
3099 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3102 for (int i = 0; i < strlen(parameters[1]); i++)
3104 if (parameters[1][i] == '+')
3108 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3110 outpars[strlen(outpars)-1] = '+';
3114 strcat(outpars,"+");
3120 if (parameters[1][i] == '-')
3124 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3126 outpars[strlen(outpars)-1] = '-';
3130 strcat(outpars,"-");
3137 log(DEBUG,"begin mode processing entry");
3143 log(DEBUG,"umode %c being added",parameters[1][i]);
3144 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3146 char umode = parameters[1][i];
3147 log(DEBUG,"umode %c is an allowed umode",umode);
3148 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3150 dmodes[strlen(dmodes)+1]='\0';
3151 dmodes[strlen(dmodes)] = parameters[1][i];
3152 outpars[strlen(outpars)+1]='\0';
3153 outpars[strlen(outpars)] = parameters[1][i];
3159 // can only remove a mode they already have
3160 log(DEBUG,"umode %c being removed",parameters[1][i]);
3161 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3163 char umode = parameters[1][i];
3164 log(DEBUG,"umode %c is an allowed umode",umode);
3165 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3171 outpars[strlen(outpars)+1]='\0';
3172 outpars[strlen(outpars)] = parameters[1][i];
3175 for (q = 0; q < strlen(dmodes); q++)
3177 if (dmodes[q] != parameters[1][i])
3184 strcpy(dmodes,temp);
3191 if (strlen(outpars))
3197 while (i < strlen (outpars))
3199 b[z++] = outpars[i++];
3201 if (i<strlen(outpars)-1)
3203 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3205 // someones playing silly buggers and trying
3206 // to put a +- or -+ into the line...
3210 if (i == strlen(outpars)-1)
3212 if ((outpars[i] == '-') || (outpars[i] == '+'))
3220 if ((b[z] == '-') || (b[z] == '+'))
3223 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3226 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3228 // M token for a usermode must go to all servers
3229 char buffer[MAXBUF];
3230 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3231 NetSendToAll(buffer);
3233 if (strlen(dmodes)>MAXMODES)
3235 dmodes[MAXMODES-1] = '\0';
3237 log(DEBUG,"Stripped mode line");
3238 log(DEBUG,"Line dest is now %s",dmodes);
3239 strncpy(dest->modes,dmodes,MAXMODES);
3246 Ptr = FindChan(parameters[0]);
3249 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true,false,false);
3253 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3259 void merge_mode(char **parameters, int pcnt)
3265 char outpars[MAXBUF];
3267 dest = Find(parameters[0]);
3269 // fix: ChroNiCk found this - we cant use this as debug if its null!
3272 log(DEBUG,"merge_mode on %s",dest->nick);
3275 if ((dest) && (pcnt > 1))
3277 log(DEBUG,"params > 1");
3279 char dmodes[MAXBUF];
3280 strncpy(dmodes,dest->modes,MAXBUF);
3282 strcpy(outpars,"+");
3285 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3288 for (int i = 0; i < strlen(parameters[1]); i++)
3290 if (parameters[1][i] == '+')
3294 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3296 outpars[strlen(outpars)-1] = '+';
3300 strcat(outpars,"+");
3306 if (parameters[1][i] == '-')
3310 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3312 outpars[strlen(outpars)-1] = '-';
3316 strcat(outpars,"-");
3323 log(DEBUG,"begin mode processing entry");
3329 log(DEBUG,"umode %c being added",parameters[1][i]);
3330 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],"o",true)))
3332 char umode = parameters[1][i];
3333 log(DEBUG,"umode %c is an allowed umode",umode);
3334 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3336 dmodes[strlen(dmodes)+1]='\0';
3337 dmodes[strlen(dmodes)] = parameters[1][i];
3338 outpars[strlen(outpars)+1]='\0';
3339 outpars[strlen(outpars)] = parameters[1][i];
3345 // can only remove a mode they already have
3346 log(DEBUG,"umode %c being removed",parameters[1][i]);
3347 if ((allowed_umode(parameters[1][i],"o",false)) && (strchr(dmodes,parameters[1][i])))
3349 char umode = parameters[1][i];
3350 log(DEBUG,"umode %c is an allowed umode",umode);
3351 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3357 outpars[strlen(outpars)+1]='\0';
3358 outpars[strlen(outpars)] = parameters[1][i];
3361 for (q = 0; q < strlen(dmodes); q++)
3363 if (dmodes[q] != parameters[1][i])
3370 strcpy(dmodes,temp);
3377 if (strlen(outpars))
3383 while (i < strlen (outpars))
3385 b[z++] = outpars[i++];
3387 if (i<strlen(outpars)-1)
3389 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3391 // someones playing silly buggers and trying
3392 // to put a +- or -+ into the line...
3396 if (i == strlen(outpars)-1)
3398 if ((outpars[i] == '-') || (outpars[i] == '+'))
3406 if ((b[z] == '-') || (b[z] == '+'))
3409 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3412 if (strlen(dmodes)>MAXMODES)
3414 dmodes[MAXMODES-1] = '\0';
3416 log(DEBUG,"Stripped mode line");
3417 log(DEBUG,"Line dest is now %s",dmodes);
3418 strncpy(dest->modes,dmodes,MAXMODES);
3425 Ptr = FindChan(parameters[0]);
3429 strncpy(s2.nick,ServerName,NICKMAX);
3430 strcpy(s2.modes,"o");
3432 process_modes(parameters,&s2,Ptr,STATUS_OP,pcnt,true,true,false);
3437 void merge_mode2(char **parameters, int pcnt, userrec* user)
3443 char outpars[MAXBUF];
3445 dest = Find(parameters[0]);
3447 // fix: ChroNiCk found this - we cant use this as debug if its null!
3450 log(DEBUG,"merge_mode on %s",dest->nick);
3453 if ((dest) && (pcnt > 1))
3455 log(DEBUG,"params > 1");
3457 char dmodes[MAXBUF];
3458 strncpy(dmodes,dest->modes,MAXBUF);
3460 strcpy(outpars,"+");
3463 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3466 for (int i = 0; i < strlen(parameters[1]); i++)
3468 if (parameters[1][i] == '+')
3472 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3474 outpars[strlen(outpars)-1] = '+';
3478 strcat(outpars,"+");
3484 if (parameters[1][i] == '-')
3488 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3490 outpars[strlen(outpars)-1] = '-';
3494 strcat(outpars,"-");
3501 log(DEBUG,"begin mode processing entry");
3507 log(DEBUG,"umode %c being added",parameters[1][i]);
3508 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3510 char umode = parameters[1][i];
3511 log(DEBUG,"umode %c is an allowed umode",umode);
3512 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3514 dmodes[strlen(dmodes)+1]='\0';
3515 dmodes[strlen(dmodes)] = parameters[1][i];
3516 outpars[strlen(outpars)+1]='\0';
3517 outpars[strlen(outpars)] = parameters[1][i];
3523 // can only remove a mode they already have
3524 log(DEBUG,"umode %c being removed",parameters[1][i]);
3525 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3527 char umode = parameters[1][i];
3528 log(DEBUG,"umode %c is an allowed umode",umode);
3529 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3535 outpars[strlen(outpars)+1]='\0';
3536 outpars[strlen(outpars)] = parameters[1][i];
3539 for (q = 0; q < strlen(dmodes); q++)
3541 if (dmodes[q] != parameters[1][i])
3548 strcpy(dmodes,temp);
3555 if (strlen(outpars))
3561 while (i < strlen (outpars))
3563 b[z++] = outpars[i++];
3565 if (i<strlen(outpars)-1)
3567 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3569 // someones playing silly buggers and trying
3570 // to put a +- or -+ into the line...
3574 if (i == strlen(outpars)-1)
3576 if ((outpars[i] == '-') || (outpars[i] == '+'))
3584 if ((b[z] == '-') || (b[z] == '+'))
3587 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3590 WriteTo(user,dest,"MODE :%s",b);
3592 if (strlen(dmodes)>MAXMODES)
3594 dmodes[MAXMODES-1] = '\0';
3596 log(DEBUG,"Stripped mode line");
3597 log(DEBUG,"Line dest is now %s",dmodes);
3598 strncpy(dest->modes,dmodes,MAXMODES);
3605 Ptr = FindChan(parameters[0]);
3608 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3613 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,true);
3619 /* This function pokes and hacks at a parameter list like the following:
3621 * PART #winbot, #darkgalaxy :m00!
3623 * to turn it into a series of individual calls like this:
3625 * PART #winbot :m00!
3626 * PART #darkgalaxy :m00!
3628 * The seperate calls are sent to a callback function provided by the caller
3629 * (the caller will usually call itself recursively). The callback function
3630 * must be a command handler. Calling this function on a line with no list causes
3631 * no action to be taken. You must provide a starting and ending parameter number
3632 * where the range of the list can be found, useful if you have a terminating
3633 * parameter as above which is actually not part of the list, or parameters
3634 * before the actual list as well. This code is used by many functions which
3635 * can function as "one to list" (see the RFC) */
3637 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
3642 char blog[32][MAXBUF];
3643 char blog2[32][MAXBUF];
3644 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
3645 char keystr[MAXBUF];
3648 for (int i = 0; i <32; i++)
3651 for (int i = 0; i <32; i++)
3652 strcpy(blog2[i],"");
3655 for (int i = 0; i <10; i++)
3659 parameters[i] = moo;
3664 if (pcnt > 1) /* we have a key to copy */
3666 strcpy(keystr,parameters[1]);
3670 if (!parameters[start])
3674 if (!strchr(parameters[start],','))
3679 for (int i = start; i <= end; i++)
3683 strcat(plist,parameters[i]);
3691 for (int i = 0; i < t; i++)
3693 if (plist[i] == ',')
3696 strcpy(blog[j++],param);
3700 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3705 strcpy(blog[j++],param);
3708 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3713 if ((joins) && (keystr))
3715 if (strchr(keystr,','))
3719 t2 = strlen(keystr);
3720 for (int i = 0; i < t2; i++)
3722 if (keystr[i] == ',')
3725 strcpy(blog2[j++],param);
3729 strcpy(blog2[j++],param);
3734 for (j = 0; j < total; j++)
3740 for (q = end; q < pcnt-1; q++)
3742 if (parameters[q+1])
3744 pars[q-end+1] = parameters[q+1];
3747 if ((joins) && (parameters[1]))
3758 /* repeatedly call the function with the hacked parameter list */
3759 if ((joins) && (pcnt > 1))
3763 // pars[1] already set up and containing key from blog2[j]
3768 pars[1] = parameters[1];
3774 fn(pars,pcnt-(end-start),u);
3782 void handle_join(char **parameters, int pcnt, userrec *user)
3787 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3789 if (parameters[0][0] == '#')
3791 Ptr = add_channel(user,parameters[0],parameters[1],false);
3796 void handle_part(char **parameters, int pcnt, userrec *user)
3802 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3804 del_channel(user,parameters[0],parameters[1],false);
3808 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3810 del_channel(user,parameters[0],NULL,false);
3814 void handle_kick(char **parameters, int pcnt, userrec *user)
3816 chanrec* Ptr = FindChan(parameters[0]);
3817 userrec* u = Find(parameters[1]);
3821 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3825 if (!has_channel(u,Ptr))
3827 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3831 char reason[MAXBUF];
3835 strncpy(reason,parameters[2],MAXBUF);
3836 if (strlen(reason)>MAXKICK)
3838 reason[MAXKICK-1] = '\0';
3841 kick_channel(user,u,Ptr,reason);
3845 strcpy(reason,user->nick);
3846 kick_channel(user,u,Ptr,reason);
3849 // this must be propogated so that channel membership is kept in step network-wide
3851 char buffer[MAXBUF];
3852 snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
3853 NetSendToAll(buffer);
3857 void handle_die(char **parameters, int pcnt, userrec *user)
3859 log(DEBUG,"die: %s",user->nick);
3860 if (!strcmp(parameters[0],diepass))
3862 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3868 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3872 void handle_restart(char **parameters, int pcnt, userrec *user)
3874 log(DEBUG,"restart: %s",user->nick);
3875 if (!strcmp(parameters[0],restartpass))
3877 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3880 /* Will finish this later when i can be arsed :) */
3884 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3889 void kill_link(userrec *user,const char* r)
3891 user_hash::iterator iter = clientlist.find(user->nick);
3893 char reason[MAXBUF];
3895 strncpy(reason,r,MAXBUF);
3897 if (strlen(reason)>MAXQUIT)
3899 reason[MAXQUIT-1] = '\0';
3902 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3903 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3904 log(DEBUG,"closing fd %d",user->fd);
3906 /* bugfix, cant close() a nonblocking socket (sux!) */
3907 if (user->registered == 7) {
3908 FOREACH_MOD OnUserQuit(user);
3909 WriteCommonExcept(user,"QUIT :%s",reason);
3911 // Q token must go to ALL servers!!!
3912 char buffer[MAXBUF];
3913 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
3914 NetSendToAll(buffer);
3917 /* push the socket on a stack of sockets due to be closed at the next opportunity
3918 * 'Client exited' is an exception to this as it means the client side has already
3919 * closed the socket, we don't need to do it.
3921 fd_reap.push_back(user->fd);
3923 bool do_purge = false;
3925 if (user->registered == 7) {
3926 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3930 if (iter != clientlist.end())
3932 log(DEBUG,"deleting user hash value %d",iter->second);
3933 if ((iter->second) && (user->registered == 7)) {
3934 delete iter->second;
3936 clientlist.erase(iter);
3939 if (user->registered == 7) {
3940 purge_empty_chans();
3945 void handle_kill(char **parameters, int pcnt, userrec *user)
3947 userrec *u = Find(parameters[0]);
3948 char killreason[MAXBUF];
3950 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3953 if (strcmp(ServerName,u->server))
3956 WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3957 sprintf(killreason,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
3958 WriteCommonExcept(u,"QUIT :%s",killreason);
3959 // K token must go to ALL servers!!!
3960 char buffer[MAXBUF];
3961 snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
3962 NetSendToAll(buffer);
3964 user_hash::iterator iter = clientlist.find(u->nick);
3965 if (iter != clientlist.end())
3967 log(DEBUG,"deleting user hash value %d",iter->second);
3968 if ((iter->second) && (user->registered == 7)) {
3969 delete iter->second;
3971 clientlist.erase(iter);
3973 purge_empty_chans();
3978 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3979 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3980 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3981 kill_link(u,killreason);
3986 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3990 void handle_summon(char **parameters, int pcnt, userrec *user)
3992 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3995 void handle_users(char **parameters, int pcnt, userrec *user)
3997 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
4001 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
4003 char* Passwd(userrec *user)
4005 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4007 if (match(user->host,i->host) && (i->type == CC_ALLOW))
4015 bool IsDenied(userrec *user)
4017 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4019 if (match(user->host,i->host) && (i->type == CC_DENY))
4029 void handle_pass(char **parameters, int pcnt, userrec *user)
4031 // Check to make sure they havnt registered -- Fix by FCS
4032 if (user->registered == 7)
4034 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4037 if (!strcasecmp(parameters[0],Passwd(user)))
4039 user->haspassed = true;
4043 void handle_invite(char **parameters, int pcnt, userrec *user)
4045 userrec* u = Find(parameters[0]);
4046 chanrec* c = FindChan(parameters[1]);
4052 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
4058 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
4067 if (cstatus(user,c) < STATUS_HOP)
4069 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
4073 if (has_channel(u,c))
4075 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
4078 if (!has_channel(user,c))
4080 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
4083 u->InviteTo(c->name);
4084 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
4085 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
4087 // i token must go to ALL servers!!!
4088 char buffer[MAXBUF];
4089 snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
4090 NetSendToAll(buffer);
4093 void handle_topic(char **parameters, int pcnt, userrec *user)
4099 if (strlen(parameters[0]) <= CHANMAX)
4101 Ptr = FindChan(parameters[0]);
4106 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
4107 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
4111 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
4116 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4123 if (strlen(parameters[0]) <= CHANMAX)
4125 Ptr = FindChan(parameters[0]);
4128 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
4130 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
4135 strncpy(topic,parameters[1],MAXBUF);
4136 if (strlen(topic)>MAXTOPIC)
4138 topic[MAXTOPIC-1] = '\0';
4141 strcpy(Ptr->topic,topic);
4142 strcpy(Ptr->setby,user->nick);
4143 Ptr->topicset = time(NULL);
4144 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
4146 // t token must go to ALL servers!!!
4147 char buffer[MAXBUF];
4148 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
4149 NetSendToAll(buffer);
4153 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4159 /* sends out an error notice to all connected clients (not to be used
4162 void send_error(char *s)
4164 log(DEBUG,"send_error: %s",s);
4165 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4167 if (isnick(i->second->nick))
4169 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
4173 // fix - unregistered connections receive ERROR, not NOTICE
4174 Write(i->second->fd,"ERROR :%s",s);
4179 void Error(int status)
4181 signal (SIGALRM, SIG_IGN);
4182 signal (SIGPIPE, SIG_IGN);
4183 signal (SIGTERM, SIG_IGN);
4184 signal (SIGABRT, SIG_IGN);
4185 signal (SIGSEGV, SIG_IGN);
4186 signal (SIGURG, SIG_IGN);
4187 signal (SIGKILL, SIG_IGN);
4188 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
4189 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
4194 int main(int argc, char *argv[])
4198 log(DEBUG,"*** InspIRCd starting up!");
4199 if (!FileExists(CONFIG_FILE))
4201 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
4202 log(DEBUG,"main: no config");
4203 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
4207 if (!strcmp(argv[1],"-nofork")) {
4211 if (InspIRCd() == ERROR)
4213 log(DEBUG,"main: daemon function bailed");
4214 printf("ERROR: could not initialise. Shutting down.\n");
4221 template<typename T> inline string ConvToStr(const T &in)
4224 if (!(tmp << in)) return string();
4228 /* re-allocates a nick in the user_hash after they change nicknames,
4229 * returns a pointer to the new user as it may have moved */
4231 userrec* ReHashNick(char* Old, char* New)
4233 user_hash::iterator newnick;
4234 user_hash::iterator oldnick = clientlist.find(Old);
4236 log(DEBUG,"ReHashNick: %s %s",Old,New);
4238 if (!strcasecmp(Old,New))
4240 log(DEBUG,"old nick is new nick, skipping");
4241 return oldnick->second;
4244 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
4246 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
4248 clientlist[New] = new userrec();
4249 clientlist[New] = oldnick->second;
4250 /*delete oldnick->second; */
4251 clientlist.erase(oldnick);
4253 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
4255 return clientlist[New];
4258 /* adds or updates an entry in the whowas list */
4259 void AddWhoWas(userrec* u)
4261 user_hash::iterator iter = whowas.find(u->nick);
4262 userrec *a = new userrec();
4263 strcpy(a->nick,u->nick);
4264 strcpy(a->ident,u->ident);
4265 strcpy(a->dhost,u->dhost);
4266 strcpy(a->host,u->host);
4267 strcpy(a->fullname,u->fullname);
4268 strcpy(a->server,u->server);
4269 a->signon = u->signon;
4271 /* MAX_WHOWAS: max number of /WHOWAS items
4272 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
4273 * can be replaced by a newer one
4276 if (iter == whowas.end())
4278 if (whowas.size() == WHOWAS_MAX)
4280 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
4282 // 3600 seconds in an hour ;)
4283 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
4287 log(DEBUG,"added WHOWAS entry, purged an old record");
4294 log(DEBUG,"added fresh WHOWAS entry");
4295 whowas[a->nick] = a;
4300 log(DEBUG,"updated WHOWAS entry");
4301 delete iter->second;
4307 /* add a client connection to the sockets list */
4308 void AddClient(int socket, char* host, int port, bool iscached)
4312 char resolved[MAXBUF];
4315 user_hash::iterator iter;
4317 tempnick = ConvToStr(socket) + "-unknown";
4318 sprintf(tn2,"%d-unknown",socket);
4320 iter = clientlist.find(tempnick);
4322 if (iter != clientlist.end()) return;
4325 * It is OK to access the value here this way since we know
4326 * it exists, we just created it above.
4328 * At NO other time should you access a value in a map or a
4329 * hash_map this way.
4331 clientlist[tempnick] = new userrec();
4333 NonBlocking(socket);
4334 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
4336 clientlist[tempnick]->fd = socket;
4337 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
4338 strncpy(clientlist[tempnick]->host, host,160);
4339 strncpy(clientlist[tempnick]->dhost, host,160);
4340 strncpy(clientlist[tempnick]->server, ServerName,256);
4341 strncpy(clientlist[tempnick]->ident, "unknown",9);
4342 clientlist[tempnick]->registered = 0;
4343 clientlist[tempnick]->signon = time(NULL);
4344 clientlist[tempnick]->nping = time(NULL)+240;
4345 clientlist[tempnick]->lastping = 1;
4346 clientlist[tempnick]->port = port;
4350 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
4354 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
4357 // set the registration timeout for this user
4358 unsigned long class_regtimeout = 90;
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_regtimeout = (unsigned long)i->registration_timeout;
4368 int class_flood = 0;
4369 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4371 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4373 class_flood = i->flood;
4378 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
4379 clientlist[tempnick]->flood = class_flood;
4381 for (int i = 0; i < MAXCHANS; i++)
4383 clientlist[tempnick]->chans[i].channel = NULL;
4384 clientlist[tempnick]->chans[i].uc_modes = 0;
4387 if (clientlist.size() == MAXCLIENTS)
4388 kill_link(clientlist[tempnick],"No more connections allowed in this class");
4391 void handle_names(char **parameters, int pcnt, userrec *user)
4395 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
4397 c = FindChan(parameters[0]);
4400 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
4402 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
4406 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4410 void handle_privmsg(char **parameters, int pcnt, userrec *user)
4415 user->idle_lastmsg = time(NULL);
4417 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
4419 if (parameters[0][0] == '#')
4421 chan = FindChan(parameters[0]);
4424 if ((chan->noexternal) && (!has_channel(user,chan)))
4426 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4429 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4431 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4437 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4442 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
4444 // if any users of this channel are on remote servers, broadcast the packet
4445 char buffer[MAXBUF];
4446 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
4447 NetSendToCommon(user,buffer);
4451 /* no such nick/channel */
4452 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4457 dest = Find(parameters[0]);
4460 if (strcmp(dest->awaymsg,""))
4462 /* auto respond with aweh msg */
4463 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
4468 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
4475 if (!strcmp(dest->server,user->server))
4477 // direct write, same server
4478 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
4482 char buffer[MAXBUF];
4483 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
4484 NetSendToOne(dest->server,buffer);
4489 /* no such nick/channel */
4490 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4494 void handle_notice(char **parameters, int pcnt, userrec *user)
4499 user->idle_lastmsg = time(NULL);
4501 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
4503 if (parameters[0][0] == '#')
4505 chan = FindChan(parameters[0]);
4508 if ((chan->noexternal) && (!has_channel(user,chan)))
4510 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4513 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4515 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4521 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4526 ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
4528 // if any users of this channel are on remote servers, broadcast the packet
4529 char buffer[MAXBUF];
4530 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
4531 NetSendToCommon(user,buffer);
4535 /* no such nick/channel */
4536 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4541 dest = Find(parameters[0]);
4546 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
4551 if (!strcmp(dest->server,user->server))
4553 // direct write, same server
4554 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
4558 char buffer[MAXBUF];
4559 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
4560 NetSendToOne(dest->server,buffer);
4565 /* no such nick/channel */
4566 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4572 char* chlist(userrec *user)
4577 log(DEBUG,"chlist: %s",user->nick);
4583 for (int i = 0; i != MAXCHANS; i++)
4585 if (user->chans[i].channel != NULL)
4587 if (user->chans[i].channel->name)
4589 strcpy(cmp,user->chans[i].channel->name);
4591 if (!strstr(lst,cmp))
4593 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
4595 strcat(lst,cmode(user,user->chans[i].channel));
4596 strcat(lst,user->chans[i].channel->name);
4605 lst[strlen(lst)-1] = '\0'; // chop trailing space
4610 void handle_info(char **parameters, int pcnt, userrec *user)
4612 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
4613 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
4614 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
4615 FOREACH_MOD OnInfo(user);
4616 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
4619 void handle_time(char **parameters, int pcnt, userrec *user)
4622 struct tm * timeinfo;
4625 timeinfo = localtime ( &rawtime );
4626 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
4630 void handle_whois(char **parameters, int pcnt, userrec *user)
4635 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
4637 dest = Find(parameters[0]);
4640 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
4641 if (dest->registered == 7)
4643 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
4644 if ((user == dest) || (strchr(user->modes,'o')))
4646 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
4648 if (strcmp(chlist(dest),""))
4650 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
4652 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
4653 if (strcmp(dest->awaymsg,""))
4655 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
4657 if (strchr(dest->modes,'o'))
4659 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
4661 FOREACH_MOD OnWhois(user,dest);
4662 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
4663 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
4665 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
4669 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4674 /* no such nick/channel */
4675 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4679 void send_network_quit(const char* nick, const char* reason)
4681 char buffer[MAXBUF];
4682 snprintf(buffer,MAXBUF,"Q %s :%s",nick,reason);
4683 NetSendToAll(buffer);
4686 void handle_quit(char **parameters, int pcnt, userrec *user)
4688 user_hash::iterator iter = clientlist.find(user->nick);
4691 if (user->registered == 7)
4693 /* theres more to do here, but for now just close the socket */
4696 if (parameters[0][0] == ':')
4700 reason = parameters[0];
4702 if (strlen(reason)>MAXQUIT)
4704 reason[MAXQUIT-1] = '\0';
4707 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
4708 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
4709 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
4711 char buffer[MAXBUF];
4712 snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
4713 NetSendToAll(buffer);
4717 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
4718 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
4719 WriteCommonExcept(user,"QUIT :Client exited");
4721 char buffer[MAXBUF];
4722 snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
4723 NetSendToAll(buffer);
4725 FOREACH_MOD OnUserQuit(user);
4729 /* push the socket on a stack of sockets due to be closed at the next opportunity */
4730 fd_reap.push_back(user->fd);
4732 if (iter != clientlist.end())
4734 clientlist.erase(iter);
4735 log(DEBUG,"deleting user hash value %d",iter->second);
4736 //if ((user) && (user->registered == 7)) {
4741 if (user->registered == 7) {
4742 purge_empty_chans();
4746 void handle_who(char **parameters, int pcnt, userrec *user)
4748 chanrec* Ptr = NULL;
4750 /* theres more to do here, but for now just close the socket */
4753 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
4755 if (user->chans[0].channel)
4757 Ptr = user->chans[0].channel;
4758 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4760 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4762 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);
4768 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4772 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
4776 if (parameters[0][0] == '#')
4778 Ptr = FindChan(parameters[0]);
4781 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4783 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
4785 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);
4788 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4792 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4797 userrec* u = Find(parameters[0]);
4798 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);
4803 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4805 Ptr = user->chans[0].channel;
4806 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4808 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4810 if (strchr(i->second->modes,'o'))
4812 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);
4816 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4822 void handle_wallops(char **parameters, int pcnt, userrec *user)
4824 WriteWallOps(user,false,"%s",parameters[0]);
4827 void handle_list(char **parameters, int pcnt, userrec *user)
4831 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4832 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4834 if ((!i->second->c_private) && (!i->second->secret))
4836 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4839 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4843 void handle_rehash(char **parameters, int pcnt, userrec *user)
4845 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4847 FOREACH_MOD OnRehash();
4848 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4854 return clientlist.size();
4858 int usercount_invisible(void)
4862 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4864 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4869 int usercount_opers(void)
4873 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4875 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4880 int usercount_unknown(void)
4884 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4886 if ((i->second->fd) && (i->second->registered != 7))
4892 long chancount(void)
4894 return chanlist.size();
4897 long count_servs(void)
4900 //for (int j = 0; j < 255; j++)
4902 // if (servers[j] != NULL)
4908 long servercount(void)
4910 return count_servs()+1;
4916 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4918 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
4924 void handle_lusers(char **parameters, int pcnt, userrec *user)
4926 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4927 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4928 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4929 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4930 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
4933 void handle_admin(char **parameters, int pcnt, userrec *user)
4935 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4936 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4937 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4938 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4941 void ShowMOTD(userrec *user)
4945 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4948 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4949 for (int i = 0; i != MOTD.size(); i++)
4951 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4953 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4956 void ShowRULES(userrec *user)
4960 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4963 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4964 for (int i = 0; i != RULES.size(); i++)
4966 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4968 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4971 /* shows the message of the day, and any other on-logon stuff */
4972 void ConnectUser(userrec *user)
4974 user->registered = 7;
4975 user->idle_lastmsg = time(NULL);
4976 log(DEBUG,"ConnectUser: %s",user->nick);
4978 if (strcmp(Passwd(user),"") && (!user->haspassed))
4980 kill_link(user,"Invalid password");
4985 kill_link(user,"Unauthorised connection");
4989 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4990 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4991 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4992 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4993 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4994 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);
4995 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);
4997 FOREACH_MOD OnUserConnect(user);
4998 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
5000 char buffer[MAXBUF];
5001 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);
5002 NetSendToAll(buffer);
5005 void handle_version(char **parameters, int pcnt, userrec *user)
5007 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Revision$ $Date$",ServerName,SYSTEM);
5010 void handle_ping(char **parameters, int pcnt, userrec *user)
5012 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
5015 void handle_pong(char **parameters, int pcnt, userrec *user)
5017 // set the user as alive so they survive to next ping
5021 void handle_motd(char **parameters, int pcnt, userrec *user)
5026 void handle_rules(char **parameters, int pcnt, userrec *user)
5031 void handle_user(char **parameters, int pcnt, userrec *user)
5033 if (user->registered < 3)
5035 if (isident(parameters[0]) == 0) {
5036 // This kinda Sucks, According to the RFC thou, its either this,
5037 // or "You have already registered" :p -- Craig
5038 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
5041 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
5042 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
5043 strncat(user->ident,parameters[0],IDENTMAX);
5044 strncpy(user->fullname,parameters[3],128);
5045 user->registered = (user->registered | 1);
5050 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
5053 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
5054 if (user->registered == 3)
5056 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5061 void handle_userhost(char **parameters, int pcnt, userrec *user)
5063 char Return[MAXBUF],junk[MAXBUF];
5064 sprintf(Return,"302 %s :",user->nick);
5065 for (int i = 0; i < pcnt; i++)
5067 userrec *u = Find(parameters[i]);
5070 if (strchr(u->modes,'o'))
5072 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
5073 strcat(Return,junk);
5077 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
5078 strcat(Return,junk);
5082 WriteServ(user->fd,Return);
5086 void handle_ison(char **parameters, int pcnt, userrec *user)
5088 char Return[MAXBUF];
5089 sprintf(Return,"303 %s :",user->nick);
5090 for (int i = 0; i < pcnt; i++)
5092 userrec *u = Find(parameters[i]);
5095 strcat(Return,u->nick);
5099 WriteServ(user->fd,Return);
5103 void handle_away(char **parameters, int pcnt, userrec *user)
5107 strcpy(user->awaymsg,parameters[0]);
5108 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
5112 strcpy(user->awaymsg,"");
5113 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
5117 void handle_whowas(char **parameters, int pcnt, userrec* user)
5119 user_hash::iterator i = whowas.find(parameters[0]);
5121 if (i == whowas.end())
5123 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
5124 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5128 time_t rawtime = i->second->signon;
5132 timeinfo = localtime(&rawtime);
5133 strcpy(b,asctime(timeinfo));
5134 b[strlen(b)-1] = '\0';
5136 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
5137 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
5138 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5143 void handle_trace(char **parameters, int pcnt, userrec *user)
5145 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5149 if (isnick(i->second->nick))
5151 if (strchr(i->second->modes,'o'))
5153 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
5157 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
5162 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
5168 void handle_modules(char **parameters, int pcnt, userrec *user)
5170 for (int i = 0; i < module_names.size(); i++)
5172 Version V = modules[i]->GetVersion();
5173 char modulename[MAXBUF];
5174 strncpy(modulename,module_names[i].c_str(),256);
5175 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));
5179 // calls a handler function for a command
5181 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
5183 for (int i = 0; i < cmdlist.size(); i++)
5185 if (!strcasecmp(cmdlist[i].command,commandname))
5187 if (cmdlist[i].handler_function)
5189 if (pcnt>=cmdlist[i].min_params)
5191 if (strchr(user->modes,cmdlist[i].flags_needed))
5193 cmdlist[i].handler_function(parameters,pcnt,user);
5201 void handle_stats(char **parameters, int pcnt, userrec *user)
5207 if (strlen(parameters[0])>1)
5209 /* make the stats query 1 character long */
5210 parameters[0][1] = '\0';
5213 /* stats m (list number of times each command has been used, plus bytecount) */
5214 if (!strcasecmp(parameters[0],"m"))
5216 for (int i = 0; i < cmdlist.size(); i++)
5218 if (cmdlist[i].handler_function)
5220 if (cmdlist[i].use_count)
5222 /* RPL_STATSCOMMANDS */
5223 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
5230 /* stats z (debug and memory info) */
5231 if (!strcasecmp(parameters[0],"z"))
5233 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
5234 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
5235 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
5236 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
5237 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
5238 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
5239 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
5240 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
5244 if (!strcasecmp(parameters[0],"o"))
5246 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5248 char LoginName[MAXBUF];
5249 char HostName[MAXBUF];
5250 char OperType[MAXBUF];
5251 ConfValue("oper","name",i,LoginName,&config_f);
5252 ConfValue("oper","host",i,HostName,&config_f);
5253 ConfValue("oper","type",i,OperType,&config_f);
5254 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
5258 /* stats l (show user I/O stats) */
5259 if (!strcasecmp(parameters[0],"l"))
5261 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
5262 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5264 if (isnick(i->second->nick))
5266 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);
5270 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);
5276 /* stats u (show server uptime) */
5277 if (!strcasecmp(parameters[0],"u"))
5279 time_t current_time = 0;
5280 current_time = time(NULL);
5281 time_t server_uptime = current_time - startup_time;
5283 stime = gmtime(&server_uptime);
5284 /* i dont know who the hell would have an ircd running for over a year nonstop, but
5285 * Craig suggested this, and it seemed a good idea so in it went */
5286 if (stime->tm_year > 70)
5288 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);
5292 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);
5296 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
5297 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
5301 void handle_connect(char **parameters, int pcnt, userrec *user)
5303 char Link_ServerName[1024];
5304 char Link_IPAddr[1024];
5305 char Link_Port[1024];
5306 char Link_Pass[1024];
5310 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5314 ConfValue("link","name",i,Link_ServerName,&config_f);
5315 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5316 ConfValue("link","port",i,Link_Port,&config_f);
5317 ConfValue("link","sendpass",i,Link_Pass,&config_f);
5318 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5319 LinkPort = atoi(Link_Port);
5320 if (match(Link_ServerName,parameters[0])) {
5328 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
5332 // TODO: Perform a check here to stop a server being linked twice!
5334 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
5336 if (me[defaultRoute])
5338 me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName);
5343 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);
5347 void handle_squit(char **parameters, int pcnt, userrec *user)
5349 // send out an squit across the mesh and then clear the server list (for local squit)
5352 char islast(const char* s)
5355 for (int j = 0; j < 32; j++)
5359 for (int k = 0; k < me[j]->connectors.size(); k++)
5361 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
5365 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
5375 long map_count(const char* s)
5378 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
5380 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
5385 void handle_links(char **parameters, int pcnt, userrec *user)
5387 WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
5388 for (int j = 0; j < 32; j++)
5392 for (int k = 0; k < me[j]->connectors.size(); k++)
5394 WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,me[j]->connectors[k].GetServerName().c_str(),ServerName,me[j]->connectors[k].GetDescription().c_str());
5398 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
5401 void handle_map(char **parameters, int pcnt, userrec *user)
5404 snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
5405 while (strlen(line) < 50)
5407 WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)usercnt())*100));
5408 for (int j = 0; j < 32; j++)
5412 for (int k = 0; k < me[j]->connectors.size(); k++)
5414 snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(me[j]->connectors[k].GetServerName().c_str()),me[j]->connectors[k].GetServerName().c_str());
5415 while (strlen(line) < 50)
5417 WriteServ(user->fd,"%s%d (%.2f%%)",line,map_count(me[j]->connectors[k].GetServerName().c_str()),(float)(((float)map_count(me[j]->connectors[k].GetServerName().c_str())/(float)usercnt())*100));
5421 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
5425 void handle_oper(char **parameters, int pcnt, userrec *user)
5427 char LoginName[MAXBUF];
5428 char Password[MAXBUF];
5429 char OperType[MAXBUF];
5430 char TypeName[MAXBUF];
5431 char Hostname[MAXBUF];
5434 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5436 ConfValue("oper","name",i,LoginName,&config_f);
5437 ConfValue("oper","password",i,Password,&config_f);
5438 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
5440 /* correct oper credentials */
5441 ConfValue("oper","type",i,OperType,&config_f);
5442 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
5443 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
5444 WriteServ(user->fd,"MODE %s :+o",user->nick);
5445 for (j =0; j < ConfValueEnum("type",&config_f); j++)
5447 ConfValue("type","name",j,TypeName,&config_f);
5448 if (!strcmp(TypeName,OperType))
5450 /* found this oper's opertype */
5451 ConfValue("type","host",j,Hostname,&config_f);
5452 ChangeDisplayedHost(user,Hostname);
5455 if (!strchr(user->modes,'o'))
5457 strcat(user->modes,"o");
5459 FOREACH_MOD OnOper(user);
5464 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
5465 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
5468 void handle_nick(char **parameters, int pcnt, userrec *user)
5472 log(DEBUG,"not enough params for handle_nick");
5477 log(DEBUG,"invalid parameter passed to handle_nick");
5480 if (!strlen(parameters[0]))
5482 log(DEBUG,"zero length new nick passed to handle_nick");
5487 log(DEBUG,"invalid user passed to handle_nick");
5492 log(DEBUG,"invalid old nick passed to handle_nick");
5495 if (!strcasecmp(user->nick,parameters[0]))
5497 log(DEBUG,"old nick is new nick, skipping");
5502 if (strlen(parameters[0]) > 1)
5504 if (parameters[0][0] == ':')
5509 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
5511 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
5515 if (isnick(parameters[0]) == 0)
5517 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
5521 if (user->registered == 7)
5523 WriteCommon(user,"NICK %s",parameters[0]);
5525 // Q token must go to ALL servers!!!
5526 char buffer[MAXBUF];
5527 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
5528 NetSendToAll(buffer);
5532 /* change the nick of the user in the users_hash */
5533 user = ReHashNick(user->nick, parameters[0]);
5534 /* actually change the nick within the record */
5536 if (!user->nick) return;
5538 strncpy(user->nick, parameters[0],NICKMAX);
5540 log(DEBUG,"new nick set: %s",user->nick);
5542 if (user->registered < 3)
5543 user->registered = (user->registered | 2);
5544 if (user->registered == 3)
5546 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5549 log(DEBUG,"exit nickchange: %s",user->nick);
5552 void force_nickchange(userrec* user,const char* newnick)
5561 strncpy(nick,newnick,MAXBUF);
5563 if (user->registered == 7)
5567 handle_nick(pars,1,user);
5573 int process_parameters(char **command_p,char *parameters)
5578 q = strlen(parameters);
5581 /* no parameters, command_p invalid! */
5584 if (parameters[0] == ':')
5586 command_p[0] = parameters+1;
5591 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
5593 /* only one parameter */
5594 command_p[0] = parameters;
5595 if (parameters[0] == ':')
5597 if (strchr(parameters,' ') != NULL)
5605 command_p[j++] = parameters;
5606 for (int i = 0; i <= q; i++)
5608 if (parameters[i] == ' ')
5610 command_p[j++] = parameters+i+1;
5611 parameters[i] = '\0';
5612 if (command_p[j-1][0] == ':')
5614 *command_p[j-1]++; /* remove dodgy ":" */
5616 /* parameter like this marks end of the sequence */
5620 return j; /* returns total number of items in the list */
5623 void process_command(userrec *user, char* cmd)
5627 char *command_p[127];
5628 char p[MAXBUF], temp[MAXBUF];
5629 int i, j, items, cmd_found;
5631 for (int i = 0; i < 127; i++)
5632 command_p[i] = NULL;
5642 if (!strcmp(cmd,""))
5647 int total_params = 0;
5650 for (int q = 0; q < strlen(cmd)-1; q++)
5652 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
5655 // found a 'trailing', we dont count them after this.
5663 // another phidjit bug...
5664 if (total_params > 126)
5666 kill_link(user,"Protocol violation (1)");
5672 std::string tmp = cmd;
5673 for (int i = 0; i <= MODCOUNT; i++)
5675 std::string oldtmp = tmp;
5676 modules[i]->OnServerRaw(tmp,true);
5679 log(DEBUG,"A Module changed the input string!");
5680 log(DEBUG,"New string: %s",tmp.c_str());
5681 log(DEBUG,"Old string: %s",oldtmp.c_str());
5685 strncpy(cmd,tmp.c_str(),MAXBUF);
5688 if (!strchr(cmd,' '))
5690 /* no parameters, lets skip the formalities and not chop up
5692 log(DEBUG,"About to preprocess command with no params");
5694 command_p[0] = NULL;
5696 for (int i = 0; i <= strlen(cmd); i++)
5698 cmd[i] = toupper(cmd[i]);
5700 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
5707 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
5708 for (int i = 0; i < strlen(temp); i++)
5710 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
5716 /* split the full string into a command plus parameters */
5720 if (strchr(cmd,' '))
5722 for (int i = 0; i <= strlen(cmd); i++)
5724 /* capitalise the command ONLY, leave params intact */
5725 cmd[i] = toupper(cmd[i]);
5726 /* are we nearly there yet?! :P */
5730 parameters = cmd+i+1;
5738 for (int i = 0; i <= strlen(cmd); i++)
5740 cmd[i] = toupper(cmd[i]);
5747 if (strlen(command)>MAXCOMMAND)
5749 kill_link(user,"Protocol violation (2)");
5753 for (int x = 0; x < strlen(command); x++)
5755 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
5757 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
5759 if (strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
5761 kill_link(user,"Protocol violation (3)");
5768 for (int i = 0; i != cmdlist.size(); i++)
5770 if (strcmp(cmdlist[i].command,""))
5772 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
5774 log(DEBUG,"Found matching command");
5778 if (strcmp(parameters,""))
5780 items = process_parameters(command_p,parameters);
5785 command_p[0] = NULL;
5791 command_p[0] = NULL;
5796 log(DEBUG,"Processing command");
5798 /* activity resets the ping pending timer */
5799 user->nping = time(NULL) + 120;
5800 if ((items) < cmdlist[i].min_params)
5802 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
5803 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
5806 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
5808 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
5809 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
5813 /* if the command isnt USER, PASS, or NICK, and nick is empty,
5815 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
5817 if ((!isnick(user->nick)) || (user->registered != 7))
5819 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5820 WriteServ(user->fd,"451 %s :You have not registered",command);
5824 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
5826 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
5827 if (cmdlist[i].handler_function)
5829 /* ikky /stats counters */
5834 user->bytes_in += strlen(temp);
5837 cmdlist[i].use_count++;
5838 cmdlist[i].total_bytes+=strlen(temp);
5841 /* WARNING: nothing may come after the
5842 * command handler call, as the handler
5843 * may free the user structure! */
5845 cmdlist[i].handler_function(command_p,items,user);
5851 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5852 WriteServ(user->fd,"451 %s :You have not registered",command);
5860 if ((!cmd_found) && (user))
5862 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
5863 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
5868 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
5871 /* create the command and push it onto the table */
5872 strcpy(comm.command,cmd);
5873 comm.handler_function = f;
5874 comm.flags_needed = flags;
5875 comm.min_params = minparams;
5877 comm.total_bytes = 0;
5878 cmdlist.push_back(comm);
5879 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
5882 void SetupCommandTable(void)
5884 createcommand("USER",handle_user,0,4);
5885 createcommand("NICK",handle_nick,0,1);
5886 createcommand("QUIT",handle_quit,0,0);
5887 createcommand("VERSION",handle_version,0,0);
5888 createcommand("PING",handle_ping,0,1);
5889 createcommand("PONG",handle_pong,0,1);
5890 createcommand("ADMIN",handle_admin,0,0);
5891 createcommand("PRIVMSG",handle_privmsg,0,2);
5892 createcommand("INFO",handle_info,0,0);
5893 createcommand("TIME",handle_time,0,0);
5894 createcommand("WHOIS",handle_whois,0,1);
5895 createcommand("WALLOPS",handle_wallops,'o',1);
5896 createcommand("NOTICE",handle_notice,0,2);
5897 createcommand("JOIN",handle_join,0,1);
5898 createcommand("NAMES",handle_names,0,1);
5899 createcommand("PART",handle_part,0,1);
5900 createcommand("KICK",handle_kick,0,2);
5901 createcommand("MODE",handle_mode,0,1);
5902 createcommand("TOPIC",handle_topic,0,1);
5903 createcommand("WHO",handle_who,0,1);
5904 createcommand("MOTD",handle_motd,0,0);
5905 createcommand("RULES",handle_rules,0,0);
5906 createcommand("OPER",handle_oper,0,2);
5907 createcommand("LIST",handle_list,0,0);
5908 createcommand("DIE",handle_die,'o',1);
5909 createcommand("RESTART",handle_restart,'o',1);
5910 createcommand("KILL",handle_kill,'o',2);
5911 createcommand("REHASH",handle_rehash,'o',0);
5912 createcommand("LUSERS",handle_lusers,0,0);
5913 createcommand("STATS",handle_stats,0,1);
5914 createcommand("USERHOST",handle_userhost,0,1);
5915 createcommand("AWAY",handle_away,0,0);
5916 createcommand("ISON",handle_ison,0,0);
5917 createcommand("SUMMON",handle_summon,0,0);
5918 createcommand("USERS",handle_users,0,0);
5919 createcommand("INVITE",handle_invite,0,2);
5920 createcommand("PASS",handle_pass,0,1);
5921 createcommand("TRACE",handle_trace,'o',0);
5922 createcommand("WHOWAS",handle_whowas,0,1);
5923 createcommand("CONNECT",handle_connect,'o',1);
5924 createcommand("SQUIT",handle_squit,'o',1);
5925 createcommand("MODULES",handle_modules,'o',0);
5926 createcommand("LINKS",handle_links,0,0);
5927 createcommand("MAP",handle_map,0,0);
5930 void process_buffer(const char* cmdbuf,userrec *user)
5934 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5941 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5944 if (!strcmp(cmdbuf,""))
5948 strncpy(cmd,cmdbuf,MAXBUF);
5949 if (!strcmp(cmd,""))
5953 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5955 cmd[strlen(cmd)-1] = '\0';
5957 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5959 cmd[strlen(cmd)-1] = '\0';
5961 if (!strcmp(cmd,""))
5965 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5967 if ((user) && (cmd))
5969 process_command(user,cmd);
5973 void DoSync(serverrec* serv, char* udp_host)
5976 // send start of sync marker: Y <timestamp>
5977 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
5978 // except the ones its receiving it from.
5979 snprintf(data,MAXBUF,"Y %d",time(NULL));
5980 serv->SendPacket(data,udp_host);
5981 // send users and channels
5982 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
5984 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);
5985 serv->SendPacket(data,udp_host);
5986 if (strcmp(chlist(u->second),""))
5988 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
5989 serv->SendPacket(data,udp_host);
5992 // send channel modes, topics etc...
5993 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
5995 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
5996 serv->SendPacket(data,udp_host);
5997 if (strcmp(c->second->topic,""))
5999 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
6000 serv->SendPacket(data,udp_host);
6002 // send current banlist
6004 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
6006 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
6007 serv->SendPacket(data,udp_host);
6010 // send end of sync marker: E <timestamp>
6011 snprintf(data,MAXBUF,"F %d",time(NULL));
6012 serv->SendPacket(data,udp_host);
6013 // ircd sends its serverlist after the end of sync here
6017 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6019 char* src = strtok(params," ");
6020 char* dest = strtok(NULL," :");
6021 char* text = strtok(NULL,"\r\n");
6024 userrec* user = Find(src);
6027 userrec* dst = Find(dest);
6031 WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
6035 chanrec* d = FindChan(dest);
6038 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
6046 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6048 char* src = strtok(params," ");
6049 char* dest = strtok(NULL," :");
6050 char* text = strtok(NULL,"\r\n");
6053 userrec* user = Find(src);
6056 userrec* dst = Find(dest);
6060 WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
6064 chanrec* d = FindChan(dest);
6067 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
6074 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6076 char* nick = strtok(params," ");
6077 char* from = strtok(NULL," ");
6078 char* channel = strtok(NULL," ");
6079 userrec* u = Find(nick);
6080 userrec* user = Find(from);
6081 chanrec* c = FindChan(channel);
6082 if ((c) && (u) && (user))
6084 u->InviteTo(c->name);
6085 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
6089 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6091 char* setby = strtok(params," ");
6092 char* channel = strtok(NULL," :");
6093 char* topic = strtok(NULL,"\r\n");
6095 userrec* u = Find(setby);
6096 chanrec* c = FindChan(channel);
6099 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
6100 strncpy(c->topic,topic,MAXTOPIC);
6101 strncpy(c->setby,u->nick,NICKMAX);
6106 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6108 char* tm = strtok(params," ");
6109 char* setby = strtok(NULL," ");
6110 char* channel = strtok(NULL," :");
6111 char* topic = strtok(NULL,"\r\n");
6113 time_t TS = atoi(tm);
6114 chanrec* c = FindChan(channel);
6117 // in the case of topics and TS, the *NEWER*
6118 if (TS <= c->topicset)
6120 WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
6121 strncpy(c->topic,topic,MAXTOPIC);
6122 strncpy(c->setby,setby,NICKMAX);
6127 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6130 char original[MAXBUF],target[MAXBUF];
6131 strncpy(original,params,MAXBUF);
6133 char* parameter = strtok(params," ");
6134 strncpy(target,parameter,MAXBUF);
6137 pars[index++] = parameter;
6138 parameter = strtok(NULL," ");
6140 merge_mode(pars,index);
6141 if (FindChan(target))
6143 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
6147 WriteTo(NULL,Find(target),"MODE %s",original);
6151 // m is modes set by users only (not servers) valid targets are channels or users.
6153 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6155 // m blah #chatspike +b *!test@*4
6157 char original[MAXBUF];
6158 strncpy(original,params,MAXBUF);
6160 if (!strchr(params,' '))
6162 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
6168 char* src = strtok(params," ");
6169 userrec* user = Find(src);
6173 log(DEBUG,"Found user: %s",user->nick);
6174 char* parameter = strtok(NULL," ");
6177 pars[index++] = parameter;
6178 parameter = strtok(NULL," ");
6181 log(DEBUG,"Calling merge_mode2");
6182 merge_mode2(pars,index,user);
6187 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6189 char* nick = strtok(params," ");
6190 char* channel = strtok(NULL," :");
6191 char* reason = strtok(NULL,"\r\n");
6192 userrec* user = Find(nick);
6196 if (strcmp(reason,""))
6198 del_channel(user,channel,reason,true);
6202 del_channel(user,channel,NULL,true);
6207 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6209 char* src = strtok(params," ");
6210 char* nick = strtok(NULL," :");
6211 char* reason = strtok(NULL,"\r\n");
6212 char kreason[MAXBUF];
6215 userrec* u = Find(nick);
6216 userrec* user = Find(src);
6220 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
6221 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
6222 snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
6223 kill_link(u,kreason);
6227 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6229 char* nick = strtok(params," :");
6230 char* reason = strtok(NULL,"\r\n");
6233 userrec* user = Find(nick);
6237 if (strlen(reason)>MAXQUIT)
6239 reason[MAXQUIT-1] = '\0';
6243 WriteCommonExcept(user,"QUIT :%s",reason);
6245 user_hash::iterator iter = clientlist.find(user->nick);
6247 if (iter != clientlist.end())
6249 log(DEBUG,"deleting user hash value %d",iter->second);
6250 if ((iter->second) && (user->registered == 7)) {
6251 delete iter->second;
6253 clientlist.erase(iter);
6256 purge_empty_chans();
6260 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6262 char* oldnick = strtok(params," ");
6263 char* newnick = strtok(NULL," ");
6265 userrec* user = Find(oldnick);
6269 WriteCommon(user,"NICK %s",newnick);
6270 user = ReHashNick(user->nick, newnick);
6272 if (!user->nick) return;
6273 strncpy(user->nick, newnick,NICKMAX);
6274 log(DEBUG,"new nick set: %s",user->nick);
6278 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6279 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6281 char* src = strtok(params," ");
6282 char* dest = strtok(NULL," ");
6283 char* channel = strtok(NULL," :");
6284 char* reason = strtok(NULL,"\r\n");
6286 userrec* s = Find(src);
6287 userrec* d = Find(dest);
6288 chanrec* c = FindChan(channel);
6289 if ((s) && (d) && (c))
6291 kick_channel(s,d,c,reason);
6295 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6297 char* who = strtok(params," :");
6298 char* text = strtok(NULL,"\r\n");
6300 userrec* s = Find(who);
6303 WriteWallOps(s,true,text);
6308 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6310 char* tm = strtok(params," ");
6311 char* nick = strtok(NULL," ");
6312 char* host = strtok(NULL," ");
6313 char* dhost = strtok(NULL," ");
6314 char* ident = strtok(NULL," ");
6315 char* modes = strtok(NULL," ");
6316 char* server = strtok(NULL," :");
6317 char* gecos = strtok(NULL,"\r\n");
6320 time_t TS = atoi(tm);
6321 user_hash::iterator iter = clientlist.find(nick);
6322 if (iter != clientlist.end())
6325 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
6326 if (TS >= iter->second->age)
6329 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
6330 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
6331 // client on remote server is older than the local user, kill the local user
6332 kill_link(iter->second,str);
6335 clientlist[nick] = new userrec();
6336 // remote users have an fd of -1. This is so that our Write abstraction
6337 // routines know to route any messages to this record away to whatever server
6339 clientlist[nick]->fd = -1;
6340 strncpy(clientlist[nick]->nick, nick,NICKMAX);
6341 strncpy(clientlist[nick]->host, host,160);
6342 strncpy(clientlist[nick]->dhost, dhost,160);
6343 strncpy(clientlist[nick]->server, server,256);
6344 strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
6345 strncpy(clientlist[nick]->fullname, gecos,128);
6346 clientlist[nick]->signon = TS;
6347 clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
6348 clientlist[nick]->lastping = 1;
6349 clientlist[nick]->port = 0; // so is this...
6350 clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
6351 clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
6352 for (int i = 0; i < MAXCHANS; i++)
6354 clientlist[nick]->chans[i].channel = NULL;
6355 clientlist[nick]->chans[i].uc_modes = 0;
6359 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6361 long tdiff = time(NULL) - atoi(params);
6363 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
6366 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6368 char* nick = strtok(params," :");
6369 char* gecos = strtok(NULL,"\r\n");
6371 userrec* user = Find(nick);
6374 strncpy(user->fullname,gecos,MAXBUF);
6377 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6379 char* nick = strtok(params," :");
6380 char* host = strtok(NULL,"\r\n");
6382 userrec* user = Find(nick);
6385 strncpy(user->dhost,host,160);
6388 void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6391 // + test3.chatspike.net 7010 -2016508415
6392 char* servername = strtok(params," ");
6393 char* ipaddr = strtok(NULL," ");
6394 char* ipport = strtok(NULL," ");
6395 char* cookie = strtok(NULL," ");
6398 log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
6399 me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
6403 void handle_R(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6405 char* server = strtok(params," ");
6406 char* data = strtok(NULL,"\r\n");
6407 log(DEBUG,"Forwarded packet '%s' to '%s'",data,server);
6408 NetSendToOne(server,data);
6411 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6414 // The J token currently has no timestamp - this needs looking at
6415 // because it will allow splitriding.
6416 char* nick = strtok(params," ");
6417 char* channel = strtok(NULL," ");
6418 userrec* user = Find(nick);
6421 if ((user != NULL) && (strcmp(channel,"")))
6423 char privilage = '\0';
6424 if (channel[0] != '#')
6426 privilage = channel[0];
6429 add_channel(user,channel,"",true);
6431 // now work out the privilages they should have on each channel
6432 // and send the appropriate servermodes.
6433 for (int i = 0; i != MAXCHANS; i++)
6435 if (user->chans[i].channel)
6437 if (!strcasecmp(user->chans[i].channel->name,channel))
6439 if (privilage == '@')
6441 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
6442 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
6444 if (privilage == '%')
6446 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
6447 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
6449 if (privilage == '+')
6451 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
6452 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
6459 channel = strtok(NULL," ");
6463 void NetSendMyRoutingTable()
6465 // send out a line saying what is reachable to us.
6466 // E.g. if A is linked to B C and D, send out:
6468 // if its only linked to B and D send out:
6470 // if it has no links, dont even send out the line at all.
6471 char buffer[MAXBUF];
6472 sprintf(buffer,"$ %s",ServerName);
6473 bool sendit = false;
6474 for (int i = 0; i < 32; i++)
6478 for (int j = 0; j < me[i]->connectors.size(); j++)
6480 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
6482 strncat(buffer," ",MAXBUF);
6483 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
6490 NetSendToAll(buffer);
6493 void handle_dollar(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6495 log(DEBUG,"Storing routing table...");
6496 char* sourceserver = strtok(params," ");
6497 char* server = strtok(NULL," ");
6498 for (int i = 0; i < 32; i++)
6502 for (int j = 0; j < me[i]->connectors.size(); j++)
6504 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),sourceserver))
6506 me[i]->connectors[j].routes.clear();
6507 log(DEBUG,"Found entry for source server.");
6511 me[i]->connectors[j].routes.push_back(server);
6512 log(DEBUG,"*** Stored route: %s -> %s -> %s",ServerName,sourceserver,server);
6513 server = strtok(NULL," ");
6520 log(DEBUG,"Warning! routing table received from nonexistent server!");
6524 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,char* ipaddr,int port)
6526 long authcookie = rand()*rand();
6527 char buffer[MAXBUF];
6534 nb_start = time(NULL);
6535 WriteOpers("Server %s is starting netburst.",udp_host);
6536 // now broadcast this new servers address out to all servers that are linked to us,
6537 // except the newcomer. They'll all attempt to connect back to it.
6539 // give the server its authcookie.
6540 snprintf(buffer,MAXBUF,"~ %d",authcookie);
6541 source->SendPacket(buffer,udp_host);
6542 // tell all the other servers to use this authcookie to connect back again
6543 // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
6544 snprintf(buffer,MAXBUF,"+ %s %s %d %d",udp_host,ipaddr,port,authcookie);
6545 NetSendToAllExcept(udp_host,buffer);
6549 // once stored, this authcookie permits other servers to log in
6550 // without user or password, using it.
6552 auth_cookies.push_back(atoi(params));
6553 log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
6555 // connect back to a server using an authcookie
6557 handle_plus(token,params,source,reply,udp_host);
6561 handle_dollar(token,params,source,reply,udp_host);
6563 // R <server> <data>
6564 // redirect token, send all of <data> along to the given
6565 // server as this server has been found to still have a route to it
6567 handle_R(token,params,source,reply,udp_host);
6572 reply->SendPacket("!",udp_host);
6582 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
6583 // introduce remote client
6585 handle_N(token,params,source,reply,udp_host);
6587 // a <NICK> :<GECOS>
6588 // change GECOS (SETNAME)
6590 handle_a(token,params,source,reply,udp_host);
6593 // change displayed host (SETHOST)
6595 handle_b(token,params,source,reply,udp_host);
6597 // t <NICK> <CHANNEL> :<TOPIC>
6598 // change a channel topic
6600 handle_t(token,params,source,reply,udp_host);
6602 // i <NICK> <CHANNEL>
6603 // invite a user to a channel
6605 handle_i(token,params,source,reply,udp_host);
6607 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6608 // kick a user from a channel
6610 handle_k(token,params,source,reply,udp_host);
6612 // n <NICK> <NEWNICK>
6613 // change nickname of client -- a server should only be able to
6614 // change the nicknames of clients that reside on it unless
6617 handle_n(token,params,source,reply,udp_host);
6619 // J <NICK> <CHANLIST>
6620 // Join user to channel list, merge channel permissions
6622 handle_J(token,params,source,reply,udp_host);
6624 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
6625 // change channel topic (netburst only)
6627 handle_T(token,params,source,reply,udp_host);
6629 // M <TARGET> <MODES> [MODE-PARAMETERS]
6630 // Server setting modes on an object
6632 handle_M(token,params,source,reply,udp_host);
6634 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
6635 // User setting modes on an object
6637 handle_m(token,params,source,reply,udp_host);
6639 // P <SOURCE> <TARGET> :<TEXT>
6640 // Send a private/channel message
6642 handle_P(token,params,source,reply,udp_host);
6644 // V <SOURCE> <TARGET> :<TEXT>
6645 // Send a private/channel notice
6647 handle_V(token,params,source,reply,udp_host);
6649 // L <SOURCE> <CHANNEL> :<REASON>
6650 // User parting a channel
6652 handle_L(token,params,source,reply,udp_host);
6654 // Q <SOURCE> :<REASON>
6657 handle_Q(token,params,source,reply,udp_host);
6659 // K <SOURCE> <DEST> :<REASON>
6662 handle_K(token,params,source,reply,udp_host);
6664 // @ <SOURCE> :<TEXT>
6667 handle_AT(token,params,source,reply,udp_host);
6672 WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
6673 handle_F(token,params,source,reply,udp_host);
6677 // Send netburst now
6679 WriteOpers("Sending my netburst to %s",udp_host);
6680 DoSync(source,udp_host);
6681 WriteOpers("Send of netburst to %s completed",udp_host);
6682 NetSendMyRoutingTable();
6686 WriteOpers("WARNING! Unknown datagram type '%c'",token);
6692 void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
6694 char response[10240];
6695 char token = udp_msg[0];
6696 char* params = udp_msg + 2;
6697 char finalparam[1024];
6698 strcpy(finalparam," :xxxx");
6699 if (strstr(params," :")) {
6700 strncpy(finalparam,strstr(params," :"),1024);
6703 char* cookie = strtok(params," ");
6704 char* servername = strtok(NULL," ");
6705 char* serverdesc = finalparam+2;
6706 WriteOpers("AuthCookie CONNECT from %s (%s)",servername,udp_host);
6707 for (int u = 0; u < auth_cookies.size(); u++)
6709 if (auth_cookies[u] == atoi(cookie))
6711 WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
6714 for (int j = 0; j < 32; j++)
6718 for (int k = 0; k < me[j]->connectors.size(); k++)
6720 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
6722 me[j]->connectors[k].SetServerName(servername);
6723 NetSendMyRoutingTable();
6728 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",udp_host);
6736 // bad cookie, bad bad! go sit in the corner!
6737 WriteOpers("Bad cookie from %s!",servername);
6742 // S test.chatspike.net password :ChatSpike InspIRCd test server
6743 char* servername = strtok(params," ");
6744 char* password = strtok(NULL," ");
6745 char* serverdesc = finalparam+2;
6746 WriteOpers("CONNECT from %s (%s)",servername,udp_host);
6748 for (int j = 0; j < serv->connectors.size(); j++)
6750 if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
6752 serv->connectors[j].SetServerName(servername);
6757 char Link_ServerName[1024];
6758 char Link_IPAddr[1024];
6759 char Link_Port[1024];
6760 char Link_Pass[1024];
6761 char Link_SendPass[1024];
6764 // search for a corresponding <link> block in the config files
6765 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6767 ConfValue("link","name",i,Link_ServerName,&config_f);
6768 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6769 ConfValue("link","port",i,Link_Port,&config_f);
6770 ConfValue("link","recvpass",i,Link_Pass,&config_f);
6771 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6772 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6773 LinkPort = atoi(Link_Port);
6774 if (!strcasecmp(Link_ServerName,servername))
6776 // we have a matching link line -
6777 // send a 'diminutive' server message back...
6778 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
6779 serv->SendPacket(response,servername);
6783 char buffer[MAXBUF];
6784 sprintf(buffer,"E :Access is denied (no matching link block)");
6785 serv->SendPacket(buffer,udp_host);
6786 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6791 // S test.chatspike.net password :ChatSpike InspIRCd test server
6792 char* servername = strtok(params," ");
6793 char* password = strtok(NULL," ");
6794 char* serverdesc = finalparam+2;
6796 // TODO: we should do a check here to ensure that this server is one we recently initiated a
6797 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
6798 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
6799 // a connect, so put out an oper alert!
6804 // for now, just accept all, we'll fix that later.
6805 WriteOpers("%s accepted our link credentials ",servername);
6807 char Link_ServerName[1024];
6808 char Link_IPAddr[1024];
6809 char Link_Port[1024];
6810 char Link_Pass[1024];
6811 char Link_SendPass[1024];
6814 // search for a corresponding <link> block in the config files
6815 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6817 ConfValue("link","name",i,Link_ServerName,&config_f);
6818 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6819 ConfValue("link","port",i,Link_Port,&config_f);
6820 ConfValue("link","recvpass",i,Link_Pass,&config_f);
6821 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6822 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6823 LinkPort = atoi(Link_Port);
6824 if (!strcasecmp(Link_ServerName,servername))
6826 // matching link at this end too, we're all done!
6827 // at this point we must begin key exchange and insert this
6828 // server into our 'active' table.
6829 for (int j = 0; j < 32; j++)
6833 for (int k = 0; k < me[j]->connectors.size(); k++)
6835 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
6837 char buffer[MAXBUF];
6838 sprintf(buffer,"X 0");
6839 serv->SendPacket(buffer,udp_host);
6840 DoSync(me[j],udp_host);
6841 NetSendMyRoutingTable();
6846 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
6851 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
6854 char buffer[MAXBUF];
6855 sprintf(buffer,"E :Access is denied (no matching link block)");
6856 serv->SendPacket(buffer,udp_host);
6857 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6862 char* error_message = finalparam+2;
6863 WriteOpers("ERROR from %s: %s",udp_host,error_message);
6864 // remove this server from any lists
6869 serverrec* source_server = NULL;
6871 for (int j = 0; j < 32; j++)
6875 for (int x = 0; x < me[j]->connectors.size(); x++)
6877 log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
6878 if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
6880 log(DEBUG,"match! process restricted stuff here");
6881 // found a valid ircd_connector.
6882 // TODO: Fix this so it only lets servers in that are in the
6883 // STATE_CONNECTED state!!!
6884 process_restricted_commands(token,params,me[j],serv,udp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
6891 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
6895 int reap_counter = 0;
6899 struct sockaddr_in client, server;
6900 char addrs[MAXBUF][255];
6901 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
6903 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
6904 int selectResult = 0, selectResult2 = 0;
6905 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
6906 char resolvedHost[MAXBUF];
6910 log_file = fopen("ircd.log","a+");
6913 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
6917 log(DEBUG,"InspIRCd: startup: begin");
6921 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
6923 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
6925 SetupCommandTable();
6926 log(DEBUG,"InspIRCd: startup: default command table set up");
6929 if (strcmp(DieValue,""))
6931 printf("WARNING: %s\n\n",DieValue);
6934 log(DEBUG,"InspIRCd: startup: read config");
6936 int count2 = 0, count3 = 0;
6938 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
6940 ConfValue("bind","port",count,configToken,&config_f);
6941 ConfValue("bind","address",count,Addr,&config_f);
6942 ConfValue("bind","type",count,Type,&config_f);
6943 if (!strcmp(Type,"servers"))
6945 char Default[MAXBUF];
6946 strcpy(Default,"no");
6947 ConfValue("bind","default",count,Default,&config_f);
6948 if (strchr(Default,'y'))
6950 defaultRoute = count3;
6951 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
6953 me[count3] = new serverrec(ServerName,100L,false);
6954 me[count3]->CreateListener(Addr,atoi(configToken));
6959 ports[count2] = atoi(configToken);
6960 strcpy(addrs[count2],Addr);
6963 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
6966 UDPportCount = count3;
6968 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
6970 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
6974 /* BugFix By Craig! :p */
6976 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
6978 char modfile[MAXBUF];
6979 ConfValue("module","name",count2,configToken,&config_f);
6980 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
6981 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
6982 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
6983 /* If The File Doesnt exist, Trying to load it
6984 * Will Segfault the IRCd.. So, check to see if
6985 * it Exists, Before Proceeding. */
6986 if (FileExists(modfile))
6988 factory[count] = new ircd_module(modfile);
6989 if (factory[count]->LastError())
6991 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
6992 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
6995 if (factory[count]->factory)
6997 modules[count] = factory[count]->factory->CreateModule();
6998 /* save the module and the module's classfactory, if
6999 * this isnt done, random crashes can occur :/ */
7000 module_names.push_back(modfile);
7004 log(DEBUG,"Unable to load %s",modfile);
7005 sprintf("Unable to load %s\nExiting...\n",modfile);
7008 /* Increase the Count */
7013 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
7014 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
7017 MODCOUNT = count - 1;
7018 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
7020 printf("\nInspIRCd is now running!\n");
7022 startup_time = time(NULL);
7026 log(VERBOSE,"Not forking as -nofork was specified");
7030 if (DaemonSeed() == ERROR)
7032 log(DEBUG,"InspIRCd: startup: can't daemonise");
7033 printf("ERROR: could not go into daemon mode. Shutting down.\n");
7039 /* setup select call */
7040 FD_ZERO(&selectFds);
7041 log(DEBUG,"InspIRCd: startup: zero selects");
7042 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
7044 for (count = 0; count < portCount; count++)
7046 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
7048 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
7051 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
7053 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
7055 else /* well we at least bound to one socket so we'll continue */
7061 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
7063 /* if we didn't bind to anything then abort */
7064 if (boundPortCount == 0)
7066 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
7071 length = sizeof (client);
7072 char udp_msg[MAXBUF], udp_host[MAXBUF];
7074 /* main loop, this never returns */
7082 user_hash::iterator count2 = clientlist.begin();
7084 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
7085 // them in a list, then reap the list every second or so.
7086 if (reap_counter>2500)
7088 if (fd_reap.size() > 0)
7090 for( int n = 0; n < fd_reap.size(); n++)
7092 Blocking(fd_reap[n]);
7094 NonBlocking(fd_reap[n]);
7103 FD_ZERO(&serverfds);
7106 for (int x = 0; x != UDPportCount; x++)
7108 FD_SET(me[x]->fd, &serverfds);
7114 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
7117 for (int x = 0; x != UDPportCount; x++)
7119 if (FD_ISSET (me[x]->fd, &serverfds))
7121 char remotehost[MAXBUF],resolved[MAXBUF];
7122 length = sizeof (client);
7123 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
7124 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
7125 if(CleanAndResolve(resolved, remotehost) != TRUE)
7127 strncpy(resolved,remotehost,MAXBUF);
7129 // add to this connections ircd_connector vector
7130 me[x]->AddIncoming(incomingSockfd,resolved,ntohs(client.sin_port));
7135 for (int x = 0; x < UDPportCount; x++)
7137 std::deque<std::string> msgs;
7139 if (me[x]->RecvPacket(msgs, udp_host))
7141 for (int ctr = 0; ctr < msgs.size(); ctr++)
7143 char udp_msg[MAXBUF];
7144 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
7145 if (strlen(udp_msg)<1)
7147 log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
7150 // during a netburst, send all data to all other linked servers
7151 if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
7153 NetSendToAllExcept(udp_host,udp_msg);
7155 FOREACH_MOD OnPacketReceive(udp_msg);
7156 handle_link_packet(udp_msg, udp_host, me[x]);
7163 while (count2 != clientlist.end())
7166 tval.tv_usec = tval.tv_sec = 0;
7168 int total_in_this_set = 0;
7170 user_hash::iterator xcount = count2;
7171 user_hash::iterator endingiter = count2;
7173 if (!count2->second) break;
7176 if (count2->second->fd != 0)
7178 // assemble up to 64 sockets into an fd_set
7179 // to implement a pooling mechanism.
7181 // This should be up to 64x faster than the
7182 // old implementation.
7183 while (total_in_this_set < 64)
7185 if (count2 != clientlist.end())
7187 // we don't check the state of remote users.
7188 if (count2->second->fd > 0)
7190 FD_SET (count2->second->fd, &sfd);
7192 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
7193 // their connection class.
7194 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
7196 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
7197 kill_link(count2->second,"Registration timeout");
7200 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
7202 if ((!count2->second->lastping) && (count2->second->registered == 7))
7204 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
7205 kill_link(count2->second,"Ping timeout");
7208 Write(count2->second->fd,"PING :%s",ServerName);
7209 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
7210 count2->second->lastping = 0;
7211 count2->second->nping = time(NULL)+120;
7215 total_in_this_set++;
7220 endingiter = count2;
7221 count2 = xcount; // roll back to where we were
7227 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
7229 // now loop through all of the items in this pool if any are waiting
7230 //if (selectResult2 > 0)
7231 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
7234 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
7236 log(DEBUG,"Reading fd %d",count2a->second->fd);
7237 memset(data, 0, 10240);
7238 result = read(count2a->second->fd, data, 10240);
7242 log(DEBUG,"Read %d characters from socket",result);
7243 userrec* current = count2a->second;
7244 int currfd = current->fd;
7245 char* l = strtok(data,"\n");
7250 if ((floodlines > current->flood) && (current->flood != 0))
7252 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7253 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7254 kill_link(current,"Excess flood");
7257 char sanitized[NetBufferSize];
7258 memset(sanitized, 0, NetBufferSize);
7260 for (int pt = 0; pt < strlen(l); pt++)
7264 sanitized[ptt++] = l[pt];
7267 sanitized[ptt] = '\0';
7268 if (strlen(sanitized))
7272 // we're gonna re-scan to check if the nick is gone, after every
7273 // command - if it has, we're gonna bail
7274 bool find_again = false;
7275 process_buffer(sanitized,current);
7277 // look for the user's record in case it's changed
7278 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
7280 if (c2->second->fd == currfd)
7282 // found again, update pointer
7283 current == c2->second;
7292 l = strtok(NULL,"\n");
7297 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
7299 log(DEBUG,"killing: %s",count2a->second->nick);
7300 kill_link(count2a->second,strerror(errno));
7304 // result EAGAIN means nothing read
7305 if (result == EAGAIN)
7313 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
7314 kill_link(count2a->second,"Client exited");
7315 // must bail here? kill_link removes the hash, corrupting the iterator
7316 log(DEBUG,"Bailing from client exit");
7320 else if (result > 0)
7325 for (int q = 0; q < total_in_this_set; q++)
7327 // there is no iterator += operator :(
7328 //if (count2 != clientlist.end())
7335 // set up select call
7336 for (count = 0; count < boundPortCount; count++)
7338 FD_SET (openSockfd[count], &selectFds);
7342 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
7344 /* select is reporting a waiting socket. Poll them all to find out which */
7345 if (selectResult > 0)
7347 char target[MAXBUF], resolved[MAXBUF];
7348 for (count = 0; count < boundPortCount; count++)
7350 if (FD_ISSET (openSockfd[count], &selectFds))
7352 length = sizeof (client);
7353 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
7355 address_cache::iterator iter = IP.find(client.sin_addr);
7356 bool iscached = false;
7357 if (iter == IP.end())
7359 /* ip isn't in cache, add it */
7360 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
7361 if(CleanAndResolve(resolved, target) != TRUE)
7363 strncpy(resolved,target,MAXBUF);
7365 /* hostname now in 'target' */
7366 IP[client.sin_addr] = new string(resolved);
7367 /* hostname in cache */
7371 /* found ip (cached) */
7372 strncpy(resolved, iter->second->c_str(), MAXBUF);
7376 if (incomingSockfd < 0)
7378 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
7379 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
7383 AddClient(incomingSockfd, resolved, ports[count], iscached);
7384 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
7391 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
7394 close (incomingSockfd);