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>
46 #include "connection.h"
56 #define nspace __gnu_cxx
61 int LogLevel = DEFAULT;
62 char ServerName[MAXBUF];
64 char ServerDesc[MAXBUF];
65 char AdminName[MAXBUF];
66 char AdminEmail[MAXBUF];
67 char AdminNick[MAXBUF];
69 char restartpass[MAXBUF];
73 char PrefixQuit[MAXBUF];
74 char DieValue[MAXBUF];
76 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
77 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
79 time_t startup_time = time(NULL);
80 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
83 extern vector<Module*> modules;
84 std::vector<std::string> module_names;
85 extern vector<ircd_module*> factory;
86 std::vector<int> fd_reap;
94 template<> struct nspace::hash<in_addr>
96 size_t operator()(const struct in_addr &a) const
99 memcpy(&q,&a,sizeof(size_t));
104 template<> struct nspace::hash<string>
106 size_t operator()(const string &s) const
109 static struct hash<const char *> strhash;
121 bool operator()(const string& s1, const string& s2) const
123 char a[MAXBUF],b[MAXBUF];
124 strcpy(a,s1.c_str());
125 strcpy(b,s2.c_str());
126 return (strcasecmp(a,b) == 0);
131 struct InAddr_HashComp
134 bool operator()(const in_addr &s1, const in_addr &s2) const
139 memcpy(&q,&s1,sizeof(size_t));
140 memcpy(&p,&s2,sizeof(size_t));
148 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
149 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
150 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
151 typedef std::deque<command_t> command_table;
157 user_hash clientlist;
160 command_table cmdlist;
167 struct linger linger = { 0 };
168 char bannerBuffer[MAXBUF];
169 int boundPortCount = 0;
170 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
171 int defaultRoute = 0;
175 long MyKey = C.GenKey();
179 int has_channel(userrec *u, chanrec *c);
180 int usercount(chanrec *c);
181 int usercount_i(chanrec *c);
182 void update_stats_l(int fd,int data_out);
183 char* Passwd(userrec *user);
184 bool IsDenied(userrec *user);
185 void AddWhoWas(userrec* u);
187 std::vector<long> auth_cookies;
188 std::stringstream config_f(stringstream::in | stringstream::out);
190 void safedelete(userrec *p)
194 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
195 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
201 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
205 void safedelete(chanrec *p)
211 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
215 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
220 void tidystring(char* str)
222 // strips out double spaces before a : parameter
225 bool go_again = true;
232 while ((str[0] == ' ') && (strlen(str)>0))
239 bool noparse = false;
242 while (a < strlen(str))
244 if ((a<strlen(str)-1) && (noparse==false))
246 if ((str[a] == ' ') && (str[a+1] == ' '))
248 log(DEBUG,"Tidied extra space out of string: %s",str);
256 if ((str[a] == ' ') && (str[a+1] == ':'))
262 temp[t++] = str[a++];
265 strncpy(str,temp,MAXBUF);
269 /* chop a string down to 512 characters and preserve linefeed (irc max
276 log(DEBUG,"ERROR! Null string passed to chop()!");
280 FOREACH_MOD OnServerRaw(temp,false);
281 const char* str2 = temp.c_str();
282 sprintf(str,"%s",str2);
285 if (strlen(str) >= 512)
296 char Revision[] = "$Revision$";
299 char *v1 = strtok_r(s1," ",&savept);
301 char *v2 = strtok_r(s1," ",&savept);
303 return (long)(atof(v2)*10000);
307 std::string getservername()
312 std::string getserverdesc()
317 std::string getnetworkname()
322 std::string getadminname()
327 std::string getadminemail()
332 std::string getadminnick()
337 void log(int level,char *text, ...)
339 char textbuffer[MAXBUF];
342 struct tm * timeinfo;
343 if (level < LogLevel)
347 timeinfo = localtime (&rawtime);
352 va_start (argsPtr, text);
353 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
355 strcpy(b,asctime(timeinfo));
356 b[strlen(b)-1] = ':';
357 fprintf(log_file,"%s %s\n",b,textbuffer);
360 // nofork enabled? display it on terminal too
361 printf("%s %s\n",b,textbuffer);
366 void readfile(file_cache &F, const char* fname)
369 char linebuf[MAXBUF];
371 log(DEBUG,"readfile: loading %s",fname);
373 file = fopen(fname,"r");
378 fgets(linebuf,sizeof(linebuf),file);
379 linebuf[strlen(linebuf)-1]='\0';
380 if (!strcmp(linebuf,""))
386 F.push_back(linebuf);
393 log(DEBUG,"readfile: failed to load file: %s",fname);
395 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
398 void ReadConfig(void)
400 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
403 LoadConf(CONFIG_FILE,&config_f);
405 ConfValue("server","name",0,ServerName,&config_f);
406 ConfValue("server","description",0,ServerDesc,&config_f);
407 ConfValue("server","network",0,Network,&config_f);
408 ConfValue("admin","name",0,AdminName,&config_f);
409 ConfValue("admin","email",0,AdminEmail,&config_f);
410 ConfValue("admin","nick",0,AdminNick,&config_f);
411 ConfValue("files","motd",0,motd,&config_f);
412 ConfValue("files","rules",0,rules,&config_f);
413 ConfValue("power","diepass",0,diepass,&config_f);
414 ConfValue("power","pause",0,pauseval,&config_f);
415 ConfValue("power","restartpass",0,restartpass,&config_f);
416 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
417 ConfValue("die","value",0,DieValue,&config_f);
418 ConfValue("options","loglevel",0,dbg,&config_f);
419 ConfValue("options","netbuffersize",0,NB,&config_f);
420 NetBufferSize = atoi(NB);
421 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
423 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
424 NetBufferSize = 10240;
426 if (!strcmp(dbg,"debug"))
428 if (!strcmp(dbg,"verbose"))
430 if (!strcmp(dbg,"default"))
432 if (!strcmp(dbg,"sparse"))
434 if (!strcmp(dbg,"none"))
437 log(DEBUG,"Reading message of the day");
438 readfile(RULES,rules);
439 log(DEBUG,"Reading connect classes");
441 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
444 ConfValue("connect","allow",i,Value,&config_f);
445 ConfValue("connect","timeout",i,timeout,&config_f);
446 ConfValue("connect","flood",i,flood,&config_f);
447 if (strcmp(Value,""))
449 strcpy(c.host,Value);
452 ConfValue("connect","password",i,Value,&config_f);
453 strcpy(c.pass,Value);
454 c.registration_timeout = 90; // default is 2 minutes
455 c.flood = atoi(flood);
458 c.registration_timeout = atoi(timeout);
460 Classes.push_back(c);
461 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
465 ConfValue("connect","deny",i,Value,&config_f);
466 strcpy(c.host,Value);
468 Classes.push_back(c);
469 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
478 log(DEBUG,"Blocking: %d",s);
479 flags = fcntl(s, F_GETFL, 0);
480 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
483 void NonBlocking(int s)
486 log(DEBUG,"NonBlocking: %d",s);
487 flags = fcntl(s, F_GETFL, 0);
488 //fcntl(s, F_SETFL, O_NONBLOCK);
489 fcntl(s, F_SETFL, flags | O_NONBLOCK);
493 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
495 struct hostent *hostPtr = NULL;
498 memset (resolvedHost, '\0',MAXBUF);
499 if(unresolvedHost == NULL)
501 if ((inet_aton(unresolvedHost,&addr)) == 0)
503 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
505 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
507 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
511 /* write formatted text to a socket, in same format as printf */
513 void Write(int sock,char *text, ...)
517 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
520 char textbuffer[MAXBUF];
524 va_start (argsPtr, text);
525 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
527 sprintf(tb,"%s\r\n",textbuffer);
531 write(sock,tb,strlen(tb));
532 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
536 /* write a server formatted numeric response to a single socket */
538 void WriteServ(int sock, char* text, ...)
542 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
545 char textbuffer[MAXBUF],tb[MAXBUF];
547 va_start (argsPtr, text);
549 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
551 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
555 write(sock,tb,strlen(tb));
556 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
560 /* write text from an originating user to originating user */
562 void WriteFrom(int sock, userrec *user,char* text, ...)
564 if ((!text) || (!user))
566 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
569 char textbuffer[MAXBUF],tb[MAXBUF];
571 va_start (argsPtr, text);
573 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
575 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
579 write(sock,tb,strlen(tb));
580 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
584 /* write text to an destination user from a source user (e.g. user privmsg) */
586 void WriteTo(userrec *source, userrec *dest,char *data, ...)
588 if ((!dest) || (!data))
590 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
593 char textbuffer[MAXBUF],tb[MAXBUF];
595 va_start (argsPtr, data);
596 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
600 // if no source given send it from the server.
603 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
607 WriteFrom(dest->fd,source,"%s",textbuffer);
611 /* write formatted text from a source user to all users on a channel
612 * including the sender (NOT for privmsg, notice etc!) */
614 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
616 if ((!Ptr) || (!user) || (!text))
618 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
621 char textbuffer[MAXBUF];
623 va_start (argsPtr, text);
624 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
626 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
628 if (has_channel(i->second,Ptr))
630 WriteTo(user,i->second,"%s",textbuffer);
635 /* write formatted text from a source user to all users on a channel
636 * including the sender (NOT for privmsg, notice etc!) doesnt send to
637 * users on remote servers */
639 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
641 if ((!Ptr) || (!text))
643 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
646 char textbuffer[MAXBUF];
648 va_start (argsPtr, text);
649 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
651 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
653 if (has_channel(i->second,Ptr))
655 if (i->second->fd != -1)
659 WriteServ(i->second->fd,"%s",textbuffer);
663 WriteTo(user,i->second,"%s",textbuffer);
671 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
673 if ((!Ptr) || (!user) || (!text))
675 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
678 char textbuffer[MAXBUF];
680 va_start (argsPtr, text);
681 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
683 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
687 if (has_channel(i->second,Ptr))
689 WriteServ(i->second->fd,"%s",textbuffer);
696 /* write formatted text from a source user to all users on a channel except
697 * for the sender (for privmsg etc) */
699 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
701 if ((!Ptr) || (!user) || (!text))
703 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
706 char textbuffer[MAXBUF];
708 va_start (argsPtr, text);
709 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
712 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
716 if (has_channel(i->second,Ptr) && (user != i->second))
718 WriteTo(user,i->second,"%s",textbuffer);
724 int c_count(userrec* u)
727 for (int i =0; i != MAXCHANS; i++)
728 if (u->chans[i].channel != NULL)
735 std::string GetServerDescription(char* servername)
737 for (int j = 0; j < 32; j++)
741 for (int k = 0; k < me[j]->connectors.size(); k++)
743 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
745 return me[j]->connectors[k].GetDescription();
749 return ServerDesc; // not a remote server that can be found, it must be me.
754 /* return 0 or 1 depending if users u and u2 share one or more common channels
755 * (used by QUIT, NICK etc which arent channel specific notices) */
757 int common_channels(userrec *u, userrec *u2)
764 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
767 for (int i = 0; i != MAXCHANS; i++)
769 for (z = 0; z != MAXCHANS; z++)
771 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
773 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
775 if ((c_count(u)) && (c_count(u2)))
786 /* write a formatted string to all users who share at least one common
787 * channel, including the source user e.g. for use in NICK */
789 void WriteCommon(userrec *u, char* text, ...)
793 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
797 if (u->registered != 7) {
798 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
802 char textbuffer[MAXBUF];
804 va_start (argsPtr, text);
805 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
808 WriteFrom(u->fd,u,"%s",textbuffer);
810 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
814 if (common_channels(u,i->second) && (i->second != u))
816 WriteFrom(i->second->fd,u,"%s",textbuffer);
822 /* write a formatted string to all users who share at least one common
823 * channel, NOT including the source user e.g. for use in QUIT */
825 void WriteCommonExcept(userrec *u, char* text, ...)
829 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
833 if (u->registered != 7) {
834 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
838 char textbuffer[MAXBUF];
840 va_start (argsPtr, text);
841 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
844 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
848 if ((common_channels(u,i->second)) && (u != i->second))
850 WriteFrom(i->second->fd,u,"%s",textbuffer);
856 void WriteOpers(char* text, ...)
860 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
864 char textbuffer[MAXBUF];
866 va_start (argsPtr, text);
867 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
870 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
874 if (strchr(i->second->modes,'o'))
876 if (strchr(i->second->modes,'s'))
878 // send server notices to all with +s
879 // (TODO: needs SNOMASKs)
880 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
887 // returns TRUE of any users on channel C occupy server 'servername'.
889 bool ChanAnyOnThisServer(chanrec *c,char* servername)
891 log(DEBUG,"ChanAnyOnThisServer");
892 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
894 if (has_channel(i->second,c))
896 if (!strcasecmp(i->second->server,servername))
905 // returns true if user 'u' shares any common channels with any users on server 'servername'
907 bool CommonOnThisServer(userrec* u,const char* servername)
909 log(DEBUG,"ChanAnyOnThisServer");
910 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
912 if ((common_channels(u,i->second)) && (u != i->second))
914 if (!strcasecmp(i->second->server,servername))
916 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
925 void NetSendToCommon(userrec* u, char* s)
928 snprintf(buffer,MAXBUF,"%s",s);
930 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
932 for (int j = 0; j < 32; j++)
936 for (int k = 0; k < me[j]->connectors.size(); k++)
938 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
940 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
948 void NetSendToAll(char* s)
951 snprintf(buffer,MAXBUF,"%s",s);
953 log(DEBUG,"NetSendToAll: '%s'",s);
955 for (int j = 0; j < 32; j++)
959 for (int k = 0; k < me[j]->connectors.size(); k++)
961 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
967 void NetSendToAllAlive(char* s)
970 snprintf(buffer,MAXBUF,"%s",s);
972 log(DEBUG,"NetSendToAllAlive: '%s'",s);
974 for (int j = 0; j < 32; j++)
978 for (int k = 0; k < me[j]->connectors.size(); k++)
980 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
982 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
986 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
994 void NetSendToOne(char* target,char* s)
997 snprintf(buffer,MAXBUF,"%s",s);
999 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
1001 for (int j = 0; j < 32; j++)
1005 for (int k = 0; k < me[j]->connectors.size(); k++)
1007 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1009 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1016 void NetSendToAllExcept(const char* target,char* s)
1018 char buffer[MAXBUF];
1019 snprintf(buffer,MAXBUF,"%s",s);
1021 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
1023 for (int j = 0; j < 32; j++)
1027 for (int k = 0; k < me[j]->connectors.size(); k++)
1029 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1031 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1039 bool hasumode(userrec* user, char mode)
1043 return (strchr(user->modes,mode)>0);
1048 void WriteMode(const char* modes, int flags, const char* text, ...)
1050 if ((!text) || (!modes) || (!flags))
1052 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1056 char textbuffer[MAXBUF];
1058 va_start (argsPtr, text);
1059 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1062 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1066 bool send_to_user = false;
1068 if (flags == WM_AND)
1070 send_to_user = true;
1071 for (int n = 0; n < strlen(modes); n++)
1073 if (!hasumode(i->second,modes[n]))
1075 send_to_user = false;
1080 else if (flags == WM_OR)
1082 send_to_user = false;
1083 for (int n = 0; n < strlen(modes); n++)
1085 if (hasumode(i->second,modes[n]))
1087 send_to_user = true;
1095 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1101 void ChangeName(userrec* user, const char* gecos)
1103 strncpy(user->fullname,gecos,MAXBUF);
1105 // TODO: replace these with functions:
1106 // NetSendToAll - to all
1107 // NetSendToCommon - to all that hold users sharing a common channel with another user
1108 // NetSendToOne - to one server
1109 // NetSendToAllExcept - send to all but one
1110 // all by servername
1112 char buffer[MAXBUF];
1113 snprintf(buffer,MAXBUF,"a %s :%s",user->nick,gecos);
1114 NetSendToAll(buffer);
1117 void ChangeDisplayedHost(userrec* user, const char* host)
1119 strncpy(user->dhost,host,160);
1120 char buffer[MAXBUF];
1121 snprintf(buffer,MAXBUF,"b %s %s",user->nick,host);
1122 NetSendToAll(buffer);
1125 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1127 if ((!text) || (!source))
1129 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1134 char textbuffer[MAXBUF];
1136 va_start (argsPtr, text);
1137 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1140 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1144 if (strchr(i->second->modes,'w'))
1146 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
1153 char buffer[MAXBUF];
1154 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1155 NetSendToAll(buffer);
1159 /* convert a string to lowercase. Note following special circumstances
1160 * taken from RFC 1459. Many "official" server branches still hold to this
1161 * rule so i will too;
1163 * Because of IRC's scandanavian origin, the characters {}| are
1164 * considered to be the lower case equivalents of the characters []\,
1165 * respectively. This is a critical issue when determining the
1166 * equivalence of two nicknames.
1169 void strlower(char *n)
1175 for (int i = 0; i != strlen(n); i++)
1177 n[i] = tolower(n[i]);
1187 /* verify that a user's ident and nickname is valid */
1189 int isident(const char* n)
1201 for (int i = 0; i != strlen(n); i++)
1203 if ((n[i] < 33) || (n[i] > 125))
1207 /* can't occur ANYWHERE in an Ident! */
1208 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1217 int isnick(const char* n)
1229 if (strlen(n) > NICKMAX-1)
1233 for (int i = 0; i != strlen(n); i++)
1235 if ((n[i] < 33) || (n[i] > 125))
1239 /* can't occur ANYWHERE in a nickname! */
1240 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1244 /* can't occur as the first char of a nickname... */
1245 if ((strchr("0123456789",n[i])) && (!i))
1253 /* Find a user record by nickname and return a pointer to it */
1255 userrec* Find(string nick)
1257 user_hash::iterator iter = clientlist.find(nick);
1259 if (iter == clientlist.end())
1260 /* Couldn't find it */
1263 return iter->second;
1266 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1268 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1272 if (i->second->fd == fd)
1274 i->second->bytes_out+=data_out;
1275 i->second->cmds_out++;
1282 /* find a channel record by channel name and return a pointer to it */
1284 chanrec* FindChan(const char* chan)
1288 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1292 chan_hash::iterator iter = chanlist.find(chan);
1294 if (iter == chanlist.end())
1295 /* Couldn't find it */
1298 return iter->second;
1302 void purge_empty_chans(void)
1304 int go_again = 1, purge = 0;
1309 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1312 if (!usercount(i->second))
1314 /* kill the record */
1315 if (i != chanlist.end())
1317 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1327 log(DEBUG,"skipped purge for %s",i->second->name);
1332 log(DEBUG,"completed channel purge, killed %d",purge);
1335 /* returns the status character for a given user on a channel, e.g. @ for op,
1336 * % for halfop etc. If the user has several modes set, the highest mode
1337 * the user has must be returned. */
1339 char* cmode(userrec *user, chanrec *chan)
1341 if ((!user) || (!chan))
1343 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1348 for (int i = 0; i != MAXCHANS; i++)
1350 if ((user->chans[i].channel == chan) && (chan != NULL))
1352 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1356 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1360 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1369 char scratch[MAXBUF];
1370 char sparam[MAXBUF];
1372 char* chanmodes(chanrec *chan)
1376 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1383 if (chan->noexternal)
1385 strncat(scratch,"n",MAXMODES);
1387 if (chan->topiclock)
1389 strncat(scratch,"t",MAXMODES);
1391 if (strcmp(chan->key,""))
1393 strncat(scratch,"k",MAXMODES);
1397 strncat(scratch,"l",MAXMODES);
1399 if (chan->inviteonly)
1401 strncat(scratch,"i",MAXMODES);
1403 if (chan->moderated)
1405 strncat(scratch,"m",MAXMODES);
1409 strncat(scratch,"s",MAXMODES);
1411 if (chan->c_private)
1413 strncat(scratch,"p",MAXMODES);
1415 if (strcmp(chan->key,""))
1417 strncat(sparam,chan->key,MAXBUF);
1422 sprintf(foo," %d",chan->limit);
1423 strncat(sparam,foo,MAXBUF);
1425 if (strlen(chan->custom_modes))
1427 strncat(scratch,chan->custom_modes,MAXMODES);
1428 for (int z = 0; z < strlen(chan->custom_modes); z++)
1430 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1433 strncat(sparam," ",MAXBUF);
1434 strncat(sparam,extparam.c_str(),MAXBUF);
1438 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1439 strncat(scratch,sparam,MAXMODES);
1443 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1444 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1445 * highest mode the user has must be returned. */
1447 int cstatus(userrec *user, chanrec *chan)
1449 if ((!chan) || (!user))
1451 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1455 for (int i = 0; i != MAXCHANS; i++)
1457 if ((user->chans[i].channel == chan) && (chan != NULL))
1459 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1463 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1467 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1469 return STATUS_VOICE;
1471 return STATUS_NORMAL;
1477 /* compile a userlist of a channel into a string, each nick seperated by
1478 * spaces and op, voice etc status shown as @ and + */
1480 void userlist(userrec *user,chanrec *c)
1482 if ((!c) || (!user))
1484 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1488 sprintf(list,"353 %s = %s :", user->nick, c->name);
1489 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1491 if (has_channel(i->second,c))
1493 if (isnick(i->second->nick))
1495 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1497 /* user is +i, and source not on the channel, does not show
1498 * nick in NAMES list */
1501 strcat(list,cmode(i->second,c));
1502 strcat(list,i->second->nick);
1504 if (strlen(list)>(480-NICKMAX))
1506 /* list overflowed into
1507 * multiple numerics */
1508 WriteServ(user->fd,list);
1509 sprintf(list,"353 %s = %s :", user->nick, c->name);
1514 /* if whats left in the list isnt empty, send it */
1515 if (list[strlen(list)-1] != ':')
1517 WriteServ(user->fd,list);
1521 /* return a count of the users on a specific channel accounting for
1522 * invisible users who won't increase the count. e.g. for /LIST */
1524 int usercount_i(chanrec *c)
1531 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1536 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1540 if (has_channel(i->second,c))
1542 if (isnick(i->second->nick))
1544 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1546 /* user is +i, and source not on the channel, does not show
1547 * nick in NAMES list */
1555 log(DEBUG,"usercount_i: %s %d",c->name,count);
1560 int usercount(chanrec *c)
1567 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1572 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1576 if (has_channel(i->second,c))
1578 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1585 log(DEBUG,"usercount: %s %d",c->name,count);
1590 /* add a channel to a user, creating the record for it if needed and linking
1591 * it to the user record */
1593 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1595 if ((!user) || (!cn))
1597 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1606 strncpy(cname,cn,MAXBUF);
1608 // we MUST declare this wherever we use FOREACH_RESULT
1611 if (strlen(cname) > CHANMAX-1)
1613 cname[CHANMAX-1] = '\0';
1616 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1618 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1620 return NULL; // already on the channel!
1624 if (!FindChan(cname))
1626 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1631 /* create a new one */
1632 log(DEBUG,"add_channel: creating: %s",cname);
1634 chanlist[cname] = new chanrec();
1636 strcpy(chanlist[cname]->name, cname);
1637 chanlist[cname]->topiclock = 1;
1638 chanlist[cname]->noexternal = 1;
1639 chanlist[cname]->created = time(NULL);
1640 strcpy(chanlist[cname]->topic, "");
1641 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1642 chanlist[cname]->topicset = 0;
1643 Ptr = chanlist[cname];
1644 log(DEBUG,"add_channel: created: %s",cname);
1645 /* set created to 2 to indicate user
1646 * is the first in the channel
1647 * and should be given ops */
1653 /* channel exists, just fish out a pointer to its struct */
1654 Ptr = FindChan(cname);
1657 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1659 // the override flag allows us to bypass channel modes
1660 // and bans (used by servers)
1663 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1668 if (strcmp(Ptr->key,""))
1670 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1673 log(DEBUG,"add_channel: no key given in JOIN");
1674 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1679 log(DEBUG,"key at %p is %s",key,key);
1680 if (strcasecmp(key,Ptr->key))
1682 log(DEBUG,"add_channel: bad key given in JOIN");
1683 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1688 log(DEBUG,"add_channel: no key");
1690 if (Ptr->inviteonly)
1692 log(DEBUG,"add_channel: channel is +i");
1693 if (user->IsInvited(Ptr->name))
1695 /* user was invited to channel */
1696 /* there may be an optional channel NOTICE here */
1700 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1704 log(DEBUG,"add_channel: channel is not +i");
1708 if (usercount(Ptr) == Ptr->limit)
1710 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1715 log(DEBUG,"add_channel: about to walk banlist");
1717 /* check user against the channel banlist */
1720 if (Ptr->bans.size())
1722 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1724 if (match(user->GetFullHost(),i->data))
1726 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1733 log(DEBUG,"add_channel: bans checked");
1736 if ((Ptr) && (user))
1738 user->RemoveInvite(Ptr->name);
1741 log(DEBUG,"add_channel: invites removed");
1746 log(DEBUG,"Overridden checks");
1754 log(DEBUG,"Passed channel checks");
1756 for (int i =0; i != MAXCHANS; i++)
1758 log(DEBUG,"Check location %d",i);
1759 if (user->chans[i].channel == NULL)
1761 log(DEBUG,"Adding into their channel list at location %d",i);
1765 /* first user in is given ops */
1766 user->chans[i].uc_modes = UCMODE_OP;
1770 user->chans[i].uc_modes = 0;
1772 user->chans[i].channel = Ptr;
1773 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1775 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1777 // use the stamdard J token with no privilages.
1778 char buffer[MAXBUF];
1779 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1780 NetSendToAll(buffer);
1783 log(DEBUG,"Sent JOIN to client");
1787 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1788 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1791 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1792 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1793 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1794 FOREACH_MOD OnUserJoin(user,Ptr);
1798 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1799 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1803 /* remove a channel from a users record, and remove the record from memory
1804 * if the channel has become empty */
1806 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1808 if ((!user) || (!cname))
1810 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1817 if ((!cname) || (!user))
1822 Ptr = FindChan(cname);
1829 FOREACH_MOD OnUserPart(user,Ptr);
1830 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1832 for (int i =0; i != MAXCHANS; i++)
1834 /* zap it from the channel list of the user */
1835 if (user->chans[i].channel == Ptr)
1839 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1843 char buffer[MAXBUF];
1844 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1845 NetSendToAll(buffer);
1854 char buffer[MAXBUF];
1855 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1856 NetSendToAll(buffer);
1859 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1861 user->chans[i].uc_modes = 0;
1862 user->chans[i].channel = NULL;
1863 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1868 /* if there are no users left on the channel */
1869 if (!usercount(Ptr))
1871 chan_hash::iterator iter = chanlist.find(Ptr->name);
1873 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1875 /* kill the record */
1876 if (iter != chanlist.end())
1878 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1879 delete iter->second;
1880 chanlist.erase(iter);
1886 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1888 if ((!src) || (!user) || (!Ptr) || (!reason))
1890 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1897 if ((!Ptr) || (!user) || (!src))
1902 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1904 if (!has_channel(user,Ptr))
1906 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1909 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1911 if (cstatus(src,Ptr) == STATUS_HOP)
1913 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1917 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1923 for (int i =0; i != MAXCHANS; i++)
1925 /* zap it from the channel list of the user */
1926 if (user->chans[i].channel)
1927 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1929 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1930 user->chans[i].uc_modes = 0;
1931 user->chans[i].channel = NULL;
1932 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1937 /* if there are no users left on the channel */
1938 if (!usercount(Ptr))
1940 chan_hash::iterator iter = chanlist.find(Ptr->name);
1942 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1944 /* kill the record */
1945 if (iter != chanlist.end())
1947 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1948 delete iter->second;
1949 chanlist.erase(iter);
1955 /* returns 1 if user u has channel c in their record, 0 if not */
1957 int has_channel(userrec *u, chanrec *c)
1961 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1964 for (int i =0; i != MAXCHANS; i++)
1966 if (u->chans[i].channel == c)
1974 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1979 if ((!user) || (!dest) || (!chan))
1981 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1984 if (status < STATUS_OP)
1986 log(DEBUG,"%s cant give ops to %s because they nave status %d and needs %d",user->nick,dest,status,STATUS_OP);
1987 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1994 log(DEFAULT,"the target nickname given to give_ops was invalid");
1995 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2001 log(DEFAULT,"the target nickname given to give_ops couldnt be found");
2002 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2007 for (int i = 0; i != MAXCHANS; i++)
2009 if ((d->chans[i].channel != NULL) && (chan != NULL))
2010 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2012 if (d->chans[i].uc_modes & UCMODE_OP)
2014 /* mode already set on user, dont allow multiple */
2015 log(DEFAULT,"The target user given to give_ops was already opped on the channel");
2018 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
2019 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
2023 log(DEFAULT,"The target channel given to give_ops was not in the users mode list");
2029 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
2034 if ((!user) || (!dest) || (!chan))
2036 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
2039 if (status != STATUS_OP)
2041 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2049 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2054 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2059 for (int i = 0; i != MAXCHANS; i++)
2061 if ((d->chans[i].channel != NULL) && (chan != NULL))
2062 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2064 if (d->chans[i].uc_modes & UCMODE_HOP)
2066 /* mode already set on user, dont allow multiple */
2069 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
2070 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
2079 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
2084 if ((!user) || (!dest) || (!chan))
2086 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
2089 if (status < STATUS_HOP)
2091 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2099 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2104 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2109 for (int i = 0; i != MAXCHANS; i++)
2111 if ((d->chans[i].channel != NULL) && (chan != NULL))
2112 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2114 if (d->chans[i].uc_modes & UCMODE_VOICE)
2116 /* mode already set on user, dont allow multiple */
2119 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
2120 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
2129 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
2134 if ((!user) || (!dest) || (!chan))
2136 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
2139 if (status < STATUS_OP)
2141 log(DEBUG,"%s cant give ops to %s because they have status %d and needs %d",user->nick,dest,status,STATUS_OP);
2142 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2150 log(DEBUG,"take_ops was given an invalid target nickname of %s",dest);
2151 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2156 log(DEBUG,"take_ops couldnt resolve the target nickname: %s",dest);
2157 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2162 for (int i = 0; i != MAXCHANS; i++)
2164 if ((d->chans[i].channel != NULL) && (chan != NULL))
2165 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2167 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
2169 /* mode already set on user, dont allow multiple */
2172 d->chans[i].uc_modes ^= UCMODE_OP;
2173 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
2177 log(DEBUG,"take_ops couldnt locate the target channel in the target users list");
2183 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
2188 if ((!user) || (!dest) || (!chan))
2190 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
2193 if (status != STATUS_OP)
2195 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2203 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2208 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2213 for (int i = 0; i != MAXCHANS; i++)
2215 if ((d->chans[i].channel != NULL) && (chan != NULL))
2216 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2218 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
2220 /* mode already set on user, dont allow multiple */
2223 d->chans[i].uc_modes ^= UCMODE_HOP;
2224 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
2233 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
2238 if ((!user) || (!dest) || (!chan))
2240 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
2243 if (status < STATUS_HOP)
2245 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2253 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2258 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2263 for (int i = 0; i != MAXCHANS; i++)
2265 if ((d->chans[i].channel != NULL) && (chan != NULL))
2266 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2268 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
2270 /* mode already set on user, dont allow multiple */
2273 d->chans[i].uc_modes ^= UCMODE_VOICE;
2274 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
2283 void TidyBan(char *ban)
2286 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
2290 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
2294 char* pos_of_pling = strchr(temp,'!');
2295 char* pos_of_at = strchr(temp,'@');
2297 pos_of_pling[0] = '\0';
2298 pos_of_at[0] = '\0';
2302 strncpy(NICK,temp,NICKMAX);
2303 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
2304 strncpy(HOST,pos_of_at,160);
2306 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
2309 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
2311 if ((!user) || (!dest) || (!chan)) {
2312 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
2317 if ((!user) || (!dest) || (!chan))
2319 if (strchr(dest,'!')==0)
2321 if (strchr(dest,'@')==0)
2323 for (int i = 0; i < strlen(dest); i++)
2326 for (int i = 0; i < strlen(dest); i++)
2330 for (int i = 0; i < strlen(dest); i++)
2336 for (int i = 0; i < strlen(dest); i++)
2341 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2344 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2346 if (!strcasecmp(i->data,dest))
2348 // dont allow a user to set the same ban twice
2353 b.set_time = time(NULL);
2354 strncpy(b.data,dest,MAXBUF);
2355 strncpy(b.set_by,user->nick,NICKMAX);
2356 chan->bans.push_back(b);
2360 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2362 if ((!user) || (!dest) || (!chan)) {
2363 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2367 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2368 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2370 if (!strcasecmp(i->data,dest))
2372 chan->bans.erase(i);
2379 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode, bool silent, bool local)
2382 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2386 char modelist[MAXBUF];
2387 char outlist[MAXBUF];
2388 char outstr[MAXBUF];
2389 char outpars[32][MAXBUF];
2395 bool k_set = false, l_set = false;
2402 log(DEBUG,"process_modes: start: parameters=%d",pcnt);
2404 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2405 /* parameters[2] onwards are parameters for
2406 * modes that require them :) */
2407 strcpy(outlist,"+");
2410 log(DEBUG,"process_modes: modelist: %s",modelist);
2412 for (ptr = 0; ptr < strlen(modelist); ptr++)
2417 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2418 char modechar = modelist[ptr];
2419 switch (modelist[ptr])
2424 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2426 outlist[strlen(outlist)-1] = '-';
2430 strcat(outlist,"-");
2440 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2442 outlist[strlen(outlist)-1] = '+';
2446 strcat(outlist,"+");
2454 if ((param >= pcnt)) break;
2455 log(DEBUG,"Enough parameters left");
2458 log(DEBUG,"calling give_ops");
2459 r = give_ops(user,parameters[param++],chan,status);
2463 log(DEBUG,"calling take_ops");
2464 r = take_ops(user,parameters[param++],chan,status);
2468 strcat(outlist,"o");
2469 strcpy(outpars[pc++],parameters[param-1]);
2474 if ((param >= pcnt)) break;
2477 r = give_hops(user,parameters[param++],chan,status);
2481 r = take_hops(user,parameters[param++],chan,status);
2485 strcat(outlist,"h");
2486 strcpy(outpars[pc++],parameters[param-1]);
2492 if ((param >= pcnt)) break;
2495 r = give_voice(user,parameters[param++],chan,status);
2499 r = take_voice(user,parameters[param++],chan,status);
2503 strcat(outlist,"v");
2504 strcpy(outpars[pc++],parameters[param-1]);
2509 if ((param >= pcnt)) break;
2512 r = add_ban(user,parameters[param++],chan,status);
2516 r = take_ban(user,parameters[param++],chan,status);
2520 strcat(outlist,"b");
2521 strcpy(outpars[pc++],parameters[param-1]);
2527 if ((param >= pcnt))
2535 if (!strcmp(chan->key,""))
2537 strcat(outlist,"k");
2539 strcpy(key,parameters[param++]);
2540 if (strlen(key)>32) {
2543 strcpy(outpars[pc++],key);
2544 strcpy(chan->key,key);
2550 /* checks on -k are case sensitive and only accurate to the
2551 first 32 characters */
2553 strcpy(key,parameters[param++]);
2554 if (strlen(key)>32) {
2557 /* only allow -k if correct key given */
2558 if (!strcmp(chan->key,key))
2560 strcat(outlist,"k");
2561 strcpy(chan->key,"");
2562 strcpy(outpars[pc++],key);
2572 strcat(outlist,"l");
2577 if ((param >= pcnt)) break;
2583 bool invalid = false;
2584 for (int i = 0; i < strlen(parameters[param]); i++)
2586 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2591 if (atoi(parameters[param]) < 1)
2599 chan->limit = atoi(parameters[param]);
2602 strcat(outlist,"l");
2603 strcpy(outpars[pc++],parameters[param++]);
2610 if (chan->inviteonly != mdir)
2612 strcat(outlist,"i");
2614 chan->inviteonly = mdir;
2618 if (chan->topiclock != mdir)
2620 strcat(outlist,"t");
2622 chan->topiclock = mdir;
2626 if (chan->noexternal != mdir)
2628 strcat(outlist,"n");
2630 chan->noexternal = mdir;
2634 if (chan->moderated != mdir)
2636 strcat(outlist,"m");
2638 chan->moderated = mdir;
2642 if (chan->secret != mdir)
2644 strcat(outlist,"s");
2645 if (chan->c_private)
2647 chan->c_private = 0;
2650 strcat(outlist,"-p+");
2654 strcat(outlist,"+p-");
2658 chan->secret = mdir;
2662 if (chan->c_private != mdir)
2664 strcat(outlist,"p");
2670 strcat(outlist,"-s+");
2674 strcat(outlist,"+s-");
2678 chan->c_private = mdir;
2682 log(DEBUG,"Preprocessing custom mode %c",modechar);
2685 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2687 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2690 if (ModeDefined(modechar,MT_CHANNEL))
2692 log(DEBUG,"A module has claimed this mode");
2695 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2697 p.push_back(parameters[param]);
2699 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2701 p.push_back(parameters[param]);
2704 bool handled = false;
2707 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2708 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2709 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2715 for (int i = 0; i <= MODCOUNT; i++)
2719 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2721 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2722 char app[] = {modechar, 0};
2725 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2727 strcat(outlist, app);
2729 else if (!strchr(outlist,modechar))
2731 strcat(outlist, app);
2734 chan->SetCustomMode(modechar,mdir);
2735 // include parameters in output if mode has them
2736 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2738 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2739 strcpy(outpars[pc++],parameters[param++]);
2741 // break, because only one module can handle the mode.
2753 /* this ensures only the *valid* modes are sent out onto the network */
2754 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2756 outlist[strlen(outlist)-1] = '\0';
2758 if (strcmp(outlist,""))
2760 strcpy(outstr,outlist);
2761 for (ptr = 0; ptr < pc; ptr++)
2764 strcat(outstr,outpars[ptr]);
2768 log(DEBUG,"Local mode change");
2769 WriteChannelLocal(chan, user, "MODE %s %s",chan->name,outstr);
2777 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2778 // M token for a usermode must go to all servers
2779 char buffer[MAXBUF];
2780 snprintf(buffer,MAXBUF,"M %s %s",chan->name, outstr);
2781 NetSendToAll(buffer);
2789 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2790 // M token for a usermode must go to all servers
2791 char buffer[MAXBUF];
2792 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick,chan->name, outstr);
2793 NetSendToAll(buffer);
2800 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2802 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2804 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2805 // RFC1459 specified modes
2806 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2808 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2812 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2813 if ((strchr(sourcemodes,'o')) && (!adding))
2815 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2818 else if (umode == 'o')
2820 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2824 // process any module-defined modes that need oper
2825 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2827 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2831 if (ModeDefined(umode,MT_CLIENT))
2833 // process any module-defined modes that don't need oper
2834 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2835 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2837 // no, this mode needs oper, and this user 'aint got what it takes!
2843 // anything else - return false.
2844 log(DEBUG,"umode %c not known by any ruleset",umode);
2848 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2855 strncpy(s2->nick,ServerName,NICKMAX);
2856 strcpy(s2->modes,"o");
2863 if (ModeDefined(umode,MT_CLIENT))
2865 for (int i = 0; i <= MODCOUNT; i++)
2867 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2869 log(DEBUG,"Module claims umode %c",umode);
2873 log(DEBUG,"No module claims umode %c",umode);
2892 void handle_mode(char **parameters, int pcnt, userrec *user)
2898 char outpars[MAXBUF];
2900 dest = Find(parameters[0]);
2907 if ((dest) && (pcnt == 1))
2909 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2913 if ((dest) && (pcnt > 1))
2915 char dmodes[MAXBUF];
2916 strncpy(dmodes,dest->modes,MAXBUF);
2917 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2922 if (strchr(user->modes,'o'))
2933 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2937 strcpy(outpars,"+");
2940 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2943 for (int i = 0; i < strlen(parameters[1]); i++)
2945 if (parameters[1][i] == '+')
2949 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2951 outpars[strlen(outpars)-1] = '+';
2955 strcat(outpars,"+");
2961 if (parameters[1][i] == '-')
2965 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2967 outpars[strlen(outpars)-1] = '-';
2971 strcat(outpars,"-");
2979 if (strchr(user->modes,'o'))
2985 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2994 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2996 char umode = parameters[1][i];
2997 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2999 dmodes[strlen(dmodes)+1]='\0';
3000 dmodes[strlen(dmodes)] = parameters[1][i];
3001 outpars[strlen(outpars)+1]='\0';
3002 outpars[strlen(outpars)] = parameters[1][i];
3008 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3010 char umode = parameters[1][i];
3011 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3017 outpars[strlen(outpars)+1]='\0';
3018 outpars[strlen(outpars)] = parameters[1][i];
3021 for (q = 0; q < strlen(dmodes); q++)
3023 if (dmodes[q] != parameters[1][i])
3030 strcpy(dmodes,temp);
3037 if (strlen(outpars))
3043 while (i < strlen (outpars))
3045 b[z++] = outpars[i++];
3047 if (i<strlen(outpars)-1)
3049 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3051 // someones playing silly buggers and trying
3052 // to put a +- or -+ into the line...
3056 if (i == strlen(outpars)-1)
3058 if ((outpars[i] == '-') || (outpars[i] == '+'))
3066 if ((b[z] == '-') || (b[z] == '+'))
3069 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3072 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3074 // M token for a usermode must go to all servers
3075 char buffer[MAXBUF];
3076 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3077 NetSendToAll(buffer);
3079 if (strlen(dmodes)>MAXMODES)
3081 dmodes[MAXMODES-1] = '\0';
3083 log(DEBUG,"Stripped mode line");
3084 log(DEBUG,"Line dest is now %s",dmodes);
3085 strncpy(dest->modes,dmodes,MAXMODES);
3092 Ptr = FindChan(parameters[0]);
3097 /* just /modes #channel */
3098 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
3099 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
3105 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
3108 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
3110 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
3112 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
3117 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3119 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
3123 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,false);
3127 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3134 void server_mode(char **parameters, int pcnt, userrec *user)
3140 char outpars[MAXBUF];
3142 dest = Find(parameters[0]);
3144 // fix: ChroNiCk found this - we cant use this as debug if its null!
3147 log(DEBUG,"server_mode on %s",dest->nick);
3150 if ((dest) && (pcnt > 1))
3152 log(DEBUG,"params > 1");
3154 char dmodes[MAXBUF];
3155 strncpy(dmodes,dest->modes,MAXBUF);
3157 strcpy(outpars,"+");
3160 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3163 for (int i = 0; i < strlen(parameters[1]); i++)
3165 if (parameters[1][i] == '+')
3169 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3171 outpars[strlen(outpars)-1] = '+';
3175 strcat(outpars,"+");
3181 if (parameters[1][i] == '-')
3185 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3187 outpars[strlen(outpars)-1] = '-';
3191 strcat(outpars,"-");
3198 log(DEBUG,"begin mode processing entry");
3204 log(DEBUG,"umode %c being added",parameters[1][i]);
3205 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3207 char umode = parameters[1][i];
3208 log(DEBUG,"umode %c is an allowed umode",umode);
3209 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3211 dmodes[strlen(dmodes)+1]='\0';
3212 dmodes[strlen(dmodes)] = parameters[1][i];
3213 outpars[strlen(outpars)+1]='\0';
3214 outpars[strlen(outpars)] = parameters[1][i];
3220 // can only remove a mode they already have
3221 log(DEBUG,"umode %c being removed",parameters[1][i]);
3222 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3224 char umode = parameters[1][i];
3225 log(DEBUG,"umode %c is an allowed umode",umode);
3226 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3232 outpars[strlen(outpars)+1]='\0';
3233 outpars[strlen(outpars)] = parameters[1][i];
3236 for (q = 0; q < strlen(dmodes); q++)
3238 if (dmodes[q] != parameters[1][i])
3245 strcpy(dmodes,temp);
3252 if (strlen(outpars))
3258 while (i < strlen (outpars))
3260 b[z++] = outpars[i++];
3262 if (i<strlen(outpars)-1)
3264 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3266 // someones playing silly buggers and trying
3267 // to put a +- or -+ into the line...
3271 if (i == strlen(outpars)-1)
3273 if ((outpars[i] == '-') || (outpars[i] == '+'))
3281 if ((b[z] == '-') || (b[z] == '+'))
3284 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3287 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3289 // M token for a usermode must go to all servers
3290 char buffer[MAXBUF];
3291 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3292 NetSendToAll(buffer);
3294 if (strlen(dmodes)>MAXMODES)
3296 dmodes[MAXMODES-1] = '\0';
3298 log(DEBUG,"Stripped mode line");
3299 log(DEBUG,"Line dest is now %s",dmodes);
3300 strncpy(dest->modes,dmodes,MAXMODES);
3307 Ptr = FindChan(parameters[0]);
3310 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true,false,false);
3314 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3320 void merge_mode(char **parameters, int pcnt)
3326 char outpars[MAXBUF];
3328 dest = Find(parameters[0]);
3330 // fix: ChroNiCk found this - we cant use this as debug if its null!
3333 log(DEBUG,"merge_mode on %s",dest->nick);
3336 if ((dest) && (pcnt > 1))
3338 log(DEBUG,"params > 1");
3340 char dmodes[MAXBUF];
3341 strncpy(dmodes,dest->modes,MAXBUF);
3343 strcpy(outpars,"+");
3346 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3349 for (int i = 0; i < strlen(parameters[1]); i++)
3351 if (parameters[1][i] == '+')
3355 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3357 outpars[strlen(outpars)-1] = '+';
3361 strcat(outpars,"+");
3367 if (parameters[1][i] == '-')
3371 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3373 outpars[strlen(outpars)-1] = '-';
3377 strcat(outpars,"-");
3384 log(DEBUG,"begin mode processing entry");
3390 log(DEBUG,"umode %c being added",parameters[1][i]);
3391 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],"o",true)))
3393 char umode = parameters[1][i];
3394 log(DEBUG,"umode %c is an allowed umode",umode);
3395 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3397 dmodes[strlen(dmodes)+1]='\0';
3398 dmodes[strlen(dmodes)] = parameters[1][i];
3399 outpars[strlen(outpars)+1]='\0';
3400 outpars[strlen(outpars)] = parameters[1][i];
3406 // can only remove a mode they already have
3407 log(DEBUG,"umode %c being removed",parameters[1][i]);
3408 if ((allowed_umode(parameters[1][i],"o",false)) && (strchr(dmodes,parameters[1][i])))
3410 char umode = parameters[1][i];
3411 log(DEBUG,"umode %c is an allowed umode",umode);
3412 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3418 outpars[strlen(outpars)+1]='\0';
3419 outpars[strlen(outpars)] = parameters[1][i];
3422 for (q = 0; q < strlen(dmodes); q++)
3424 if (dmodes[q] != parameters[1][i])
3431 strcpy(dmodes,temp);
3438 if (strlen(outpars))
3444 while (i < strlen (outpars))
3446 b[z++] = outpars[i++];
3448 if (i<strlen(outpars)-1)
3450 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3452 // someones playing silly buggers and trying
3453 // to put a +- or -+ into the line...
3457 if (i == strlen(outpars)-1)
3459 if ((outpars[i] == '-') || (outpars[i] == '+'))
3467 if ((b[z] == '-') || (b[z] == '+'))
3470 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3473 if (strlen(dmodes)>MAXMODES)
3475 dmodes[MAXMODES-1] = '\0';
3477 log(DEBUG,"Stripped mode line");
3478 log(DEBUG,"Line dest is now %s",dmodes);
3479 strncpy(dest->modes,dmodes,MAXMODES);
3486 Ptr = FindChan(parameters[0]);
3490 strncpy(s2.nick,ServerName,NICKMAX);
3491 strcpy(s2.modes,"o");
3493 process_modes(parameters,&s2,Ptr,STATUS_OP,pcnt,true,true,false);
3498 void merge_mode2(char **parameters, int pcnt, userrec* user)
3504 char outpars[MAXBUF];
3506 dest = Find(parameters[0]);
3508 // fix: ChroNiCk found this - we cant use this as debug if its null!
3511 log(DEBUG,"merge_mode on %s",dest->nick);
3514 if ((dest) && (pcnt > 1))
3516 log(DEBUG,"params > 1");
3518 char dmodes[MAXBUF];
3519 strncpy(dmodes,dest->modes,MAXBUF);
3521 strcpy(outpars,"+");
3524 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3527 for (int i = 0; i < strlen(parameters[1]); i++)
3529 if (parameters[1][i] == '+')
3533 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3535 outpars[strlen(outpars)-1] = '+';
3539 strcat(outpars,"+");
3545 if (parameters[1][i] == '-')
3549 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3551 outpars[strlen(outpars)-1] = '-';
3555 strcat(outpars,"-");
3562 log(DEBUG,"begin mode processing entry");
3568 log(DEBUG,"umode %c being added",parameters[1][i]);
3569 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3571 char umode = parameters[1][i];
3572 log(DEBUG,"umode %c is an allowed umode",umode);
3573 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3575 dmodes[strlen(dmodes)+1]='\0';
3576 dmodes[strlen(dmodes)] = parameters[1][i];
3577 outpars[strlen(outpars)+1]='\0';
3578 outpars[strlen(outpars)] = parameters[1][i];
3584 // can only remove a mode they already have
3585 log(DEBUG,"umode %c being removed",parameters[1][i]);
3586 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3588 char umode = parameters[1][i];
3589 log(DEBUG,"umode %c is an allowed umode",umode);
3590 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3596 outpars[strlen(outpars)+1]='\0';
3597 outpars[strlen(outpars)] = parameters[1][i];
3600 for (q = 0; q < strlen(dmodes); q++)
3602 if (dmodes[q] != parameters[1][i])
3609 strcpy(dmodes,temp);
3616 if (strlen(outpars))
3622 while (i < strlen (outpars))
3624 b[z++] = outpars[i++];
3626 if (i<strlen(outpars)-1)
3628 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3630 // someones playing silly buggers and trying
3631 // to put a +- or -+ into the line...
3635 if (i == strlen(outpars)-1)
3637 if ((outpars[i] == '-') || (outpars[i] == '+'))
3645 if ((b[z] == '-') || (b[z] == '+'))
3648 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3651 WriteTo(user,dest,"MODE :%s",b);
3653 if (strlen(dmodes)>MAXMODES)
3655 dmodes[MAXMODES-1] = '\0';
3657 log(DEBUG,"Stripped mode line");
3658 log(DEBUG,"Line dest is now %s",dmodes);
3659 strncpy(dest->modes,dmodes,MAXMODES);
3666 Ptr = FindChan(parameters[0]);
3669 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3674 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,true);
3680 /* This function pokes and hacks at a parameter list like the following:
3682 * PART #winbot, #darkgalaxy :m00!
3684 * to turn it into a series of individual calls like this:
3686 * PART #winbot :m00!
3687 * PART #darkgalaxy :m00!
3689 * The seperate calls are sent to a callback function provided by the caller
3690 * (the caller will usually call itself recursively). The callback function
3691 * must be a command handler. Calling this function on a line with no list causes
3692 * no action to be taken. You must provide a starting and ending parameter number
3693 * where the range of the list can be found, useful if you have a terminating
3694 * parameter as above which is actually not part of the list, or parameters
3695 * before the actual list as well. This code is used by many functions which
3696 * can function as "one to list" (see the RFC) */
3698 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
3703 char blog[32][MAXBUF];
3704 char blog2[32][MAXBUF];
3705 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
3706 char keystr[MAXBUF];
3709 for (int i = 0; i <32; i++)
3712 for (int i = 0; i <32; i++)
3713 strcpy(blog2[i],"");
3716 for (int i = 0; i <10; i++)
3720 parameters[i] = moo;
3725 if (pcnt > 1) /* we have a key to copy */
3727 strcpy(keystr,parameters[1]);
3731 if (!parameters[start])
3735 if (!strchr(parameters[start],','))
3740 for (int i = start; i <= end; i++)
3744 strcat(plist,parameters[i]);
3752 for (int i = 0; i < t; i++)
3754 if (plist[i] == ',')
3757 strcpy(blog[j++],param);
3761 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3766 strcpy(blog[j++],param);
3769 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3774 if ((joins) && (keystr))
3776 if (strchr(keystr,','))
3780 t2 = strlen(keystr);
3781 for (int i = 0; i < t2; i++)
3783 if (keystr[i] == ',')
3786 strcpy(blog2[j++],param);
3790 strcpy(blog2[j++],param);
3795 for (j = 0; j < total; j++)
3801 for (q = end; q < pcnt-1; q++)
3803 if (parameters[q+1])
3805 pars[q-end+1] = parameters[q+1];
3808 if ((joins) && (parameters[1]))
3819 /* repeatedly call the function with the hacked parameter list */
3820 if ((joins) && (pcnt > 1))
3824 // pars[1] already set up and containing key from blog2[j]
3829 pars[1] = parameters[1];
3835 fn(pars,pcnt-(end-start),u);
3843 void handle_join(char **parameters, int pcnt, userrec *user)
3848 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3850 if (parameters[0][0] == '#')
3852 Ptr = add_channel(user,parameters[0],parameters[1],false);
3857 void handle_part(char **parameters, int pcnt, userrec *user)
3863 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3865 del_channel(user,parameters[0],parameters[1],false);
3869 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3871 del_channel(user,parameters[0],NULL,false);
3875 void handle_kick(char **parameters, int pcnt, userrec *user)
3877 chanrec* Ptr = FindChan(parameters[0]);
3878 userrec* u = Find(parameters[1]);
3882 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3886 if (!has_channel(u,Ptr))
3888 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3892 char reason[MAXBUF];
3896 strncpy(reason,parameters[2],MAXBUF);
3897 if (strlen(reason)>MAXKICK)
3899 reason[MAXKICK-1] = '\0';
3902 kick_channel(user,u,Ptr,reason);
3906 strcpy(reason,user->nick);
3907 kick_channel(user,u,Ptr,reason);
3910 // this must be propogated so that channel membership is kept in step network-wide
3912 char buffer[MAXBUF];
3913 snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
3914 NetSendToAll(buffer);
3918 void handle_die(char **parameters, int pcnt, userrec *user)
3920 log(DEBUG,"die: %s",user->nick);
3921 if (!strcmp(parameters[0],diepass))
3923 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3929 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3933 void handle_restart(char **parameters, int pcnt, userrec *user)
3935 log(DEBUG,"restart: %s",user->nick);
3936 if (!strcmp(parameters[0],restartpass))
3938 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3941 /* Will finish this later when i can be arsed :) */
3945 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3950 void kill_link(userrec *user,const char* r)
3952 user_hash::iterator iter = clientlist.find(user->nick);
3954 char reason[MAXBUF];
3956 strncpy(reason,r,MAXBUF);
3958 if (strlen(reason)>MAXQUIT)
3960 reason[MAXQUIT-1] = '\0';
3963 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3964 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3965 log(DEBUG,"closing fd %d",user->fd);
3967 /* bugfix, cant close() a nonblocking socket (sux!) */
3968 if (user->registered == 7) {
3969 FOREACH_MOD OnUserQuit(user);
3970 WriteCommonExcept(user,"QUIT :%s",reason);
3972 // Q token must go to ALL servers!!!
3973 char buffer[MAXBUF];
3974 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
3975 NetSendToAll(buffer);
3978 /* push the socket on a stack of sockets due to be closed at the next opportunity
3979 * 'Client exited' is an exception to this as it means the client side has already
3980 * closed the socket, we don't need to do it.
3982 fd_reap.push_back(user->fd);
3984 bool do_purge = false;
3986 if (user->registered == 7) {
3987 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3991 if (iter != clientlist.end())
3993 log(DEBUG,"deleting user hash value %d",iter->second);
3994 if ((iter->second) && (user->registered == 7)) {
3995 delete iter->second;
3997 clientlist.erase(iter);
4000 if (user->registered == 7) {
4001 purge_empty_chans();
4006 void handle_kill(char **parameters, int pcnt, userrec *user)
4008 userrec *u = Find(parameters[0]);
4009 char killreason[MAXBUF];
4011 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
4014 if (strcmp(ServerName,u->server))
4017 WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
4018 sprintf(killreason,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
4019 WriteCommonExcept(u,"QUIT :%s",killreason);
4020 // K token must go to ALL servers!!!
4021 char buffer[MAXBUF];
4022 snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
4023 NetSendToAll(buffer);
4025 user_hash::iterator iter = clientlist.find(u->nick);
4026 if (iter != clientlist.end())
4028 log(DEBUG,"deleting user hash value %d",iter->second);
4029 if ((iter->second) && (user->registered == 7)) {
4030 delete iter->second;
4032 clientlist.erase(iter);
4034 purge_empty_chans();
4039 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
4040 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
4041 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
4042 kill_link(u,killreason);
4047 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4051 void handle_summon(char **parameters, int pcnt, userrec *user)
4053 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
4056 void handle_users(char **parameters, int pcnt, userrec *user)
4058 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
4062 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
4064 char* Passwd(userrec *user)
4066 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4068 if (match(user->host,i->host) && (i->type == CC_ALLOW))
4076 bool IsDenied(userrec *user)
4078 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4080 if (match(user->host,i->host) && (i->type == CC_DENY))
4090 void handle_pass(char **parameters, int pcnt, userrec *user)
4092 // Check to make sure they havnt registered -- Fix by FCS
4093 if (user->registered == 7)
4095 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4098 if (!strcasecmp(parameters[0],Passwd(user)))
4100 user->haspassed = true;
4104 void handle_invite(char **parameters, int pcnt, userrec *user)
4106 userrec* u = Find(parameters[0]);
4107 chanrec* c = FindChan(parameters[1]);
4113 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
4119 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
4128 if (cstatus(user,c) < 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, c->name);
4134 if (has_channel(u,c))
4136 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
4139 if (!has_channel(user,c))
4141 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
4144 u->InviteTo(c->name);
4145 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
4146 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
4148 // i token must go to ALL servers!!!
4149 char buffer[MAXBUF];
4150 snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
4151 NetSendToAll(buffer);
4154 void handle_topic(char **parameters, int pcnt, userrec *user)
4160 if (strlen(parameters[0]) <= CHANMAX)
4162 Ptr = FindChan(parameters[0]);
4167 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
4168 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
4172 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
4177 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4184 if (strlen(parameters[0]) <= CHANMAX)
4186 Ptr = FindChan(parameters[0]);
4189 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
4191 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
4196 strncpy(topic,parameters[1],MAXBUF);
4197 if (strlen(topic)>MAXTOPIC)
4199 topic[MAXTOPIC-1] = '\0';
4202 strcpy(Ptr->topic,topic);
4203 strcpy(Ptr->setby,user->nick);
4204 Ptr->topicset = time(NULL);
4205 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
4207 // t token must go to ALL servers!!!
4208 char buffer[MAXBUF];
4209 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
4210 NetSendToAll(buffer);
4214 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4220 /* sends out an error notice to all connected clients (not to be used
4223 void send_error(char *s)
4225 log(DEBUG,"send_error: %s",s);
4226 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4228 if (isnick(i->second->nick))
4230 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
4234 // fix - unregistered connections receive ERROR, not NOTICE
4235 Write(i->second->fd,"ERROR :%s",s);
4240 void Error(int status)
4242 signal (SIGALRM, SIG_IGN);
4243 signal (SIGPIPE, SIG_IGN);
4244 signal (SIGTERM, SIG_IGN);
4245 signal (SIGABRT, SIG_IGN);
4246 signal (SIGSEGV, SIG_IGN);
4247 signal (SIGURG, SIG_IGN);
4248 signal (SIGKILL, SIG_IGN);
4249 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
4250 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
4255 int main(int argc, char *argv[])
4259 log(DEBUG,"*** InspIRCd starting up!");
4260 if (!FileExists(CONFIG_FILE))
4262 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
4263 log(DEBUG,"main: no config");
4264 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
4268 if (!strcmp(argv[1],"-nofork")) {
4272 if (InspIRCd() == ERROR)
4274 log(DEBUG,"main: daemon function bailed");
4275 printf("ERROR: could not initialise. Shutting down.\n");
4282 template<typename T> inline string ConvToStr(const T &in)
4285 if (!(tmp << in)) return string();
4289 /* re-allocates a nick in the user_hash after they change nicknames,
4290 * returns a pointer to the new user as it may have moved */
4292 userrec* ReHashNick(char* Old, char* New)
4294 user_hash::iterator newnick;
4295 user_hash::iterator oldnick = clientlist.find(Old);
4297 log(DEBUG,"ReHashNick: %s %s",Old,New);
4299 if (!strcasecmp(Old,New))
4301 log(DEBUG,"old nick is new nick, skipping");
4302 return oldnick->second;
4305 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
4307 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
4309 clientlist[New] = new userrec();
4310 clientlist[New] = oldnick->second;
4311 /*delete oldnick->second; */
4312 clientlist.erase(oldnick);
4314 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
4316 return clientlist[New];
4319 /* adds or updates an entry in the whowas list */
4320 void AddWhoWas(userrec* u)
4322 user_hash::iterator iter = whowas.find(u->nick);
4323 userrec *a = new userrec();
4324 strcpy(a->nick,u->nick);
4325 strcpy(a->ident,u->ident);
4326 strcpy(a->dhost,u->dhost);
4327 strcpy(a->host,u->host);
4328 strcpy(a->fullname,u->fullname);
4329 strcpy(a->server,u->server);
4330 a->signon = u->signon;
4332 /* MAX_WHOWAS: max number of /WHOWAS items
4333 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
4334 * can be replaced by a newer one
4337 if (iter == whowas.end())
4339 if (whowas.size() == WHOWAS_MAX)
4341 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
4343 // 3600 seconds in an hour ;)
4344 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
4348 log(DEBUG,"added WHOWAS entry, purged an old record");
4355 log(DEBUG,"added fresh WHOWAS entry");
4356 whowas[a->nick] = a;
4361 log(DEBUG,"updated WHOWAS entry");
4362 delete iter->second;
4368 /* add a client connection to the sockets list */
4369 void AddClient(int socket, char* host, int port, bool iscached)
4373 char resolved[MAXBUF];
4376 user_hash::iterator iter;
4378 tempnick = ConvToStr(socket) + "-unknown";
4379 sprintf(tn2,"%d-unknown",socket);
4381 iter = clientlist.find(tempnick);
4383 if (iter != clientlist.end()) return;
4386 * It is OK to access the value here this way since we know
4387 * it exists, we just created it above.
4389 * At NO other time should you access a value in a map or a
4390 * hash_map this way.
4392 clientlist[tempnick] = new userrec();
4394 NonBlocking(socket);
4395 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
4397 clientlist[tempnick]->fd = socket;
4398 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
4399 strncpy(clientlist[tempnick]->host, host,160);
4400 strncpy(clientlist[tempnick]->dhost, host,160);
4401 strncpy(clientlist[tempnick]->server, ServerName,256);
4402 strncpy(clientlist[tempnick]->ident, "unknown",9);
4403 clientlist[tempnick]->registered = 0;
4404 clientlist[tempnick]->signon = time(NULL);
4405 clientlist[tempnick]->nping = time(NULL)+240;
4406 clientlist[tempnick]->lastping = 1;
4407 clientlist[tempnick]->port = port;
4411 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
4415 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
4418 // set the registration timeout for this user
4419 unsigned long class_regtimeout = 90;
4420 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4422 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4424 class_regtimeout = (unsigned long)i->registration_timeout;
4429 int class_flood = 0;
4430 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4432 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4434 class_flood = i->flood;
4439 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
4440 clientlist[tempnick]->flood = class_flood;
4442 for (int i = 0; i < MAXCHANS; i++)
4444 clientlist[tempnick]->chans[i].channel = NULL;
4445 clientlist[tempnick]->chans[i].uc_modes = 0;
4448 if (clientlist.size() == MAXCLIENTS)
4449 kill_link(clientlist[tempnick],"No more connections allowed in this class");
4452 void handle_names(char **parameters, int pcnt, userrec *user)
4456 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
4458 c = FindChan(parameters[0]);
4461 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
4463 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
4467 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4471 void handle_privmsg(char **parameters, int pcnt, userrec *user)
4476 user->idle_lastmsg = time(NULL);
4478 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
4480 if (parameters[0][0] == '#')
4482 chan = FindChan(parameters[0]);
4485 if ((chan->noexternal) && (!has_channel(user,chan)))
4487 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4490 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4492 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4498 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4503 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
4505 // if any users of this channel are on remote servers, broadcast the packet
4506 char buffer[MAXBUF];
4507 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
4508 NetSendToCommon(user,buffer);
4512 /* no such nick/channel */
4513 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4518 dest = Find(parameters[0]);
4521 if (strcmp(dest->awaymsg,""))
4523 /* auto respond with aweh msg */
4524 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
4529 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
4536 if (!strcmp(dest->server,user->server))
4538 // direct write, same server
4539 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
4543 char buffer[MAXBUF];
4544 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
4545 NetSendToOne(dest->server,buffer);
4550 /* no such nick/channel */
4551 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4555 void handle_notice(char **parameters, int pcnt, userrec *user)
4560 user->idle_lastmsg = time(NULL);
4562 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
4564 if (parameters[0][0] == '#')
4566 chan = FindChan(parameters[0]);
4569 if ((chan->noexternal) && (!has_channel(user,chan)))
4571 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4574 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4576 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4582 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4587 ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
4589 // if any users of this channel are on remote servers, broadcast the packet
4590 char buffer[MAXBUF];
4591 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
4592 NetSendToCommon(user,buffer);
4596 /* no such nick/channel */
4597 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4602 dest = Find(parameters[0]);
4607 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
4612 if (!strcmp(dest->server,user->server))
4614 // direct write, same server
4615 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
4619 char buffer[MAXBUF];
4620 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
4621 NetSendToOne(dest->server,buffer);
4626 /* no such nick/channel */
4627 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4633 char* chlist(userrec *user)
4638 log(DEBUG,"chlist: %s",user->nick);
4644 for (int i = 0; i != MAXCHANS; i++)
4646 if (user->chans[i].channel != NULL)
4648 if (user->chans[i].channel->name)
4650 strcpy(cmp,user->chans[i].channel->name);
4652 if (!strstr(lst,cmp))
4654 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
4656 strcat(lst,cmode(user,user->chans[i].channel));
4657 strcat(lst,user->chans[i].channel->name);
4666 lst[strlen(lst)-1] = '\0'; // chop trailing space
4671 void handle_info(char **parameters, int pcnt, userrec *user)
4673 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
4674 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
4675 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
4676 FOREACH_MOD OnInfo(user);
4677 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
4680 void handle_time(char **parameters, int pcnt, userrec *user)
4683 struct tm * timeinfo;
4686 timeinfo = localtime ( &rawtime );
4687 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
4691 void handle_whois(char **parameters, int pcnt, userrec *user)
4696 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
4698 dest = Find(parameters[0]);
4701 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
4702 if (dest->registered == 7)
4704 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
4705 if ((user == dest) || (strchr(user->modes,'o')))
4707 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
4709 if (strcmp(chlist(dest),""))
4711 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
4713 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, GetServerDescription(dest->server).c_str());
4714 if (strcmp(dest->awaymsg,""))
4716 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
4718 if (strchr(dest->modes,'o'))
4720 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
4722 FOREACH_MOD OnWhois(user,dest);
4723 if (!strcasecmp(user->server,dest->server))
4725 // idle time and signon line can only be sent if youre on the same server (according to RFC)
4726 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
4729 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
4733 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4738 /* no such nick/channel */
4739 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4743 void send_network_quit(const char* nick, const char* reason)
4745 char buffer[MAXBUF];
4746 snprintf(buffer,MAXBUF,"Q %s :%s",nick,reason);
4747 NetSendToAll(buffer);
4750 void handle_quit(char **parameters, int pcnt, userrec *user)
4752 user_hash::iterator iter = clientlist.find(user->nick);
4755 if (user->registered == 7)
4757 /* theres more to do here, but for now just close the socket */
4760 if (parameters[0][0] == ':')
4764 reason = parameters[0];
4766 if (strlen(reason)>MAXQUIT)
4768 reason[MAXQUIT-1] = '\0';
4771 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
4772 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
4773 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
4775 char buffer[MAXBUF];
4776 snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
4777 NetSendToAll(buffer);
4781 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
4782 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
4783 WriteCommonExcept(user,"QUIT :Client exited");
4785 char buffer[MAXBUF];
4786 snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
4787 NetSendToAll(buffer);
4789 FOREACH_MOD OnUserQuit(user);
4793 /* push the socket on a stack of sockets due to be closed at the next opportunity */
4794 fd_reap.push_back(user->fd);
4796 if (iter != clientlist.end())
4798 clientlist.erase(iter);
4799 log(DEBUG,"deleting user hash value %d",iter->second);
4800 //if ((user) && (user->registered == 7)) {
4805 if (user->registered == 7) {
4806 purge_empty_chans();
4810 void handle_who(char **parameters, int pcnt, userrec *user)
4812 chanrec* Ptr = NULL;
4814 /* theres more to do here, but for now just close the socket */
4817 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
4819 if (user->chans[0].channel)
4821 Ptr = user->chans[0].channel;
4822 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4824 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4826 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);
4832 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4836 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
4840 if (parameters[0][0] == '#')
4842 Ptr = FindChan(parameters[0]);
4845 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4847 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
4849 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);
4852 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4856 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4861 userrec* u = Find(parameters[0]);
4862 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);
4867 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4869 Ptr = user->chans[0].channel;
4870 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4872 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4874 if (strchr(i->second->modes,'o'))
4876 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);
4880 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4886 void handle_wallops(char **parameters, int pcnt, userrec *user)
4888 WriteWallOps(user,false,"%s",parameters[0]);
4891 void handle_list(char **parameters, int pcnt, userrec *user)
4895 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4896 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4898 if ((!i->second->c_private) && (!i->second->secret))
4900 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4903 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4907 void handle_rehash(char **parameters, int pcnt, userrec *user)
4909 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4911 FOREACH_MOD OnRehash();
4912 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4918 return clientlist.size();
4922 int usercount_invisible(void)
4926 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4928 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4933 int usercount_opers(void)
4937 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4939 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4944 int usercount_unknown(void)
4948 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4950 if ((i->second->fd) && (i->second->registered != 7))
4956 long chancount(void)
4958 return chanlist.size();
4961 long count_servs(void)
4964 //for (int j = 0; j < 255; j++)
4966 // if (servers[j] != NULL)
4972 long servercount(void)
4974 return count_servs()+1;
4980 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4982 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
4988 void handle_lusers(char **parameters, int pcnt, userrec *user)
4990 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4991 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4992 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4993 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4994 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
4997 void handle_admin(char **parameters, int pcnt, userrec *user)
4999 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
5000 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
5001 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
5002 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
5005 void ShowMOTD(userrec *user)
5009 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
5012 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
5013 for (int i = 0; i != MOTD.size(); i++)
5015 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
5017 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
5020 void ShowRULES(userrec *user)
5024 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
5027 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
5028 for (int i = 0; i != RULES.size(); i++)
5030 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
5032 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
5035 /* shows the message of the day, and any other on-logon stuff */
5036 void ConnectUser(userrec *user)
5038 user->registered = 7;
5039 user->idle_lastmsg = time(NULL);
5040 log(DEBUG,"ConnectUser: %s",user->nick);
5042 if (strcmp(Passwd(user),"") && (!user->haspassed))
5044 kill_link(user,"Invalid password");
5049 kill_link(user,"Unauthorised connection");
5053 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
5054 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
5055 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
5056 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
5057 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
5058 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);
5059 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);
5061 FOREACH_MOD OnUserConnect(user);
5062 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
5064 char buffer[MAXBUF];
5065 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);
5066 NetSendToAll(buffer);
5069 void handle_version(char **parameters, int pcnt, userrec *user)
5071 char Revision[] = "$Revision$";
5073 char *s1 = Revision;
5075 char *v1 = strtok_r(s1," ",&savept);
5077 char *v2 = strtok_r(s1," ",&savept);
5080 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
5083 void handle_ping(char **parameters, int pcnt, userrec *user)
5085 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
5088 void handle_pong(char **parameters, int pcnt, userrec *user)
5090 // set the user as alive so they survive to next ping
5094 void handle_motd(char **parameters, int pcnt, userrec *user)
5099 void handle_rules(char **parameters, int pcnt, userrec *user)
5104 void handle_user(char **parameters, int pcnt, userrec *user)
5106 if (user->registered < 3)
5108 if (isident(parameters[0]) == 0) {
5109 // This kinda Sucks, According to the RFC thou, its either this,
5110 // or "You have already registered" :p -- Craig
5111 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
5114 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
5115 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
5116 strncat(user->ident,parameters[0],IDENTMAX);
5117 strncpy(user->fullname,parameters[3],128);
5118 user->registered = (user->registered | 1);
5123 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
5126 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
5127 if (user->registered == 3)
5129 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5134 void handle_userhost(char **parameters, int pcnt, userrec *user)
5136 char Return[MAXBUF],junk[MAXBUF];
5137 sprintf(Return,"302 %s :",user->nick);
5138 for (int i = 0; i < pcnt; i++)
5140 userrec *u = Find(parameters[i]);
5143 if (strchr(u->modes,'o'))
5145 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
5146 strcat(Return,junk);
5150 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
5151 strcat(Return,junk);
5155 WriteServ(user->fd,Return);
5159 void handle_ison(char **parameters, int pcnt, userrec *user)
5161 char Return[MAXBUF];
5162 sprintf(Return,"303 %s :",user->nick);
5163 for (int i = 0; i < pcnt; i++)
5165 userrec *u = Find(parameters[i]);
5168 strcat(Return,u->nick);
5172 WriteServ(user->fd,Return);
5176 void handle_away(char **parameters, int pcnt, userrec *user)
5180 strcpy(user->awaymsg,parameters[0]);
5181 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
5185 strcpy(user->awaymsg,"");
5186 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
5190 void handle_whowas(char **parameters, int pcnt, userrec* user)
5192 user_hash::iterator i = whowas.find(parameters[0]);
5194 if (i == whowas.end())
5196 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
5197 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5201 time_t rawtime = i->second->signon;
5205 timeinfo = localtime(&rawtime);
5206 strcpy(b,asctime(timeinfo));
5207 b[strlen(b)-1] = '\0';
5209 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
5210 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
5211 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5216 void handle_trace(char **parameters, int pcnt, userrec *user)
5218 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5222 if (isnick(i->second->nick))
5224 if (strchr(i->second->modes,'o'))
5226 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
5230 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
5235 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
5241 void handle_modules(char **parameters, int pcnt, userrec *user)
5243 for (int i = 0; i < module_names.size(); i++)
5245 Version V = modules[i]->GetVersion();
5246 char modulename[MAXBUF];
5247 strncpy(modulename,module_names[i].c_str(),256);
5248 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));
5252 // calls a handler function for a command
5254 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
5256 for (int i = 0; i < cmdlist.size(); i++)
5258 if (!strcasecmp(cmdlist[i].command,commandname))
5260 if (cmdlist[i].handler_function)
5262 if (pcnt>=cmdlist[i].min_params)
5264 if (strchr(user->modes,cmdlist[i].flags_needed))
5266 cmdlist[i].handler_function(parameters,pcnt,user);
5274 void handle_stats(char **parameters, int pcnt, userrec *user)
5280 if (strlen(parameters[0])>1)
5282 /* make the stats query 1 character long */
5283 parameters[0][1] = '\0';
5286 /* stats m (list number of times each command has been used, plus bytecount) */
5287 if (!strcasecmp(parameters[0],"m"))
5289 for (int i = 0; i < cmdlist.size(); i++)
5291 if (cmdlist[i].handler_function)
5293 if (cmdlist[i].use_count)
5295 /* RPL_STATSCOMMANDS */
5296 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
5303 /* stats z (debug and memory info) */
5304 if (!strcasecmp(parameters[0],"z"))
5306 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
5307 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
5308 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
5309 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
5310 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
5311 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
5312 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
5313 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
5317 if (!strcasecmp(parameters[0],"o"))
5319 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5321 char LoginName[MAXBUF];
5322 char HostName[MAXBUF];
5323 char OperType[MAXBUF];
5324 ConfValue("oper","name",i,LoginName,&config_f);
5325 ConfValue("oper","host",i,HostName,&config_f);
5326 ConfValue("oper","type",i,OperType,&config_f);
5327 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
5331 /* stats l (show user I/O stats) */
5332 if (!strcasecmp(parameters[0],"l"))
5334 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
5335 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5337 if (isnick(i->second->nick))
5339 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);
5343 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);
5349 /* stats u (show server uptime) */
5350 if (!strcasecmp(parameters[0],"u"))
5352 time_t current_time = 0;
5353 current_time = time(NULL);
5354 time_t server_uptime = current_time - startup_time;
5356 stime = gmtime(&server_uptime);
5357 /* i dont know who the hell would have an ircd running for over a year nonstop, but
5358 * Craig suggested this, and it seemed a good idea so in it went */
5359 if (stime->tm_year > 70)
5361 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);
5365 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);
5369 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
5370 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
5374 void handle_connect(char **parameters, int pcnt, userrec *user)
5376 char Link_ServerName[1024];
5377 char Link_IPAddr[1024];
5378 char Link_Port[1024];
5379 char Link_Pass[1024];
5383 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5387 ConfValue("link","name",i,Link_ServerName,&config_f);
5388 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5389 ConfValue("link","port",i,Link_Port,&config_f);
5390 ConfValue("link","sendpass",i,Link_Pass,&config_f);
5391 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5392 LinkPort = atoi(Link_Port);
5393 if (match(Link_ServerName,parameters[0])) {
5401 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
5405 // TODO: Perform a check here to stop a server being linked twice!
5407 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
5409 if (me[defaultRoute])
5411 me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName,me[defaultRoute]->port);
5416 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);
5420 void DoSplitEveryone()
5422 bool go_again = true;
5426 for (int i = 0; i < 32; i++)
5430 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
5432 if (strcasecmp(j->GetServerName().c_str(),ServerName))
5435 j->CloseConnection();
5436 me[i]->connectors.erase(j);
5444 log(DEBUG,"Removed server. Will remove clients...");
5445 // iterate through the userlist and remove all users on this server.
5446 // because we're dealing with a mesh, we dont have to deal with anything
5447 // "down-route" from this server (nice huh)
5449 char reason[MAXBUF];
5453 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
5455 if (strcasecmp(u->second->server,ServerName))
5457 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
5458 kill_link(u->second,reason);
5468 void handle_squit(char **parameters, int pcnt, userrec *user)
5470 // send out an squit across the mesh and then clear the server list (for local squit)
5473 WriteOpers("SQUIT command issued by %s",user->nick);
5474 char buffer[MAXBUF];
5475 snprintf(buffer,MAXBUF,"& %s",ServerName);
5476 NetSendToAll(buffer);
5481 WriteServ(user->fd,"NOTICE :*** Remote SQUIT not supported yet.");
5485 char islast(const char* s)
5488 for (int j = 0; j < 32; j++)
5492 for (int k = 0; k < me[j]->connectors.size(); k++)
5494 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
5498 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
5508 long map_count(const char* s)
5511 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
5513 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
5518 void handle_links(char **parameters, int pcnt, userrec *user)
5520 WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
5521 for (int j = 0; j < 32; j++)
5525 for (int k = 0; k < me[j]->connectors.size(); k++)
5527 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());
5531 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
5534 void handle_map(char **parameters, int pcnt, userrec *user)
5537 snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
5538 while (strlen(line) < 50)
5540 WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)usercnt())*100));
5541 for (int j = 0; j < 32; j++)
5545 for (int k = 0; k < me[j]->connectors.size(); k++)
5547 snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(me[j]->connectors[k].GetServerName().c_str()),me[j]->connectors[k].GetServerName().c_str());
5548 while (strlen(line) < 50)
5550 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));
5554 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
5558 void handle_oper(char **parameters, int pcnt, userrec *user)
5560 char LoginName[MAXBUF];
5561 char Password[MAXBUF];
5562 char OperType[MAXBUF];
5563 char TypeName[MAXBUF];
5564 char Hostname[MAXBUF];
5567 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5569 ConfValue("oper","name",i,LoginName,&config_f);
5570 ConfValue("oper","password",i,Password,&config_f);
5571 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
5573 /* correct oper credentials */
5574 ConfValue("oper","type",i,OperType,&config_f);
5575 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
5576 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
5577 WriteServ(user->fd,"MODE %s :+o",user->nick);
5578 for (j =0; j < ConfValueEnum("type",&config_f); j++)
5580 ConfValue("type","name",j,TypeName,&config_f);
5581 if (!strcmp(TypeName,OperType))
5583 /* found this oper's opertype */
5584 ConfValue("type","host",j,Hostname,&config_f);
5585 ChangeDisplayedHost(user,Hostname);
5588 if (!strchr(user->modes,'o'))
5590 strcat(user->modes,"o");
5592 FOREACH_MOD OnOper(user);
5597 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
5598 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
5601 void handle_nick(char **parameters, int pcnt, userrec *user)
5605 log(DEBUG,"not enough params for handle_nick");
5610 log(DEBUG,"invalid parameter passed to handle_nick");
5613 if (!strlen(parameters[0]))
5615 log(DEBUG,"zero length new nick passed to handle_nick");
5620 log(DEBUG,"invalid user passed to handle_nick");
5625 log(DEBUG,"invalid old nick passed to handle_nick");
5628 if (!strcasecmp(user->nick,parameters[0]))
5630 log(DEBUG,"old nick is new nick, skipping");
5635 if (strlen(parameters[0]) > 1)
5637 if (parameters[0][0] == ':')
5642 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
5644 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
5648 if (isnick(parameters[0]) == 0)
5650 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
5654 if (user->registered == 7)
5656 WriteCommon(user,"NICK %s",parameters[0]);
5658 // Q token must go to ALL servers!!!
5659 char buffer[MAXBUF];
5660 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
5661 NetSendToAll(buffer);
5665 /* change the nick of the user in the users_hash */
5666 user = ReHashNick(user->nick, parameters[0]);
5667 /* actually change the nick within the record */
5669 if (!user->nick) return;
5671 strncpy(user->nick, parameters[0],NICKMAX);
5673 log(DEBUG,"new nick set: %s",user->nick);
5675 if (user->registered < 3)
5676 user->registered = (user->registered | 2);
5677 if (user->registered == 3)
5679 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5682 log(DEBUG,"exit nickchange: %s",user->nick);
5685 void force_nickchange(userrec* user,const char* newnick)
5694 strncpy(nick,newnick,MAXBUF);
5696 if (user->registered == 7)
5700 handle_nick(pars,1,user);
5706 int process_parameters(char **command_p,char *parameters)
5711 q = strlen(parameters);
5714 /* no parameters, command_p invalid! */
5717 if (parameters[0] == ':')
5719 command_p[0] = parameters+1;
5724 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
5726 /* only one parameter */
5727 command_p[0] = parameters;
5728 if (parameters[0] == ':')
5730 if (strchr(parameters,' ') != NULL)
5738 command_p[j++] = parameters;
5739 for (int i = 0; i <= q; i++)
5741 if (parameters[i] == ' ')
5743 command_p[j++] = parameters+i+1;
5744 parameters[i] = '\0';
5745 if (command_p[j-1][0] == ':')
5747 *command_p[j-1]++; /* remove dodgy ":" */
5749 /* parameter like this marks end of the sequence */
5753 return j; /* returns total number of items in the list */
5756 void process_command(userrec *user, char* cmd)
5760 char *command_p[127];
5761 char p[MAXBUF], temp[MAXBUF];
5762 int i, j, items, cmd_found;
5764 for (int i = 0; i < 127; i++)
5765 command_p[i] = NULL;
5775 if (!strcmp(cmd,""))
5780 int total_params = 0;
5783 for (int q = 0; q < strlen(cmd)-1; q++)
5785 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
5788 // found a 'trailing', we dont count them after this.
5796 // another phidjit bug...
5797 if (total_params > 126)
5799 kill_link(user,"Protocol violation (1)");
5805 std::string tmp = cmd;
5806 for (int i = 0; i <= MODCOUNT; i++)
5808 std::string oldtmp = tmp;
5809 modules[i]->OnServerRaw(tmp,true);
5812 log(DEBUG,"A Module changed the input string!");
5813 log(DEBUG,"New string: %s",tmp.c_str());
5814 log(DEBUG,"Old string: %s",oldtmp.c_str());
5818 strncpy(cmd,tmp.c_str(),MAXBUF);
5821 if (!strchr(cmd,' '))
5823 /* no parameters, lets skip the formalities and not chop up
5825 log(DEBUG,"About to preprocess command with no params");
5827 command_p[0] = NULL;
5829 for (int i = 0; i <= strlen(cmd); i++)
5831 cmd[i] = toupper(cmd[i]);
5833 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
5840 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
5841 for (int i = 0; i < strlen(temp); i++)
5843 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
5849 /* split the full string into a command plus parameters */
5853 if (strchr(cmd,' '))
5855 for (int i = 0; i <= strlen(cmd); i++)
5857 /* capitalise the command ONLY, leave params intact */
5858 cmd[i] = toupper(cmd[i]);
5859 /* are we nearly there yet?! :P */
5863 parameters = cmd+i+1;
5871 for (int i = 0; i <= strlen(cmd); i++)
5873 cmd[i] = toupper(cmd[i]);
5880 if (strlen(command)>MAXCOMMAND)
5882 kill_link(user,"Protocol violation (2)");
5886 for (int x = 0; x < strlen(command); x++)
5888 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
5890 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
5892 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
5894 kill_link(user,"Protocol violation (3)");
5901 for (int i = 0; i != cmdlist.size(); i++)
5903 if (strcmp(cmdlist[i].command,""))
5905 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
5907 log(DEBUG,"Found matching command");
5911 if (strcmp(parameters,""))
5913 items = process_parameters(command_p,parameters);
5918 command_p[0] = NULL;
5924 command_p[0] = NULL;
5929 log(DEBUG,"Processing command");
5931 /* activity resets the ping pending timer */
5932 user->nping = time(NULL) + 120;
5933 if ((items) < cmdlist[i].min_params)
5935 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
5936 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
5939 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
5941 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
5942 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
5946 /* if the command isnt USER, PASS, or NICK, and nick is empty,
5948 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
5950 if ((!isnick(user->nick)) || (user->registered != 7))
5952 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5953 WriteServ(user->fd,"451 %s :You have not registered",command);
5957 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
5959 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
5960 if (cmdlist[i].handler_function)
5962 /* ikky /stats counters */
5967 user->bytes_in += strlen(temp);
5970 cmdlist[i].use_count++;
5971 cmdlist[i].total_bytes+=strlen(temp);
5974 /* WARNING: nothing may come after the
5975 * command handler call, as the handler
5976 * may free the user structure! */
5978 cmdlist[i].handler_function(command_p,items,user);
5984 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5985 WriteServ(user->fd,"451 %s :You have not registered",command);
5993 if ((!cmd_found) && (user))
5995 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
5996 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
6001 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
6004 /* create the command and push it onto the table */
6005 strcpy(comm.command,cmd);
6006 comm.handler_function = f;
6007 comm.flags_needed = flags;
6008 comm.min_params = minparams;
6010 comm.total_bytes = 0;
6011 cmdlist.push_back(comm);
6012 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
6015 void SetupCommandTable(void)
6017 createcommand("USER",handle_user,0,4);
6018 createcommand("NICK",handle_nick,0,1);
6019 createcommand("QUIT",handle_quit,0,0);
6020 createcommand("VERSION",handle_version,0,0);
6021 createcommand("PING",handle_ping,0,1);
6022 createcommand("PONG",handle_pong,0,1);
6023 createcommand("ADMIN",handle_admin,0,0);
6024 createcommand("PRIVMSG",handle_privmsg,0,2);
6025 createcommand("INFO",handle_info,0,0);
6026 createcommand("TIME",handle_time,0,0);
6027 createcommand("WHOIS",handle_whois,0,1);
6028 createcommand("WALLOPS",handle_wallops,'o',1);
6029 createcommand("NOTICE",handle_notice,0,2);
6030 createcommand("JOIN",handle_join,0,1);
6031 createcommand("NAMES",handle_names,0,1);
6032 createcommand("PART",handle_part,0,1);
6033 createcommand("KICK",handle_kick,0,2);
6034 createcommand("MODE",handle_mode,0,1);
6035 createcommand("TOPIC",handle_topic,0,1);
6036 createcommand("WHO",handle_who,0,1);
6037 createcommand("MOTD",handle_motd,0,0);
6038 createcommand("RULES",handle_rules,0,0);
6039 createcommand("OPER",handle_oper,0,2);
6040 createcommand("LIST",handle_list,0,0);
6041 createcommand("DIE",handle_die,'o',1);
6042 createcommand("RESTART",handle_restart,'o',1);
6043 createcommand("KILL",handle_kill,'o',2);
6044 createcommand("REHASH",handle_rehash,'o',0);
6045 createcommand("LUSERS",handle_lusers,0,0);
6046 createcommand("STATS",handle_stats,0,1);
6047 createcommand("USERHOST",handle_userhost,0,1);
6048 createcommand("AWAY",handle_away,0,0);
6049 createcommand("ISON",handle_ison,0,0);
6050 createcommand("SUMMON",handle_summon,0,0);
6051 createcommand("USERS",handle_users,0,0);
6052 createcommand("INVITE",handle_invite,0,2);
6053 createcommand("PASS",handle_pass,0,1);
6054 createcommand("TRACE",handle_trace,'o',0);
6055 createcommand("WHOWAS",handle_whowas,0,1);
6056 createcommand("CONNECT",handle_connect,'o',1);
6057 createcommand("SQUIT",handle_squit,'o',0);
6058 createcommand("MODULES",handle_modules,'o',0);
6059 createcommand("LINKS",handle_links,0,0);
6060 createcommand("MAP",handle_map,0,0);
6063 void process_buffer(const char* cmdbuf,userrec *user)
6067 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
6074 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
6077 if (!strcmp(cmdbuf,""))
6081 strncpy(cmd,cmdbuf,MAXBUF);
6082 if (!strcmp(cmd,""))
6086 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
6088 cmd[strlen(cmd)-1] = '\0';
6090 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
6092 cmd[strlen(cmd)-1] = '\0';
6094 if (!strcmp(cmd,""))
6098 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
6100 if ((user) && (cmd))
6102 process_command(user,cmd);
6106 void DoSync(serverrec* serv, char* udp_host)
6109 // send start of sync marker: Y <timestamp>
6110 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
6111 // except the ones its receiving it from.
6112 snprintf(data,MAXBUF,"Y %d",time(NULL));
6113 serv->SendPacket(data,udp_host);
6114 // send users and channels
6115 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
6117 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);
6118 serv->SendPacket(data,udp_host);
6119 if (strcmp(chlist(u->second),""))
6121 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
6122 serv->SendPacket(data,udp_host);
6125 // send channel modes, topics etc...
6126 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
6128 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
6129 serv->SendPacket(data,udp_host);
6130 if (strcmp(c->second->topic,""))
6132 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
6133 serv->SendPacket(data,udp_host);
6135 // send current banlist
6137 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
6139 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
6140 serv->SendPacket(data,udp_host);
6143 // send end of sync marker: E <timestamp>
6144 snprintf(data,MAXBUF,"F %d",time(NULL));
6145 serv->SendPacket(data,udp_host);
6146 // ircd sends its serverlist after the end of sync here
6150 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6152 char* src = strtok(params," ");
6153 char* dest = strtok(NULL," :");
6154 char* text = strtok(NULL,"\r\n");
6157 userrec* user = Find(src);
6160 userrec* dst = Find(dest);
6164 WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
6168 chanrec* d = FindChan(dest);
6171 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
6179 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6181 char* src = strtok(params," ");
6182 char* dest = strtok(NULL," :");
6183 char* text = strtok(NULL,"\r\n");
6186 userrec* user = Find(src);
6189 userrec* dst = Find(dest);
6193 WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
6197 chanrec* d = FindChan(dest);
6200 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
6207 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6209 char* nick = strtok(params," ");
6210 char* from = strtok(NULL," ");
6211 char* channel = strtok(NULL," ");
6212 userrec* u = Find(nick);
6213 userrec* user = Find(from);
6214 chanrec* c = FindChan(channel);
6215 if ((c) && (u) && (user))
6217 u->InviteTo(c->name);
6218 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
6222 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6224 char* setby = strtok(params," ");
6225 char* channel = strtok(NULL," :");
6226 char* topic = strtok(NULL,"\r\n");
6228 userrec* u = Find(setby);
6229 chanrec* c = FindChan(channel);
6232 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
6233 strncpy(c->topic,topic,MAXTOPIC);
6234 strncpy(c->setby,u->nick,NICKMAX);
6239 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6241 char* tm = strtok(params," ");
6242 char* setby = strtok(NULL," ");
6243 char* channel = strtok(NULL," :");
6244 char* topic = strtok(NULL,"\r\n");
6246 time_t TS = atoi(tm);
6247 chanrec* c = FindChan(channel);
6250 // in the case of topics and TS, the *NEWER*
6251 if (TS <= c->topicset)
6253 WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
6254 strncpy(c->topic,topic,MAXTOPIC);
6255 strncpy(c->setby,setby,NICKMAX);
6260 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6263 char original[MAXBUF],target[MAXBUF];
6264 strncpy(original,params,MAXBUF);
6266 char* parameter = strtok(params," ");
6267 strncpy(target,parameter,MAXBUF);
6270 pars[index++] = parameter;
6271 parameter = strtok(NULL," ");
6273 merge_mode(pars,index);
6274 if (FindChan(target))
6276 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
6280 WriteTo(NULL,Find(target),"MODE %s",original);
6284 // m is modes set by users only (not servers) valid targets are channels or users.
6286 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6288 // m blah #chatspike +b *!test@*4
6290 char original[MAXBUF];
6291 strncpy(original,params,MAXBUF);
6293 if (!strchr(params,' '))
6295 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
6301 char* src = strtok(params," ");
6302 userrec* user = Find(src);
6306 log(DEBUG,"Found user: %s",user->nick);
6307 char* parameter = strtok(NULL," ");
6310 pars[index++] = parameter;
6311 parameter = strtok(NULL," ");
6314 log(DEBUG,"Calling merge_mode2");
6315 merge_mode2(pars,index,user);
6320 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6322 char* nick = strtok(params," ");
6323 char* channel = strtok(NULL," :");
6324 char* reason = strtok(NULL,"\r\n");
6325 userrec* user = Find(nick);
6329 if (strcmp(reason,""))
6331 del_channel(user,channel,reason,true);
6335 del_channel(user,channel,NULL,true);
6340 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6342 char* src = strtok(params," ");
6343 char* nick = strtok(NULL," :");
6344 char* reason = strtok(NULL,"\r\n");
6345 char kreason[MAXBUF];
6348 userrec* u = Find(nick);
6349 userrec* user = Find(src);
6353 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
6354 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
6355 snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
6356 kill_link(u,kreason);
6360 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6362 char* nick = strtok(params," :");
6363 char* reason = strtok(NULL,"\r\n");
6366 userrec* user = Find(nick);
6370 if (strlen(reason)>MAXQUIT)
6372 reason[MAXQUIT-1] = '\0';
6376 WriteCommonExcept(user,"QUIT :%s",reason);
6378 user_hash::iterator iter = clientlist.find(user->nick);
6380 if (iter != clientlist.end())
6382 log(DEBUG,"deleting user hash value %d",iter->second);
6383 if ((iter->second) && (user->registered == 7)) {
6384 delete iter->second;
6386 clientlist.erase(iter);
6389 purge_empty_chans();
6393 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6395 char* oldnick = strtok(params," ");
6396 char* newnick = strtok(NULL," ");
6398 userrec* user = Find(oldnick);
6402 WriteCommon(user,"NICK %s",newnick);
6403 user = ReHashNick(user->nick, newnick);
6405 if (!user->nick) return;
6406 strncpy(user->nick, newnick,NICKMAX);
6407 log(DEBUG,"new nick set: %s",user->nick);
6411 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6412 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6414 char* src = strtok(params," ");
6415 char* dest = strtok(NULL," ");
6416 char* channel = strtok(NULL," :");
6417 char* reason = strtok(NULL,"\r\n");
6419 userrec* s = Find(src);
6420 userrec* d = Find(dest);
6421 chanrec* c = FindChan(channel);
6422 if ((s) && (d) && (c))
6424 kick_channel(s,d,c,reason);
6428 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6430 char* who = strtok(params," :");
6431 char* text = strtok(NULL,"\r\n");
6433 userrec* s = Find(who);
6436 WriteWallOps(s,true,text);
6441 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6443 char* tm = strtok(params," ");
6444 char* nick = strtok(NULL," ");
6445 char* host = strtok(NULL," ");
6446 char* dhost = strtok(NULL," ");
6447 char* ident = strtok(NULL," ");
6448 char* modes = strtok(NULL," ");
6449 char* server = strtok(NULL," :");
6450 char* gecos = strtok(NULL,"\r\n");
6453 time_t TS = atoi(tm);
6454 user_hash::iterator iter = clientlist.find(nick);
6455 if (iter != clientlist.end())
6458 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
6460 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
6461 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
6462 kill_link(iter->second,str);
6464 clientlist[nick] = new userrec();
6465 // remote users have an fd of -1. This is so that our Write abstraction
6466 // routines know to route any messages to this record away to whatever server
6468 clientlist[nick]->fd = -1;
6469 strncpy(clientlist[nick]->nick, nick,NICKMAX);
6470 strncpy(clientlist[nick]->host, host,160);
6471 strncpy(clientlist[nick]->dhost, dhost,160);
6472 strncpy(clientlist[nick]->server, server,256);
6473 strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
6474 strncpy(clientlist[nick]->fullname, gecos,128);
6475 clientlist[nick]->signon = TS;
6476 clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
6477 clientlist[nick]->lastping = 1;
6478 clientlist[nick]->port = 0; // so is this...
6479 clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
6480 clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
6481 for (int i = 0; i < MAXCHANS; i++)
6483 clientlist[nick]->chans[i].channel = NULL;
6484 clientlist[nick]->chans[i].uc_modes = 0;
6488 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6490 long tdiff = time(NULL) - atoi(params);
6492 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
6495 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6497 char* nick = strtok(params," :");
6498 char* gecos = strtok(NULL,"\r\n");
6500 userrec* user = Find(nick);
6503 strncpy(user->fullname,gecos,MAXBUF);
6506 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6508 char* nick = strtok(params," ");
6509 char* host = strtok(NULL," ");
6511 userrec* user = Find(nick);
6514 strncpy(user->dhost,host,160);
6517 void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6520 // + test3.chatspike.net 7010 -2016508415
6521 char* servername = strtok(params," ");
6522 char* ipaddr = strtok(NULL," ");
6523 char* ipport = strtok(NULL," ");
6524 char* cookie = strtok(NULL," ");
6525 log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
6528 bool conn_already = false;
6529 for (int i = 0; i < 32; i++)
6533 for (int j = 0; j < me[i]->connectors.size(); j++)
6535 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),servername))
6537 if (me[i]->connectors[j].GetServerPort() == atoi(ipport))
6539 log(DEBUG,"Already got a connection to %s:%d, ignoring +",ipaddr,atoi(ipport));
6540 conn_already = true;
6547 me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
6550 void handle_R(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6552 char* server = strtok(params," ");
6553 char* data = strtok(NULL,"\r\n");
6554 log(DEBUG,"Forwarded packet '%s' to '%s'",data,server);
6555 NetSendToOne(server,data);
6558 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6561 // The J token currently has no timestamp - this needs looking at
6562 // because it will allow splitriding.
6563 char* nick = strtok(params," ");
6564 char* channel = strtok(NULL," ");
6565 userrec* user = Find(nick);
6568 if ((user != NULL) && (strcmp(channel,"")))
6570 char privilage = '\0';
6571 if (channel[0] != '#')
6573 privilage = channel[0];
6576 add_channel(user,channel,"",true);
6578 // now work out the privilages they should have on each channel
6579 // and send the appropriate servermodes.
6580 for (int i = 0; i != MAXCHANS; i++)
6582 if (user->chans[i].channel)
6584 if (!strcasecmp(user->chans[i].channel->name,channel))
6586 if (privilage == '@')
6588 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
6589 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
6591 if (privilage == '%')
6593 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
6594 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
6596 if (privilage == '+')
6598 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
6599 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
6606 channel = strtok(NULL," ");
6610 void NetSendMyRoutingTable()
6612 // send out a line saying what is reachable to us.
6613 // E.g. if A is linked to B C and D, send out:
6615 // if its only linked to B and D send out:
6617 // if it has no links, dont even send out the line at all.
6618 char buffer[MAXBUF];
6619 sprintf(buffer,"$ %s",ServerName);
6620 bool sendit = false;
6621 for (int i = 0; i < 32; i++)
6625 for (int j = 0; j < me[i]->connectors.size(); j++)
6627 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
6629 strncat(buffer," ",MAXBUF);
6630 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
6637 NetSendToAll(buffer);
6640 void handle_dollar(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6642 log(DEBUG,"Storing routing table...");
6643 char* sourceserver = strtok(params," ");
6644 char* server = strtok(NULL," ");
6645 for (int i = 0; i < 32; i++)
6649 for (int j = 0; j < me[i]->connectors.size(); j++)
6651 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),sourceserver))
6653 me[i]->connectors[j].routes.clear();
6654 log(DEBUG,"Found entry for source server.");
6658 me[i]->connectors[j].routes.push_back(server);
6659 log(DEBUG,"*** Stored route: %s -> %s -> %s",ServerName,sourceserver,server);
6660 server = strtok(NULL," ");
6667 log(DEBUG,"Warning! routing table received from nonexistent server!");
6671 void DoSplit(const char* params)
6673 bool go_again = true;
6677 for (int i = 0; i < 32; i++)
6681 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
6683 if (!strcasecmp(j->GetServerName().c_str(),params))
6686 j->CloseConnection();
6687 me[i]->connectors.erase(j);
6695 log(DEBUG,"Removed server. Will remove clients...");
6696 // iterate through the userlist and remove all users on this server.
6697 // because we're dealing with a mesh, we dont have to deal with anything
6698 // "down-route" from this server (nice huh)
6700 char reason[MAXBUF];
6701 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
6705 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
6707 if (!strcasecmp(u->second->server,params))
6709 kill_link(u->second,reason);
6717 // removes a server. Will NOT remove its users!
6719 void RemoveServer(const char* name)
6721 bool go_again = true;
6725 for (int i = 0; i < 32; i++)
6729 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
6731 if (!strcasecmp(j->GetServerName().c_str(),name))
6734 j->CloseConnection();
6735 me[i]->connectors.erase(j);
6745 void handle_amp(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6747 log(DEBUG,"Netsplit! %s split from mesh, removing!",params);
6748 bool go_again = true;
6752 for (int i = 0; i < 32; i++)
6756 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
6758 if (!strcasecmp(j->GetServerName().c_str(),params))
6761 j->CloseConnection();
6762 me[i]->connectors.erase(j);
6770 log(DEBUG,"Removed server. Will remove clients...");
6771 // iterate through the userlist and remove all users on this server.
6772 // because we're dealing with a mesh, we dont have to deal with anything
6773 // "down-route" from this server (nice huh)
6775 char reason[MAXBUF];
6776 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
6780 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
6782 if (!strcasecmp(u->second->server,params))
6784 kill_link(u->second,reason);
6795 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,char* ipaddr,int port)
6797 char buffer[MAXBUF];
6804 nb_start = time(NULL);
6805 WriteOpers("Server %s is starting netburst.",udp_host);
6806 // now broadcast this new servers address out to all servers that are linked to us,
6807 // except the newcomer. They'll all attempt to connect back to it.
6808 authcookie = rand()*rand();
6809 snprintf(buffer,MAXBUF,"~ %d",authcookie);
6810 NetSendToAll(buffer);
6814 // once stored, this authcookie permits other servers to log in
6815 // without user or password, using it.
6817 auth_cookies.push_back(atoi(params));
6818 log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
6820 // connect back to a server using an authcookie
6822 handle_plus(token,params,source,reply,udp_host);
6826 handle_dollar(token,params,source,reply,udp_host);
6828 // node unreachable - we cant route to a server, sooooo we slit it off.
6829 // servers can generate these for themselves for an squit.
6831 handle_amp(token,params,source,reply,udp_host);
6833 // R <server> <data>
6834 // redirect token, send all of <data> along to the given
6835 // server as this server has been found to still have a route to it
6837 handle_R(token,params,source,reply,udp_host);
6842 reply->SendPacket("!",udp_host);
6852 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
6853 // introduce remote client
6855 handle_N(token,params,source,reply,udp_host);
6857 // a <NICK> :<GECOS>
6858 // change GECOS (SETNAME)
6860 handle_a(token,params,source,reply,udp_host);
6863 // change displayed host (SETHOST)
6865 handle_b(token,params,source,reply,udp_host);
6867 // t <NICK> <CHANNEL> :<TOPIC>
6868 // change a channel topic
6870 handle_t(token,params,source,reply,udp_host);
6872 // i <NICK> <CHANNEL>
6873 // invite a user to a channel
6875 handle_i(token,params,source,reply,udp_host);
6877 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6878 // kick a user from a channel
6880 handle_k(token,params,source,reply,udp_host);
6882 // n <NICK> <NEWNICK>
6883 // change nickname of client -- a server should only be able to
6884 // change the nicknames of clients that reside on it unless
6887 handle_n(token,params,source,reply,udp_host);
6889 // J <NICK> <CHANLIST>
6890 // Join user to channel list, merge channel permissions
6892 handle_J(token,params,source,reply,udp_host);
6894 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
6895 // change channel topic (netburst only)
6897 handle_T(token,params,source,reply,udp_host);
6899 // M <TARGET> <MODES> [MODE-PARAMETERS]
6900 // Server setting modes on an object
6902 handle_M(token,params,source,reply,udp_host);
6904 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
6905 // User setting modes on an object
6907 handle_m(token,params,source,reply,udp_host);
6909 // P <SOURCE> <TARGET> :<TEXT>
6910 // Send a private/channel message
6912 handle_P(token,params,source,reply,udp_host);
6914 // V <SOURCE> <TARGET> :<TEXT>
6915 // Send a private/channel notice
6917 handle_V(token,params,source,reply,udp_host);
6919 // L <SOURCE> <CHANNEL> :<REASON>
6920 // User parting a channel
6922 handle_L(token,params,source,reply,udp_host);
6924 // Q <SOURCE> :<REASON>
6927 handle_Q(token,params,source,reply,udp_host);
6929 // K <SOURCE> <DEST> :<REASON>
6932 handle_K(token,params,source,reply,udp_host);
6934 // @ <SOURCE> :<TEXT>
6937 handle_AT(token,params,source,reply,udp_host);
6942 WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
6943 handle_F(token,params,source,reply,udp_host);
6945 // tell all the other servers to use this authcookie to connect back again
6946 // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
6947 snprintf(buffer,MAXBUF,"+ %s %s %d %d",udp_host,ipaddr,port,authcookie);
6948 NetSendToAllExcept(udp_host,buffer);
6951 // Send netburst now
6953 WriteOpers("Sending my netburst to %s",udp_host);
6954 DoSync(source,udp_host);
6955 WriteOpers("Send of netburst to %s completed",udp_host);
6956 NetSendMyRoutingTable();
6960 WriteOpers("WARNING! Unknown datagram type '%c'",token);
6966 void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
6968 char response[10240];
6969 char token = udp_msg[0];
6970 char* params = udp_msg + 2;
6971 char finalparam[1024];
6972 strcpy(finalparam," :xxxx");
6973 if (strstr(udp_msg," :")) {
6974 strncpy(finalparam,strstr(udp_msg," :"),1024);
6977 char* cookie = strtok(params," ");
6978 char* servername = strtok(NULL," ");
6979 char* serverdesc = finalparam+2;
6981 WriteOpers("AuthCookie CONNECT from %s (%s)",servername,udp_host);
6983 for (int u = 0; u < auth_cookies.size(); u++)
6985 if (auth_cookies[u] == atoi(cookie))
6987 WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
6990 for (int j = 0; j < 32; j++)
6994 for (int k = 0; k < me[j]->connectors.size(); k++)
6996 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
6998 me[j]->connectors[k].SetServerName(servername);
6999 me[j]->connectors[k].SetDescription(serverdesc);
7000 me[j]->connectors[k].SetState(STATE_CONNECTED);
7001 NetSendMyRoutingTable();
7006 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",udp_host);
7014 // bad cookie, bad bad! go sit in the corner!
7015 WriteOpers("Bad cookie from %s!",servername);
7020 // S test.chatspike.net password portn :ChatSpike InspIRCd test server
7021 char* servername = strtok(params," ");
7022 char* password = strtok(NULL," ");
7023 char* myport = strtok(NULL," ");
7024 char* revision = strtok(NULL," ");
7025 char* serverdesc = finalparam+2;
7027 WriteOpers("CONNECT from %s (%s) (their port: %d)",servername,udp_host,atoi(myport));
7029 ircd_connector* cn = serv->FindHost(servername);
7033 WriteOpers("CONNECT aborted: Server %s already exists from %s",servername,ServerName);
7034 char buffer[MAXBUF];
7035 sprintf(buffer,"E :Server %s already exists!",servername);
7036 serv->SendPacket(buffer,udp_host);
7037 RemoveServer(udp_host);
7041 if (atoi(revision) != GetRevision())
7043 WriteOpers("CONNECT aborted: Could not link to %s, is an incompatible version %s, our version is %d",servername,revision,GetRevision());
7044 char buffer[MAXBUF];
7045 sprintf(buffer,"E :Version number mismatch");
7046 serv->SendPacket(buffer,udp_host);
7047 RemoveServer(udp_host);
7048 RemoveServer(servername);
7052 for (int j = 0; j < serv->connectors.size(); j++)
7054 if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
7056 serv->connectors[j].SetServerName(servername);
7057 serv->connectors[j].SetDescription(serverdesc);
7058 serv->connectors[j].SetServerPort(atoi(myport));
7063 char Link_ServerName[1024];
7064 char Link_IPAddr[1024];
7065 char Link_Port[1024];
7066 char Link_Pass[1024];
7067 char Link_SendPass[1024];
7070 // search for a corresponding <link> block in the config files
7071 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
7073 ConfValue("link","name",i,Link_ServerName,&config_f);
7074 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
7075 ConfValue("link","port",i,Link_Port,&config_f);
7076 ConfValue("link","recvpass",i,Link_Pass,&config_f);
7077 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
7078 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
7079 LinkPort = atoi(Link_Port);
7080 if (!strcasecmp(Link_ServerName,servername))
7082 // we have a matching link line -
7083 // send a 'diminutive' server message back...
7084 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
7085 serv->SendPacket(response,servername);
7087 for (int t = 0; t < serv->connectors.size(); t++)
7089 if (!strcasecmp(serv->connectors[t].GetServerName().c_str(),servername))
7091 serv->connectors[t].SetState(STATE_CONNECTED);
7098 char buffer[MAXBUF];
7099 sprintf(buffer,"E :Access is denied (no matching link block)");
7100 serv->SendPacket(buffer,udp_host);
7101 WriteOpers("CONNECT from %s denied, no matching link block",servername);
7102 RemoveServer(udp_host);
7103 RemoveServer(servername);
7108 // S test.chatspike.net password :ChatSpike InspIRCd test server
7109 char* servername = strtok(params," ");
7110 char* password = strtok(NULL," ");
7111 char* serverdesc = finalparam+2;
7113 // TODO: we should do a check here to ensure that this server is one we recently initiated a
7114 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
7115 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
7116 // a connect, so put out an oper alert!
7118 // for now, just accept all, we'll fix that later.
7119 WriteOpers("%s accepted our link credentials ",servername);
7121 char Link_ServerName[1024];
7122 char Link_IPAddr[1024];
7123 char Link_Port[1024];
7124 char Link_Pass[1024];
7125 char Link_SendPass[1024];
7128 // search for a corresponding <link> block in the config files
7129 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
7131 ConfValue("link","name",i,Link_ServerName,&config_f);
7132 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
7133 ConfValue("link","port",i,Link_Port,&config_f);
7134 ConfValue("link","recvpass",i,Link_Pass,&config_f);
7135 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
7136 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
7137 LinkPort = atoi(Link_Port);
7138 if (!strcasecmp(Link_ServerName,servername))
7140 // matching link at this end too, we're all done!
7141 // at this point we must begin key exchange and insert this
7142 // server into our 'active' table.
7143 for (int j = 0; j < 32; j++)
7147 for (int k = 0; k < me[j]->connectors.size(); k++)
7149 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
7151 char buffer[MAXBUF];
7152 me[j]->connectors[k].SetDescription(serverdesc);
7153 me[j]->connectors[k].SetState(STATE_CONNECTED);
7154 sprintf(buffer,"X 0");
7155 serv->SendPacket(buffer,udp_host);
7156 DoSync(me[j],udp_host);
7157 NetSendMyRoutingTable();
7162 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
7167 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
7170 char buffer[MAXBUF];
7171 sprintf(buffer,"E :Access is denied (no matching link block)");
7172 serv->SendPacket(buffer,udp_host);
7173 WriteOpers("CONNECT from %s denied, no matching link block",servername);
7174 RemoveServer(udp_host);
7175 RemoveServer(servername);
7180 char* error_message = finalparam+2;
7181 WriteOpers("ERROR from %s: %s",udp_host,error_message);
7186 serverrec* source_server = NULL;
7188 for (int j = 0; j < 32; j++)
7192 for (int x = 0; x < me[j]->connectors.size(); x++)
7194 log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
7195 if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
7197 if (me[j]->connectors[x].GetState() == STATE_CONNECTED)
7199 // found a valid ircd_connector.
7200 process_restricted_commands(token,params,me[j],serv,udp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
7208 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
7212 int reap_counter = 0;
7216 struct sockaddr_in client, server;
7217 char addrs[MAXBUF][255];
7218 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
7220 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
7221 int selectResult = 0, selectResult2 = 0;
7222 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
7223 char resolvedHost[MAXBUF];
7227 log_file = fopen("ircd.log","a+");
7230 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
7234 log(DEBUG,"InspIRCd: startup: begin");
7238 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
7240 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
7242 SetupCommandTable();
7243 log(DEBUG,"InspIRCd: startup: default command table set up");
7246 if (strcmp(DieValue,""))
7248 printf("WARNING: %s\n\n",DieValue);
7251 log(DEBUG,"InspIRCd: startup: read config");
7253 int count2 = 0, count3 = 0;
7255 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
7257 ConfValue("bind","port",count,configToken,&config_f);
7258 ConfValue("bind","address",count,Addr,&config_f);
7259 ConfValue("bind","type",count,Type,&config_f);
7260 if (!strcmp(Type,"servers"))
7262 char Default[MAXBUF];
7263 strcpy(Default,"no");
7264 ConfValue("bind","default",count,Default,&config_f);
7265 if (strchr(Default,'y'))
7267 defaultRoute = count3;
7268 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
7270 me[count3] = new serverrec(ServerName,100L,false);
7271 me[count3]->CreateListener(Addr,atoi(configToken));
7276 ports[count2] = atoi(configToken);
7277 strcpy(addrs[count2],Addr);
7280 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
7283 UDPportCount = count3;
7285 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
7287 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
7291 /* BugFix By Craig! :p */
7293 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
7295 char modfile[MAXBUF];
7296 ConfValue("module","name",count2,configToken,&config_f);
7297 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
7298 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
7299 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
7300 /* If The File Doesnt exist, Trying to load it
7301 * Will Segfault the IRCd.. So, check to see if
7302 * it Exists, Before Proceeding. */
7303 if (FileExists(modfile))
7305 factory[count] = new ircd_module(modfile);
7306 if (factory[count]->LastError())
7308 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
7309 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
7312 if (factory[count]->factory)
7314 modules[count] = factory[count]->factory->CreateModule();
7315 /* save the module and the module's classfactory, if
7316 * this isnt done, random crashes can occur :/ */
7317 module_names.push_back(modfile);
7321 log(DEBUG,"Unable to load %s",modfile);
7322 sprintf("Unable to load %s\nExiting...\n",modfile);
7325 /* Increase the Count */
7330 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
7331 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
7334 MODCOUNT = count - 1;
7335 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
7337 printf("\nInspIRCd is now running!\n");
7339 startup_time = time(NULL);
7343 log(VERBOSE,"Not forking as -nofork was specified");
7347 if (DaemonSeed() == ERROR)
7349 log(DEBUG,"InspIRCd: startup: can't daemonise");
7350 printf("ERROR: could not go into daemon mode. Shutting down.\n");
7356 /* setup select call */
7357 FD_ZERO(&selectFds);
7358 log(DEBUG,"InspIRCd: startup: zero selects");
7359 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
7361 for (count = 0; count < portCount; count++)
7363 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
7365 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
7368 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
7370 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
7372 else /* well we at least bound to one socket so we'll continue */
7378 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
7380 /* if we didn't bind to anything then abort */
7381 if (boundPortCount == 0)
7383 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
7388 length = sizeof (client);
7389 char udp_msg[MAXBUF], udp_host[MAXBUF];
7391 /* main loop, this never returns */
7394 #ifdef _POSIX_PRIORITY_SCHEDULING
7402 user_hash::iterator count2 = clientlist.begin();
7404 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
7405 // them in a list, then reap the list every second or so.
7406 if (reap_counter>300)
7408 if (fd_reap.size() > 0)
7410 for( int n = 0; n < fd_reap.size(); n++)
7412 Blocking(fd_reap[n]);
7414 NonBlocking(fd_reap[n]);
7423 FD_ZERO(&serverfds);
7426 for (int x = 0; x != UDPportCount; x++)
7428 FD_SET(me[x]->fd, &serverfds);
7434 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
7437 for (int x = 0; x != UDPportCount; x++)
7439 if (FD_ISSET (me[x]->fd, &serverfds))
7441 char remotehost[MAXBUF],resolved[MAXBUF];
7442 length = sizeof (client);
7443 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
7444 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
7445 if(CleanAndResolve(resolved, remotehost) != TRUE)
7447 strncpy(resolved,remotehost,MAXBUF);
7449 // add to this connections ircd_connector vector
7450 // *FIX* - we need the LOCAL port not the remote port in &client!
7451 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
7456 for (int x = 0; x < UDPportCount; x++)
7458 std::deque<std::string> msgs;
7460 if (me[x]->RecvPacket(msgs, udp_host))
7462 for (int ctr = 0; ctr < msgs.size(); ctr++)
7464 char udp_msg[MAXBUF];
7465 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
7466 if (strlen(udp_msg)<1)
7468 log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
7471 // during a netburst, send all data to all other linked servers
7472 if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
7474 NetSendToAllExcept(udp_host,udp_msg);
7476 FOREACH_MOD OnPacketReceive(udp_msg);
7477 handle_link_packet(udp_msg, udp_host, me[x]);
7484 while (count2 != clientlist.end())
7487 tval.tv_usec = tval.tv_sec = 0;
7489 int total_in_this_set = 0;
7491 user_hash::iterator xcount = count2;
7492 user_hash::iterator endingiter = count2;
7494 if (!count2->second) break;
7497 if (count2->second->fd != 0)
7499 // assemble up to 64 sockets into an fd_set
7500 // to implement a pooling mechanism.
7502 // This should be up to 64x faster than the
7503 // old implementation.
7504 while (total_in_this_set < 64)
7506 if (count2 != clientlist.end())
7508 // we don't check the state of remote users.
7509 if (count2->second->fd > 0)
7511 FD_SET (count2->second->fd, &sfd);
7513 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
7514 // their connection class.
7515 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
7517 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
7518 kill_link(count2->second,"Registration timeout");
7521 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
7523 if ((!count2->second->lastping) && (count2->second->registered == 7))
7525 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
7526 kill_link(count2->second,"Ping timeout");
7529 Write(count2->second->fd,"PING :%s",ServerName);
7530 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
7531 count2->second->lastping = 0;
7532 count2->second->nping = time(NULL)+120;
7536 total_in_this_set++;
7541 endingiter = count2;
7542 count2 = xcount; // roll back to where we were
7548 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
7550 // now loop through all of the items in this pool if any are waiting
7551 //if (selectResult2 > 0)
7552 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
7555 #ifdef _POSIX_PRIORITY_SCHEDULING
7560 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
7562 log(DEBUG,"Reading fd %d",count2a->second->fd);
7563 memset(data, 0, 10240);
7564 result = read(count2a->second->fd, data, 10240);
7569 log(DEBUG,"Read %d characters from socket",result);
7570 userrec* current = count2a->second;
7571 int currfd = current->fd;
7572 char* l = strtok(data,"\n");
7577 if ((floodlines > current->flood) && (current->flood != 0))
7579 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7580 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7581 kill_link(current,"Excess flood");
7584 char sanitized[NetBufferSize];
7585 memset(sanitized, 0, NetBufferSize);
7587 for (int pt = 0; pt < strlen(l); pt++)
7591 sanitized[ptt++] = l[pt];
7594 sanitized[ptt] = '\0';
7595 if (strlen(sanitized))
7599 // we're gonna re-scan to check if the nick is gone, after every
7600 // command - if it has, we're gonna bail
7601 bool find_again = false;
7602 process_buffer(sanitized,current);
7604 // look for the user's record in case it's changed
7605 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
7607 if (c2->second->fd == currfd)
7609 // found again, update pointer
7610 current == c2->second;
7619 l = strtok(NULL,"\n");
7624 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
7626 log(DEBUG,"killing: %s",count2a->second->nick);
7627 kill_link(count2a->second,strerror(errno));
7631 // result EAGAIN means nothing read
7632 if (result == EAGAIN)
7640 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
7641 kill_link(count2a->second,"Client exited");
7642 // must bail here? kill_link removes the hash, corrupting the iterator
7643 log(DEBUG,"Bailing from client exit");
7647 else if (result > 0)
7652 for (int q = 0; q < total_in_this_set; q++)
7654 // there is no iterator += operator :(
7655 //if (count2 != clientlist.end())
7662 // set up select call
7663 for (count = 0; count < boundPortCount; count++)
7665 FD_SET (openSockfd[count], &selectFds);
7669 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
7671 /* select is reporting a waiting socket. Poll them all to find out which */
7672 if (selectResult > 0)
7674 char target[MAXBUF], resolved[MAXBUF];
7675 for (count = 0; count < boundPortCount; count++)
7677 if (FD_ISSET (openSockfd[count], &selectFds))
7679 length = sizeof (client);
7680 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
7682 address_cache::iterator iter = IP.find(client.sin_addr);
7683 bool iscached = false;
7684 if (iter == IP.end())
7686 /* ip isn't in cache, add it */
7687 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
7688 if(CleanAndResolve(resolved, target) != TRUE)
7690 strncpy(resolved,target,MAXBUF);
7692 /* hostname now in 'target' */
7693 IP[client.sin_addr] = new string(resolved);
7694 /* hostname in cache */
7698 /* found ip (cached) */
7699 strncpy(resolved, iter->second->c_str(), MAXBUF);
7703 if (incomingSockfd < 0)
7705 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
7706 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
7710 AddClient(incomingSockfd, resolved, ports[count], iscached);
7711 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
7718 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
7721 close (incomingSockfd);