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
80 extern vector<Module*> modules;
81 vector<string> module_names;
82 extern vector<ircd_module*> factory;
93 template<> struct nspace::hash<in_addr>
95 size_t operator()(const struct in_addr &a) const
98 memcpy(&q,&a,sizeof(size_t));
103 template<> struct nspace::hash<string>
105 size_t operator()(const string &s) const
108 static struct hash<const char *> strhash;
120 bool operator()(const string& s1, const string& s2) const
122 char a[MAXBUF],b[MAXBUF];
123 strcpy(a,s1.c_str());
124 strcpy(b,s2.c_str());
125 return (strcasecmp(a,b) == 0);
130 struct InAddr_HashComp
133 bool operator()(const in_addr &s1, const in_addr &s2) const
138 memcpy(&q,&s1,sizeof(size_t));
139 memcpy(&p,&s2,sizeof(size_t));
147 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
148 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
149 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
150 typedef std::deque<command_t> command_table;
153 serverrec* servers[255];
157 user_hash clientlist;
160 command_table cmdlist;
167 struct linger linger = { 0 };
168 char bannerBuffer[MAXBUF];
169 int boundPortCount = 0;
170 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
171 int defaultRoute = 0;
175 long MyKey = C.GenKey();
179 int has_channel(userrec *u, chanrec *c);
180 int usercount(chanrec *c);
181 int usercount_i(chanrec *c);
182 void update_stats_l(int fd,int data_out);
183 char* Passwd(userrec *user);
184 bool IsDenied(userrec *user);
185 void AddWhoWas(userrec* u);
187 std::stringstream config_f(stringstream::in | stringstream::out);
189 void safedelete(userrec *p)
193 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
194 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
200 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
204 void safedelete(chanrec *p)
210 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
214 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
219 void tidystring(char* str)
221 // strips out double spaces before a : parameter
224 bool go_again = true;
231 while ((str[0] == ' ') && (strlen(str)>0))
238 bool noparse = false;
241 while (a < strlen(str))
243 if ((a<strlen(str)-1) && (noparse==false))
245 if ((str[a] == ' ') && (str[a+1] == ' '))
247 log(DEBUG,"Tidied extra space out of string: %s",str);
255 if ((str[a] == ' ') && (str[a+1] == ':'))
261 temp[t++] = str[a++];
264 strncpy(str,temp,MAXBUF);
268 /* chop a string down to 512 characters and preserve linefeed (irc max
275 log(DEBUG,"ERROR! Null string passed to chop()!");
279 FOREACH_MOD OnServerRaw(temp,false);
280 const char* str2 = temp.c_str();
281 sprintf(str,"%s",str2);
284 if (strlen(str) >= 512)
293 std::string getservername()
298 std::string getserverdesc()
303 std::string getnetworkname()
308 std::string getadminname()
313 std::string getadminemail()
318 std::string getadminnick()
323 void log(int level,char *text, ...)
325 char textbuffer[MAXBUF];
328 struct tm * timeinfo;
329 if (level < LogLevel)
333 timeinfo = localtime (&rawtime);
338 va_start (argsPtr, text);
339 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
341 strcpy(b,asctime(timeinfo));
342 b[strlen(b)-1] = ':';
343 fprintf(log_file,"%s %s\n",b,textbuffer);
346 // nofork enabled? display it on terminal too
347 printf("%s %s\n",b,textbuffer);
352 void readfile(file_cache &F, const char* fname)
355 char linebuf[MAXBUF];
357 log(DEBUG,"readfile: loading %s",fname);
359 file = fopen(fname,"r");
364 fgets(linebuf,sizeof(linebuf),file);
365 linebuf[strlen(linebuf)-1]='\0';
366 if (!strcmp(linebuf,""))
372 F.push_back(linebuf);
379 log(DEBUG,"readfile: failed to load file: %s",fname);
381 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
384 void ReadConfig(void)
386 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
389 LoadConf(CONFIG_FILE,&config_f);
391 ConfValue("server","name",0,ServerName,&config_f);
392 ConfValue("server","description",0,ServerDesc,&config_f);
393 ConfValue("server","network",0,Network,&config_f);
394 ConfValue("admin","name",0,AdminName,&config_f);
395 ConfValue("admin","email",0,AdminEmail,&config_f);
396 ConfValue("admin","nick",0,AdminNick,&config_f);
397 ConfValue("files","motd",0,motd,&config_f);
398 ConfValue("files","rules",0,rules,&config_f);
399 ConfValue("power","diepass",0,diepass,&config_f);
400 ConfValue("power","pause",0,pauseval,&config_f);
401 ConfValue("power","restartpass",0,restartpass,&config_f);
402 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
403 ConfValue("die","value",0,DieValue,&config_f);
404 ConfValue("options","loglevel",0,dbg,&config_f);
405 ConfValue("options","netbuffersize",0,NB,&config_f);
406 NetBufferSize = atoi(NB);
407 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
409 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
410 NetBufferSize = 10240;
412 if (!strcmp(dbg,"debug"))
414 if (!strcmp(dbg,"verbose"))
416 if (!strcmp(dbg,"default"))
418 if (!strcmp(dbg,"sparse"))
420 if (!strcmp(dbg,"none"))
423 log(DEBUG,"Reading message of the day");
424 readfile(RULES,rules);
425 log(DEBUG,"Reading connect classes");
427 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
430 ConfValue("connect","allow",i,Value,&config_f);
431 ConfValue("connect","timeout",i,timeout,&config_f);
432 ConfValue("connect","flood",i,flood,&config_f);
433 if (strcmp(Value,""))
435 strcpy(c.host,Value);
438 ConfValue("connect","password",i,Value,&config_f);
439 strcpy(c.pass,Value);
440 c.registration_timeout = 90; // default is 2 minutes
441 c.flood = atoi(flood);
444 c.registration_timeout = atoi(timeout);
446 Classes.push_back(c);
447 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
451 ConfValue("connect","deny",i,Value,&config_f);
452 strcpy(c.host,Value);
454 Classes.push_back(c);
455 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
464 log(DEBUG,"Blocking: %d",s);
465 flags = fcntl(s, F_GETFL, 0);
466 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
469 void NonBlocking(int s)
472 log(DEBUG,"NonBlocking: %d",s);
473 flags = fcntl(s, F_GETFL, 0);
474 //fcntl(s, F_SETFL, O_NONBLOCK);
475 fcntl(s, F_SETFL, flags | O_NONBLOCK);
479 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
481 struct hostent *hostPtr = NULL;
484 memset (resolvedHost, '\0',MAXBUF);
485 if(unresolvedHost == NULL)
487 if ((inet_aton(unresolvedHost,&addr)) == 0)
489 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
491 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
493 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
497 /* write formatted text to a socket, in same format as printf */
499 void Write(int sock,char *text, ...)
503 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
506 char textbuffer[MAXBUF];
510 va_start (argsPtr, text);
511 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
513 sprintf(tb,"%s\r\n",textbuffer);
515 write(sock,tb,strlen(tb));
516 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
519 /* write a server formatted numeric response to a single socket */
521 void WriteServ(int sock, char* text, ...)
525 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
528 char textbuffer[MAXBUF],tb[MAXBUF];
530 va_start (argsPtr, text);
532 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
534 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
536 write(sock,tb,strlen(tb));
537 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
540 /* write text from an originating user to originating user */
542 void WriteFrom(int sock, userrec *user,char* text, ...)
544 if ((!text) || (!user))
546 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
549 char textbuffer[MAXBUF],tb[MAXBUF];
551 va_start (argsPtr, text);
553 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
555 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
557 write(sock,tb,strlen(tb));
558 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
561 /* write text to an destination user from a source user (e.g. user privmsg) */
563 void WriteTo(userrec *source, userrec *dest,char *data, ...)
565 if ((!source) || (!dest) || (!data))
567 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
570 char textbuffer[MAXBUF],tb[MAXBUF];
572 va_start (argsPtr, data);
573 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
576 WriteFrom(dest->fd,source,"%s",textbuffer);
579 /* write formatted text from a source user to all users on a channel
580 * including the sender (NOT for privmsg, notice etc!) */
582 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
584 if ((!Ptr) || (!user) || (!text))
586 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
589 char textbuffer[MAXBUF];
591 va_start (argsPtr, text);
592 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
594 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
596 if (has_channel(i->second,Ptr))
598 WriteTo(user,i->second,"%s",textbuffer);
603 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
605 if ((!Ptr) || (!user) || (!text))
607 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
610 char textbuffer[MAXBUF];
612 va_start (argsPtr, text);
613 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
615 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
619 if (has_channel(i->second,Ptr))
621 WriteServ(i->second->fd,"%s",textbuffer);
628 /* write formatted text from a source user to all users on a channel except
629 * for the sender (for privmsg etc) */
631 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
633 if ((!Ptr) || (!user) || (!text))
635 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
638 char textbuffer[MAXBUF];
640 va_start (argsPtr, text);
641 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
644 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
648 if (has_channel(i->second,Ptr) && (user != i->second))
650 WriteTo(user,i->second,"%s",textbuffer);
656 int c_count(userrec* u)
659 for (int i =0; i != MAXCHANS; i++)
660 if (u->chans[i].channel != NULL)
666 /* return 0 or 1 depending if users u and u2 share one or more common channels
667 * (used by QUIT, NICK etc which arent channel specific notices) */
669 int common_channels(userrec *u, userrec *u2)
676 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
679 for (i = 0; i != MAXCHANS; i++)
681 for (z = 0; z != MAXCHANS; z++)
683 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
685 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
687 if ((c_count(u)) && (c_count(u2)))
698 /* write a formatted string to all users who share at least one common
699 * channel, including the source user e.g. for use in NICK */
701 void WriteCommon(userrec *u, char* text, ...)
705 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
709 if (u->registered != 7) {
710 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
714 char textbuffer[MAXBUF];
716 va_start (argsPtr, text);
717 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
720 WriteFrom(u->fd,u,"%s",textbuffer);
722 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
726 if (common_channels(u,i->second) && (i->second != u))
728 WriteFrom(i->second->fd,u,"%s",textbuffer);
734 /* write a formatted string to all users who share at least one common
735 * channel, NOT including the source user e.g. for use in QUIT */
737 void WriteCommonExcept(userrec *u, char* text, ...)
741 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
745 if (u->registered != 7) {
746 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
750 char textbuffer[MAXBUF];
752 va_start (argsPtr, text);
753 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
756 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
760 if ((common_channels(u,i->second)) && (u != i->second))
762 WriteFrom(i->second->fd,u,"%s",textbuffer);
768 void WriteOpers(char* text, ...)
772 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
776 char textbuffer[MAXBUF];
778 va_start (argsPtr, text);
779 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
782 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
786 if (strchr(i->second->modes,'o'))
788 if (strchr(i->second->modes,'s'))
790 // send server notices to all with +s
791 // (TODO: needs SNOMASKs)
792 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
799 bool hasumode(userrec* user, char mode)
803 return (strchr(user->modes,mode)>0);
808 void WriteMode(const char* modes, int flags, const char* text, ...)
810 if ((!text) || (!modes) || (!flags))
812 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
816 char textbuffer[MAXBUF];
818 va_start (argsPtr, text);
819 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
822 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
826 bool send_to_user = false;
831 for (int n = 0; n < strlen(modes); n++)
833 if (!hasumode(i->second,modes[n]))
835 send_to_user = false;
840 else if (flags == WM_OR)
842 send_to_user = false;
843 for (int n = 0; n < strlen(modes); n++)
845 if (hasumode(i->second,modes[n]))
855 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
861 void WriteWallOps(userrec *source, char* text, ...)
863 if ((!text) || (!source))
865 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
870 char textbuffer[MAXBUF];
872 va_start (argsPtr, text);
873 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
876 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
880 if (strchr(i->second->modes,'w'))
882 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
888 /* convert a string to lowercase. Note following special circumstances
889 * taken from RFC 1459. Many "official" server branches still hold to this
890 * rule so i will too;
892 * Because of IRC's scandanavian origin, the characters {}| are
893 * considered to be the lower case equivalents of the characters []\,
894 * respectively. This is a critical issue when determining the
895 * equivalence of two nicknames.
898 void strlower(char *n)
904 for (int i = 0; i != strlen(n); i++)
906 n[i] = tolower(n[i]);
916 /* verify that a user's ident and nickname is valid */
918 int isident(const char* n)
931 for (i = 0; i != strlen(n); i++)
933 if ((n[i] < 33) || (n[i] > 125))
937 /* can't occur ANYWHERE in an Ident! */
938 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
947 int isnick(const char* n)
959 if (strlen(n) > NICKMAX-1)
963 for (i = 0; i != strlen(n); i++)
965 if ((n[i] < 33) || (n[i] > 125))
969 /* can't occur ANYWHERE in a nickname! */
970 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
974 /* can't occur as the first char of a nickname... */
975 if ((strchr("0123456789",n[i])) && (!i))
983 /* Find a user record by nickname and return a pointer to it */
985 userrec* Find(string nick)
987 user_hash::iterator iter = clientlist.find(nick);
989 if (iter == clientlist.end())
990 /* Couldn't find it */
996 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
998 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1002 if (i->second->fd == fd)
1004 i->second->bytes_out+=data_out;
1005 i->second->cmds_out++;
1012 /* find a channel record by channel name and return a pointer to it */
1014 chanrec* FindChan(const char* chan)
1018 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1022 chan_hash::iterator iter = chanlist.find(chan);
1024 if (iter == chanlist.end())
1025 /* Couldn't find it */
1028 return iter->second;
1032 void purge_empty_chans(void)
1034 int go_again = 1, purge = 0;
1039 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1042 if (!usercount(i->second))
1044 /* kill the record */
1045 if (i != chanlist.end())
1047 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1057 log(DEBUG,"skipped purge for %s",i->second->name);
1062 log(DEBUG,"completed channel purge, killed %d",purge);
1065 /* returns the status character for a given user on a channel, e.g. @ for op,
1066 * % for halfop etc. If the user has several modes set, the highest mode
1067 * the user has must be returned. */
1069 char* cmode(userrec *user, chanrec *chan)
1071 if ((!user) || (!chan))
1073 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1078 for (i = 0; i != MAXCHANS; i++)
1080 if ((user->chans[i].channel == chan) && (chan != NULL))
1082 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1086 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1090 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1099 char scratch[MAXBUF];
1100 char sparam[MAXBUF];
1102 char* chanmodes(chanrec *chan)
1106 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1113 if (chan->noexternal)
1115 strncat(scratch,"n",MAXMODES);
1117 if (chan->topiclock)
1119 strncat(scratch,"t",MAXMODES);
1121 if (strcmp(chan->key,""))
1123 strncat(scratch,"k",MAXMODES);
1127 strncat(scratch,"l",MAXMODES);
1129 if (chan->inviteonly)
1131 strncat(scratch,"i",MAXMODES);
1133 if (chan->moderated)
1135 strncat(scratch,"m",MAXMODES);
1139 strncat(scratch,"s",MAXMODES);
1141 if (chan->c_private)
1143 strncat(scratch,"p",MAXMODES);
1145 if (strcmp(chan->key,""))
1147 strncat(sparam,chan->key,MAXBUF);
1152 sprintf(foo," %d",chan->limit);
1153 strncat(sparam,foo,MAXBUF);
1155 if (strlen(chan->custom_modes))
1157 strncat(scratch,chan->custom_modes,MAXMODES);
1158 for (int z = 0; z < strlen(chan->custom_modes); z++)
1160 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1163 strncat(sparam," ",MAXBUF);
1164 strncat(sparam,extparam.c_str(),MAXBUF);
1168 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1169 strncat(scratch,sparam,MAXMODES);
1173 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1174 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1175 * highest mode the user has must be returned. */
1177 int cstatus(userrec *user, chanrec *chan)
1179 if ((!chan) || (!user))
1181 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1186 for (i = 0; i != MAXCHANS; i++)
1188 if ((user->chans[i].channel == chan) && (chan != NULL))
1190 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1194 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1198 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1200 return STATUS_VOICE;
1202 return STATUS_NORMAL;
1208 /* compile a userlist of a channel into a string, each nick seperated by
1209 * spaces and op, voice etc status shown as @ and + */
1211 void userlist(userrec *user,chanrec *c)
1213 if ((!c) || (!user))
1215 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1219 sprintf(list,"353 %s = %s :", user->nick, c->name);
1220 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1222 if (has_channel(i->second,c))
1224 if (isnick(i->second->nick))
1226 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1228 /* user is +i, and source not on the channel, does not show
1229 * nick in NAMES list */
1232 strcat(list,cmode(i->second,c));
1233 strcat(list,i->second->nick);
1235 if (strlen(list)>(480-NICKMAX))
1237 /* list overflowed into
1238 * multiple numerics */
1239 WriteServ(user->fd,list);
1240 sprintf(list,"353 %s = %s :", user->nick, c->name);
1245 /* if whats left in the list isnt empty, send it */
1246 if (list[strlen(list)-1] != ':')
1248 WriteServ(user->fd,list);
1252 /* return a count of the users on a specific channel accounting for
1253 * invisible users who won't increase the count. e.g. for /LIST */
1255 int usercount_i(chanrec *c)
1262 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1267 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1271 if (has_channel(i->second,c))
1273 if (isnick(i->second->nick))
1275 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1277 /* user is +i, and source not on the channel, does not show
1278 * nick in NAMES list */
1286 log(DEBUG,"usercount_i: %s %d",c->name,count);
1291 int usercount(chanrec *c)
1298 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1303 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1307 if (has_channel(i->second,c))
1309 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1316 log(DEBUG,"usercount: %s %d",c->name,count);
1321 /* add a channel to a user, creating the record for it if needed and linking
1322 * it to the user record */
1324 chanrec* add_channel(userrec *user, const char* cn, const char* key)
1326 if ((!user) || (!cn))
1328 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1337 strncpy(cname,cn,MAXBUF);
1339 // we MUST declare this wherever we use FOREACH_RESULT
1342 if ((!cname) || (!user))
1346 if (strlen(cname) > CHANMAX-1)
1348 cname[CHANMAX-1] = '\0';
1351 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1353 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1355 return NULL; // already on the channel!
1359 if (!FindChan(cname))
1361 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1366 /* create a new one */
1367 log(DEBUG,"add_channel: creating: %s",cname);
1369 chanlist[cname] = new chanrec();
1371 strcpy(chanlist[cname]->name, cname);
1372 chanlist[cname]->topiclock = 1;
1373 chanlist[cname]->noexternal = 1;
1374 chanlist[cname]->created = time(NULL);
1375 strcpy(chanlist[cname]->topic, "");
1376 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1377 chanlist[cname]->topicset = 0;
1378 Ptr = chanlist[cname];
1379 log(DEBUG,"add_channel: created: %s",cname);
1380 /* set created to 2 to indicate user
1381 * is the first in the channel
1382 * and should be given ops */
1388 /* channel exists, just fish out a pointer to its struct */
1389 Ptr = FindChan(cname);
1392 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1397 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1398 if (strcmp(Ptr->key,""))
1400 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1403 log(DEBUG,"add_channel: no key given in JOIN");
1404 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1409 log(DEBUG,"key at %p is %s",key,key);
1410 if (strcasecmp(key,Ptr->key))
1412 log(DEBUG,"add_channel: bad key given in JOIN");
1413 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1418 log(DEBUG,"add_channel: no key");
1420 if (Ptr->inviteonly)
1422 log(DEBUG,"add_channel: channel is +i");
1423 if (user->IsInvited(Ptr->name))
1425 /* user was invited to channel */
1426 /* there may be an optional channel NOTICE here */
1430 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1434 log(DEBUG,"add_channel: channel is not +i");
1438 if (usercount(Ptr) == Ptr->limit)
1440 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1445 log(DEBUG,"add_channel: about to walk banlist");
1447 /* check user against the channel banlist */
1448 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1450 if (match(user->GetFullHost(),i->data))
1452 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1457 log(DEBUG,"add_channel: bans checked");
1459 user->RemoveInvite(Ptr->name);
1461 log(DEBUG,"add_channel: invites removed");
1467 log(DEBUG,"Passed channel checks");
1469 for (i =0; i != MAXCHANS; i++)
1471 if (user->chans[i].channel == NULL)
1473 log(DEBUG,"Adding into their channel list");
1477 /* first user in is given ops */
1478 user->chans[i].uc_modes = UCMODE_OP;
1482 user->chans[i].uc_modes = 0;
1484 user->chans[i].channel = Ptr;
1485 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1487 log(DEBUG,"Sent JOIN to client");
1491 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1492 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1495 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1496 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1497 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1498 FOREACH_MOD OnUserJoin(user,Ptr);
1502 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1503 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1507 /* remove a channel from a users record, and remove the record from memory
1508 * if the channel has become empty */
1510 chanrec* del_channel(userrec *user, const char* cname, const char* reason)
1512 if ((!user) || (!cname))
1514 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1522 if ((!cname) || (!user))
1527 Ptr = FindChan(cname);
1534 FOREACH_MOD OnUserPart(user,Ptr);
1535 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1537 for (i =0; i != MAXCHANS; i++)
1539 /* zap it from the channel list of the user */
1540 if (user->chans[i].channel == Ptr)
1544 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1548 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1550 user->chans[i].uc_modes = 0;
1551 user->chans[i].channel = NULL;
1552 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1557 /* if there are no users left on the channel */
1558 if (!usercount(Ptr))
1560 chan_hash::iterator iter = chanlist.find(Ptr->name);
1562 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1564 /* kill the record */
1565 if (iter != chanlist.end())
1567 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1568 delete iter->second;
1569 chanlist.erase(iter);
1575 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1577 if ((!src) || (!user) || (!Ptr) || (!reason))
1579 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1586 if ((!Ptr) || (!user) || (!src))
1591 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1593 if (!has_channel(user,Ptr))
1595 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1598 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1600 if (cstatus(src,Ptr) == STATUS_HOP)
1602 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1606 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1612 for (i =0; i != MAXCHANS; i++)
1614 /* zap it from the channel list of the user */
1615 if (user->chans[i].channel == Ptr)
1617 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1618 user->chans[i].uc_modes = 0;
1619 user->chans[i].channel = NULL;
1620 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1625 /* if there are no users left on the channel */
1626 if (!usercount(Ptr))
1628 chan_hash::iterator iter = chanlist.find(Ptr->name);
1630 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1632 /* kill the record */
1633 if (iter != chanlist.end())
1635 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1636 delete iter->second;
1637 chanlist.erase(iter);
1643 /* returns 1 if user u has channel c in their record, 0 if not */
1645 int has_channel(userrec *u, chanrec *c)
1651 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1654 for (i =0; i != MAXCHANS; i++)
1656 if (u->chans[i].channel == c)
1664 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1669 if ((!user) || (!dest) || (!chan))
1671 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1674 if (status != STATUS_OP)
1676 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1683 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1689 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1694 for (i = 0; i != MAXCHANS; i++)
1696 if ((d->chans[i].channel == chan) && (chan != NULL))
1698 if (d->chans[i].uc_modes & UCMODE_OP)
1700 /* mode already set on user, dont allow multiple */
1703 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1704 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1712 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1717 if ((!user) || (!dest) || (!chan))
1719 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1722 if (status != STATUS_OP)
1724 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1732 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1737 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1742 for (i = 0; i != MAXCHANS; i++)
1744 if ((d->chans[i].channel == chan) && (chan != NULL))
1746 if (d->chans[i].uc_modes & UCMODE_HOP)
1748 /* mode already set on user, dont allow multiple */
1751 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1752 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1760 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1765 if ((!user) || (!dest) || (!chan))
1767 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1770 if (status < STATUS_HOP)
1772 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1780 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1785 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1790 for (i = 0; i != MAXCHANS; i++)
1792 if ((d->chans[i].channel == chan) && (chan != NULL))
1794 if (d->chans[i].uc_modes & UCMODE_VOICE)
1796 /* mode already set on user, dont allow multiple */
1799 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1800 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1808 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1813 if ((!user) || (!dest) || (!chan))
1815 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1818 if (status != STATUS_OP)
1820 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1828 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1833 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1838 for (i = 0; i != MAXCHANS; i++)
1840 if ((d->chans[i].channel == chan) && (chan != NULL))
1842 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1844 /* mode already set on user, dont allow multiple */
1847 d->chans[i].uc_modes ^= UCMODE_OP;
1848 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1856 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1861 if ((!user) || (!dest) || (!chan))
1863 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1866 if (status != STATUS_OP)
1868 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1876 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1881 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1886 for (i = 0; i != MAXCHANS; i++)
1888 if ((d->chans[i].channel == chan) && (chan != NULL))
1890 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1892 /* mode already set on user, dont allow multiple */
1895 d->chans[i].uc_modes ^= UCMODE_HOP;
1896 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1904 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1909 if ((!user) || (!dest) || (!chan))
1911 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1914 if (status < STATUS_HOP)
1916 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1924 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1929 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1934 for (i = 0; i != MAXCHANS; i++)
1936 if ((d->chans[i].channel == chan) && (chan != NULL))
1938 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1940 /* mode already set on user, dont allow multiple */
1943 d->chans[i].uc_modes ^= UCMODE_VOICE;
1944 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1952 void TidyBan(char *ban)
1955 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1959 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1963 char* pos_of_pling = strchr(temp,'!');
1964 char* pos_of_at = strchr(temp,'@');
1966 pos_of_pling[0] = '\0';
1967 pos_of_at[0] = '\0';
1971 strncpy(NICK,temp,NICKMAX);
1972 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1973 strncpy(HOST,pos_of_at,160);
1975 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1978 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1980 if ((!user) || (!dest) || (!chan)) {
1981 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1986 if ((!user) || (!dest) || (!chan))
1988 if (strchr(dest,'!')==0)
1990 if (strchr(dest,'@')==0)
1992 for (int i = 0; i < strlen(dest); i++)
1995 for (int i = 0; i < strlen(dest); i++)
1999 for (int i = 0; i < strlen(dest); i++)
2005 for (int i = 0; i < strlen(dest); i++)
2010 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2013 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2015 if (!strcasecmp(i->data,dest))
2017 // dont allow a user to set the same ban twice
2022 b.set_time = time(NULL);
2023 strncpy(b.data,dest,MAXBUF);
2024 strncpy(b.set_by,user->nick,NICKMAX);
2025 chan->bans.push_back(b);
2029 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2031 if ((!user) || (!dest) || (!chan)) {
2032 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2036 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2037 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2039 if (!strcasecmp(i->data,dest))
2041 chan->bans.erase(i);
2048 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
2050 if ((!parameters) || (!user)) {
2051 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2056 char modelist[MAXBUF];
2057 char outlist[MAXBUF];
2058 char outstr[MAXBUF];
2059 char outpars[32][MAXBUF];
2065 bool k_set = false, l_set = false;
2072 log(DEBUG,"process_modes: start");
2074 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2075 /* parameters[2] onwards are parameters for
2076 * modes that require them :) */
2077 strcpy(outlist,"+");
2080 log(DEBUG,"process_modes: modelist: %s",modelist);
2082 for (ptr = 0; ptr < strlen(modelist); ptr++)
2087 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2088 char modechar = modelist[ptr];
2089 switch (modelist[ptr])
2094 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2096 outlist[strlen(outlist)-1] = '-';
2100 strcat(outlist,"-");
2110 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2112 outlist[strlen(outlist)-1] = '+';
2116 strcat(outlist,"+");
2123 if ((param >= pcnt)) break;
2126 r = give_ops(user,parameters[param++],chan,status);
2130 r = take_ops(user,parameters[param++],chan,status);
2134 strcat(outlist,"o");
2135 strcpy(outpars[pc++],parameters[param-1]);
2140 if ((param >= pcnt)) break;
2143 r = give_hops(user,parameters[param++],chan,status);
2147 r = take_hops(user,parameters[param++],chan,status);
2151 strcat(outlist,"h");
2152 strcpy(outpars[pc++],parameters[param-1]);
2158 if ((param >= pcnt)) break;
2161 r = give_voice(user,parameters[param++],chan,status);
2165 r = take_voice(user,parameters[param++],chan,status);
2169 strcat(outlist,"v");
2170 strcpy(outpars[pc++],parameters[param-1]);
2175 if ((param >= pcnt)) break;
2178 r = add_ban(user,parameters[param++],chan,status);
2182 r = take_ban(user,parameters[param++],chan,status);
2186 strcat(outlist,"b");
2187 strcpy(outpars[pc++],parameters[param-1]);
2193 if ((param >= pcnt))
2201 if (!strcmp(chan->key,""))
2203 strcat(outlist,"k");
2205 strcpy(key,parameters[param++]);
2206 if (strlen(key)>32) {
2209 strcpy(outpars[pc++],key);
2210 strcpy(chan->key,key);
2216 /* checks on -k are case sensitive and only accurate to the
2217 first 32 characters */
2219 strcpy(key,parameters[param++]);
2220 if (strlen(key)>32) {
2223 /* only allow -k if correct key given */
2224 if (!strcmp(chan->key,key))
2226 strcat(outlist,"k");
2227 strcpy(chan->key,"");
2228 strcpy(outpars[pc++],key);
2238 strcat(outlist,"l");
2243 if ((param >= pcnt)) break;
2249 bool invalid = false;
2250 for (int i = 0; i < strlen(parameters[param]); i++)
2252 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2257 if (atoi(parameters[param]) < 1)
2265 chan->limit = atoi(parameters[param]);
2268 strcat(outlist,"l");
2269 strcpy(outpars[pc++],parameters[param++]);
2276 if (chan->inviteonly != mdir)
2278 strcat(outlist,"i");
2280 chan->inviteonly = mdir;
2284 if (chan->topiclock != mdir)
2286 strcat(outlist,"t");
2288 chan->topiclock = mdir;
2292 if (chan->noexternal != mdir)
2294 strcat(outlist,"n");
2296 chan->noexternal = mdir;
2300 if (chan->moderated != mdir)
2302 strcat(outlist,"m");
2304 chan->moderated = mdir;
2308 if (chan->secret != mdir)
2310 strcat(outlist,"s");
2311 if (chan->c_private)
2313 chan->c_private = 0;
2316 strcat(outlist,"-p+");
2320 strcat(outlist,"+p-");
2324 chan->secret = mdir;
2328 if (chan->c_private != mdir)
2330 strcat(outlist,"p");
2336 strcat(outlist,"-s+");
2340 strcat(outlist,"+s-");
2344 chan->c_private = mdir;
2348 log(DEBUG,"Preprocessing custom mode %c",modechar);
2351 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2353 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2356 if (ModeDefined(modechar,MT_CHANNEL))
2358 log(DEBUG,"A module has claimed this mode");
2361 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2363 p.push_back(parameters[param]);
2365 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2367 p.push_back(parameters[param]);
2370 bool handled = false;
2373 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2374 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2375 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2381 for (int i = 0; i <= MODCOUNT; i++)
2385 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2387 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2388 char app[] = {modechar, 0};
2391 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2393 strcat(outlist, app);
2395 else if (!strchr(outlist,modechar))
2397 strcat(outlist, app);
2400 chan->SetCustomMode(modechar,mdir);
2401 // include parameters in output if mode has them
2402 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2404 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2405 strcpy(outpars[pc++],parameters[param++]);
2407 // break, because only one module can handle the mode.
2419 /* this ensures only the *valid* modes are sent out onto the network */
2420 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2422 outlist[strlen(outlist)-1] = '\0';
2424 if (strcmp(outlist,""))
2426 strcpy(outstr,outlist);
2427 for (ptr = 0; ptr < pc; ptr++)
2430 strcat(outstr,outpars[ptr]);
2434 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2438 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2443 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2445 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2447 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2448 // RFC1459 specified modes
2449 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2451 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2455 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2456 if ((strchr(sourcemodes,'o')) && (!adding))
2458 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2461 else if (umode == 'o')
2463 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2467 // process any module-defined modes that need oper
2468 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2470 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2474 if (ModeDefined(umode,MT_CLIENT))
2476 // process any module-defined modes that don't need oper
2477 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2478 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2480 // no, this mode needs oper, and this user 'aint got what it takes!
2486 // anything else - return false.
2487 log(DEBUG,"umode %c not known by any ruleset",umode);
2491 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2495 if (ModeDefined(umode,MT_CLIENT))
2497 for (int i = 0; i <= MODCOUNT; i++)
2499 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2501 log(DEBUG,"Module claims umode %c",umode);
2505 log(DEBUG,"No module claims umode %c",umode);
2510 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2515 void handle_mode(char **parameters, int pcnt, userrec *user)
2521 char outpars[MAXBUF];
2523 dest = Find(parameters[0]);
2525 if ((dest) && (pcnt == 1))
2527 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2531 if ((dest) && (pcnt > 1))
2533 char dmodes[MAXBUF];
2534 strncpy(dmodes,dest->modes,MAXBUF);
2535 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2540 if (strchr(user->modes,'o'))
2551 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2555 strcpy(outpars,"+");
2558 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2561 for (i = 0; i < strlen(parameters[1]); i++)
2563 if (parameters[1][i] == '+')
2567 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2569 outpars[strlen(outpars)-1] = '+';
2573 strcat(outpars,"+");
2579 if (parameters[1][i] == '-')
2583 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2585 outpars[strlen(outpars)-1] = '-';
2589 strcat(outpars,"-");
2597 if (strchr(user->modes,'o'))
2603 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2612 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2614 char umode = parameters[1][i];
2615 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2617 dmodes[strlen(dmodes)+1]='\0';
2618 dmodes[strlen(dmodes)] = parameters[1][i];
2619 outpars[strlen(outpars)+1]='\0';
2620 outpars[strlen(outpars)] = parameters[1][i];
2626 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2628 char umode = parameters[1][i];
2629 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2635 outpars[strlen(outpars)+1]='\0';
2636 outpars[strlen(outpars)] = parameters[1][i];
2639 for (q = 0; q < strlen(dmodes); q++)
2641 if (dmodes[q] != parameters[1][i])
2648 strcpy(dmodes,temp);
2655 if (strlen(outpars))
2661 while (i < strlen (outpars))
2663 b[z++] = outpars[i++];
2665 if (i<strlen(outpars)-1)
2667 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2669 // someones playing silly buggers and trying
2670 // to put a +- or -+ into the line...
2674 if (i == strlen(outpars)-1)
2676 if ((outpars[i] == '-') || (outpars[i] == '+'))
2684 if ((b[z] == '-') || (b[z] == '+'))
2687 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2690 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2692 if (strlen(dmodes)>MAXMODES)
2694 dmodes[MAXMODES-1] = '\0';
2696 log(DEBUG,"Stripped mode line");
2697 log(DEBUG,"Line dest is now %s",dmodes);
2698 strncpy(dest->modes,dmodes,MAXMODES);
2705 Ptr = FindChan(parameters[0]);
2710 /* just /modes #channel */
2711 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2712 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2718 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2721 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2723 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2725 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2729 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2731 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
2735 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2739 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2746 void server_mode(char **parameters, int pcnt, userrec *user)
2752 char outpars[MAXBUF];
2754 dest = Find(parameters[0]);
2756 // fix: ChroNiCk found this - we cant use this as debug if its null!
2759 log(DEBUG,"server_mode on %s",dest->nick);
2762 if ((dest) && (pcnt > 1))
2764 log(DEBUG,"params > 1");
2766 char dmodes[MAXBUF];
2767 strncpy(dmodes,dest->modes,MAXBUF);
2769 strcpy(outpars,"+");
2772 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2775 for (i = 0; i < strlen(parameters[1]); i++)
2777 if (parameters[1][i] == '+')
2781 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2783 outpars[strlen(outpars)-1] = '+';
2787 strcat(outpars,"+");
2793 if (parameters[1][i] == '-')
2797 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2799 outpars[strlen(outpars)-1] = '-';
2803 strcat(outpars,"-");
2810 log(DEBUG,"begin mode processing entry");
2816 log(DEBUG,"umode %c being added",parameters[1][i]);
2817 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2819 char umode = parameters[1][i];
2820 log(DEBUG,"umode %c is an allowed umode",umode);
2821 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2823 dmodes[strlen(dmodes)+1]='\0';
2824 dmodes[strlen(dmodes)] = parameters[1][i];
2825 outpars[strlen(outpars)+1]='\0';
2826 outpars[strlen(outpars)] = parameters[1][i];
2832 // can only remove a mode they already have
2833 log(DEBUG,"umode %c being removed",parameters[1][i]);
2834 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2836 char umode = parameters[1][i];
2837 log(DEBUG,"umode %c is an allowed umode",umode);
2838 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2844 outpars[strlen(outpars)+1]='\0';
2845 outpars[strlen(outpars)] = parameters[1][i];
2848 for (q = 0; q < strlen(dmodes); q++)
2850 if (dmodes[q] != parameters[1][i])
2857 strcpy(dmodes,temp);
2864 if (strlen(outpars))
2870 while (i < strlen (outpars))
2872 b[z++] = outpars[i++];
2874 if (i<strlen(outpars)-1)
2876 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2878 // someones playing silly buggers and trying
2879 // to put a +- or -+ into the line...
2883 if (i == strlen(outpars)-1)
2885 if ((outpars[i] == '-') || (outpars[i] == '+'))
2893 if ((b[z] == '-') || (b[z] == '+'))
2896 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2899 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2901 if (strlen(dmodes)>MAXMODES)
2903 dmodes[MAXMODES-1] = '\0';
2905 log(DEBUG,"Stripped mode line");
2906 log(DEBUG,"Line dest is now %s",dmodes);
2907 strncpy(dest->modes,dmodes,MAXMODES);
2914 Ptr = FindChan(parameters[0]);
2917 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2921 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2926 /* This function pokes and hacks at a parameter list like the following:
2928 * PART #winbot, #darkgalaxy :m00!
2930 * to turn it into a series of individual calls like this:
2932 * PART #winbot :m00!
2933 * PART #darkgalaxy :m00!
2935 * The seperate calls are sent to a callback function provided by the caller
2936 * (the caller will usually call itself recursively). The callback function
2937 * must be a command handler. Calling this function on a line with no list causes
2938 * no action to be taken. You must provide a starting and ending parameter number
2939 * where the range of the list can be found, useful if you have a terminating
2940 * parameter as above which is actually not part of the list, or parameters
2941 * before the actual list as well. This code is used by many functions which
2942 * can function as "one to list" (see the RFC) */
2944 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2949 char blog[32][MAXBUF];
2950 char blog2[32][MAXBUF];
2951 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2952 char keystr[MAXBUF];
2955 for (i = 0; i <32; i++)
2958 for (i = 0; i <32; i++)
2959 strcpy(blog2[i],"");
2962 for (i = 0; i <10; i++)
2966 parameters[i] = moo;
2971 if (pcnt > 1) /* we have a key to copy */
2973 strcpy(keystr,parameters[1]);
2977 if (!parameters[start])
2981 if (!strchr(parameters[start],','))
2986 for (i = start; i <= end; i++)
2990 strcat(plist,parameters[i]);
2998 for (i = 0; i < t; i++)
3000 if (plist[i] == ',')
3003 strcpy(blog[j++],param);
3007 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3012 strcpy(blog[j++],param);
3015 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3020 if ((joins) && (keystr))
3022 if (strchr(keystr,','))
3026 t2 = strlen(keystr);
3027 for (i = 0; i < t2; i++)
3029 if (keystr[i] == ',')
3032 strcpy(blog2[j++],param);
3036 strcpy(blog2[j++],param);
3041 for (j = 0; j < total; j++)
3047 for (q = end; q < pcnt-1; q++)
3049 if (parameters[q+1])
3051 pars[q-end+1] = parameters[q+1];
3054 if ((joins) && (parameters[1]))
3065 /* repeatedly call the function with the hacked parameter list */
3066 if ((joins) && (pcnt > 1))
3070 // pars[1] already set up and containing key from blog2[j]
3075 pars[1] = parameters[1];
3081 fn(pars,pcnt-(end-start),u);
3089 void handle_join(char **parameters, int pcnt, userrec *user)
3094 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3096 if (parameters[0][0] == '#')
3098 Ptr = add_channel(user,parameters[0],parameters[1]);
3103 void handle_part(char **parameters, int pcnt, userrec *user)
3109 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3111 del_channel(user,parameters[0],parameters[1]);
3115 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3117 del_channel(user,parameters[0],NULL);
3121 void handle_kick(char **parameters, int pcnt, userrec *user)
3123 chanrec* Ptr = FindChan(parameters[0]);
3124 userrec* u = Find(parameters[1]);
3128 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3132 if (!has_channel(u,Ptr))
3134 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3140 char reason[MAXBUF];
3141 strncpy(reason,parameters[2],MAXBUF);
3142 if (strlen(reason)>MAXKICK)
3144 reason[MAXKICK-1] = '\0';
3147 kick_channel(user,u,Ptr,reason);
3151 kick_channel(user,u,Ptr,user->nick);
3156 void handle_die(char **parameters, int pcnt, userrec *user)
3158 log(DEBUG,"die: %s",user->nick);
3159 if (!strcmp(parameters[0],diepass))
3161 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3167 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3171 void handle_restart(char **parameters, int pcnt, userrec *user)
3173 log(DEBUG,"restart: %s",user->nick);
3174 if (!strcmp(parameters[0],restartpass))
3176 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3179 /* Will finish this later when i can be arsed :) */
3183 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3188 void kill_link(userrec *user,const char* r)
3190 user_hash::iterator iter = clientlist.find(user->nick);
3192 char reason[MAXBUF];
3194 strncpy(reason,r,MAXBUF);
3196 if (strlen(reason)>MAXQUIT)
3198 reason[MAXQUIT-1] = '\0';
3201 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3202 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3203 log(DEBUG,"closing fd %d",user->fd);
3205 /* bugfix, cant close() a nonblocking socket (sux!) */
3206 if (user->registered == 7) {
3207 FOREACH_MOD OnUserQuit(user);
3208 WriteCommonExcept(user,"QUIT :%s",reason);
3211 /* push the socket on a stack of sockets due to be closed at the next opportunity
3212 * 'Client exited' is an exception to this as it means the client side has already
3213 * closed the socket, we don't need to do it.
3215 fd_reap.push_back(user->fd);
3217 bool do_purge = false;
3219 if (user->registered == 7) {
3220 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3224 if (iter != clientlist.end())
3226 log(DEBUG,"deleting user hash value %d",iter->second);
3227 if ((iter->second) && (user->registered == 7)) {
3228 delete iter->second;
3230 clientlist.erase(iter);
3233 if (user->registered == 7) {
3234 purge_empty_chans();
3241 void handle_kill(char **parameters, int pcnt, userrec *user)
3243 userrec *u = Find(parameters[0]);
3244 char killreason[MAXBUF];
3246 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3249 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3250 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3251 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3252 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3253 kill_link(u,killreason);
3257 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3261 void handle_summon(char **parameters, int pcnt, userrec *user)
3263 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3266 void handle_users(char **parameters, int pcnt, userrec *user)
3268 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3272 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3274 char* Passwd(userrec *user)
3276 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3278 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3286 bool IsDenied(userrec *user)
3288 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3290 if (match(user->host,i->host) && (i->type == CC_DENY))
3300 void handle_pass(char **parameters, int pcnt, userrec *user)
3302 // Check to make sure they havnt registered -- Fix by FCS
3303 if (user->registered == 7)
3305 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3308 if (!strcasecmp(parameters[0],Passwd(user)))
3310 user->haspassed = true;
3314 void handle_invite(char **parameters, int pcnt, userrec *user)
3316 userrec* u = Find(parameters[0]);
3317 chanrec* c = FindChan(parameters[1]);
3323 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3329 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3338 if (cstatus(user,c) < STATUS_HOP)
3340 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
3344 if (has_channel(u,c))
3346 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
3349 if (!has_channel(user,c))
3351 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
3354 u->InviteTo(c->name);
3355 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3356 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3359 void handle_topic(char **parameters, int pcnt, userrec *user)
3365 if (strlen(parameters[0]) <= CHANMAX)
3367 Ptr = FindChan(parameters[0]);
3372 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3373 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3377 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3382 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3389 if (strlen(parameters[0]) <= CHANMAX)
3391 Ptr = FindChan(parameters[0]);
3394 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3396 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
3401 strncpy(topic,parameters[1],MAXBUF);
3402 if (strlen(topic)>MAXTOPIC)
3404 topic[MAXTOPIC-1] = '\0';
3407 strcpy(Ptr->topic,topic);
3408 strcpy(Ptr->setby,user->nick);
3409 Ptr->topicset = time(NULL);
3410 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3414 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3420 /* sends out an error notice to all connected clients (not to be used
3423 void send_error(char *s)
3425 log(DEBUG,"send_error: %s",s);
3426 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3428 if (isnick(i->second->nick))
3430 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3434 // fix - unregistered connections receive ERROR, not NOTICE
3435 Write(i->second->fd,"ERROR :%s",s);
3440 void Error(int status)
3442 signal (SIGALRM, SIG_IGN);
3443 signal (SIGPIPE, SIG_IGN);
3444 signal (SIGTERM, SIG_IGN);
3445 signal (SIGABRT, SIG_IGN);
3446 signal (SIGSEGV, SIG_IGN);
3447 signal (SIGURG, SIG_IGN);
3448 signal (SIGKILL, SIG_IGN);
3449 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3450 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3455 int main (int argc, char *argv[])
3458 log(DEBUG,"*** InspIRCd starting up!");
3459 if (!FileExists(CONFIG_FILE))
3461 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3462 log(DEBUG,"main: no config");
3463 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3467 if (!strcmp(argv[1],"-nofork")) {
3471 if (InspIRCd() == ERROR)
3473 log(DEBUG,"main: daemon function bailed");
3474 printf("ERROR: could not initialise. Shutting down.\n");
3481 template<typename T> inline string ConvToStr(const T &in)
3484 if (!(tmp << in)) return string();
3488 /* re-allocates a nick in the user_hash after they change nicknames,
3489 * returns a pointer to the new user as it may have moved */
3491 userrec* ReHashNick(char* Old, char* New)
3493 user_hash::iterator newnick;
3494 user_hash::iterator oldnick = clientlist.find(Old);
3496 log(DEBUG,"ReHashNick: %s %s",Old,New);
3498 if (!strcasecmp(Old,New))
3500 log(DEBUG,"old nick is new nick, skipping");
3501 return oldnick->second;
3504 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3506 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3508 clientlist[New] = new userrec();
3509 clientlist[New] = oldnick->second;
3510 /*delete oldnick->second; */
3511 clientlist.erase(oldnick);
3513 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3515 return clientlist[New];
3518 /* adds or updates an entry in the whowas list */
3519 void AddWhoWas(userrec* u)
3521 user_hash::iterator iter = whowas.find(u->nick);
3522 userrec *a = new userrec();
3523 strcpy(a->nick,u->nick);
3524 strcpy(a->ident,u->ident);
3525 strcpy(a->dhost,u->dhost);
3526 strcpy(a->host,u->host);
3527 strcpy(a->fullname,u->fullname);
3528 strcpy(a->server,u->server);
3529 a->signon = u->signon;
3531 /* MAX_WHOWAS: max number of /WHOWAS items
3532 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3533 * can be replaced by a newer one
3536 if (iter == whowas.end())
3538 if (whowas.size() == WHOWAS_MAX)
3540 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3542 // 3600 seconds in an hour ;)
3543 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3547 log(DEBUG,"added WHOWAS entry, purged an old record");
3554 log(DEBUG,"added fresh WHOWAS entry");
3555 whowas[a->nick] = a;
3560 log(DEBUG,"updated WHOWAS entry");
3561 delete iter->second;
3567 /* add a client connection to the sockets list */
3568 void AddClient(int socket, char* host, int port, bool iscached)
3572 char resolved[MAXBUF];
3575 user_hash::iterator iter;
3577 tempnick = ConvToStr(socket) + "-unknown";
3578 sprintf(tn2,"%d-unknown",socket);
3580 iter = clientlist.find(tempnick);
3582 if (iter != clientlist.end()) return;
3585 * It is OK to access the value here this way since we know
3586 * it exists, we just created it above.
3588 * At NO other time should you access a value in a map or a
3589 * hash_map this way.
3591 clientlist[tempnick] = new userrec();
3593 NonBlocking(socket);
3594 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3596 clientlist[tempnick]->fd = socket;
3597 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3598 strncpy(clientlist[tempnick]->host, host,160);
3599 strncpy(clientlist[tempnick]->dhost, host,160);
3600 strncpy(clientlist[tempnick]->server, ServerName,256);
3601 strncpy(clientlist[tempnick]->ident, "unknown",9);
3602 clientlist[tempnick]->registered = 0;
3603 clientlist[tempnick]->signon = time(NULL);
3604 clientlist[tempnick]->nping = time(NULL)+240;
3605 clientlist[tempnick]->lastping = 1;
3606 clientlist[tempnick]->port = port;
3610 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3614 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3617 // set the registration timeout for this user
3618 unsigned long class_regtimeout = 90;
3619 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3621 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3623 class_regtimeout = (unsigned long)i->registration_timeout;
3628 int class_flood = 0;
3629 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3631 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3633 class_flood = i->flood;
3638 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3639 clientlist[tempnick]->flood = class_flood;
3641 if (clientlist.size() == MAXCLIENTS)
3642 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3645 void handle_names(char **parameters, int pcnt, userrec *user)
3649 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3651 c = FindChan(parameters[0]);
3654 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3656 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3660 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3665 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3670 user->idle_lastmsg = time(NULL);
3672 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3674 if (parameters[0][0] == '#')
3676 chan = FindChan(parameters[0]);
3679 if ((chan->noexternal) && (!has_channel(user,chan)))
3681 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3684 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3686 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3692 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3697 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3701 /* no such nick/channel */
3702 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3707 dest = Find(parameters[0]);
3710 if (strcmp(dest->awaymsg,""))
3712 /* auto respond with aweh msg */
3713 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3718 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
3723 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3727 /* no such nick/channel */
3728 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3732 void handle_notice(char **parameters, int pcnt, userrec *user)
3737 user->idle_lastmsg = time(NULL);
3739 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3741 if (parameters[0][0] == '#')
3743 chan = FindChan(parameters[0]);
3746 if ((chan->noexternal) && (!has_channel(user,chan)))
3748 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3751 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3753 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3759 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3764 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3768 /* no such nick/channel */
3769 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3774 dest = Find(parameters[0]);
3779 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
3784 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3788 /* no such nick/channel */
3789 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3795 char* chlist(userrec *user)
3800 log(DEBUG,"chlist: %s",user->nick);
3806 for (i = 0; i != MAXCHANS; i++)
3808 if (user->chans[i].channel != NULL)
3810 if (user->chans[i].channel->name)
3812 strcpy(cmp,user->chans[i].channel->name);
3814 if (!strstr(lst,cmp))
3816 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3818 strcat(lst,cmode(user,user->chans[i].channel));
3819 strcat(lst,user->chans[i].channel->name);
3829 void handle_info(char **parameters, int pcnt, userrec *user)
3831 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3832 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3833 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3834 FOREACH_MOD OnInfo(user);
3835 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3838 void handle_time(char **parameters, int pcnt, userrec *user)
3841 struct tm * timeinfo;
3844 timeinfo = localtime ( &rawtime );
3845 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3849 void handle_whois(char **parameters, int pcnt, userrec *user)
3854 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3856 dest = Find(parameters[0]);
3859 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3860 if (dest->registered == 7)
3862 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3863 if ((user == dest) || (strchr(user->modes,'o')))
3865 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3867 if (strcmp(chlist(dest),""))
3869 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3871 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3872 if (strcmp(dest->awaymsg,""))
3874 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3876 if (strchr(dest->modes,'o'))
3878 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3880 FOREACH_MOD OnWhois(user,dest);
3881 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3882 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3884 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3888 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3893 /* no such nick/channel */
3894 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3898 void handle_quit(char **parameters, int pcnt, userrec *user)
3900 user_hash::iterator iter = clientlist.find(user->nick);
3903 if (user->registered == 7)
3905 /* theres more to do here, but for now just close the socket */
3908 if (parameters[0][0] == ':')
3912 reason = parameters[0];
3914 if (strlen(reason)>MAXQUIT)
3916 reason[MAXQUIT-1] = '\0';
3919 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3920 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3921 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3925 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3926 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3927 WriteCommonExcept(user,"QUIT :Client exited");
3929 FOREACH_MOD OnUserQuit(user);
3933 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3934 fd_reap.push_back(user->fd);
3936 if (iter != clientlist.end())
3938 log(DEBUG,"deleting user hash value %d",iter->second);
3939 if ((iter->second) && (user->registered == 7)) {
3940 delete iter->second;
3942 clientlist.erase(iter);
3945 if (user->registered == 7) {
3946 purge_empty_chans();
3952 void handle_who(char **parameters, int pcnt, userrec *user)
3954 chanrec* Ptr = NULL;
3956 /* theres more to do here, but for now just close the socket */
3959 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3961 if (user->chans[0].channel)
3963 Ptr = user->chans[0].channel;
3964 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3966 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3968 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3974 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3978 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3982 if (parameters[0][0] = '#')
3984 Ptr = FindChan(parameters[0]);
3987 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3989 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3991 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3994 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3998 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4004 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4006 Ptr = user->chans[0].channel;
4007 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4009 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4011 if (strchr(i->second->modes,'o'))
4013 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
4017 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4023 void handle_wallops(char **parameters, int pcnt, userrec *user)
4025 WriteWallOps(user,"%s",parameters[0]);
4028 void handle_list(char **parameters, int pcnt, userrec *user)
4032 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4033 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4035 if ((!i->second->c_private) && (!i->second->secret))
4037 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4040 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4044 void handle_rehash(char **parameters, int pcnt, userrec *user)
4046 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4048 FOREACH_MOD OnRehash();
4049 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4055 return clientlist.size();
4059 int usercount_invisible(void)
4063 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4065 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4070 int usercount_opers(void)
4074 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4076 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4081 int usercount_unknown(void)
4085 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4087 if ((i->second->fd) && (i->second->registered != 7))
4095 return chanlist.size();
4098 int servercount(void)
4103 void handle_lusers(char **parameters, int pcnt, userrec *user)
4105 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4106 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4107 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4108 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4109 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4112 void handle_admin(char **parameters, int pcnt, userrec *user)
4114 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4115 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4116 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4117 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4120 void ShowMOTD(userrec *user)
4124 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4127 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4128 for (int i = 0; i != MOTD.size(); i++)
4130 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4132 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4135 void ShowRULES(userrec *user)
4139 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4142 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4143 for (int i = 0; i != RULES.size(); i++)
4145 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4147 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4150 /* shows the message of the day, and any other on-logon stuff */
4151 void ConnectUser(userrec *user)
4153 user->registered = 7;
4154 user->idle_lastmsg = time(NULL);
4155 log(DEBUG,"ConnectUser: %s",user->nick);
4157 if (strcmp(Passwd(user),"") && (!user->haspassed))
4159 kill_link(user,"Invalid password");
4164 kill_link(user,"Unauthorised connection");
4168 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4169 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4170 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4171 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4172 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4173 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);
4174 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);
4176 FOREACH_MOD OnUserConnect(user);
4177 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4180 void handle_version(char **parameters, int pcnt, userrec *user)
4182 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4185 void handle_ping(char **parameters, int pcnt, userrec *user)
4187 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4190 void handle_pong(char **parameters, int pcnt, userrec *user)
4192 // set the user as alive so they survive to next ping
4196 void handle_motd(char **parameters, int pcnt, userrec *user)
4201 void handle_rules(char **parameters, int pcnt, userrec *user)
4206 void handle_user(char **parameters, int pcnt, userrec *user)
4208 if (user->registered < 3)
4210 if (isident(parameters[0]) == 0) {
4211 // This kinda Sucks, According to the RFC thou, its either this,
4212 // or "You have already registered" :p -- Craig
4213 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4216 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4217 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4218 strncat(user->ident,parameters[0],IDENTMAX);
4219 strncpy(user->fullname,parameters[3],128);
4220 user->registered = (user->registered | 1);
4225 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4228 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4229 if (user->registered == 3)
4231 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4236 void handle_userhost(char **parameters, int pcnt, userrec *user)
4238 char Return[MAXBUF],junk[MAXBUF];
4239 sprintf(Return,"302 %s :",user->nick);
4240 for (int i = 0; i < pcnt; i++)
4242 userrec *u = Find(parameters[i]);
4245 if (strchr(u->modes,'o'))
4247 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4248 strcat(Return,junk);
4252 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4253 strcat(Return,junk);
4257 WriteServ(user->fd,Return);
4261 void handle_ison(char **parameters, int pcnt, userrec *user)
4263 char Return[MAXBUF];
4264 sprintf(Return,"303 %s :",user->nick);
4265 for (int i = 0; i < pcnt; i++)
4267 userrec *u = Find(parameters[i]);
4270 strcat(Return,u->nick);
4274 WriteServ(user->fd,Return);
4278 void handle_away(char **parameters, int pcnt, userrec *user)
4282 strcpy(user->awaymsg,parameters[0]);
4283 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4287 strcpy(user->awaymsg,"");
4288 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4292 void handle_whowas(char **parameters, int pcnt, userrec* user)
4294 user_hash::iterator i = whowas.find(parameters[0]);
4296 if (i == whowas.end())
4298 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4299 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4303 time_t rawtime = i->second->signon;
4307 timeinfo = localtime(&rawtime);
4308 strcpy(b,asctime(timeinfo));
4309 b[strlen(b)-1] = '\0';
4311 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4312 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4313 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4318 void handle_trace(char **parameters, int pcnt, userrec *user)
4320 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4324 if (isnick(i->second->nick))
4326 if (strchr(i->second->modes,'o'))
4328 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4332 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4337 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4343 void handle_modules(char **parameters, int pcnt, userrec *user)
4345 for (int i = 0; i < module_names.size(); i++)
4347 Version V = modules[i]->GetVersion();
4348 char modulename[MAXBUF];
4349 strncpy(modulename,module_names[i].c_str(),256);
4350 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));
4354 void handle_stats(char **parameters, int pcnt, userrec *user)
4360 if (strlen(parameters[0])>1)
4362 /* make the stats query 1 character long */
4363 parameters[0][1] = '\0';
4366 /* stats m (list number of times each command has been used, plus bytecount) */
4367 if (!strcasecmp(parameters[0],"m"))
4369 for (int i = 0; i < cmdlist.size(); i++)
4371 if (cmdlist[i].handler_function)
4373 if (cmdlist[i].use_count)
4375 /* RPL_STATSCOMMANDS */
4376 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4383 /* stats z (debug and memory info) */
4384 if (!strcasecmp(parameters[0],"z"))
4386 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4387 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4388 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4389 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4390 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4391 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4392 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4393 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4397 if (!strcasecmp(parameters[0],"o"))
4399 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
4401 char LoginName[MAXBUF];
4402 char HostName[MAXBUF];
4403 char OperType[MAXBUF];
4404 ConfValue("oper","name",i,LoginName,&config_f);
4405 ConfValue("oper","host",i,HostName,&config_f);
4406 ConfValue("oper","type",i,OperType,&config_f);
4407 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4411 /* stats l (show user I/O stats) */
4412 if (!strcasecmp(parameters[0],"l"))
4414 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4415 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4417 if (isnick(i->second->nick))
4419 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);
4423 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);
4429 /* stats u (show server uptime) */
4430 if (!strcasecmp(parameters[0],"u"))
4432 time_t current_time = 0;
4433 current_time = time(NULL);
4434 time_t server_uptime = current_time - startup_time;
4436 stime = gmtime(&server_uptime);
4437 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4438 * Craig suggested this, and it seemed a good idea so in it went */
4439 if (stime->tm_year > 70)
4441 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);
4445 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);
4449 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4450 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4454 void handle_connect(char **parameters, int pcnt, userrec *user)
4456 char Link_ServerName[1024];
4457 char Link_IPAddr[1024];
4458 char Link_Port[1024];
4459 char Link_Pass[1024];
4463 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4465 ConfValue("link","name",i,Link_ServerName,&config_f);
4466 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4467 ConfValue("link","port",i,Link_Port,&config_f);
4468 ConfValue("link","sendpass",i,Link_Pass,&config_f);
4469 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4470 LinkPort = atoi(Link_Port);
4471 if (match(Link_ServerName,parameters[0])) {
4477 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4481 // TODO: Perform a check here to stop a server being linked twice!
4483 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4485 if (me[defaultRoute])
4488 // at this point parameters[0] is an ip in a string.
4489 // TODO: Look this up from the <link> blocks instead!
4490 for (int j = 0; j < 255; j++) {
4491 if (servers[j] == NULL) {
4492 servers[j] = new serverrec;
4493 strcpy(servers[j]->internal_addr,Link_IPAddr);
4494 strcpy(servers[j]->name,Link_ServerName);
4495 log(DEBUG,"Allocated new serverrec");
4496 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4498 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4503 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4507 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);
4511 void handle_squit(char **parameters, int pcnt, userrec *user)
4513 // send out an squit across the mesh and then clear the server list (for local squit)
4516 void handle_oper(char **parameters, int pcnt, userrec *user)
4518 char LoginName[MAXBUF];
4519 char Password[MAXBUF];
4520 char OperType[MAXBUF];
4521 char TypeName[MAXBUF];
4522 char Hostname[MAXBUF];
4525 for (i = 0; i < ConfValueEnum("oper",&config_f); i++)
4527 ConfValue("oper","name",i,LoginName,&config_f);
4528 ConfValue("oper","password",i,Password,&config_f);
4529 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4531 /* correct oper credentials */
4532 ConfValue("oper","type",i,OperType,&config_f);
4533 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4534 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4535 WriteServ(user->fd,"MODE %s :+o",user->nick);
4536 for (j =0; j < ConfValueEnum("type",&config_f); j++)
4538 ConfValue("type","name",j,TypeName,&config_f);
4539 if (!strcmp(TypeName,OperType))
4541 /* found this oper's opertype */
4542 ConfValue("type","host",j,Hostname,&config_f);
4543 strncpy(user->dhost,Hostname,256);
4546 if (!strchr(user->modes,'o'))
4548 strcat(user->modes,"o");
4550 FOREACH_MOD OnOper(user);
4555 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4556 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4559 void handle_nick(char **parameters, int pcnt, userrec *user)
4563 log(DEBUG,"not enough params for handle_nick");
4568 log(DEBUG,"invalid parameter passed to handle_nick");
4571 if (!strlen(parameters[0]))
4573 log(DEBUG,"zero length new nick passed to handle_nick");
4578 log(DEBUG,"invalid user passed to handle_nick");
4583 log(DEBUG,"invalid old nick passed to handle_nick");
4586 if (!strcasecmp(user->nick,parameters[0]))
4588 log(DEBUG,"old nick is new nick, skipping");
4593 if (strlen(parameters[0]) > 1)
4595 if (parameters[0][0] == ':')
4600 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4602 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4606 if (isnick(parameters[0]) == 0)
4608 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4612 if (user->registered == 7)
4614 WriteCommon(user,"NICK %s",parameters[0]);
4617 /* change the nick of the user in the users_hash */
4618 user = ReHashNick(user->nick, parameters[0]);
4619 /* actually change the nick within the record */
4621 if (!user->nick) return;
4623 strncpy(user->nick, parameters[0],NICKMAX);
4625 log(DEBUG,"new nick set: %s",user->nick);
4627 if (user->registered < 3)
4628 user->registered = (user->registered | 2);
4629 if (user->registered == 3)
4631 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4634 log(DEBUG,"exit nickchange: %s",user->nick);
4637 void force_nickchange(userrec* user,const char* newnick)
4646 strncpy(nick,newnick,MAXBUF);
4648 if (user->registered == 7)
4652 handle_nick(pars,1,user);
4658 int process_parameters(char **command_p,char *parameters)
4663 q = strlen(parameters);
4666 /* no parameters, command_p invalid! */
4669 if (parameters[0] == ':')
4671 command_p[0] = parameters+1;
4676 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4678 /* only one parameter */
4679 command_p[0] = parameters;
4680 if (parameters[0] == ':')
4682 if (strchr(parameters,' ') != NULL)
4690 command_p[j++] = parameters;
4691 for (i = 0; i <= q; i++)
4693 if (parameters[i] == ' ')
4695 command_p[j++] = parameters+i+1;
4696 parameters[i] = '\0';
4697 if (command_p[j-1][0] == ':')
4699 *command_p[j-1]++; /* remove dodgy ":" */
4701 /* parameter like this marks end of the sequence */
4705 return j; /* returns total number of items in the list */
4708 void process_command(userrec *user, char* cmd)
4712 char *command_p[127];
4713 char p[MAXBUF], temp[MAXBUF];
4714 int i, j, items, cmd_found;
4716 for (int i = 0; i < 127; i++)
4717 command_p[i] = NULL;
4727 if (!strcmp(cmd,""))
4732 int total_params = 0;
4735 for (int q = 0; q < strlen(cmd)-1; q++)
4737 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
4740 // found a 'trailing', we dont count them after this.
4748 // another phidjit bug...
4749 if (total_params > 126)
4751 kill_link(user,"Protocol violation (1)");
4758 FOREACH_MOD OnServerRaw(tmp,true);
4759 const char* cmd2 = tmp.c_str();
4760 snprintf(cmd,512,"%s",cmd2);
4762 if (!strchr(cmd,' '))
4764 /* no parameters, lets skip the formalities and not chop up
4766 log(DEBUG,"About to preprocess command with no params");
4768 command_p[0] = NULL;
4770 for (int i = 0; i <= strlen(cmd); i++)
4772 cmd[i] = toupper(cmd[i]);
4774 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
4781 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4782 for (i = 0; i < strlen(temp); i++)
4784 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4790 /* split the full string into a command plus parameters */
4794 if (strchr(cmd,' '))
4796 for (i = 0; i <= strlen(cmd); i++)
4798 /* capitalise the command ONLY, leave params intact */
4799 cmd[i] = toupper(cmd[i]);
4800 /* are we nearly there yet?! :P */
4804 parameters = cmd+i+1;
4812 for (i = 0; i <= strlen(cmd); i++)
4814 cmd[i] = toupper(cmd[i]);
4821 if (strlen(command)>MAXCOMMAND)
4823 kill_link(user,"Protocol violation (2)");
4827 for (int x = 0; x < strlen(command); x++)
4829 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
4831 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
4833 if (strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
4835 kill_link(user,"Protocol violation (3)");
4842 for (i = 0; i != cmdlist.size(); i++)
4844 if (strcmp(cmdlist[i].command,""))
4846 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
4848 log(DEBUG,"Found matching command");
4852 if (strcmp(parameters,""))
4854 items = process_parameters(command_p,parameters);
4859 command_p[0] = NULL;
4865 command_p[0] = NULL;
4870 log(DEBUG,"Processing command");
4872 /* activity resets the ping pending timer */
4873 user->nping = time(NULL) + 120;
4874 if ((items) < cmdlist[i].min_params)
4876 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4877 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4880 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4882 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4883 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4887 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4889 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
4891 if ((!isnick(user->nick)) || (user->registered != 7))
4893 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4894 WriteServ(user->fd,"451 %s :You have not registered",command);
4898 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4900 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4901 if (cmdlist[i].handler_function)
4903 /* ikky /stats counters */
4908 user->bytes_in += strlen(temp);
4911 cmdlist[i].use_count++;
4912 cmdlist[i].total_bytes+=strlen(temp);
4915 /* WARNING: nothing may come after the
4916 * command handler call, as the handler
4917 * may free the user structure! */
4919 cmdlist[i].handler_function(command_p,items,user);
4925 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4926 WriteServ(user->fd,"451 %s :You have not registered",command);
4934 if ((!cmd_found) && (user))
4936 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4937 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4942 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4945 /* create the command and push it onto the table */
4946 strcpy(comm.command,cmd);
4947 comm.handler_function = f;
4948 comm.flags_needed = flags;
4949 comm.min_params = minparams;
4951 comm.total_bytes = 0;
4952 cmdlist.push_back(comm);
4953 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4956 void SetupCommandTable(void)
4958 createcommand("USER",handle_user,0,4);
4959 createcommand("NICK",handle_nick,0,1);
4960 createcommand("QUIT",handle_quit,0,0);
4961 createcommand("VERSION",handle_version,0,0);
4962 createcommand("PING",handle_ping,0,1);
4963 createcommand("PONG",handle_pong,0,1);
4964 createcommand("ADMIN",handle_admin,0,0);
4965 createcommand("PRIVMSG",handle_privmsg,0,2);
4966 createcommand("INFO",handle_info,0,0);
4967 createcommand("TIME",handle_time,0,0);
4968 createcommand("WHOIS",handle_whois,0,1);
4969 createcommand("WALLOPS",handle_wallops,'o',1);
4970 createcommand("NOTICE",handle_notice,0,2);
4971 createcommand("JOIN",handle_join,0,1);
4972 createcommand("NAMES",handle_names,0,1);
4973 createcommand("PART",handle_part,0,1);
4974 createcommand("KICK",handle_kick,0,2);
4975 createcommand("MODE",handle_mode,0,1);
4976 createcommand("TOPIC",handle_topic,0,1);
4977 createcommand("WHO",handle_who,0,1);
4978 createcommand("MOTD",handle_motd,0,0);
4979 createcommand("RULES",handle_rules,0,0);
4980 createcommand("OPER",handle_oper,0,2);
4981 createcommand("LIST",handle_list,0,0);
4982 createcommand("DIE",handle_die,'o',1);
4983 createcommand("RESTART",handle_restart,'o',1);
4984 createcommand("KILL",handle_kill,'o',2);
4985 createcommand("REHASH",handle_rehash,'o',0);
4986 createcommand("LUSERS",handle_lusers,0,0);
4987 createcommand("STATS",handle_stats,0,1);
4988 createcommand("USERHOST",handle_userhost,0,1);
4989 createcommand("AWAY",handle_away,0,0);
4990 createcommand("ISON",handle_ison,0,0);
4991 createcommand("SUMMON",handle_summon,0,0);
4992 createcommand("USERS",handle_users,0,0);
4993 createcommand("INVITE",handle_invite,0,2);
4994 createcommand("PASS",handle_pass,0,1);
4995 createcommand("TRACE",handle_trace,'o',0);
4996 createcommand("WHOWAS",handle_whowas,0,1);
4997 createcommand("CONNECT",handle_connect,'o',1);
4998 createcommand("SQUIT",handle_squit,'o',1);
4999 createcommand("MODULES",handle_modules,'o',0);
5002 void process_buffer(const char* cmdbuf,userrec *user)
5006 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5013 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5016 if (!strcmp(cmdbuf,""))
5020 strncpy(cmd,cmdbuf,MAXBUF);
5021 if (!strcmp(cmd,""))
5025 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5027 cmd[strlen(cmd)-1] = '\0';
5029 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5031 cmd[strlen(cmd)-1] = '\0';
5033 if (!strcmp(cmd,""))
5037 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5039 if ((user) && (cmd))
5041 process_command(user,cmd);
5045 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5047 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
5051 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
5053 char response[10240];
5054 char token = udp_msg[0];
5055 char* params = udp_msg + 2;
5056 char finalparam[1024];
5057 strcpy(finalparam," :xxxx");
5058 if (strstr(params," :")) {
5059 strncpy(finalparam,strstr(params," :"),1024);
5062 // S test.chatspike.net password :ChatSpike InspIRCd test server
5063 char* servername = strtok(params," ");
5064 char* password = strtok(NULL," ");
5065 char* serverdesc = finalparam+2;
5066 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
5069 char Link_ServerName[1024];
5070 char Link_IPAddr[1024];
5071 char Link_Port[1024];
5072 char Link_Pass[1024];
5073 char Link_SendPass[1024];
5076 // search for a corresponding <link> block in the config files
5077 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5079 ConfValue("link","name",i,Link_ServerName,&config_f);
5080 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5081 ConfValue("link","port",i,Link_Port,&config_f);
5082 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5083 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5084 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5085 LinkPort = atoi(Link_Port);
5086 if (!strcasecmp(Link_ServerName,servername)) {
5087 if (!strcasecmp(Link_IPAddr,udp_host)) {
5088 if (LinkPort == udp_port) {
5089 // we have a matching link line -
5090 // send a 'diminutive' server message back...
5091 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
5092 serv->SendPacket(response,udp_host,udp_port,0);
5093 WriteOpers("CONNECT from %s accepted, authenticating",servername);
5094 for (int j = 0; j < 255; j++) {
5095 if (servers[j] == NULL) {
5096 servers[j] = new serverrec;
5097 strcpy(servers[j]->internal_addr,udp_host);
5098 strcpy(servers[j]->name,servername);
5099 // create a server record for this server
5100 snprintf(response,10240,"O %d",MyKey);
5101 serv->SendPacket(response,udp_host,udp_port,0);
5105 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
5109 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5113 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5117 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5120 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5121 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5126 // if this is received, this means the server-ip that sent it said "OK" to credentials.
5127 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
5128 // array, which is only added by an 'S' packet or BeginLink().
5129 for (int i = 0; i < 255; i++) {
5130 if (servers[i] != NULL) {
5131 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
5132 servers[i]->key = atoi(params);
5133 log(DEBUG,"Key for this server is now %d",servers[i]->key);
5134 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
5139 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
5143 // S test.chatspike.net password :ChatSpike InspIRCd test server
5144 char* servername = strtok(params," ");
5145 char* password = strtok(NULL," ");
5146 char* serverdesc = finalparam+2;
5148 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5149 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5150 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5151 // a connect, so put out an oper alert!
5156 // for now, just accept all, we'll fix that later.
5157 WriteOpers("%s accepted our link credentials ",servername);
5159 char Link_ServerName[1024];
5160 char Link_IPAddr[1024];
5161 char Link_Port[1024];
5162 char Link_Pass[1024];
5163 char Link_SendPass[1024];
5166 // search for a corresponding <link> block in the config files
5167 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5169 ConfValue("link","name",i,Link_ServerName,&config_f);
5170 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5171 ConfValue("link","port",i,Link_Port,&config_f);
5172 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5173 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5174 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5175 LinkPort = atoi(Link_Port);
5176 if (!strcasecmp(Link_ServerName,servername)) {
5177 if (!strcasecmp(Link_IPAddr,udp_host)) {
5178 if (LinkPort == udp_port) {
5179 // matching link at this end too, we're all done!
5180 // at this point we must begin key exchange and insert this
5181 // server into our 'active' table.
5182 for (int j = 0; j < 255; j++) {
5183 if (servers[j] != NULL) {
5184 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5185 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5186 snprintf(response,10240,"O %d",MyKey);
5187 serv->SendPacket(response,udp_host,udp_port,0);
5192 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5197 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5201 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5205 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5208 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5209 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5214 char* error_message = finalparam+2;
5215 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5216 // remove this server from any lists
5217 for (int j = 0; j < 255; j++) {
5218 if (servers[j] != NULL) {
5219 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5229 serverrec* source_server = NULL;
5231 for (int j = 0; j < 255; j++) {
5232 if (servers[j] != NULL) {
5233 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5234 if (servers[j]->key == theirkey) {
5235 // found a valid key for this server, can process restricted stuff here
5236 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5244 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5248 int reap_counter = 0;
5252 struct sockaddr_in client, server;
5253 char addrs[MAXBUF][255];
5254 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5256 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5257 int selectResult = 0, selectResult2 = 0;
5258 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5259 char resolvedHost[MAXBUF];
5263 log_file = fopen("ircd.log","a+");
5266 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5270 log(DEBUG,"InspIRCd: startup: begin");
5274 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5276 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5278 SetupCommandTable();
5279 log(DEBUG,"InspIRCd: startup: default command table set up");
5282 if (strcmp(DieValue,""))
5284 printf("WARNING: %s\n\n",DieValue);
5287 log(DEBUG,"InspIRCd: startup: read config");
5289 int count2 = 0, count3 = 0;
5291 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5293 ConfValue("bind","port",count,configToken,&config_f);
5294 ConfValue("bind","address",count,Addr,&config_f);
5295 ConfValue("bind","type",count,Type,&config_f);
5296 if (!strcmp(Type,"servers"))
5298 char Default[MAXBUF];
5299 strcpy(Default,"no");
5300 ConfValue("bind","default",count,Default,&config_f);
5301 if (strchr(Default,'y'))
5303 defaultRoute = count3;
5304 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5306 me[count3] = new serverrec(ServerName,100L,false);
5307 me[count3]->CreateListener(Addr,atoi(configToken));
5312 ports[count2] = atoi(configToken);
5313 strcpy(addrs[count2],Addr);
5316 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5319 UDPportCount = count3;
5321 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5323 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5327 /* BugFix By Craig! :p */
5329 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5331 char modfile[MAXBUF];
5332 ConfValue("module","name",count2,configToken,&config_f);
5333 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5334 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5335 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5336 /* If The File Doesnt exist, Trying to load it
5337 * Will Segfault the IRCd.. So, check to see if
5338 * it Exists, Before Proceeding. */
5339 if (FileExists(modfile))
5341 factory[count] = new ircd_module(modfile);
5342 if (factory[count]->LastError())
5344 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5345 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5348 if (factory[count]->factory)
5350 modules[count] = factory[count]->factory->CreateModule();
5351 /* save the module and the module's classfactory, if
5352 * this isnt done, random crashes can occur :/ */
5353 module_names.push_back(modfile);
5357 log(DEBUG,"Unable to load %s",modfile);
5358 sprintf("Unable to load %s\nExiting...\n",modfile);
5361 /* Increase the Count */
5366 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5367 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5370 MODCOUNT = count - 1;
5371 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5373 printf("\nInspIRCd is now running!\n");
5375 startup_time = time(NULL);
5379 log(VERBOSE,"Not forking as -nofork was specified");
5383 if (DaemonSeed() == ERROR)
5385 log(DEBUG,"InspIRCd: startup: can't daemonise");
5386 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5392 /* setup select call */
5393 FD_ZERO(&selectFds);
5394 log(DEBUG,"InspIRCd: startup: zero selects");
5395 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5397 for (count = 0; count < portCount; count++)
5399 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5401 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5404 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5406 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5408 else /* well we at least bound to one socket so we'll continue */
5414 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5416 /* if we didn't bind to anything then abort */
5417 if (boundPortCount == 0)
5419 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5423 length = sizeof (client);
5424 int flip_flop = 0, udp_port = 0;
5425 char udp_msg[MAXBUF], udp_host[MAXBUF];
5427 /* main loop, this never returns */
5431 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5432 // them in a list, then reap the list every second or so.
5433 if (reap_counter>5000) {
5434 if (fd_reap.size() > 0) {
5435 for( int n = 0; n < fd_reap.size(); n++)
5437 Blocking(fd_reap[n]);
5439 NonBlocking(fd_reap[n]);
5447 for (int x = 0; x != UDPportCount; x++)
5450 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5452 if (strlen(udp_msg)<1) {
5453 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5457 FOREACH_MOD OnPacketReceive(udp_msg);
5458 // Packets must go back via the route they arrived on :)
5459 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5465 struct timeval tval;
5468 user_hash::iterator count2 = clientlist.begin();
5470 while (count2 != clientlist.end())
5473 tval.tv_usec = tval.tv_sec = 0;
5475 int total_in_this_set = 0;
5477 user_hash::iterator xcount = count2;
5478 user_hash::iterator endingiter = count2;
5480 if (!count2->second) break;
5483 if (count2->second->fd)
5485 // assemble up to 64 sockets into an fd_set
5486 // to implement a pooling mechanism.
5488 // This should be up to 64x faster than the
5489 // old implementation.
5490 while (total_in_this_set < 64)
5492 if (count2 != clientlist.end())
5494 FD_SET (count2->second->fd, &sfd);
5496 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5497 // their connection class.
5498 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
5500 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5501 kill_link(count2->second,"Registration timeout");
5504 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5506 if ((!count2->second->lastping) && (count2->second->registered == 7))
5508 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5509 kill_link(count2->second,"Ping timeout");
5512 Write(count2->second->fd,"PING :%s",ServerName);
5513 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5514 count2->second->lastping = 0;
5515 count2->second->nping = time(NULL)+120;
5518 total_in_this_set++;
5523 endingiter = count2;
5524 count2 = xcount; // roll back to where we were
5530 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
5532 // now loop through all of the items in this pool if any are waiting
5533 //if (selectResult2 > 0)
5534 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
5536 std::vector<string> datastream;
5541 if (FD_ISSET (count2a->second->fd, &sfd))
5543 memset(data, 0, 10240);
5544 result = read(count2a->second->fd, data, 10240);
5548 userrec* current = count2a->second;
5549 int currfd = current->fd;
5550 char* l = strtok(data,"\n");
5555 if ((floodlines > current->flood) && (current->flood != 0))
5557 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
5558 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
5559 kill_link(current,"Excess flood");
5562 char sanitized[NetBufferSize];
5563 memset(sanitized, 0, NetBufferSize);
5565 for (int pt = 0; pt < strlen(l); pt++)
5569 sanitized[ptt++] = l[pt];
5572 sanitized[ptt] = '\0';
5573 if (strlen(sanitized))
5577 // we're gonna re-scan to check if the nick is gone, after every
5578 // command - if it has, we're gonna bail
5579 bool find_again = false;
5580 process_buffer(sanitized,current);
5582 // look for the user's record in case it's changed
5583 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
5585 if (c2->second->fd == currfd)
5587 // found again, update pointer
5588 current == c2->second;
5597 l = strtok(NULL,"\n");
5602 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
5604 log(DEBUG,"killing: %s",count2a->second->nick);
5605 kill_link(count2a->second,strerror(errno));
5609 // result EAGAIN means nothing read
5610 if (result == EAGAIN)
5618 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
5619 kill_link(count2a->second,"Client exited");
5620 // must bail here? kill_link removes the hash, corrupting the iterator
5621 log(DEBUG,"Bailing from client exit");
5625 else if (result > 0)
5630 for (int q = 0; q < total_in_this_set; q++)
5632 // there is no iterator += operator :(
5633 //if (count2 != clientlist.end())
5640 // set up select call
5641 for (count = 0; count < boundPortCount; count++)
5643 FD_SET (openSockfd[count], &selectFds);
5646 /* added timeout! select was waiting forever... wank... :/ */
5658 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5660 /* select is reporting a waiting socket. Poll them all to find out which */
5661 if (selectResult > 0)
5663 char target[MAXBUF], resolved[MAXBUF];
5664 for (count = 0; count < boundPortCount; count++)
5666 if (FD_ISSET (openSockfd[count], &selectFds))
5668 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5670 address_cache::iterator iter = IP.find(client.sin_addr);
5671 bool iscached = false;
5672 if (iter == IP.end())
5674 /* ip isn't in cache, add it */
5675 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5676 if(CleanAndResolve(resolved, target) != TRUE)
5678 strncpy(resolved,target,MAXBUF);
5680 /* hostname now in 'target' */
5681 IP[client.sin_addr] = new string(resolved);
5682 /* hostname in cache */
5686 /* found ip (cached) */
5687 strncpy(resolved, iter->second->c_str(), MAXBUF);
5691 if (incomingSockfd < 0)
5693 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5694 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5698 AddClient(incomingSockfd, resolved, ports[count], iscached);
5699 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5706 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
5709 close (incomingSockfd);