1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
44 #include "connection.h"
54 #define nspace __gnu_cxx
59 int LogLevel = DEFAULT;
60 char ServerName[MAXBUF];
62 char ServerDesc[MAXBUF];
63 char AdminName[MAXBUF];
64 char AdminEmail[MAXBUF];
65 char AdminNick[MAXBUF];
67 char restartpass[MAXBUF];
71 char PrefixQuit[MAXBUF];
72 char DieValue[MAXBUF];
74 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
75 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
77 time_t startup_time = time(NULL);
78 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
79 time_t nb_start = time(NULL);
81 extern vector<Module*> modules;
82 std::vector<std::string> module_names;
83 extern vector<ircd_module*> factory;
84 std::vector<int> fd_reap;
92 template<> struct nspace::hash<in_addr>
94 size_t operator()(const struct in_addr &a) const
97 memcpy(&q,&a,sizeof(size_t));
102 template<> struct nspace::hash<string>
104 size_t operator()(const string &s) const
107 static struct hash<const char *> strhash;
119 bool operator()(const string& s1, const string& s2) const
121 char a[MAXBUF],b[MAXBUF];
122 strcpy(a,s1.c_str());
123 strcpy(b,s2.c_str());
124 return (strcasecmp(a,b) == 0);
129 struct InAddr_HashComp
132 bool operator()(const in_addr &s1, const in_addr &s2) const
137 memcpy(&q,&s1,sizeof(size_t));
138 memcpy(&p,&s2,sizeof(size_t));
146 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
147 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
148 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
149 typedef std::deque<command_t> command_table;
152 serverrec* servers[255];
156 user_hash clientlist;
159 command_table cmdlist;
166 struct linger linger = { 0 };
167 char bannerBuffer[MAXBUF];
168 int boundPortCount = 0;
169 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
170 int defaultRoute = 0;
174 long MyKey = C.GenKey();
178 int has_channel(userrec *u, chanrec *c);
179 int usercount(chanrec *c);
180 int usercount_i(chanrec *c);
181 void update_stats_l(int fd,int data_out);
182 char* Passwd(userrec *user);
183 bool IsDenied(userrec *user);
184 void AddWhoWas(userrec* u);
186 std::stringstream config_f(stringstream::in | stringstream::out);
188 void safedelete(userrec *p)
192 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
193 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
199 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
203 void safedelete(chanrec *p)
209 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
213 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
218 void tidystring(char* str)
220 // strips out double spaces before a : parameter
223 bool go_again = true;
230 while ((str[0] == ' ') && (strlen(str)>0))
237 bool noparse = false;
240 while (a < strlen(str))
242 if ((a<strlen(str)-1) && (noparse==false))
244 if ((str[a] == ' ') && (str[a+1] == ' '))
246 log(DEBUG,"Tidied extra space out of string: %s",str);
254 if ((str[a] == ' ') && (str[a+1] == ':'))
260 temp[t++] = str[a++];
263 strncpy(str,temp,MAXBUF);
267 /* chop a string down to 512 characters and preserve linefeed (irc max
274 log(DEBUG,"ERROR! Null string passed to chop()!");
278 FOREACH_MOD OnServerRaw(temp,false);
279 const char* str2 = temp.c_str();
280 sprintf(str,"%s",str2);
283 if (strlen(str) >= 512)
292 std::string getservername()
297 std::string getserverdesc()
302 std::string getnetworkname()
307 std::string getadminname()
312 std::string getadminemail()
317 std::string getadminnick()
322 void log(int level,char *text, ...)
324 char textbuffer[MAXBUF];
327 struct tm * timeinfo;
328 if (level < LogLevel)
332 timeinfo = localtime (&rawtime);
337 va_start (argsPtr, text);
338 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
340 strcpy(b,asctime(timeinfo));
341 b[strlen(b)-1] = ':';
342 fprintf(log_file,"%s %s\n",b,textbuffer);
345 // nofork enabled? display it on terminal too
346 printf("%s %s\n",b,textbuffer);
351 void readfile(file_cache &F, const char* fname)
354 char linebuf[MAXBUF];
356 log(DEBUG,"readfile: loading %s",fname);
358 file = fopen(fname,"r");
363 fgets(linebuf,sizeof(linebuf),file);
364 linebuf[strlen(linebuf)-1]='\0';
365 if (!strcmp(linebuf,""))
371 F.push_back(linebuf);
378 log(DEBUG,"readfile: failed to load file: %s",fname);
380 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
383 void ReadConfig(void)
385 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
388 LoadConf(CONFIG_FILE,&config_f);
390 ConfValue("server","name",0,ServerName,&config_f);
391 ConfValue("server","description",0,ServerDesc,&config_f);
392 ConfValue("server","network",0,Network,&config_f);
393 ConfValue("admin","name",0,AdminName,&config_f);
394 ConfValue("admin","email",0,AdminEmail,&config_f);
395 ConfValue("admin","nick",0,AdminNick,&config_f);
396 ConfValue("files","motd",0,motd,&config_f);
397 ConfValue("files","rules",0,rules,&config_f);
398 ConfValue("power","diepass",0,diepass,&config_f);
399 ConfValue("power","pause",0,pauseval,&config_f);
400 ConfValue("power","restartpass",0,restartpass,&config_f);
401 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
402 ConfValue("die","value",0,DieValue,&config_f);
403 ConfValue("options","loglevel",0,dbg,&config_f);
404 ConfValue("options","netbuffersize",0,NB,&config_f);
405 NetBufferSize = atoi(NB);
406 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
408 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
409 NetBufferSize = 10240;
411 if (!strcmp(dbg,"debug"))
413 if (!strcmp(dbg,"verbose"))
415 if (!strcmp(dbg,"default"))
417 if (!strcmp(dbg,"sparse"))
419 if (!strcmp(dbg,"none"))
422 log(DEBUG,"Reading message of the day");
423 readfile(RULES,rules);
424 log(DEBUG,"Reading connect classes");
426 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
429 ConfValue("connect","allow",i,Value,&config_f);
430 ConfValue("connect","timeout",i,timeout,&config_f);
431 ConfValue("connect","flood",i,flood,&config_f);
432 if (strcmp(Value,""))
434 strcpy(c.host,Value);
437 ConfValue("connect","password",i,Value,&config_f);
438 strcpy(c.pass,Value);
439 c.registration_timeout = 90; // default is 2 minutes
440 c.flood = atoi(flood);
443 c.registration_timeout = atoi(timeout);
445 Classes.push_back(c);
446 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
450 ConfValue("connect","deny",i,Value,&config_f);
451 strcpy(c.host,Value);
453 Classes.push_back(c);
454 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
463 log(DEBUG,"Blocking: %d",s);
464 flags = fcntl(s, F_GETFL, 0);
465 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
468 void NonBlocking(int s)
471 log(DEBUG,"NonBlocking: %d",s);
472 flags = fcntl(s, F_GETFL, 0);
473 //fcntl(s, F_SETFL, O_NONBLOCK);
474 fcntl(s, F_SETFL, flags | O_NONBLOCK);
478 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
480 struct hostent *hostPtr = NULL;
483 memset (resolvedHost, '\0',MAXBUF);
484 if(unresolvedHost == NULL)
486 if ((inet_aton(unresolvedHost,&addr)) == 0)
488 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
490 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
492 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
496 /* write formatted text to a socket, in same format as printf */
498 void Write(int sock,char *text, ...)
502 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
505 char textbuffer[MAXBUF];
509 va_start (argsPtr, text);
510 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
512 sprintf(tb,"%s\r\n",textbuffer);
516 write(sock,tb,strlen(tb));
517 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
521 /* write a server formatted numeric response to a single socket */
523 void WriteServ(int sock, char* text, ...)
527 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
530 char textbuffer[MAXBUF],tb[MAXBUF];
532 va_start (argsPtr, text);
534 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
536 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
540 write(sock,tb,strlen(tb));
541 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
545 /* write text from an originating user to originating user */
547 void WriteFrom(int sock, userrec *user,char* text, ...)
549 if ((!text) || (!user))
551 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
554 char textbuffer[MAXBUF],tb[MAXBUF];
556 va_start (argsPtr, text);
558 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
560 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
564 write(sock,tb,strlen(tb));
565 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
569 /* write text to an destination user from a source user (e.g. user privmsg) */
571 void WriteTo(userrec *source, userrec *dest,char *data, ...)
573 if ((!dest) || (!data))
575 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
578 char textbuffer[MAXBUF],tb[MAXBUF];
580 va_start (argsPtr, data);
581 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
585 // if no source given send it from the server.
588 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
592 WriteFrom(dest->fd,source,"%s",textbuffer);
596 /* write formatted text from a source user to all users on a channel
597 * including the sender (NOT for privmsg, notice etc!) */
599 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
601 if ((!Ptr) || (!user) || (!text))
603 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
606 char textbuffer[MAXBUF];
608 va_start (argsPtr, text);
609 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
611 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
613 if (has_channel(i->second,Ptr))
615 WriteTo(user,i->second,"%s",textbuffer);
620 /* write formatted text from a source user to all users on a channel
621 * including the sender (NOT for privmsg, notice etc!) doesnt send to
622 * users on remote servers */
624 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
626 if ((!Ptr) || (!text))
628 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
631 char textbuffer[MAXBUF];
633 va_start (argsPtr, text);
634 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
636 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
638 if (has_channel(i->second,Ptr))
640 if (i->second->fd != -1)
644 WriteServ(i->second->fd,"%s",textbuffer);
648 WriteTo(user,i->second,"%s",textbuffer);
656 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
658 if ((!Ptr) || (!user) || (!text))
660 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
663 char textbuffer[MAXBUF];
665 va_start (argsPtr, text);
666 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
668 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
672 if (has_channel(i->second,Ptr))
674 WriteServ(i->second->fd,"%s",textbuffer);
681 /* write formatted text from a source user to all users on a channel except
682 * for the sender (for privmsg etc) */
684 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
686 if ((!Ptr) || (!user) || (!text))
688 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
691 char textbuffer[MAXBUF];
693 va_start (argsPtr, text);
694 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
697 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
701 if (has_channel(i->second,Ptr) && (user != i->second))
703 WriteTo(user,i->second,"%s",textbuffer);
709 int c_count(userrec* u)
712 for (int i =0; i != MAXCHANS; i++)
713 if (u->chans[i].channel != NULL)
719 /* return 0 or 1 depending if users u and u2 share one or more common channels
720 * (used by QUIT, NICK etc which arent channel specific notices) */
722 int common_channels(userrec *u, userrec *u2)
729 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
732 for (int i = 0; i != MAXCHANS; i++)
734 for (z = 0; z != MAXCHANS; z++)
736 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
738 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
740 if ((c_count(u)) && (c_count(u2)))
751 /* write a formatted string to all users who share at least one common
752 * channel, including the source user e.g. for use in NICK */
754 void WriteCommon(userrec *u, char* text, ...)
758 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
762 if (u->registered != 7) {
763 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
767 char textbuffer[MAXBUF];
769 va_start (argsPtr, text);
770 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
773 WriteFrom(u->fd,u,"%s",textbuffer);
775 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
779 if (common_channels(u,i->second) && (i->second != u))
781 WriteFrom(i->second->fd,u,"%s",textbuffer);
787 /* write a formatted string to all users who share at least one common
788 * channel, NOT including the source user e.g. for use in QUIT */
790 void WriteCommonExcept(userrec *u, char* text, ...)
794 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
798 if (u->registered != 7) {
799 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
803 char textbuffer[MAXBUF];
805 va_start (argsPtr, text);
806 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
809 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
813 if ((common_channels(u,i->second)) && (u != i->second))
815 WriteFrom(i->second->fd,u,"%s",textbuffer);
821 void WriteOpers(char* text, ...)
825 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
829 char textbuffer[MAXBUF];
831 va_start (argsPtr, text);
832 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
835 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
839 if (strchr(i->second->modes,'o'))
841 if (strchr(i->second->modes,'s'))
843 // send server notices to all with +s
844 // (TODO: needs SNOMASKs)
845 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
852 // returns TRUE of any users on channel C occupy server 'servername'.
854 bool ChanAnyOnThisServer(chanrec *c,char* servername)
856 log(DEBUG,"ChanAnyOnThisServer");
857 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
859 if (has_channel(i->second,c))
861 if (!strcasecmp(i->second->server,servername))
870 // returns true if user 'u' shares any common channels with any users on server 'servername'
872 bool CommonOnThisServer(userrec* u,char* servername)
874 log(DEBUG,"ChanAnyOnThisServer");
875 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
877 if ((common_channels(u,i->second)) && (u != i->second))
879 if (!strcasecmp(i->second->server,servername))
890 bool hasumode(userrec* user, char mode)
894 return (strchr(user->modes,mode)>0);
899 void WriteMode(const char* modes, int flags, const char* text, ...)
901 if ((!text) || (!modes) || (!flags))
903 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
907 char textbuffer[MAXBUF];
909 va_start (argsPtr, text);
910 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
913 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
917 bool send_to_user = false;
922 for (int n = 0; n < strlen(modes); n++)
924 if (!hasumode(i->second,modes[n]))
926 send_to_user = false;
931 else if (flags == WM_OR)
933 send_to_user = false;
934 for (int n = 0; n < strlen(modes); n++)
936 if (hasumode(i->second,modes[n]))
946 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
952 void WriteWallOps(userrec *source, char* text, ...)
954 if ((!text) || (!source))
956 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
961 char textbuffer[MAXBUF];
963 va_start (argsPtr, text);
964 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
967 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
971 if (strchr(i->second->modes,'w'))
973 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
979 /* convert a string to lowercase. Note following special circumstances
980 * taken from RFC 1459. Many "official" server branches still hold to this
981 * rule so i will too;
983 * Because of IRC's scandanavian origin, the characters {}| are
984 * considered to be the lower case equivalents of the characters []\,
985 * respectively. This is a critical issue when determining the
986 * equivalence of two nicknames.
989 void strlower(char *n)
995 for (int i = 0; i != strlen(n); i++)
997 n[i] = tolower(n[i]);
1007 /* verify that a user's ident and nickname is valid */
1009 int isident(const char* n)
1021 for (int i = 0; i != strlen(n); i++)
1023 if ((n[i] < 33) || (n[i] > 125))
1027 /* can't occur ANYWHERE in an Ident! */
1028 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1037 int isnick(const char* n)
1049 if (strlen(n) > NICKMAX-1)
1053 for (int i = 0; i != strlen(n); i++)
1055 if ((n[i] < 33) || (n[i] > 125))
1059 /* can't occur ANYWHERE in a nickname! */
1060 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1064 /* can't occur as the first char of a nickname... */
1065 if ((strchr("0123456789",n[i])) && (!i))
1073 /* Find a user record by nickname and return a pointer to it */
1075 userrec* Find(string nick)
1077 user_hash::iterator iter = clientlist.find(nick);
1079 if (iter == clientlist.end())
1080 /* Couldn't find it */
1083 return iter->second;
1086 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1088 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1092 if (i->second->fd == fd)
1094 i->second->bytes_out+=data_out;
1095 i->second->cmds_out++;
1102 /* find a channel record by channel name and return a pointer to it */
1104 chanrec* FindChan(const char* chan)
1108 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1112 chan_hash::iterator iter = chanlist.find(chan);
1114 if (iter == chanlist.end())
1115 /* Couldn't find it */
1118 return iter->second;
1122 void purge_empty_chans(void)
1124 int go_again = 1, purge = 0;
1129 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1132 if (!usercount(i->second))
1134 /* kill the record */
1135 if (i != chanlist.end())
1137 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1147 log(DEBUG,"skipped purge for %s",i->second->name);
1152 log(DEBUG,"completed channel purge, killed %d",purge);
1155 /* returns the status character for a given user on a channel, e.g. @ for op,
1156 * % for halfop etc. If the user has several modes set, the highest mode
1157 * the user has must be returned. */
1159 char* cmode(userrec *user, chanrec *chan)
1161 if ((!user) || (!chan))
1163 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1168 for (int i = 0; i != MAXCHANS; i++)
1170 if ((user->chans[i].channel == chan) && (chan != NULL))
1172 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1176 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1180 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1189 char scratch[MAXBUF];
1190 char sparam[MAXBUF];
1192 char* chanmodes(chanrec *chan)
1196 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1203 if (chan->noexternal)
1205 strncat(scratch,"n",MAXMODES);
1207 if (chan->topiclock)
1209 strncat(scratch,"t",MAXMODES);
1211 if (strcmp(chan->key,""))
1213 strncat(scratch,"k",MAXMODES);
1217 strncat(scratch,"l",MAXMODES);
1219 if (chan->inviteonly)
1221 strncat(scratch,"i",MAXMODES);
1223 if (chan->moderated)
1225 strncat(scratch,"m",MAXMODES);
1229 strncat(scratch,"s",MAXMODES);
1231 if (chan->c_private)
1233 strncat(scratch,"p",MAXMODES);
1235 if (strcmp(chan->key,""))
1237 strncat(sparam,chan->key,MAXBUF);
1242 sprintf(foo," %d",chan->limit);
1243 strncat(sparam,foo,MAXBUF);
1245 if (strlen(chan->custom_modes))
1247 strncat(scratch,chan->custom_modes,MAXMODES);
1248 for (int z = 0; z < strlen(chan->custom_modes); z++)
1250 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1253 strncat(sparam," ",MAXBUF);
1254 strncat(sparam,extparam.c_str(),MAXBUF);
1258 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1259 strncat(scratch,sparam,MAXMODES);
1263 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1264 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1265 * highest mode the user has must be returned. */
1267 int cstatus(userrec *user, chanrec *chan)
1269 if ((!chan) || (!user))
1271 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1275 for (int i = 0; i != MAXCHANS; i++)
1277 if ((user->chans[i].channel == chan) && (chan != NULL))
1279 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1283 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1287 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1289 return STATUS_VOICE;
1291 return STATUS_NORMAL;
1297 /* compile a userlist of a channel into a string, each nick seperated by
1298 * spaces and op, voice etc status shown as @ and + */
1300 void userlist(userrec *user,chanrec *c)
1302 if ((!c) || (!user))
1304 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1308 sprintf(list,"353 %s = %s :", user->nick, c->name);
1309 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1311 if (has_channel(i->second,c))
1313 if (isnick(i->second->nick))
1315 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1317 /* user is +i, and source not on the channel, does not show
1318 * nick in NAMES list */
1321 strcat(list,cmode(i->second,c));
1322 strcat(list,i->second->nick);
1324 if (strlen(list)>(480-NICKMAX))
1326 /* list overflowed into
1327 * multiple numerics */
1328 WriteServ(user->fd,list);
1329 sprintf(list,"353 %s = %s :", user->nick, c->name);
1334 /* if whats left in the list isnt empty, send it */
1335 if (list[strlen(list)-1] != ':')
1337 WriteServ(user->fd,list);
1341 /* return a count of the users on a specific channel accounting for
1342 * invisible users who won't increase the count. e.g. for /LIST */
1344 int usercount_i(chanrec *c)
1351 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1356 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1360 if (has_channel(i->second,c))
1362 if (isnick(i->second->nick))
1364 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1366 /* user is +i, and source not on the channel, does not show
1367 * nick in NAMES list */
1375 log(DEBUG,"usercount_i: %s %d",c->name,count);
1380 int usercount(chanrec *c)
1387 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1392 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1396 if (has_channel(i->second,c))
1398 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1405 log(DEBUG,"usercount: %s %d",c->name,count);
1410 /* add a channel to a user, creating the record for it if needed and linking
1411 * it to the user record */
1413 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1415 if ((!user) || (!cn))
1417 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1426 strncpy(cname,cn,MAXBUF);
1428 // we MUST declare this wherever we use FOREACH_RESULT
1431 if (strlen(cname) > CHANMAX-1)
1433 cname[CHANMAX-1] = '\0';
1436 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1438 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1440 return NULL; // already on the channel!
1444 if (!FindChan(cname))
1446 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1451 /* create a new one */
1452 log(DEBUG,"add_channel: creating: %s",cname);
1454 chanlist[cname] = new chanrec();
1456 strcpy(chanlist[cname]->name, cname);
1457 chanlist[cname]->topiclock = 1;
1458 chanlist[cname]->noexternal = 1;
1459 chanlist[cname]->created = time(NULL);
1460 strcpy(chanlist[cname]->topic, "");
1461 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1462 chanlist[cname]->topicset = 0;
1463 Ptr = chanlist[cname];
1464 log(DEBUG,"add_channel: created: %s",cname);
1465 /* set created to 2 to indicate user
1466 * is the first in the channel
1467 * and should be given ops */
1473 /* channel exists, just fish out a pointer to its struct */
1474 Ptr = FindChan(cname);
1477 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1479 // the override flag allows us to bypass channel modes
1480 // and bans (used by servers)
1483 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1488 if (strcmp(Ptr->key,""))
1490 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1493 log(DEBUG,"add_channel: no key given in JOIN");
1494 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1499 log(DEBUG,"key at %p is %s",key,key);
1500 if (strcasecmp(key,Ptr->key))
1502 log(DEBUG,"add_channel: bad key given in JOIN");
1503 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1508 log(DEBUG,"add_channel: no key");
1510 if (Ptr->inviteonly)
1512 log(DEBUG,"add_channel: channel is +i");
1513 if (user->IsInvited(Ptr->name))
1515 /* user was invited to channel */
1516 /* there may be an optional channel NOTICE here */
1520 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1524 log(DEBUG,"add_channel: channel is not +i");
1528 if (usercount(Ptr) == Ptr->limit)
1530 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1535 log(DEBUG,"add_channel: about to walk banlist");
1537 /* check user against the channel banlist */
1540 if (Ptr->bans.size())
1542 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1544 if (match(user->GetFullHost(),i->data))
1546 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1553 log(DEBUG,"add_channel: bans checked");
1556 if ((Ptr) && (user))
1558 user->RemoveInvite(Ptr->name);
1561 log(DEBUG,"add_channel: invites removed");
1566 log(DEBUG,"Overridden checks");
1574 log(DEBUG,"Passed channel checks");
1576 for (int i =0; i != MAXCHANS; i++)
1578 log(DEBUG,"Check location %d",i);
1579 if (user->chans[i].channel == NULL)
1581 log(DEBUG,"Adding into their channel list at location %d",i);
1585 /* first user in is given ops */
1586 user->chans[i].uc_modes = UCMODE_OP;
1590 user->chans[i].uc_modes = 0;
1592 user->chans[i].channel = Ptr;
1593 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1595 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1597 // use the stamdard J token with no privilages.
1598 char buffer[MAXBUF];
1599 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1600 for (int j = 0; j < 255; j++)
1602 if (servers[j] != NULL)
1604 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
1605 log(DEBUG,"Sent J token");
1610 log(DEBUG,"Sent JOIN to client");
1614 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1615 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1618 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1619 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1620 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1621 FOREACH_MOD OnUserJoin(user,Ptr);
1625 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1626 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1630 /* remove a channel from a users record, and remove the record from memory
1631 * if the channel has become empty */
1633 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1635 if ((!user) || (!cname))
1637 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1644 if ((!cname) || (!user))
1649 Ptr = FindChan(cname);
1656 FOREACH_MOD OnUserPart(user,Ptr);
1657 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1659 for (int i =0; i != MAXCHANS; i++)
1661 /* zap it from the channel list of the user */
1662 if (user->chans[i].channel == Ptr)
1666 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1670 char buffer[MAXBUF];
1671 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1672 for (int j = 0; j < 255; j++)
1674 if (servers[j] != NULL)
1676 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
1677 log(DEBUG,"Sent L token (with reason)");
1688 char buffer[MAXBUF];
1689 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1690 for (int j = 0; j < 255; j++)
1692 if (servers[j] != NULL)
1694 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
1695 log(DEBUG,"Sent L token (no reason)");
1700 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1702 user->chans[i].uc_modes = 0;
1703 user->chans[i].channel = NULL;
1704 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1709 /* if there are no users left on the channel */
1710 if (!usercount(Ptr))
1712 chan_hash::iterator iter = chanlist.find(Ptr->name);
1714 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1716 /* kill the record */
1717 if (iter != chanlist.end())
1719 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1720 delete iter->second;
1721 chanlist.erase(iter);
1727 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1729 if ((!src) || (!user) || (!Ptr) || (!reason))
1731 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1738 if ((!Ptr) || (!user) || (!src))
1743 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1745 if (!has_channel(user,Ptr))
1747 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1750 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1752 if (cstatus(src,Ptr) == STATUS_HOP)
1754 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1758 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1764 for (int i =0; i != MAXCHANS; i++)
1766 /* zap it from the channel list of the user */
1767 if (user->chans[i].channel)
1768 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1770 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1771 user->chans[i].uc_modes = 0;
1772 user->chans[i].channel = NULL;
1773 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1778 /* if there are no users left on the channel */
1779 if (!usercount(Ptr))
1781 chan_hash::iterator iter = chanlist.find(Ptr->name);
1783 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1785 /* kill the record */
1786 if (iter != chanlist.end())
1788 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1789 delete iter->second;
1790 chanlist.erase(iter);
1796 /* returns 1 if user u has channel c in their record, 0 if not */
1798 int has_channel(userrec *u, chanrec *c)
1802 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1805 for (int i =0; i != MAXCHANS; i++)
1807 if (u->chans[i].channel == c)
1815 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1820 if ((!user) || (!dest) || (!chan))
1822 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1825 if (status < STATUS_OP)
1827 log(DEBUG,"%s cant give ops to %s because they nave status %d and needs %d",user->nick,dest,status,STATUS_OP);
1828 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1835 log(DEFAULT,"the target nickname given to give_ops was invalid");
1836 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1842 log(DEFAULT,"the target nickname given to give_ops couldnt be found");
1843 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1848 for (int i = 0; i != MAXCHANS; i++)
1850 if ((d->chans[i].channel != NULL) && (chan != NULL))
1851 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1853 if (d->chans[i].uc_modes & UCMODE_OP)
1855 /* mode already set on user, dont allow multiple */
1856 log(DEFAULT,"The target user given to give_ops was already opped on the channel");
1859 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1860 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1864 log(DEFAULT,"The target channel given to give_ops was not in the users mode list");
1870 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1875 if ((!user) || (!dest) || (!chan))
1877 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1880 if (status != STATUS_OP)
1882 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1890 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1895 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1900 for (int i = 0; i != MAXCHANS; i++)
1902 if ((d->chans[i].channel != NULL) && (chan != NULL))
1903 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1905 if (d->chans[i].uc_modes & UCMODE_HOP)
1907 /* mode already set on user, dont allow multiple */
1910 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1911 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1920 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1925 if ((!user) || (!dest) || (!chan))
1927 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1930 if (status < STATUS_HOP)
1932 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1940 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1945 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1950 for (int i = 0; i != MAXCHANS; i++)
1952 if ((d->chans[i].channel != NULL) && (chan != NULL))
1953 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1955 if (d->chans[i].uc_modes & UCMODE_VOICE)
1957 /* mode already set on user, dont allow multiple */
1960 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1961 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1970 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1975 if ((!user) || (!dest) || (!chan))
1977 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1980 if (status < STATUS_OP)
1982 log(DEBUG,"%s cant give ops to %s because they have status %d and needs %d",user->nick,dest,status,STATUS_OP);
1983 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1991 log(DEBUG,"take_ops was given an invalid target nickname of %s",dest);
1992 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1997 log(DEBUG,"take_ops couldnt resolve the target nickname: %s",dest);
1998 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2003 for (int i = 0; i != MAXCHANS; i++)
2005 if ((d->chans[i].channel != NULL) && (chan != NULL))
2006 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2008 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
2010 /* mode already set on user, dont allow multiple */
2013 d->chans[i].uc_modes ^= UCMODE_OP;
2014 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
2018 log(DEBUG,"take_ops couldnt locate the target channel in the target users list");
2024 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
2029 if ((!user) || (!dest) || (!chan))
2031 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
2034 if (status != STATUS_OP)
2036 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2044 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2049 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2054 for (int i = 0; i != MAXCHANS; i++)
2056 if ((d->chans[i].channel != NULL) && (chan != NULL))
2057 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2059 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
2061 /* mode already set on user, dont allow multiple */
2064 d->chans[i].uc_modes ^= UCMODE_HOP;
2065 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
2074 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
2079 if ((!user) || (!dest) || (!chan))
2081 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
2084 if (status < STATUS_HOP)
2086 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2094 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2099 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2104 for (int i = 0; i != MAXCHANS; i++)
2106 if ((d->chans[i].channel != NULL) && (chan != NULL))
2107 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2109 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
2111 /* mode already set on user, dont allow multiple */
2114 d->chans[i].uc_modes ^= UCMODE_VOICE;
2115 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
2124 void TidyBan(char *ban)
2127 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
2131 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
2135 char* pos_of_pling = strchr(temp,'!');
2136 char* pos_of_at = strchr(temp,'@');
2138 pos_of_pling[0] = '\0';
2139 pos_of_at[0] = '\0';
2143 strncpy(NICK,temp,NICKMAX);
2144 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
2145 strncpy(HOST,pos_of_at,160);
2147 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
2150 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
2152 if ((!user) || (!dest) || (!chan)) {
2153 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
2158 if ((!user) || (!dest) || (!chan))
2160 if (strchr(dest,'!')==0)
2162 if (strchr(dest,'@')==0)
2164 for (int i = 0; i < strlen(dest); i++)
2167 for (int i = 0; i < strlen(dest); i++)
2171 for (int i = 0; i < strlen(dest); i++)
2177 for (int i = 0; i < strlen(dest); i++)
2182 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2185 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2187 if (!strcasecmp(i->data,dest))
2189 // dont allow a user to set the same ban twice
2194 b.set_time = time(NULL);
2195 strncpy(b.data,dest,MAXBUF);
2196 strncpy(b.set_by,user->nick,NICKMAX);
2197 chan->bans.push_back(b);
2201 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2203 if ((!user) || (!dest) || (!chan)) {
2204 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2208 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2209 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2211 if (!strcasecmp(i->data,dest))
2213 chan->bans.erase(i);
2220 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode, bool silent, bool local)
2223 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2227 char modelist[MAXBUF];
2228 char outlist[MAXBUF];
2229 char outstr[MAXBUF];
2230 char outpars[32][MAXBUF];
2236 bool k_set = false, l_set = false;
2243 log(DEBUG,"process_modes: start: parameters=%d",pcnt);
2245 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2246 /* parameters[2] onwards are parameters for
2247 * modes that require them :) */
2248 strcpy(outlist,"+");
2251 log(DEBUG,"process_modes: modelist: %s",modelist);
2253 for (ptr = 0; ptr < strlen(modelist); ptr++)
2258 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2259 char modechar = modelist[ptr];
2260 switch (modelist[ptr])
2265 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2267 outlist[strlen(outlist)-1] = '-';
2271 strcat(outlist,"-");
2281 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2283 outlist[strlen(outlist)-1] = '+';
2287 strcat(outlist,"+");
2295 if ((param >= pcnt)) break;
2296 log(DEBUG,"Enough parameters left");
2299 log(DEBUG,"calling give_ops");
2300 r = give_ops(user,parameters[param++],chan,status);
2304 log(DEBUG,"calling take_ops");
2305 r = take_ops(user,parameters[param++],chan,status);
2309 strcat(outlist,"o");
2310 strcpy(outpars[pc++],parameters[param-1]);
2315 if ((param >= pcnt)) break;
2318 r = give_hops(user,parameters[param++],chan,status);
2322 r = take_hops(user,parameters[param++],chan,status);
2326 strcat(outlist,"h");
2327 strcpy(outpars[pc++],parameters[param-1]);
2333 if ((param >= pcnt)) break;
2336 r = give_voice(user,parameters[param++],chan,status);
2340 r = take_voice(user,parameters[param++],chan,status);
2344 strcat(outlist,"v");
2345 strcpy(outpars[pc++],parameters[param-1]);
2350 if ((param >= pcnt)) break;
2353 r = add_ban(user,parameters[param++],chan,status);
2357 r = take_ban(user,parameters[param++],chan,status);
2361 strcat(outlist,"b");
2362 strcpy(outpars[pc++],parameters[param-1]);
2368 if ((param >= pcnt))
2376 if (!strcmp(chan->key,""))
2378 strcat(outlist,"k");
2380 strcpy(key,parameters[param++]);
2381 if (strlen(key)>32) {
2384 strcpy(outpars[pc++],key);
2385 strcpy(chan->key,key);
2391 /* checks on -k are case sensitive and only accurate to the
2392 first 32 characters */
2394 strcpy(key,parameters[param++]);
2395 if (strlen(key)>32) {
2398 /* only allow -k if correct key given */
2399 if (!strcmp(chan->key,key))
2401 strcat(outlist,"k");
2402 strcpy(chan->key,"");
2403 strcpy(outpars[pc++],key);
2413 strcat(outlist,"l");
2418 if ((param >= pcnt)) break;
2424 bool invalid = false;
2425 for (int i = 0; i < strlen(parameters[param]); i++)
2427 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2432 if (atoi(parameters[param]) < 1)
2440 chan->limit = atoi(parameters[param]);
2443 strcat(outlist,"l");
2444 strcpy(outpars[pc++],parameters[param++]);
2451 if (chan->inviteonly != mdir)
2453 strcat(outlist,"i");
2455 chan->inviteonly = mdir;
2459 if (chan->topiclock != mdir)
2461 strcat(outlist,"t");
2463 chan->topiclock = mdir;
2467 if (chan->noexternal != mdir)
2469 strcat(outlist,"n");
2471 chan->noexternal = mdir;
2475 if (chan->moderated != mdir)
2477 strcat(outlist,"m");
2479 chan->moderated = mdir;
2483 if (chan->secret != mdir)
2485 strcat(outlist,"s");
2486 if (chan->c_private)
2488 chan->c_private = 0;
2491 strcat(outlist,"-p+");
2495 strcat(outlist,"+p-");
2499 chan->secret = mdir;
2503 if (chan->c_private != mdir)
2505 strcat(outlist,"p");
2511 strcat(outlist,"-s+");
2515 strcat(outlist,"+s-");
2519 chan->c_private = mdir;
2523 log(DEBUG,"Preprocessing custom mode %c",modechar);
2526 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2528 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2531 if (ModeDefined(modechar,MT_CHANNEL))
2533 log(DEBUG,"A module has claimed this mode");
2536 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2538 p.push_back(parameters[param]);
2540 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2542 p.push_back(parameters[param]);
2545 bool handled = false;
2548 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2549 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2550 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2556 for (int i = 0; i <= MODCOUNT; i++)
2560 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2562 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2563 char app[] = {modechar, 0};
2566 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2568 strcat(outlist, app);
2570 else if (!strchr(outlist,modechar))
2572 strcat(outlist, app);
2575 chan->SetCustomMode(modechar,mdir);
2576 // include parameters in output if mode has them
2577 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2579 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2580 strcpy(outpars[pc++],parameters[param++]);
2582 // break, because only one module can handle the mode.
2594 /* this ensures only the *valid* modes are sent out onto the network */
2595 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2597 outlist[strlen(outlist)-1] = '\0';
2599 if (strcmp(outlist,""))
2601 strcpy(outstr,outlist);
2602 for (ptr = 0; ptr < pc; ptr++)
2605 strcat(outstr,outpars[ptr]);
2609 log(DEBUG,"Local mode change");
2610 WriteChannelLocal(chan, user, "MODE %s %s",chan->name,outstr);
2618 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2619 // M token for a usermode must go to all servers
2620 char buffer[MAXBUF];
2621 snprintf(buffer,MAXBUF,"M %s %s",chan->name, outstr);
2622 for (int j = 0; j < 255; j++)
2624 if (servers[j] != NULL)
2626 if (strcmp(servers[j]->name,ServerName))
2628 if (ChanAnyOnThisServer(chan,servers[j]->name))
2630 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
2631 log(DEBUG,"Sent M token");
2643 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2644 // M token for a usermode must go to all servers
2645 char buffer[MAXBUF];
2646 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick,chan->name, outstr);
2647 for (int j = 0; j < 255; j++)
2649 if (servers[j] != NULL)
2651 if (strcmp(servers[j]->name,ServerName))
2653 if (ChanAnyOnThisServer(chan,servers[j]->name))
2655 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
2656 log(DEBUG,"Sent m token");
2667 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2669 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2671 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2672 // RFC1459 specified modes
2673 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2675 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2679 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2680 if ((strchr(sourcemodes,'o')) && (!adding))
2682 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2685 else if (umode == 'o')
2687 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2691 // process any module-defined modes that need oper
2692 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2694 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2698 if (ModeDefined(umode,MT_CLIENT))
2700 // process any module-defined modes that don't need oper
2701 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2702 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2704 // no, this mode needs oper, and this user 'aint got what it takes!
2710 // anything else - return false.
2711 log(DEBUG,"umode %c not known by any ruleset",umode);
2715 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2722 strncpy(s2->nick,ServerName,NICKMAX);
2723 strcpy(s2->modes,"o");
2730 if (ModeDefined(umode,MT_CLIENT))
2732 for (int i = 0; i <= MODCOUNT; i++)
2734 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2736 log(DEBUG,"Module claims umode %c",umode);
2740 log(DEBUG,"No module claims umode %c",umode);
2750 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2760 void handle_mode(char **parameters, int pcnt, userrec *user)
2766 char outpars[MAXBUF];
2768 dest = Find(parameters[0]);
2775 if ((dest) && (pcnt == 1))
2777 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2781 if ((dest) && (pcnt > 1))
2783 char dmodes[MAXBUF];
2784 strncpy(dmodes,dest->modes,MAXBUF);
2785 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2790 if (strchr(user->modes,'o'))
2801 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2805 strcpy(outpars,"+");
2808 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2811 for (int i = 0; i < strlen(parameters[1]); i++)
2813 if (parameters[1][i] == '+')
2817 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2819 outpars[strlen(outpars)-1] = '+';
2823 strcat(outpars,"+");
2829 if (parameters[1][i] == '-')
2833 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2835 outpars[strlen(outpars)-1] = '-';
2839 strcat(outpars,"-");
2847 if (strchr(user->modes,'o'))
2853 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2862 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2864 char umode = parameters[1][i];
2865 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2867 dmodes[strlen(dmodes)+1]='\0';
2868 dmodes[strlen(dmodes)] = parameters[1][i];
2869 outpars[strlen(outpars)+1]='\0';
2870 outpars[strlen(outpars)] = parameters[1][i];
2876 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2878 char umode = parameters[1][i];
2879 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2885 outpars[strlen(outpars)+1]='\0';
2886 outpars[strlen(outpars)] = parameters[1][i];
2889 for (q = 0; q < strlen(dmodes); q++)
2891 if (dmodes[q] != parameters[1][i])
2898 strcpy(dmodes,temp);
2905 if (strlen(outpars))
2911 while (i < strlen (outpars))
2913 b[z++] = outpars[i++];
2915 if (i<strlen(outpars)-1)
2917 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2919 // someones playing silly buggers and trying
2920 // to put a +- or -+ into the line...
2924 if (i == strlen(outpars)-1)
2926 if ((outpars[i] == '-') || (outpars[i] == '+'))
2934 if ((b[z] == '-') || (b[z] == '+'))
2937 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2940 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2942 // M token for a usermode must go to all servers
2943 char buffer[MAXBUF];
2944 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
2945 for (int j = 0; j < 255; j++)
2947 if (servers[j] != NULL)
2949 if (strcmp(servers[j]->name,ServerName))
2951 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
2952 log(DEBUG,"Sent m token");
2957 if (strlen(dmodes)>MAXMODES)
2959 dmodes[MAXMODES-1] = '\0';
2961 log(DEBUG,"Stripped mode line");
2962 log(DEBUG,"Line dest is now %s",dmodes);
2963 strncpy(dest->modes,dmodes,MAXMODES);
2970 Ptr = FindChan(parameters[0]);
2975 /* just /modes #channel */
2976 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2977 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2983 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2986 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2988 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2990 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2995 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2997 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
3001 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,false);
3005 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3012 void server_mode(char **parameters, int pcnt, userrec *user)
3018 char outpars[MAXBUF];
3020 dest = Find(parameters[0]);
3022 // fix: ChroNiCk found this - we cant use this as debug if its null!
3025 log(DEBUG,"server_mode on %s",dest->nick);
3028 if ((dest) && (pcnt > 1))
3030 log(DEBUG,"params > 1");
3032 char dmodes[MAXBUF];
3033 strncpy(dmodes,dest->modes,MAXBUF);
3035 strcpy(outpars,"+");
3038 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3041 for (int i = 0; i < strlen(parameters[1]); i++)
3043 if (parameters[1][i] == '+')
3047 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3049 outpars[strlen(outpars)-1] = '+';
3053 strcat(outpars,"+");
3059 if (parameters[1][i] == '-')
3063 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3065 outpars[strlen(outpars)-1] = '-';
3069 strcat(outpars,"-");
3076 log(DEBUG,"begin mode processing entry");
3082 log(DEBUG,"umode %c being added",parameters[1][i]);
3083 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3085 char umode = parameters[1][i];
3086 log(DEBUG,"umode %c is an allowed umode",umode);
3087 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3089 dmodes[strlen(dmodes)+1]='\0';
3090 dmodes[strlen(dmodes)] = parameters[1][i];
3091 outpars[strlen(outpars)+1]='\0';
3092 outpars[strlen(outpars)] = parameters[1][i];
3098 // can only remove a mode they already have
3099 log(DEBUG,"umode %c being removed",parameters[1][i]);
3100 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3102 char umode = parameters[1][i];
3103 log(DEBUG,"umode %c is an allowed umode",umode);
3104 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3110 outpars[strlen(outpars)+1]='\0';
3111 outpars[strlen(outpars)] = parameters[1][i];
3114 for (q = 0; q < strlen(dmodes); q++)
3116 if (dmodes[q] != parameters[1][i])
3123 strcpy(dmodes,temp);
3130 if (strlen(outpars))
3136 while (i < strlen (outpars))
3138 b[z++] = outpars[i++];
3140 if (i<strlen(outpars)-1)
3142 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3144 // someones playing silly buggers and trying
3145 // to put a +- or -+ into the line...
3149 if (i == strlen(outpars)-1)
3151 if ((outpars[i] == '-') || (outpars[i] == '+'))
3159 if ((b[z] == '-') || (b[z] == '+'))
3162 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3165 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3167 // M token for a usermode must go to all servers
3168 char buffer[MAXBUF];
3169 snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3170 for (int j = 0; j < 255; j++)
3172 if (servers[j] != NULL)
3174 if (strcmp(servers[j]->name,ServerName))
3176 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
3177 log(DEBUG,"Sent m token");
3182 if (strlen(dmodes)>MAXMODES)
3184 dmodes[MAXMODES-1] = '\0';
3186 log(DEBUG,"Stripped mode line");
3187 log(DEBUG,"Line dest is now %s",dmodes);
3188 strncpy(dest->modes,dmodes,MAXMODES);
3195 Ptr = FindChan(parameters[0]);
3198 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true,false,false);
3202 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3208 void merge_mode(char **parameters, int pcnt)
3214 char outpars[MAXBUF];
3216 dest = Find(parameters[0]);
3218 // fix: ChroNiCk found this - we cant use this as debug if its null!
3221 log(DEBUG,"merge_mode on %s",dest->nick);
3224 if ((dest) && (pcnt > 1))
3226 log(DEBUG,"params > 1");
3228 char dmodes[MAXBUF];
3229 strncpy(dmodes,dest->modes,MAXBUF);
3231 strcpy(outpars,"+");
3234 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3237 for (int i = 0; i < strlen(parameters[1]); i++)
3239 if (parameters[1][i] == '+')
3243 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3245 outpars[strlen(outpars)-1] = '+';
3249 strcat(outpars,"+");
3255 if (parameters[1][i] == '-')
3259 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3261 outpars[strlen(outpars)-1] = '-';
3265 strcat(outpars,"-");
3272 log(DEBUG,"begin mode processing entry");
3278 log(DEBUG,"umode %c being added",parameters[1][i]);
3279 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],"o",true)))
3281 char umode = parameters[1][i];
3282 log(DEBUG,"umode %c is an allowed umode",umode);
3283 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3285 dmodes[strlen(dmodes)+1]='\0';
3286 dmodes[strlen(dmodes)] = parameters[1][i];
3287 outpars[strlen(outpars)+1]='\0';
3288 outpars[strlen(outpars)] = parameters[1][i];
3294 // can only remove a mode they already have
3295 log(DEBUG,"umode %c being removed",parameters[1][i]);
3296 if ((allowed_umode(parameters[1][i],"o",false)) && (strchr(dmodes,parameters[1][i])))
3298 char umode = parameters[1][i];
3299 log(DEBUG,"umode %c is an allowed umode",umode);
3300 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3306 outpars[strlen(outpars)+1]='\0';
3307 outpars[strlen(outpars)] = parameters[1][i];
3310 for (q = 0; q < strlen(dmodes); q++)
3312 if (dmodes[q] != parameters[1][i])
3319 strcpy(dmodes,temp);
3326 if (strlen(outpars))
3332 while (i < strlen (outpars))
3334 b[z++] = outpars[i++];
3336 if (i<strlen(outpars)-1)
3338 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3340 // someones playing silly buggers and trying
3341 // to put a +- or -+ into the line...
3345 if (i == strlen(outpars)-1)
3347 if ((outpars[i] == '-') || (outpars[i] == '+'))
3355 if ((b[z] == '-') || (b[z] == '+'))
3358 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3361 if (strlen(dmodes)>MAXMODES)
3363 dmodes[MAXMODES-1] = '\0';
3365 log(DEBUG,"Stripped mode line");
3366 log(DEBUG,"Line dest is now %s",dmodes);
3367 strncpy(dest->modes,dmodes,MAXMODES);
3374 Ptr = FindChan(parameters[0]);
3378 strncpy(s2.nick,ServerName,NICKMAX);
3379 strcpy(s2.modes,"o");
3381 process_modes(parameters,&s2,Ptr,STATUS_OP,pcnt,true,true,false);
3386 void merge_mode2(char **parameters, int pcnt, userrec* user)
3392 char outpars[MAXBUF];
3394 dest = Find(parameters[0]);
3396 // fix: ChroNiCk found this - we cant use this as debug if its null!
3399 log(DEBUG,"merge_mode on %s",dest->nick);
3402 if ((dest) && (pcnt > 1))
3404 log(DEBUG,"params > 1");
3406 char dmodes[MAXBUF];
3407 strncpy(dmodes,dest->modes,MAXBUF);
3409 strcpy(outpars,"+");
3412 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3415 for (int i = 0; i < strlen(parameters[1]); i++)
3417 if (parameters[1][i] == '+')
3421 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3423 outpars[strlen(outpars)-1] = '+';
3427 strcat(outpars,"+");
3433 if (parameters[1][i] == '-')
3437 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3439 outpars[strlen(outpars)-1] = '-';
3443 strcat(outpars,"-");
3450 log(DEBUG,"begin mode processing entry");
3456 log(DEBUG,"umode %c being added",parameters[1][i]);
3457 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3459 char umode = parameters[1][i];
3460 log(DEBUG,"umode %c is an allowed umode",umode);
3461 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3463 dmodes[strlen(dmodes)+1]='\0';
3464 dmodes[strlen(dmodes)] = parameters[1][i];
3465 outpars[strlen(outpars)+1]='\0';
3466 outpars[strlen(outpars)] = parameters[1][i];
3472 // can only remove a mode they already have
3473 log(DEBUG,"umode %c being removed",parameters[1][i]);
3474 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3476 char umode = parameters[1][i];
3477 log(DEBUG,"umode %c is an allowed umode",umode);
3478 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3484 outpars[strlen(outpars)+1]='\0';
3485 outpars[strlen(outpars)] = parameters[1][i];
3488 for (q = 0; q < strlen(dmodes); q++)
3490 if (dmodes[q] != parameters[1][i])
3497 strcpy(dmodes,temp);
3504 if (strlen(outpars))
3510 while (i < strlen (outpars))
3512 b[z++] = outpars[i++];
3514 if (i<strlen(outpars)-1)
3516 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3518 // someones playing silly buggers and trying
3519 // to put a +- or -+ into the line...
3523 if (i == strlen(outpars)-1)
3525 if ((outpars[i] == '-') || (outpars[i] == '+'))
3533 if ((b[z] == '-') || (b[z] == '+'))
3536 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3539 WriteTo(user,dest,"MODE :%s",b);
3541 if (strlen(dmodes)>MAXMODES)
3543 dmodes[MAXMODES-1] = '\0';
3545 log(DEBUG,"Stripped mode line");
3546 log(DEBUG,"Line dest is now %s",dmodes);
3547 strncpy(dest->modes,dmodes,MAXMODES);
3554 Ptr = FindChan(parameters[0]);
3557 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3562 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,true);
3568 /* This function pokes and hacks at a parameter list like the following:
3570 * PART #winbot, #darkgalaxy :m00!
3572 * to turn it into a series of individual calls like this:
3574 * PART #winbot :m00!
3575 * PART #darkgalaxy :m00!
3577 * The seperate calls are sent to a callback function provided by the caller
3578 * (the caller will usually call itself recursively). The callback function
3579 * must be a command handler. Calling this function on a line with no list causes
3580 * no action to be taken. You must provide a starting and ending parameter number
3581 * where the range of the list can be found, useful if you have a terminating
3582 * parameter as above which is actually not part of the list, or parameters
3583 * before the actual list as well. This code is used by many functions which
3584 * can function as "one to list" (see the RFC) */
3586 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
3591 char blog[32][MAXBUF];
3592 char blog2[32][MAXBUF];
3593 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
3594 char keystr[MAXBUF];
3597 for (int i = 0; i <32; i++)
3600 for (int i = 0; i <32; i++)
3601 strcpy(blog2[i],"");
3604 for (int i = 0; i <10; i++)
3608 parameters[i] = moo;
3613 if (pcnt > 1) /* we have a key to copy */
3615 strcpy(keystr,parameters[1]);
3619 if (!parameters[start])
3623 if (!strchr(parameters[start],','))
3628 for (int i = start; i <= end; i++)
3632 strcat(plist,parameters[i]);
3640 for (int i = 0; i < t; i++)
3642 if (plist[i] == ',')
3645 strcpy(blog[j++],param);
3649 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3654 strcpy(blog[j++],param);
3657 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3662 if ((joins) && (keystr))
3664 if (strchr(keystr,','))
3668 t2 = strlen(keystr);
3669 for (int i = 0; i < t2; i++)
3671 if (keystr[i] == ',')
3674 strcpy(blog2[j++],param);
3678 strcpy(blog2[j++],param);
3683 for (j = 0; j < total; j++)
3689 for (q = end; q < pcnt-1; q++)
3691 if (parameters[q+1])
3693 pars[q-end+1] = parameters[q+1];
3696 if ((joins) && (parameters[1]))
3707 /* repeatedly call the function with the hacked parameter list */
3708 if ((joins) && (pcnt > 1))
3712 // pars[1] already set up and containing key from blog2[j]
3717 pars[1] = parameters[1];
3723 fn(pars,pcnt-(end-start),u);
3731 void handle_join(char **parameters, int pcnt, userrec *user)
3736 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3738 if (parameters[0][0] == '#')
3740 Ptr = add_channel(user,parameters[0],parameters[1],false);
3745 void handle_part(char **parameters, int pcnt, userrec *user)
3751 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3753 del_channel(user,parameters[0],parameters[1],false);
3757 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3759 del_channel(user,parameters[0],NULL,false);
3763 void handle_kick(char **parameters, int pcnt, userrec *user)
3765 chanrec* Ptr = FindChan(parameters[0]);
3766 userrec* u = Find(parameters[1]);
3770 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3774 if (!has_channel(u,Ptr))
3776 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3780 char reason[MAXBUF];
3784 strncpy(reason,parameters[2],MAXBUF);
3785 if (strlen(reason)>MAXKICK)
3787 reason[MAXKICK-1] = '\0';
3790 kick_channel(user,u,Ptr,reason);
3794 strcpy(reason,user->nick);
3795 kick_channel(user,u,Ptr,reason);
3798 // this must be propogated so that channel membership is kept in step network-wide
3800 char buffer[MAXBUF];
3801 snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
3802 for (int j = 0; j < 255; j++)
3804 if (servers[j] != NULL)
3806 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
3807 log(DEBUG,"Sent k token");
3814 void handle_die(char **parameters, int pcnt, userrec *user)
3816 log(DEBUG,"die: %s",user->nick);
3817 if (!strcmp(parameters[0],diepass))
3819 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3825 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3829 void handle_restart(char **parameters, int pcnt, userrec *user)
3831 log(DEBUG,"restart: %s",user->nick);
3832 if (!strcmp(parameters[0],restartpass))
3834 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3837 /* Will finish this later when i can be arsed :) */
3841 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3846 void kill_link(userrec *user,const char* r)
3848 user_hash::iterator iter = clientlist.find(user->nick);
3850 char reason[MAXBUF];
3852 strncpy(reason,r,MAXBUF);
3854 if (strlen(reason)>MAXQUIT)
3856 reason[MAXQUIT-1] = '\0';
3859 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3860 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3861 log(DEBUG,"closing fd %d",user->fd);
3863 /* bugfix, cant close() a nonblocking socket (sux!) */
3864 if (user->registered == 7) {
3865 FOREACH_MOD OnUserQuit(user);
3866 WriteCommonExcept(user,"QUIT :%s",reason);
3868 // Q token must go to ALL servers!!!
3869 char buffer[MAXBUF];
3870 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
3871 for (int j = 0; j < 255; j++)
3873 if (servers[j] != NULL)
3875 if (strcmp(servers[j]->name,ServerName))
3877 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
3878 log(DEBUG,"Sent Q token");
3884 /* push the socket on a stack of sockets due to be closed at the next opportunity
3885 * 'Client exited' is an exception to this as it means the client side has already
3886 * closed the socket, we don't need to do it.
3888 fd_reap.push_back(user->fd);
3890 bool do_purge = false;
3892 if (user->registered == 7) {
3893 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3897 if (iter != clientlist.end())
3899 log(DEBUG,"deleting user hash value %d",iter->second);
3900 if ((iter->second) && (user->registered == 7)) {
3901 delete iter->second;
3903 clientlist.erase(iter);
3906 if (user->registered == 7) {
3907 purge_empty_chans();
3912 void handle_kill(char **parameters, int pcnt, userrec *user)
3914 userrec *u = Find(parameters[0]);
3915 char killreason[MAXBUF];
3917 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3920 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3921 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3922 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3923 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3924 kill_link(u,killreason);
3928 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3932 void handle_summon(char **parameters, int pcnt, userrec *user)
3934 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3937 void handle_users(char **parameters, int pcnt, userrec *user)
3939 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3943 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3945 char* Passwd(userrec *user)
3947 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3949 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3957 bool IsDenied(userrec *user)
3959 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3961 if (match(user->host,i->host) && (i->type == CC_DENY))
3971 void handle_pass(char **parameters, int pcnt, userrec *user)
3973 // Check to make sure they havnt registered -- Fix by FCS
3974 if (user->registered == 7)
3976 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3979 if (!strcasecmp(parameters[0],Passwd(user)))
3981 user->haspassed = true;
3985 void handle_invite(char **parameters, int pcnt, userrec *user)
3987 userrec* u = Find(parameters[0]);
3988 chanrec* c = FindChan(parameters[1]);
3994 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
4000 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
4009 if (cstatus(user,c) < STATUS_HOP)
4011 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
4015 if (has_channel(u,c))
4017 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
4020 if (!has_channel(user,c))
4022 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
4025 u->InviteTo(c->name);
4026 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
4027 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
4029 // i token must go to ALL servers!!!
4030 char buffer[MAXBUF];
4031 snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
4032 for (int j = 0; j < 255; j++)
4034 if (servers[j] != NULL)
4036 if (strcmp(servers[j]->name,ServerName))
4038 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4039 log(DEBUG,"Sent i token");
4045 void handle_topic(char **parameters, int pcnt, userrec *user)
4051 if (strlen(parameters[0]) <= CHANMAX)
4053 Ptr = FindChan(parameters[0]);
4058 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
4059 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
4063 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
4068 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4075 if (strlen(parameters[0]) <= CHANMAX)
4077 Ptr = FindChan(parameters[0]);
4080 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
4082 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
4087 strncpy(topic,parameters[1],MAXBUF);
4088 if (strlen(topic)>MAXTOPIC)
4090 topic[MAXTOPIC-1] = '\0';
4093 strcpy(Ptr->topic,topic);
4094 strcpy(Ptr->setby,user->nick);
4095 Ptr->topicset = time(NULL);
4096 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
4098 // t token must go to ALL servers!!!
4099 char buffer[MAXBUF];
4100 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
4101 for (int j = 0; j < 255; j++)
4103 if (servers[j] != NULL)
4105 if (strcmp(servers[j]->name,ServerName))
4107 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4108 log(DEBUG,"Sent t token");
4115 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4121 /* sends out an error notice to all connected clients (not to be used
4124 void send_error(char *s)
4126 log(DEBUG,"send_error: %s",s);
4127 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4129 if (isnick(i->second->nick))
4131 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
4135 // fix - unregistered connections receive ERROR, not NOTICE
4136 Write(i->second->fd,"ERROR :%s",s);
4141 void Error(int status)
4143 signal (SIGALRM, SIG_IGN);
4144 signal (SIGPIPE, SIG_IGN);
4145 signal (SIGTERM, SIG_IGN);
4146 signal (SIGABRT, SIG_IGN);
4147 signal (SIGSEGV, SIG_IGN);
4148 signal (SIGURG, SIG_IGN);
4149 signal (SIGKILL, SIG_IGN);
4150 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
4151 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
4156 int main (int argc, char *argv[])
4159 log(DEBUG,"*** InspIRCd starting up!");
4160 if (!FileExists(CONFIG_FILE))
4162 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
4163 log(DEBUG,"main: no config");
4164 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
4168 if (!strcmp(argv[1],"-nofork")) {
4172 if (InspIRCd() == ERROR)
4174 log(DEBUG,"main: daemon function bailed");
4175 printf("ERROR: could not initialise. Shutting down.\n");
4182 template<typename T> inline string ConvToStr(const T &in)
4185 if (!(tmp << in)) return string();
4189 /* re-allocates a nick in the user_hash after they change nicknames,
4190 * returns a pointer to the new user as it may have moved */
4192 userrec* ReHashNick(char* Old, char* New)
4194 user_hash::iterator newnick;
4195 user_hash::iterator oldnick = clientlist.find(Old);
4197 log(DEBUG,"ReHashNick: %s %s",Old,New);
4199 if (!strcasecmp(Old,New))
4201 log(DEBUG,"old nick is new nick, skipping");
4202 return oldnick->second;
4205 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
4207 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
4209 clientlist[New] = new userrec();
4210 clientlist[New] = oldnick->second;
4211 /*delete oldnick->second; */
4212 clientlist.erase(oldnick);
4214 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
4216 return clientlist[New];
4219 /* adds or updates an entry in the whowas list */
4220 void AddWhoWas(userrec* u)
4222 user_hash::iterator iter = whowas.find(u->nick);
4223 userrec *a = new userrec();
4224 strcpy(a->nick,u->nick);
4225 strcpy(a->ident,u->ident);
4226 strcpy(a->dhost,u->dhost);
4227 strcpy(a->host,u->host);
4228 strcpy(a->fullname,u->fullname);
4229 strcpy(a->server,u->server);
4230 a->signon = u->signon;
4232 /* MAX_WHOWAS: max number of /WHOWAS items
4233 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
4234 * can be replaced by a newer one
4237 if (iter == whowas.end())
4239 if (whowas.size() == WHOWAS_MAX)
4241 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
4243 // 3600 seconds in an hour ;)
4244 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
4248 log(DEBUG,"added WHOWAS entry, purged an old record");
4255 log(DEBUG,"added fresh WHOWAS entry");
4256 whowas[a->nick] = a;
4261 log(DEBUG,"updated WHOWAS entry");
4262 delete iter->second;
4268 /* add a client connection to the sockets list */
4269 void AddClient(int socket, char* host, int port, bool iscached)
4273 char resolved[MAXBUF];
4276 user_hash::iterator iter;
4278 tempnick = ConvToStr(socket) + "-unknown";
4279 sprintf(tn2,"%d-unknown",socket);
4281 iter = clientlist.find(tempnick);
4283 if (iter != clientlist.end()) return;
4286 * It is OK to access the value here this way since we know
4287 * it exists, we just created it above.
4289 * At NO other time should you access a value in a map or a
4290 * hash_map this way.
4292 clientlist[tempnick] = new userrec();
4294 NonBlocking(socket);
4295 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
4297 clientlist[tempnick]->fd = socket;
4298 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
4299 strncpy(clientlist[tempnick]->host, host,160);
4300 strncpy(clientlist[tempnick]->dhost, host,160);
4301 strncpy(clientlist[tempnick]->server, ServerName,256);
4302 strncpy(clientlist[tempnick]->ident, "unknown",9);
4303 clientlist[tempnick]->registered = 0;
4304 clientlist[tempnick]->signon = time(NULL);
4305 clientlist[tempnick]->nping = time(NULL)+240;
4306 clientlist[tempnick]->lastping = 1;
4307 clientlist[tempnick]->port = port;
4311 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
4315 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
4318 // set the registration timeout for this user
4319 unsigned long class_regtimeout = 90;
4320 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4322 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4324 class_regtimeout = (unsigned long)i->registration_timeout;
4329 int class_flood = 0;
4330 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4332 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4334 class_flood = i->flood;
4339 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
4340 clientlist[tempnick]->flood = class_flood;
4342 for (int i = 0; i < MAXCHANS; i++)
4344 clientlist[tempnick]->chans[i].channel = NULL;
4345 clientlist[tempnick]->chans[i].uc_modes = 0;
4348 if (clientlist.size() == MAXCLIENTS)
4349 kill_link(clientlist[tempnick],"No more connections allowed in this class");
4352 void handle_names(char **parameters, int pcnt, userrec *user)
4356 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
4358 c = FindChan(parameters[0]);
4361 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
4363 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
4367 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4371 void handle_privmsg(char **parameters, int pcnt, userrec *user)
4376 user->idle_lastmsg = time(NULL);
4378 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
4380 if (parameters[0][0] == '#')
4382 chan = FindChan(parameters[0]);
4385 if ((chan->noexternal) && (!has_channel(user,chan)))
4387 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4390 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4392 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4398 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4403 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
4405 // if any users of this channel are on remote servers, broadcast the packet
4406 char buffer[MAXBUF];
4407 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
4408 for (int j = 0; j < 255; j++)
4410 if (servers[j] != NULL)
4412 if (ChanAnyOnThisServer(chan,servers[j]->name))
4414 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4421 /* no such nick/channel */
4422 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4427 dest = Find(parameters[0]);
4430 if (strcmp(dest->awaymsg,""))
4432 /* auto respond with aweh msg */
4433 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
4438 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
4445 if (!strcmp(dest->server,user->server))
4447 // direct write, same server
4448 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
4452 for (int j = 0; j < 255; j++)
4454 if (servers[j] != NULL)
4456 if (!strcasecmp(servers[j]->name,dest->server))
4458 // direct write, same server
4459 char buffer[MAXBUF];
4460 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
4461 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4469 /* no such nick/channel */
4470 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4474 void handle_notice(char **parameters, int pcnt, userrec *user)
4479 user->idle_lastmsg = time(NULL);
4481 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
4483 if (parameters[0][0] == '#')
4485 chan = FindChan(parameters[0]);
4488 if ((chan->noexternal) && (!has_channel(user,chan)))
4490 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4493 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4495 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4501 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4506 ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
4508 // if any users of this channel are on remote servers, broadcast the packet
4509 char buffer[MAXBUF];
4510 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
4511 for (int j = 0; j < 255; j++)
4513 if (servers[j] != NULL)
4515 if (ChanAnyOnThisServer(chan,servers[j]->name))
4517 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4524 /* no such nick/channel */
4525 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4530 dest = Find(parameters[0]);
4535 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
4540 if (!strcmp(dest->server,user->server))
4542 // direct write, same server
4543 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
4547 for (int j = 0; j < 255; j++)
4549 if (servers[j] != NULL)
4551 if (!strcasecmp(servers[j]->name,dest->server))
4553 // direct write, same server
4554 char buffer[MAXBUF];
4555 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
4556 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4564 /* no such nick/channel */
4565 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4571 char* chlist(userrec *user)
4576 log(DEBUG,"chlist: %s",user->nick);
4582 for (int i = 0; i != MAXCHANS; i++)
4584 if (user->chans[i].channel != NULL)
4586 if (user->chans[i].channel->name)
4588 strcpy(cmp,user->chans[i].channel->name);
4590 if (!strstr(lst,cmp))
4592 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
4594 strcat(lst,cmode(user,user->chans[i].channel));
4595 strcat(lst,user->chans[i].channel->name);
4604 lst[strlen(lst)-1] = '\0'; // chop trailing space
4609 void handle_info(char **parameters, int pcnt, userrec *user)
4611 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
4612 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
4613 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
4614 FOREACH_MOD OnInfo(user);
4615 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
4618 void handle_time(char **parameters, int pcnt, userrec *user)
4621 struct tm * timeinfo;
4624 timeinfo = localtime ( &rawtime );
4625 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
4629 void handle_whois(char **parameters, int pcnt, userrec *user)
4634 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
4636 dest = Find(parameters[0]);
4639 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
4640 if (dest->registered == 7)
4642 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
4643 if ((user == dest) || (strchr(user->modes,'o')))
4645 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
4647 if (strcmp(chlist(dest),""))
4649 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
4651 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
4652 if (strcmp(dest->awaymsg,""))
4654 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
4656 if (strchr(dest->modes,'o'))
4658 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
4660 FOREACH_MOD OnWhois(user,dest);
4661 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
4662 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
4664 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
4668 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4673 /* no such nick/channel */
4674 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4678 void send_network_quit(const char* nick, const char* reason)
4680 char buffer[MAXBUF];
4681 snprintf(buffer,MAXBUF,"Q %s :%s",nick,reason);
4682 for (int j = 0; j < 255; j++)
4684 if (servers[j] != NULL)
4686 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4687 log(DEBUG,"Sent Q token");
4692 void handle_quit(char **parameters, int pcnt, userrec *user)
4694 user_hash::iterator iter = clientlist.find(user->nick);
4697 if (user->registered == 7)
4699 /* theres more to do here, but for now just close the socket */
4702 if (parameters[0][0] == ':')
4706 reason = parameters[0];
4708 if (strlen(reason)>MAXQUIT)
4710 reason[MAXQUIT-1] = '\0';
4713 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
4714 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
4715 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
4717 char buffer[MAXBUF];
4718 snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
4719 for (int j = 0; j < 255; j++)
4721 if (servers[j] != NULL)
4723 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4724 log(DEBUG,"Sent Q token");
4730 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
4731 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
4732 WriteCommonExcept(user,"QUIT :Client exited");
4734 char buffer[MAXBUF];
4735 snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
4736 for (int j = 0; j < 255; j++)
4738 if (servers[j] != NULL)
4740 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4741 log(DEBUG,"Sent Q token");
4745 FOREACH_MOD OnUserQuit(user);
4749 /* push the socket on a stack of sockets due to be closed at the next opportunity */
4750 fd_reap.push_back(user->fd);
4752 if (iter != clientlist.end())
4754 clientlist.erase(iter);
4755 log(DEBUG,"deleting user hash value %d",iter->second);
4756 //if ((user) && (user->registered == 7)) {
4761 if (user->registered == 7) {
4762 purge_empty_chans();
4766 void handle_who(char **parameters, int pcnt, userrec *user)
4768 chanrec* Ptr = NULL;
4770 /* theres more to do here, but for now just close the socket */
4773 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
4775 if (user->chans[0].channel)
4777 Ptr = user->chans[0].channel;
4778 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4780 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4782 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4788 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4792 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
4796 if (parameters[0][0] == '#')
4798 Ptr = FindChan(parameters[0]);
4801 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4803 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
4805 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);
4808 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4812 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4817 userrec* u = Find(parameters[0]);
4818 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);
4823 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4825 Ptr = user->chans[0].channel;
4826 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4828 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4830 if (strchr(i->second->modes,'o'))
4832 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);
4836 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4842 void handle_wallops(char **parameters, int pcnt, userrec *user)
4844 WriteWallOps(user,"%s",parameters[0]);
4847 void handle_list(char **parameters, int pcnt, userrec *user)
4851 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4852 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4854 if ((!i->second->c_private) && (!i->second->secret))
4856 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4859 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4863 void handle_rehash(char **parameters, int pcnt, userrec *user)
4865 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4867 FOREACH_MOD OnRehash();
4868 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4874 return clientlist.size();
4878 int usercount_invisible(void)
4882 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4884 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4889 int usercount_opers(void)
4893 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4895 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4900 int usercount_unknown(void)
4904 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4906 if ((i->second->fd) && (i->second->registered != 7))
4914 return chanlist.size();
4917 int servercount(void)
4922 void handle_lusers(char **parameters, int pcnt, userrec *user)
4924 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4925 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4926 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4927 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4928 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4931 void handle_admin(char **parameters, int pcnt, userrec *user)
4933 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4934 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4935 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4936 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4939 void ShowMOTD(userrec *user)
4943 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4946 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4947 for (int i = 0; i != MOTD.size(); i++)
4949 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4951 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4954 void ShowRULES(userrec *user)
4958 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4961 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4962 for (int i = 0; i != RULES.size(); i++)
4964 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4966 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4969 /* shows the message of the day, and any other on-logon stuff */
4970 void ConnectUser(userrec *user)
4972 user->registered = 7;
4973 user->idle_lastmsg = time(NULL);
4974 log(DEBUG,"ConnectUser: %s",user->nick);
4976 if (strcmp(Passwd(user),"") && (!user->haspassed))
4978 kill_link(user,"Invalid password");
4983 kill_link(user,"Unauthorised connection");
4987 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4988 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4989 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4990 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4991 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4992 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);
4993 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);
4995 FOREACH_MOD OnUserConnect(user);
4996 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4998 char buffer[MAXBUF];
4999 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);
5000 for (int j = 0; j < 255; j++)
5002 if (servers[j] != NULL)
5004 if (strcmp(servers[j]->name,ServerName))
5006 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
5007 log(DEBUG,"Sent N token");
5014 void handle_version(char **parameters, int pcnt, userrec *user)
5016 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Revision$ $Date$",ServerName,SYSTEM);
5019 void handle_ping(char **parameters, int pcnt, userrec *user)
5021 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
5024 void handle_pong(char **parameters, int pcnt, userrec *user)
5026 // set the user as alive so they survive to next ping
5030 void handle_motd(char **parameters, int pcnt, userrec *user)
5035 void handle_rules(char **parameters, int pcnt, userrec *user)
5040 void handle_user(char **parameters, int pcnt, userrec *user)
5042 if (user->registered < 3)
5044 if (isident(parameters[0]) == 0) {
5045 // This kinda Sucks, According to the RFC thou, its either this,
5046 // or "You have already registered" :p -- Craig
5047 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
5050 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
5051 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
5052 strncat(user->ident,parameters[0],IDENTMAX);
5053 strncpy(user->fullname,parameters[3],128);
5054 user->registered = (user->registered | 1);
5059 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
5062 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
5063 if (user->registered == 3)
5065 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5070 void handle_userhost(char **parameters, int pcnt, userrec *user)
5072 char Return[MAXBUF],junk[MAXBUF];
5073 sprintf(Return,"302 %s :",user->nick);
5074 for (int i = 0; i < pcnt; i++)
5076 userrec *u = Find(parameters[i]);
5079 if (strchr(u->modes,'o'))
5081 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
5082 strcat(Return,junk);
5086 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
5087 strcat(Return,junk);
5091 WriteServ(user->fd,Return);
5095 void handle_ison(char **parameters, int pcnt, userrec *user)
5097 char Return[MAXBUF];
5098 sprintf(Return,"303 %s :",user->nick);
5099 for (int i = 0; i < pcnt; i++)
5101 userrec *u = Find(parameters[i]);
5104 strcat(Return,u->nick);
5108 WriteServ(user->fd,Return);
5112 void handle_away(char **parameters, int pcnt, userrec *user)
5116 strcpy(user->awaymsg,parameters[0]);
5117 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
5121 strcpy(user->awaymsg,"");
5122 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
5126 void handle_whowas(char **parameters, int pcnt, userrec* user)
5128 user_hash::iterator i = whowas.find(parameters[0]);
5130 if (i == whowas.end())
5132 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
5133 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5137 time_t rawtime = i->second->signon;
5141 timeinfo = localtime(&rawtime);
5142 strcpy(b,asctime(timeinfo));
5143 b[strlen(b)-1] = '\0';
5145 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
5146 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
5147 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5152 void handle_trace(char **parameters, int pcnt, userrec *user)
5154 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5158 if (isnick(i->second->nick))
5160 if (strchr(i->second->modes,'o'))
5162 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
5166 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
5171 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
5177 void handle_modules(char **parameters, int pcnt, userrec *user)
5179 for (int i = 0; i < module_names.size(); i++)
5181 Version V = modules[i]->GetVersion();
5182 char modulename[MAXBUF];
5183 strncpy(modulename,module_names[i].c_str(),256);
5184 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));
5188 // calls a handler function for a command
5190 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
5192 for (int i = 0; i < cmdlist.size(); i++)
5194 if (!strcasecmp(cmdlist[i].command,commandname))
5196 if (cmdlist[i].handler_function)
5198 if (pcnt>=cmdlist[i].min_params)
5200 if (strchr(user->modes,cmdlist[i].flags_needed))
5202 cmdlist[i].handler_function(parameters,pcnt,user);
5210 void handle_stats(char **parameters, int pcnt, userrec *user)
5216 if (strlen(parameters[0])>1)
5218 /* make the stats query 1 character long */
5219 parameters[0][1] = '\0';
5222 /* stats m (list number of times each command has been used, plus bytecount) */
5223 if (!strcasecmp(parameters[0],"m"))
5225 for (int i = 0; i < cmdlist.size(); i++)
5227 if (cmdlist[i].handler_function)
5229 if (cmdlist[i].use_count)
5231 /* RPL_STATSCOMMANDS */
5232 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
5239 /* stats z (debug and memory info) */
5240 if (!strcasecmp(parameters[0],"z"))
5242 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
5243 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
5244 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
5245 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
5246 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
5247 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
5248 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
5249 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
5253 if (!strcasecmp(parameters[0],"o"))
5255 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5257 char LoginName[MAXBUF];
5258 char HostName[MAXBUF];
5259 char OperType[MAXBUF];
5260 ConfValue("oper","name",i,LoginName,&config_f);
5261 ConfValue("oper","host",i,HostName,&config_f);
5262 ConfValue("oper","type",i,OperType,&config_f);
5263 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
5267 /* stats l (show user I/O stats) */
5268 if (!strcasecmp(parameters[0],"l"))
5270 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
5271 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5273 if (isnick(i->second->nick))
5275 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);
5279 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);
5285 /* stats u (show server uptime) */
5286 if (!strcasecmp(parameters[0],"u"))
5288 time_t current_time = 0;
5289 current_time = time(NULL);
5290 time_t server_uptime = current_time - startup_time;
5292 stime = gmtime(&server_uptime);
5293 /* i dont know who the hell would have an ircd running for over a year nonstop, but
5294 * Craig suggested this, and it seemed a good idea so in it went */
5295 if (stime->tm_year > 70)
5297 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);
5301 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);
5305 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
5306 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
5310 void handle_connect(char **parameters, int pcnt, userrec *user)
5312 char Link_ServerName[1024];
5313 char Link_IPAddr[1024];
5314 char Link_Port[1024];
5315 char Link_Pass[1024];
5319 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5321 ConfValue("link","name",i,Link_ServerName,&config_f);
5322 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5323 ConfValue("link","port",i,Link_Port,&config_f);
5324 ConfValue("link","sendpass",i,Link_Pass,&config_f);
5325 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5326 LinkPort = atoi(Link_Port);
5327 if (match(Link_ServerName,parameters[0])) {
5333 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
5337 // TODO: Perform a check here to stop a server being linked twice!
5339 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
5341 if (me[defaultRoute])
5344 // at this point parameters[0] is an ip in a string.
5345 // TODO: Look this up from the <link> blocks instead!
5346 for (int j = 0; j < 255; j++) {
5347 if (servers[j] == NULL) {
5348 servers[j] = new serverrec;
5349 strcpy(servers[j]->internal_addr,Link_IPAddr);
5350 servers[j]->internal_port = LinkPort;
5351 strcpy(servers[j]->name,Link_ServerName);
5352 log(DEBUG,"Allocated new serverrec");
5353 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
5355 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
5360 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
5364 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);
5368 void handle_squit(char **parameters, int pcnt, userrec *user)
5370 // send out an squit across the mesh and then clear the server list (for local squit)
5373 char islast(serverrec* s)
5376 for (int j = 0; j < 255; j++)
5378 if (servers[j] != NULL)
5382 if (servers[j] == s)
5390 void handle_links(char **parameters, int pcnt, userrec *user)
5392 WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
5393 for (int j = 0; j < 255; j++)
5395 if (servers[j] != NULL)
5397 WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,servers[j]->name,ServerName,servers[j]->description);
5400 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
5403 void handle_map(char **parameters, int pcnt, userrec *user)
5405 WriteServ(user->fd,"006 %s :%s",user->nick,ServerName);
5406 for (int j = 0; j < 255; j++)
5408 if (servers[j] != NULL)
5410 WriteServ(user->fd,"006 %s :%c-%s",user->nick,islast(servers[j]),servers[j]->name);
5413 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
5417 void handle_oper(char **parameters, int pcnt, userrec *user)
5419 char LoginName[MAXBUF];
5420 char Password[MAXBUF];
5421 char OperType[MAXBUF];
5422 char TypeName[MAXBUF];
5423 char Hostname[MAXBUF];
5426 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5428 ConfValue("oper","name",i,LoginName,&config_f);
5429 ConfValue("oper","password",i,Password,&config_f);
5430 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
5432 /* correct oper credentials */
5433 ConfValue("oper","type",i,OperType,&config_f);
5434 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
5435 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
5436 WriteServ(user->fd,"MODE %s :+o",user->nick);
5437 for (j =0; j < ConfValueEnum("type",&config_f); j++)
5439 ConfValue("type","name",j,TypeName,&config_f);
5440 if (!strcmp(TypeName,OperType))
5442 /* found this oper's opertype */
5443 ConfValue("type","host",j,Hostname,&config_f);
5444 strncpy(user->dhost,Hostname,256);
5447 if (!strchr(user->modes,'o'))
5449 strcat(user->modes,"o");
5451 FOREACH_MOD OnOper(user);
5456 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
5457 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
5460 void handle_nick(char **parameters, int pcnt, userrec *user)
5464 log(DEBUG,"not enough params for handle_nick");
5469 log(DEBUG,"invalid parameter passed to handle_nick");
5472 if (!strlen(parameters[0]))
5474 log(DEBUG,"zero length new nick passed to handle_nick");
5479 log(DEBUG,"invalid user passed to handle_nick");
5484 log(DEBUG,"invalid old nick passed to handle_nick");
5487 if (!strcasecmp(user->nick,parameters[0]))
5489 log(DEBUG,"old nick is new nick, skipping");
5494 if (strlen(parameters[0]) > 1)
5496 if (parameters[0][0] == ':')
5501 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
5503 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
5507 if (isnick(parameters[0]) == 0)
5509 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
5513 if (user->registered == 7)
5515 WriteCommon(user,"NICK %s",parameters[0]);
5517 // Q token must go to ALL servers!!!
5518 char buffer[MAXBUF];
5519 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
5520 for (int j = 0; j < 255; j++)
5522 if (servers[j] != NULL)
5524 if (strcmp(servers[j]->name,ServerName))
5526 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
5527 log(DEBUG,"Sent n token");
5534 /* change the nick of the user in the users_hash */
5535 user = ReHashNick(user->nick, parameters[0]);
5536 /* actually change the nick within the record */
5538 if (!user->nick) return;
5540 strncpy(user->nick, parameters[0],NICKMAX);
5542 log(DEBUG,"new nick set: %s",user->nick);
5544 if (user->registered < 3)
5545 user->registered = (user->registered | 2);
5546 if (user->registered == 3)
5548 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5551 log(DEBUG,"exit nickchange: %s",user->nick);
5554 void force_nickchange(userrec* user,const char* newnick)
5563 strncpy(nick,newnick,MAXBUF);
5565 if (user->registered == 7)
5569 handle_nick(pars,1,user);
5575 int process_parameters(char **command_p,char *parameters)
5580 q = strlen(parameters);
5583 /* no parameters, command_p invalid! */
5586 if (parameters[0] == ':')
5588 command_p[0] = parameters+1;
5593 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
5595 /* only one parameter */
5596 command_p[0] = parameters;
5597 if (parameters[0] == ':')
5599 if (strchr(parameters,' ') != NULL)
5607 command_p[j++] = parameters;
5608 for (int i = 0; i <= q; i++)
5610 if (parameters[i] == ' ')
5612 command_p[j++] = parameters+i+1;
5613 parameters[i] = '\0';
5614 if (command_p[j-1][0] == ':')
5616 *command_p[j-1]++; /* remove dodgy ":" */
5618 /* parameter like this marks end of the sequence */
5622 return j; /* returns total number of items in the list */
5625 void process_command(userrec *user, char* cmd)
5629 char *command_p[127];
5630 char p[MAXBUF], temp[MAXBUF];
5631 int i, j, items, cmd_found;
5633 for (int i = 0; i < 127; i++)
5634 command_p[i] = NULL;
5644 if (!strcmp(cmd,""))
5649 int total_params = 0;
5652 for (int q = 0; q < strlen(cmd)-1; q++)
5654 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
5657 // found a 'trailing', we dont count them after this.
5665 // another phidjit bug...
5666 if (total_params > 126)
5668 kill_link(user,"Protocol violation (1)");
5675 FOREACH_MOD OnServerRaw(tmp,true);
5676 const char* cmd2 = tmp.c_str();
5677 snprintf(cmd,512,"%s",cmd2);
5679 if (!strchr(cmd,' '))
5681 /* no parameters, lets skip the formalities and not chop up
5683 log(DEBUG,"About to preprocess command with no params");
5685 command_p[0] = NULL;
5687 for (int i = 0; i <= strlen(cmd); i++)
5689 cmd[i] = toupper(cmd[i]);
5691 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
5698 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
5699 for (int i = 0; i < strlen(temp); i++)
5701 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
5707 /* split the full string into a command plus parameters */
5711 if (strchr(cmd,' '))
5713 for (int i = 0; i <= strlen(cmd); i++)
5715 /* capitalise the command ONLY, leave params intact */
5716 cmd[i] = toupper(cmd[i]);
5717 /* are we nearly there yet?! :P */
5721 parameters = cmd+i+1;
5729 for (int i = 0; i <= strlen(cmd); i++)
5731 cmd[i] = toupper(cmd[i]);
5738 if (strlen(command)>MAXCOMMAND)
5740 kill_link(user,"Protocol violation (2)");
5744 for (int x = 0; x < strlen(command); x++)
5746 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
5748 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
5750 if (strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
5752 kill_link(user,"Protocol violation (3)");
5759 for (int i = 0; i != cmdlist.size(); i++)
5761 if (strcmp(cmdlist[i].command,""))
5763 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
5765 log(DEBUG,"Found matching command");
5769 if (strcmp(parameters,""))
5771 items = process_parameters(command_p,parameters);
5776 command_p[0] = NULL;
5782 command_p[0] = NULL;
5787 log(DEBUG,"Processing command");
5789 /* activity resets the ping pending timer */
5790 user->nping = time(NULL) + 120;
5791 if ((items) < cmdlist[i].min_params)
5793 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
5794 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
5797 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
5799 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
5800 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
5804 /* if the command isnt USER, PASS, or NICK, and nick is empty,
5806 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
5808 if ((!isnick(user->nick)) || (user->registered != 7))
5810 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5811 WriteServ(user->fd,"451 %s :You have not registered",command);
5815 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
5817 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
5818 if (cmdlist[i].handler_function)
5820 /* ikky /stats counters */
5825 user->bytes_in += strlen(temp);
5828 cmdlist[i].use_count++;
5829 cmdlist[i].total_bytes+=strlen(temp);
5832 /* WARNING: nothing may come after the
5833 * command handler call, as the handler
5834 * may free the user structure! */
5836 cmdlist[i].handler_function(command_p,items,user);
5842 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5843 WriteServ(user->fd,"451 %s :You have not registered",command);
5851 if ((!cmd_found) && (user))
5853 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
5854 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
5859 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
5862 /* create the command and push it onto the table */
5863 strcpy(comm.command,cmd);
5864 comm.handler_function = f;
5865 comm.flags_needed = flags;
5866 comm.min_params = minparams;
5868 comm.total_bytes = 0;
5869 cmdlist.push_back(comm);
5870 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
5873 void SetupCommandTable(void)
5875 createcommand("USER",handle_user,0,4);
5876 createcommand("NICK",handle_nick,0,1);
5877 createcommand("QUIT",handle_quit,0,0);
5878 createcommand("VERSION",handle_version,0,0);
5879 createcommand("PING",handle_ping,0,1);
5880 createcommand("PONG",handle_pong,0,1);
5881 createcommand("ADMIN",handle_admin,0,0);
5882 createcommand("PRIVMSG",handle_privmsg,0,2);
5883 createcommand("INFO",handle_info,0,0);
5884 createcommand("TIME",handle_time,0,0);
5885 createcommand("WHOIS",handle_whois,0,1);
5886 createcommand("WALLOPS",handle_wallops,'o',1);
5887 createcommand("NOTICE",handle_notice,0,2);
5888 createcommand("JOIN",handle_join,0,1);
5889 createcommand("NAMES",handle_names,0,1);
5890 createcommand("PART",handle_part,0,1);
5891 createcommand("KICK",handle_kick,0,2);
5892 createcommand("MODE",handle_mode,0,1);
5893 createcommand("TOPIC",handle_topic,0,1);
5894 createcommand("WHO",handle_who,0,1);
5895 createcommand("MOTD",handle_motd,0,0);
5896 createcommand("RULES",handle_rules,0,0);
5897 createcommand("OPER",handle_oper,0,2);
5898 createcommand("LIST",handle_list,0,0);
5899 createcommand("DIE",handle_die,'o',1);
5900 createcommand("RESTART",handle_restart,'o',1);
5901 createcommand("KILL",handle_kill,'o',2);
5902 createcommand("REHASH",handle_rehash,'o',0);
5903 createcommand("LUSERS",handle_lusers,0,0);
5904 createcommand("STATS",handle_stats,0,1);
5905 createcommand("USERHOST",handle_userhost,0,1);
5906 createcommand("AWAY",handle_away,0,0);
5907 createcommand("ISON",handle_ison,0,0);
5908 createcommand("SUMMON",handle_summon,0,0);
5909 createcommand("USERS",handle_users,0,0);
5910 createcommand("INVITE",handle_invite,0,2);
5911 createcommand("PASS",handle_pass,0,1);
5912 createcommand("TRACE",handle_trace,'o',0);
5913 createcommand("WHOWAS",handle_whowas,0,1);
5914 createcommand("CONNECT",handle_connect,'o',1);
5915 createcommand("SQUIT",handle_squit,'o',1);
5916 createcommand("MODULES",handle_modules,'o',0);
5917 createcommand("LINKS",handle_links,0,0);
5918 createcommand("MAP",handle_map,0,0);
5921 void process_buffer(const char* cmdbuf,userrec *user)
5925 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5932 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5935 if (!strcmp(cmdbuf,""))
5939 strncpy(cmd,cmdbuf,MAXBUF);
5940 if (!strcmp(cmd,""))
5944 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5946 cmd[strlen(cmd)-1] = '\0';
5948 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5950 cmd[strlen(cmd)-1] = '\0';
5952 if (!strcmp(cmd,""))
5956 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5958 if ((user) && (cmd))
5960 process_command(user,cmd);
5964 void DoSync(serverrec* serv, char* udp_host,int udp_port, long MyKey)
5967 // send start of sync marker: Y <timestamp>
5968 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
5969 // except the ones its receiving it from.
5970 snprintf(data,MAXBUF,"Y %d",time(NULL));
5971 serv->SendPacket(data,udp_host,udp_port,MyKey);
5972 // send users and channels
5973 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
5975 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);
5976 serv->SendPacket(data,udp_host,udp_port,MyKey);
5977 if (strcmp(chlist(u->second),""))
5979 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
5980 serv->SendPacket(data,udp_host,udp_port,MyKey);
5983 // send channel modes, topics etc...
5984 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
5986 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
5987 serv->SendPacket(data,udp_host,udp_port,MyKey);
5988 if (strcmp(c->second->topic,""))
5990 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
5991 serv->SendPacket(data,udp_host,udp_port,MyKey);
5993 // send current banlist
5995 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
5997 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
5998 serv->SendPacket(data,udp_host,udp_port,MyKey);
6001 // send end of sync marker: E <timestamp>
6002 snprintf(data,MAXBUF,"F %d",time(NULL));
6003 serv->SendPacket(data,udp_host,udp_port,MyKey);
6004 // ircd sends its serverlist after the end of sync here
6008 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6010 char* src = strtok(params," ");
6011 char* dest = strtok(NULL," :");
6012 char* text = strtok(NULL,"\r\n");
6015 userrec* user = Find(src);
6018 userrec* dst = Find(dest);
6022 WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
6026 chanrec* d = FindChan(dest);
6029 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
6037 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6039 char* src = strtok(params," ");
6040 char* dest = strtok(NULL," :");
6041 char* text = strtok(NULL,"\r\n");
6044 userrec* user = Find(src);
6047 userrec* dst = Find(dest);
6051 WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
6055 chanrec* d = FindChan(dest);
6058 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
6065 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6067 char* nick = strtok(params," ");
6068 char* from = strtok(params," ");
6069 char* channel = strtok(NULL," ");
6070 userrec* u = Find(nick);
6071 userrec* user = Find(from);
6072 chanrec* c = FindChan(channel);
6073 if ((c) && (u) && (user))
6075 u->InviteTo(c->name);
6076 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
6080 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6082 char* setby = strtok(params," ");
6083 char* channel = strtok(NULL," :");
6084 char* topic = strtok(NULL,"\r\n");
6086 userrec* u = Find(setby);
6087 chanrec* c = FindChan(channel);
6090 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
6091 strncpy(c->topic,topic,MAXTOPIC);
6092 strncpy(c->setby,u->nick,NICKMAX);
6097 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6099 char* tm = strtok(params," ");
6100 char* setby = strtok(NULL," ");
6101 char* channel = strtok(NULL," :");
6102 char* topic = strtok(NULL,"\r\n");
6104 time_t TS = atoi(tm);
6105 chanrec* c = FindChan(channel);
6108 // in the case of topics and TS, the *NEWER*
6109 if (TS <= c->topicset)
6111 WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
6112 strncpy(c->topic,topic,MAXTOPIC);
6113 strncpy(c->setby,setby,NICKMAX);
6118 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6121 char original[MAXBUF],target[MAXBUF];
6122 strncpy(original,params,MAXBUF);
6124 char* parameter = strtok(params," ");
6125 strncpy(target,parameter,MAXBUF);
6128 pars[index++] = parameter;
6129 parameter = strtok(NULL," ");
6131 merge_mode(pars,index);
6132 if (FindChan(target))
6134 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
6138 WriteTo(NULL,Find(target),"MODE %s",original);
6142 // m is modes set by users only (not servers) valid targets are channels or users.
6144 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6146 // m blah #chatspike +b *!test@*4
6148 char original[MAXBUF];
6149 strncpy(original,params,MAXBUF);
6151 if (!strchr(params,' '))
6153 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
6159 char* src = strtok(params," ");
6160 userrec* user = Find(src);
6164 log(DEBUG,"Found user: %s",user->nick);
6165 char* parameter = strtok(NULL," ");
6168 pars[index++] = parameter;
6169 parameter = strtok(NULL," ");
6172 log(DEBUG,"Calling merge_mode2");
6173 merge_mode2(pars,index,user);
6178 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6180 char* nick = strtok(params," ");
6181 char* channel = strtok(NULL," :");
6182 char* reason = strtok(NULL,"\r\n");
6183 userrec* user = Find(nick);
6187 if (strcmp(reason,""))
6189 del_channel(user,channel,reason,true);
6193 del_channel(user,channel,NULL,true);
6198 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6200 char* nick = strtok(params," :");
6201 char* reason = strtok(NULL,"\r\n");
6204 userrec* user = Find(nick);
6208 if (strlen(reason)>MAXQUIT)
6210 reason[MAXQUIT-1] = '\0';
6214 WriteCommonExcept(user,"QUIT :%s",reason);
6216 user_hash::iterator iter = clientlist.find(user->nick);
6218 if (iter != clientlist.end())
6220 log(DEBUG,"deleting user hash value %d",iter->second);
6221 if ((iter->second) && (user->registered == 7)) {
6222 delete iter->second;
6224 clientlist.erase(iter);
6227 purge_empty_chans();
6231 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6233 char* oldnick = strtok(params," ");
6234 char* newnick = strtok(NULL," ");
6236 userrec* user = Find(oldnick);
6240 WriteCommon(user,"NICK %s",newnick);
6241 user = ReHashNick(user->nick, newnick);
6243 if (!user->nick) return;
6244 strncpy(user->nick, newnick,NICKMAX);
6245 log(DEBUG,"new nick set: %s",user->nick);
6249 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6250 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6252 char* src = strtok(params," ");
6253 char* dest = strtok(NULL," ");
6254 char* channel = strtok(NULL," :");
6255 char* reason = strtok(NULL,"\r\n");
6257 userrec* s = Find(src);
6258 userrec* d = Find(dest);
6259 chanrec* c = FindChan(channel);
6260 if ((s) && (d) && (c))
6262 kick_channel(s,d,c,reason);
6266 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6268 char* tm = strtok(params," ");
6269 char* nick = strtok(NULL," ");
6270 char* host = strtok(NULL," ");
6271 char* dhost = strtok(NULL," ");
6272 char* ident = strtok(NULL," ");
6273 char* modes = strtok(NULL," ");
6274 char* server = strtok(NULL," :");
6275 char* gecos = strtok(NULL,"\r\n");
6278 time_t TS = atoi(tm);
6279 user_hash::iterator iter = clientlist.find(nick);
6280 if (iter != clientlist.end())
6283 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
6284 if (TS >= iter->second->age)
6287 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
6288 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
6289 // client on remote server is older than the local user, kill the local user
6290 kill_link(iter->second,str);
6293 clientlist[nick] = new userrec();
6294 // remote users have an fd of -1. This is so that our Write abstraction
6295 // routines know to route any messages to this record away to whatever server
6297 clientlist[nick]->fd = -1;
6298 strncpy(clientlist[nick]->nick, nick,NICKMAX);
6299 strncpy(clientlist[nick]->host, host,160);
6300 strncpy(clientlist[nick]->dhost, dhost,160);
6301 strncpy(clientlist[nick]->server, server,256);
6302 strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for '~'
6303 strncpy(clientlist[nick]->fullname, gecos,128);
6304 clientlist[nick]->signon = TS;
6305 clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
6306 clientlist[nick]->lastping = 1;
6307 clientlist[nick]->port = 0; // so is this...
6308 clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
6309 clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
6310 for (int i = 0; i < MAXCHANS; i++)
6312 clientlist[nick]->chans[i].channel = NULL;
6313 clientlist[nick]->chans[i].uc_modes = 0;
6317 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6319 long tdiff = time(NULL) - atoi(params);
6321 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
6324 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6327 // The J token currently has no timestamp - this needs looking at
6328 // because it will allow splitriding.
6329 char* nick = strtok(params," ");
6330 char* channel = strtok(NULL," ");
6331 userrec* user = Find(nick);
6334 if ((user != NULL) && (strcmp(channel,"")))
6336 char privilage = '\0';
6337 if (channel[0] != '#')
6339 privilage = channel[0];
6342 add_channel(user,channel,"",true);
6344 // now work out the privilages they should have on each channel
6345 // and send the appropriate servermodes.
6346 for (int i = 0; i != MAXCHANS; i++)
6348 if (user->chans[i].channel)
6350 if (!strcasecmp(user->chans[i].channel->name,channel))
6352 if (privilage == '@')
6354 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
6355 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
6357 if (privilage == '%')
6359 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
6360 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
6362 if (privilage == '+')
6364 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
6365 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
6372 channel = strtok(NULL," ");
6376 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
6383 nb_start = time(NULL);
6384 WriteOpers("Server %s is starting netburst.",source->name);
6386 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
6387 // introduce remote client
6389 handle_N(token,params,source,reply,udp_host,udp_port);
6391 // t <NICK> <CHANNEL> :<TOPIC>
6392 // change a channel topic
6394 handle_t(token,params,source,reply,udp_host,udp_port);
6396 // i <NICK> <CHANNEL>
6397 // invite a user to a channel
6399 handle_i(token,params,source,reply,udp_host,udp_port);
6401 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6402 // kick a user from a channel
6404 handle_k(token,params,source,reply,udp_host,udp_port);
6406 // n <NICK> <NEWNICK>
6407 // change nickname of client -- a server should only be able to
6408 // change the nicknames of clients that reside on it unless
6411 handle_n(token,params,source,reply,udp_host,udp_port);
6413 // J <NICK> <CHANLIST>
6414 // Join user to channel list, merge channel permissions
6416 handle_J(token,params,source,reply,udp_host,udp_port);
6418 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
6419 // change channel topic (netburst only)
6421 handle_T(token,params,source,reply,udp_host,udp_port);
6423 // M <TARGET> <MODES> [MODE-PARAMETERS]
6424 // Server setting modes on an object
6426 handle_M(token,params,source,reply,udp_host,udp_port);
6428 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
6429 // User setting modes on an object
6431 handle_m(token,params,source,reply,udp_host,udp_port);
6433 // P <SOURCE> <TARGET> :<TEXT>
6434 // Send a private/channel message
6436 handle_P(token,params,source,reply,udp_host,udp_port);
6438 // V <SOURCE> <TARGET> :<TEXT>
6439 // Send a private/channel notice
6441 handle_V(token,params,source,reply,udp_host,udp_port);
6443 // L <SOURCE> <CHANNEL> :<REASON>
6444 // User parting a channel
6446 handle_L(token,params,source,reply,udp_host,udp_port);
6448 // Q <SOURCE> :<REASON>
6451 handle_Q(token,params,source,reply,udp_host,udp_port);
6456 WriteOpers("Server %s has completed netburst. (%d secs)",source->name,time(NULL)-nb_start);
6457 handle_F(token,params,source,reply,udp_host,udp_port);
6461 WriteOpers("WARNING! Unknown datagram type '%c'",token);
6467 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
6469 char response[10240];
6470 char token = udp_msg[0];
6471 char* params = udp_msg + 2;
6472 char finalparam[1024];
6473 strcpy(finalparam," :xxxx");
6474 if (strstr(params," :")) {
6475 strncpy(finalparam,strstr(params," :"),1024);
6478 // S test.chatspike.net password :ChatSpike InspIRCd test server
6479 char* servername = strtok(params," ");
6480 char* password = strtok(NULL," ");
6481 char* serverdesc = finalparam+2;
6482 WriteOpers("CONNECT from %s (%s)",servername,udp_host);
6485 char Link_ServerName[1024];
6486 char Link_IPAddr[1024];
6487 char Link_Port[1024];
6488 char Link_Pass[1024];
6489 char Link_SendPass[1024];
6492 // search for a corresponding <link> block in the config files
6493 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6495 ConfValue("link","name",i,Link_ServerName,&config_f);
6496 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6497 ConfValue("link","port",i,Link_Port,&config_f);
6498 ConfValue("link","recvpass",i,Link_Pass,&config_f);
6499 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6500 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6501 LinkPort = atoi(Link_Port);
6502 if (!strcasecmp(Link_ServerName,servername)) {
6503 if (!strcasecmp(Link_IPAddr,udp_host)) {
6504 if (LinkPort == udp_port) {
6505 // we have a matching link line -
6506 // send a 'diminutive' server message back...
6507 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
6508 serv->SendPacket(response,udp_host,udp_port,0);
6509 WriteOpers("CONNECT from %s accepted, authenticating",servername);
6510 for (int j = 0; j < 255; j++) {
6511 if (servers[j] == NULL) {
6512 servers[j] = new serverrec;
6513 strcpy(servers[j]->internal_addr,udp_host);
6514 strcpy(servers[j]->name,servername);
6515 strcpy(servers[j]->description,serverdesc);
6516 servers[j]->internal_port = udp_port;
6517 // create a server record for this server
6518 snprintf(response,10240,"O %d",MyKey);
6519 serv->SendPacket(response,udp_host,udp_port,0);
6523 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
6527 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
6531 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
6535 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
6538 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
6539 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6544 // if this is received, this means the server-ip that sent it said "OK" to credentials.
6545 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
6546 // array, which is only added by an 'S' packet or BeginLink().
6547 for (int i = 0; i < 255; i++) {
6548 if (servers[i] != NULL) {
6549 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
6550 servers[i]->key = atoi(params);
6551 log(DEBUG,"Key for this server is now %d",servers[i]->key);
6552 DoSync(serv,udp_host,udp_port,MyKey);
6557 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
6561 // S test.chatspike.net password :ChatSpike InspIRCd test server
6562 char* servername = strtok(params," ");
6563 char* password = strtok(NULL," ");
6564 char* serverdesc = finalparam+2;
6566 // TODO: we should do a check here to ensure that this server is one we recently initiated a
6567 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
6568 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
6569 // a connect, so put out an oper alert!
6574 // for now, just accept all, we'll fix that later.
6575 WriteOpers("%s accepted our link credentials ",servername);
6577 char Link_ServerName[1024];
6578 char Link_IPAddr[1024];
6579 char Link_Port[1024];
6580 char Link_Pass[1024];
6581 char Link_SendPass[1024];
6584 // search for a corresponding <link> block in the config files
6585 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6587 ConfValue("link","name",i,Link_ServerName,&config_f);
6588 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6589 ConfValue("link","port",i,Link_Port,&config_f);
6590 ConfValue("link","recvpass",i,Link_Pass,&config_f);
6591 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6592 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6593 LinkPort = atoi(Link_Port);
6594 if (!strcasecmp(Link_ServerName,servername)) {
6595 if (!strcasecmp(Link_IPAddr,udp_host)) {
6596 if (LinkPort == udp_port) {
6597 // matching link at this end too, we're all done!
6598 // at this point we must begin key exchange and insert this
6599 // server into our 'active' table.
6600 for (int j = 0; j < 255; j++) {
6601 if (servers[j] != NULL) {
6602 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
6603 strcpy(servers[j]->description,serverdesc);
6604 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
6605 snprintf(response,10240,"O %d",MyKey);
6606 serv->SendPacket(response,udp_host,udp_port,0);
6611 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
6616 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
6620 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
6624 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
6627 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
6628 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6633 char* error_message = finalparam+2;
6634 WriteOpers("ERROR from %s: %s",udp_host,error_message);
6635 // remove this server from any lists
6636 for (int j = 0; j < 255; j++) {
6637 if (servers[j] != NULL) {
6638 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
6648 serverrec* source_server = NULL;
6650 for (int j = 0; j < 255; j++) {
6651 if (servers[j] != NULL) {
6652 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
6653 if (servers[j]->key == theirkey) {
6654 // found a valid key for this server, can process restricted stuff here
6655 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
6662 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
6666 int reap_counter = 0;
6670 struct sockaddr_in client, server;
6671 char addrs[MAXBUF][255];
6672 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
6674 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
6675 int selectResult = 0, selectResult2 = 0;
6676 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
6677 char resolvedHost[MAXBUF];
6681 log_file = fopen("ircd.log","a+");
6684 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
6688 log(DEBUG,"InspIRCd: startup: begin");
6692 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
6694 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
6696 SetupCommandTable();
6697 log(DEBUG,"InspIRCd: startup: default command table set up");
6700 if (strcmp(DieValue,""))
6702 printf("WARNING: %s\n\n",DieValue);
6705 log(DEBUG,"InspIRCd: startup: read config");
6707 int count2 = 0, count3 = 0;
6709 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
6711 ConfValue("bind","port",count,configToken,&config_f);
6712 ConfValue("bind","address",count,Addr,&config_f);
6713 ConfValue("bind","type",count,Type,&config_f);
6714 if (!strcmp(Type,"servers"))
6716 char Default[MAXBUF];
6717 strcpy(Default,"no");
6718 ConfValue("bind","default",count,Default,&config_f);
6719 if (strchr(Default,'y'))
6721 defaultRoute = count3;
6722 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
6724 me[count3] = new serverrec(ServerName,100L,false);
6725 me[count3]->CreateListener(Addr,atoi(configToken));
6730 ports[count2] = atoi(configToken);
6731 strcpy(addrs[count2],Addr);
6734 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
6737 UDPportCount = count3;
6739 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
6741 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
6745 /* BugFix By Craig! :p */
6747 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
6749 char modfile[MAXBUF];
6750 ConfValue("module","name",count2,configToken,&config_f);
6751 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
6752 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
6753 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
6754 /* If The File Doesnt exist, Trying to load it
6755 * Will Segfault the IRCd.. So, check to see if
6756 * it Exists, Before Proceeding. */
6757 if (FileExists(modfile))
6759 factory[count] = new ircd_module(modfile);
6760 if (factory[count]->LastError())
6762 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
6763 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
6766 if (factory[count]->factory)
6768 modules[count] = factory[count]->factory->CreateModule();
6769 /* save the module and the module's classfactory, if
6770 * this isnt done, random crashes can occur :/ */
6771 module_names.push_back(modfile);
6775 log(DEBUG,"Unable to load %s",modfile);
6776 sprintf("Unable to load %s\nExiting...\n",modfile);
6779 /* Increase the Count */
6784 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
6785 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
6788 MODCOUNT = count - 1;
6789 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
6791 printf("\nInspIRCd is now running!\n");
6793 startup_time = time(NULL);
6797 log(VERBOSE,"Not forking as -nofork was specified");
6801 if (DaemonSeed() == ERROR)
6803 log(DEBUG,"InspIRCd: startup: can't daemonise");
6804 printf("ERROR: could not go into daemon mode. Shutting down.\n");
6810 /* setup select call */
6811 FD_ZERO(&selectFds);
6812 log(DEBUG,"InspIRCd: startup: zero selects");
6813 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
6815 for (count = 0; count < portCount; count++)
6817 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
6819 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
6822 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
6824 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
6826 else /* well we at least bound to one socket so we'll continue */
6832 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
6834 /* if we didn't bind to anything then abort */
6835 if (boundPortCount == 0)
6837 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
6841 length = sizeof (client);
6842 int flip_flop = 0, udp_port = 0;
6843 char udp_msg[MAXBUF], udp_host[MAXBUF];
6845 /* main loop, this never returns */
6850 struct timeval tval;
6853 user_hash::iterator count2 = clientlist.begin();
6855 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
6856 // them in a list, then reap the list every second or so.
6857 if (reap_counter>5000)
6859 if (fd_reap.size() > 0)
6861 for( int n = 0; n < fd_reap.size(); n++)
6863 Blocking(fd_reap[n]);
6865 NonBlocking(fd_reap[n]);
6873 for (int x = 0; x != UDPportCount; x++)
6876 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
6878 if (strlen(udp_msg)<1) {
6879 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
6883 FOREACH_MOD OnPacketReceive(udp_msg);
6884 // Packets must go back via the route they arrived on :)
6885 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
6886 // link packets can manipulate the usertable so beware of
6887 // any loops here watching the user or channels hash
6888 log(DEBUG,"Sync: exit 3");
6895 while (count2 != clientlist.end())
6898 tval.tv_usec = tval.tv_sec = 0;
6900 int total_in_this_set = 0;
6902 user_hash::iterator xcount = count2;
6903 user_hash::iterator endingiter = count2;
6905 if (!count2->second) break;
6908 if (count2->second->fd != 0)
6910 // assemble up to 64 sockets into an fd_set
6911 // to implement a pooling mechanism.
6913 // This should be up to 64x faster than the
6914 // old implementation.
6915 while (total_in_this_set < 64)
6917 if (count2 != clientlist.end())
6919 // we don't check the state of remote users.
6920 if (count2->second->fd > 0)
6922 FD_SET (count2->second->fd, &sfd);
6924 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
6925 // their connection class.
6926 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
6928 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
6929 kill_link(count2->second,"Registration timeout");
6932 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
6934 if ((!count2->second->lastping) && (count2->second->registered == 7))
6936 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
6937 kill_link(count2->second,"Ping timeout");
6940 Write(count2->second->fd,"PING :%s",ServerName);
6941 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
6942 count2->second->lastping = 0;
6943 count2->second->nping = time(NULL)+120;
6947 total_in_this_set++;
6952 endingiter = count2;
6953 count2 = xcount; // roll back to where we were
6959 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
6961 // now loop through all of the items in this pool if any are waiting
6962 //if (selectResult2 > 0)
6963 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
6966 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
6968 log(DEBUG,"Reading fd %d",count2a->second->fd);
6969 memset(data, 0, 10240);
6970 result = read(count2a->second->fd, data, 10240);
6974 log(DEBUG,"Read %d characters from socket",result);
6975 userrec* current = count2a->second;
6976 int currfd = current->fd;
6977 char* l = strtok(data,"\n");
6982 if ((floodlines > current->flood) && (current->flood != 0))
6984 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
6985 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
6986 kill_link(current,"Excess flood");
6989 char sanitized[NetBufferSize];
6990 memset(sanitized, 0, NetBufferSize);
6992 for (int pt = 0; pt < strlen(l); pt++)
6996 sanitized[ptt++] = l[pt];
6999 sanitized[ptt] = '\0';
7000 if (strlen(sanitized))
7004 // we're gonna re-scan to check if the nick is gone, after every
7005 // command - if it has, we're gonna bail
7006 bool find_again = false;
7007 process_buffer(sanitized,current);
7009 // look for the user's record in case it's changed
7010 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
7012 if (c2->second->fd == currfd)
7014 // found again, update pointer
7015 current == c2->second;
7024 l = strtok(NULL,"\n");
7029 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
7031 log(DEBUG,"killing: %s",count2a->second->nick);
7032 kill_link(count2a->second,strerror(errno));
7036 // result EAGAIN means nothing read
7037 if (result == EAGAIN)
7045 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
7046 kill_link(count2a->second,"Client exited");
7047 // must bail here? kill_link removes the hash, corrupting the iterator
7048 log(DEBUG,"Bailing from client exit");
7052 else if (result > 0)
7057 for (int q = 0; q < total_in_this_set; q++)
7059 // there is no iterator += operator :(
7060 //if (count2 != clientlist.end())
7067 // set up select call
7068 for (count = 0; count < boundPortCount; count++)
7070 FD_SET (openSockfd[count], &selectFds);
7073 /* added timeout! select was waiting forever... wank... :/ */
7085 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
7087 /* select is reporting a waiting socket. Poll them all to find out which */
7088 if (selectResult > 0)
7090 char target[MAXBUF], resolved[MAXBUF];
7091 for (count = 0; count < boundPortCount; count++)
7093 if (FD_ISSET (openSockfd[count], &selectFds))
7095 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
7097 address_cache::iterator iter = IP.find(client.sin_addr);
7098 bool iscached = false;
7099 if (iter == IP.end())
7101 /* ip isn't in cache, add it */
7102 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
7103 if(CleanAndResolve(resolved, target) != TRUE)
7105 strncpy(resolved,target,MAXBUF);
7107 /* hostname now in 'target' */
7108 IP[client.sin_addr] = new string(resolved);
7109 /* hostname in cache */
7113 /* found ip (cached) */
7114 strncpy(resolved, iter->second->c_str(), MAXBUF);
7118 if (incomingSockfd < 0)
7120 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
7121 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
7125 AddClient(incomingSockfd, resolved, ports[count], iscached);
7126 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
7133 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
7136 close (incomingSockfd);