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>
43 #include "connection.h"
53 #define nspace __gnu_cxx
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
66 char restartpass[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 time_t startup_time = time(NULL);
78 extern vector<Module*> modules;
79 vector<string> module_names;
80 extern vector<ircd_module*> factory;
89 template<> struct nspace::hash<in_addr>
91 size_t operator()(const struct in_addr &a) const
94 memcpy(&q,&a,sizeof(size_t));
99 template<> struct nspace::hash<string>
101 size_t operator()(const string &s) const
104 static struct hash<const char *> strhash;
116 bool operator()(const string& s1, const string& s2) const
118 char a[MAXBUF],b[MAXBUF];
119 strcpy(a,s1.c_str());
120 strcpy(b,s2.c_str());
121 return (strcasecmp(a,b) == 0);
126 struct InAddr_HashComp
129 bool operator()(const in_addr &s1, const in_addr &s2) const
134 memcpy(&q,&s1,sizeof(size_t));
135 memcpy(&p,&s2,sizeof(size_t));
143 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
144 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
145 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
146 typedef std::deque<command_t> command_table;
149 serverrec* servers[255];
153 user_hash clientlist;
156 command_table cmdlist;
163 struct linger linger = { 0 };
164 char bannerBuffer[MAXBUF];
165 int boundPortCount = 0;
166 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
167 int defaultRoute = 0;
171 long MyKey = C.GenKey();
175 int has_channel(userrec *u, chanrec *c);
176 int usercount(chanrec *c);
177 int usercount_i(chanrec *c);
178 void update_stats_l(int fd,int data_out);
179 char* Passwd(userrec *user);
180 bool IsDenied(userrec *user);
181 void AddWhoWas(userrec* u);
183 std::stringstream config_f(stringstream::in | stringstream::out);
185 void safedelete(userrec *p)
189 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
190 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
195 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
199 void safedelete(chanrec *p)
204 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
208 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
213 void tidystring(char* str)
215 // strips out double spaces before a : parameter
218 bool go_again = true;
225 while ((str[0] == ' ') && (strlen(str)>0))
232 bool noparse = false;
235 while (a < strlen(str))
237 if ((a<strlen(str)-1) && (noparse==false))
239 if ((str[a] == ' ') && (str[a+1] == ' '))
241 log(DEBUG,"Tidied extra space out of string: %s",str);
249 if ((str[a] == ' ') && (str[a+1] == ':'))
255 temp[t++] = str[a++];
258 strncpy(str,temp,MAXBUF);
262 /* chop a string down to 512 characters and preserve linefeed (irc max
269 log(DEBUG,"ERROR! Null string passed to chop()!");
273 FOREACH_MOD OnServerRaw(temp,false);
274 const char* str2 = temp.c_str();
275 sprintf(str,"%s",str2);
278 if (strlen(str) >= 512)
287 std::string getservername()
292 std::string getserverdesc()
297 std::string getnetworkname()
302 std::string getadminname()
307 std::string getadminemail()
312 std::string getadminnick()
317 void log(int level,char *text, ...)
319 char textbuffer[MAXBUF];
322 struct tm * timeinfo;
323 if (level < LogLevel)
327 timeinfo = localtime (&rawtime);
332 va_start (argsPtr, text);
333 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
335 strcpy(b,asctime(timeinfo));
336 b[strlen(b)-1] = ':';
337 fprintf(log_file,"%s %s\n",b,textbuffer);
340 // nofork enabled? display it on terminal too
341 printf("%s %s\n",b,textbuffer);
346 void readfile(file_cache &F, const char* fname)
349 char linebuf[MAXBUF];
351 log(DEBUG,"readfile: loading %s",fname);
353 file = fopen(fname,"r");
358 fgets(linebuf,sizeof(linebuf),file);
359 linebuf[strlen(linebuf)-1]='\0';
360 if (!strcmp(linebuf,""))
366 F.push_back(linebuf);
373 log(DEBUG,"readfile: failed to load file: %s",fname);
375 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
378 void ReadConfig(void)
380 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF];
383 LoadConf(CONFIG_FILE,&config_f);
385 ConfValue("server","name",0,ServerName,&config_f);
386 ConfValue("server","description",0,ServerDesc,&config_f);
387 ConfValue("server","network",0,Network,&config_f);
388 ConfValue("admin","name",0,AdminName,&config_f);
389 ConfValue("admin","email",0,AdminEmail,&config_f);
390 ConfValue("admin","nick",0,AdminNick,&config_f);
391 ConfValue("files","motd",0,motd,&config_f);
392 ConfValue("files","rules",0,rules,&config_f);
393 ConfValue("power","diepass",0,diepass,&config_f);
394 ConfValue("power","pause",0,pauseval,&config_f);
395 ConfValue("power","restartpass",0,restartpass,&config_f);
396 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
397 ConfValue("die","value",0,DieValue,&config_f);
398 ConfValue("options","loglevel",0,dbg,&config_f);
399 if (!strcmp(dbg,"debug"))
401 if (!strcmp(dbg,"verbose"))
403 if (!strcmp(dbg,"default"))
405 if (!strcmp(dbg,"sparse"))
407 if (!strcmp(dbg,"none"))
410 log(DEBUG,"Reading message of the day");
411 readfile(RULES,rules);
412 log(DEBUG,"Reading connect classes");
414 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
417 ConfValue("connect","allow",i,Value,&config_f);
418 ConfValue("connect","timeout",i,timeout,&config_f);
419 if (strcmp(Value,""))
421 strcpy(c.host,Value);
424 ConfValue("connect","password",i,Value,&config_f);
425 strcpy(c.pass,Value);
426 c.registration_timeout = 90; // default is 2 minutes
429 c.registration_timeout = atoi(timeout);
431 Classes.push_back(c);
432 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
436 ConfValue("connect","deny",i,Value,&config_f);
437 strcpy(c.host,Value);
439 Classes.push_back(c);
440 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
449 log(DEBUG,"Blocking: %d",s);
450 flags = fcntl(s, F_GETFL, 0);
451 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
454 void NonBlocking(int s)
457 log(DEBUG,"NonBlocking: %d",s);
458 flags = fcntl(s, F_GETFL, 0);
459 fcntl(s, F_SETFL, flags | O_NONBLOCK);
463 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
465 struct hostent *hostPtr = NULL;
468 memset (resolvedHost, '\0',MAXBUF);
469 if(unresolvedHost == NULL)
471 if ((inet_aton(unresolvedHost,&addr)) == 0)
473 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
475 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
477 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
481 /* write formatted text to a socket, in same format as printf */
483 void Write(int sock,char *text, ...)
487 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
490 char textbuffer[MAXBUF];
494 va_start (argsPtr, text);
495 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
497 sprintf(tb,"%s\r\n",textbuffer);
499 write(sock,tb,strlen(tb));
500 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
503 /* write a server formatted numeric response to a single socket */
505 void WriteServ(int sock, char* text, ...)
509 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
512 char textbuffer[MAXBUF],tb[MAXBUF];
514 va_start (argsPtr, text);
516 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
518 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
520 write(sock,tb,strlen(tb));
521 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
524 /* write text from an originating user to originating user */
526 void WriteFrom(int sock, userrec *user,char* text, ...)
528 if ((!text) || (!user))
530 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
533 char textbuffer[MAXBUF],tb[MAXBUF];
535 va_start (argsPtr, text);
537 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
539 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
541 write(sock,tb,strlen(tb));
542 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
545 /* write text to an destination user from a source user (e.g. user privmsg) */
547 void WriteTo(userrec *source, userrec *dest,char *data, ...)
549 if ((!source) || (!dest) || (!data))
551 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
554 char textbuffer[MAXBUF],tb[MAXBUF];
556 va_start (argsPtr, data);
557 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
560 WriteFrom(dest->fd,source,"%s",textbuffer);
563 /* write formatted text from a source user to all users on a channel
564 * including the sender (NOT for privmsg, notice etc!) */
566 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
568 if ((!Ptr) || (!user) || (!text))
570 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
573 char textbuffer[MAXBUF];
575 va_start (argsPtr, text);
576 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
578 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
580 if (has_channel(i->second,Ptr))
582 WriteTo(user,i->second,"%s",textbuffer);
587 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
589 if ((!Ptr) || (!user) || (!text))
591 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
594 char textbuffer[MAXBUF];
596 va_start (argsPtr, text);
597 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
599 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
603 if (has_channel(i->second,Ptr))
605 WriteServ(i->second->fd,"%s",textbuffer);
612 /* write formatted text from a source user to all users on a channel except
613 * for the sender (for privmsg etc) */
615 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
617 if ((!Ptr) || (!user) || (!text))
619 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
622 char textbuffer[MAXBUF];
624 va_start (argsPtr, text);
625 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
628 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
632 if (has_channel(i->second,Ptr) && (user != i->second))
634 WriteTo(user,i->second,"%s",textbuffer);
640 int c_count(userrec* u)
643 for (int i =0; i != MAXCHANS; i++)
644 if (u->chans[i].channel != NULL)
650 /* return 0 or 1 depending if users u and u2 share one or more common channels
651 * (used by QUIT, NICK etc which arent channel specific notices) */
653 int common_channels(userrec *u, userrec *u2)
660 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
663 for (i = 0; i != MAXCHANS; i++)
665 for (z = 0; z != MAXCHANS; z++)
667 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
669 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
671 if ((c_count(u)) && (c_count(u2)))
682 /* write a formatted string to all users who share at least one common
683 * channel, including the source user e.g. for use in NICK */
685 void WriteCommon(userrec *u, char* text, ...)
689 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
693 if (u->registered != 7) {
694 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
698 char textbuffer[MAXBUF];
700 va_start (argsPtr, text);
701 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
704 WriteFrom(u->fd,u,"%s",textbuffer);
706 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
710 if (common_channels(u,i->second) && (i->second != u))
712 WriteFrom(i->second->fd,u,"%s",textbuffer);
718 /* write a formatted string to all users who share at least one common
719 * channel, NOT including the source user e.g. for use in QUIT */
721 void WriteCommonExcept(userrec *u, char* text, ...)
725 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
729 if (u->registered != 7) {
730 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
734 char textbuffer[MAXBUF];
736 va_start (argsPtr, text);
737 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
740 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
744 if ((common_channels(u,i->second)) && (u != i->second))
746 WriteFrom(i->second->fd,u,"%s",textbuffer);
752 void WriteOpers(char* text, ...)
756 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
760 char textbuffer[MAXBUF];
762 va_start (argsPtr, text);
763 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
766 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
770 if (strchr(i->second->modes,'o'))
772 if (strchr(i->second->modes,'s'))
774 // send server notices to all with +s
775 // (TODO: needs SNOMASKs)
776 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
783 bool hasumode(userrec* user, char mode)
787 return (strchr(user->modes,mode)>0);
792 void WriteMode(const char* modes, int flags, const char* text, ...)
794 if ((!text) || (!modes) || (!flags))
796 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
800 char textbuffer[MAXBUF];
802 va_start (argsPtr, text);
803 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
806 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
810 bool send_to_user = false;
815 for (int n = 0; n < strlen(modes); n++)
817 if (!hasumode(i->second,modes[n]))
819 send_to_user = false;
824 else if (flags == WM_OR)
826 send_to_user = false;
827 for (int n = 0; n < strlen(modes); n++)
829 if (hasumode(i->second,modes[n]))
839 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
845 void WriteWallOps(userrec *source, char* text, ...)
847 if ((!text) || (!source))
849 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
854 char textbuffer[MAXBUF];
856 va_start (argsPtr, text);
857 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
860 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
864 if (strchr(i->second->modes,'w'))
866 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
872 /* convert a string to lowercase. Note following special circumstances
873 * taken from RFC 1459. Many "official" server branches still hold to this
874 * rule so i will too;
876 * Because of IRC's scandanavian origin, the characters {}| are
877 * considered to be the lower case equivalents of the characters []\,
878 * respectively. This is a critical issue when determining the
879 * equivalence of two nicknames.
882 void strlower(char *n)
888 for (int i = 0; i != strlen(n); i++)
890 n[i] = tolower(n[i]);
900 /* verify that a user's ident and nickname is valid */
902 int isident(const char* n)
915 for (i = 0; i != strlen(n); i++)
917 if ((n[i] < 33) || (n[i] > 125))
921 /* can't occur ANYWHERE in an Ident! */
922 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
931 int isnick(const char* n)
943 if (strlen(n) > NICKMAX-1)
947 for (i = 0; i != strlen(n); i++)
949 if ((n[i] < 33) || (n[i] > 125))
953 /* can't occur ANYWHERE in a nickname! */
954 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
958 /* can't occur as the first char of a nickname... */
959 if ((strchr("0123456789",n[i])) && (!i))
967 /* Find a user record by nickname and return a pointer to it */
969 userrec* Find(string nick)
971 user_hash::iterator iter = clientlist.find(nick);
973 if (iter == clientlist.end())
974 /* Couldn't find it */
980 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
982 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
986 if (i->second->fd == fd)
988 i->second->bytes_out+=data_out;
989 i->second->cmds_out++;
996 /* find a channel record by channel name and return a pointer to it */
998 chanrec* FindChan(const char* chan)
1002 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1006 chan_hash::iterator iter = chanlist.find(chan);
1008 if (iter == chanlist.end())
1009 /* Couldn't find it */
1012 return iter->second;
1016 void purge_empty_chans(void)
1018 int go_again = 1, purge = 0;
1023 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1026 if (!usercount(i->second))
1028 /* kill the record */
1029 if (i != chanlist.end())
1031 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1041 log(DEBUG,"skipped purge for %s",i->second->name);
1046 log(DEBUG,"completed channel purge, killed %d",purge);
1049 /* returns the status character for a given user on a channel, e.g. @ for op,
1050 * % for halfop etc. If the user has several modes set, the highest mode
1051 * the user has must be returned. */
1053 char* cmode(userrec *user, chanrec *chan)
1055 if ((!user) || (!chan))
1057 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1062 for (i = 0; i != MAXCHANS; i++)
1064 if ((user->chans[i].channel == chan) && (chan != NULL))
1066 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1070 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1074 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1083 char scratch[MAXBUF];
1084 char sparam[MAXBUF];
1086 char* chanmodes(chanrec *chan)
1090 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1097 if (chan->noexternal)
1099 strncat(scratch,"n",MAXMODES);
1101 if (chan->topiclock)
1103 strncat(scratch,"t",MAXMODES);
1105 if (strcmp(chan->key,""))
1107 strncat(scratch,"k",MAXMODES);
1111 strncat(scratch,"l",MAXMODES);
1113 if (chan->inviteonly)
1115 strncat(scratch,"i",MAXMODES);
1117 if (chan->moderated)
1119 strncat(scratch,"m",MAXMODES);
1123 strncat(scratch,"s",MAXMODES);
1125 if (chan->c_private)
1127 strncat(scratch,"p",MAXMODES);
1129 if (strcmp(chan->key,""))
1131 strncat(sparam,chan->key,MAXBUF);
1136 sprintf(foo," %d",chan->limit);
1137 strncat(sparam,foo,MAXBUF);
1139 if (strlen(chan->custom_modes))
1141 strncat(scratch,chan->custom_modes,MAXMODES);
1142 for (int z = 0; z < strlen(chan->custom_modes); z++)
1144 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1147 strncat(sparam," ",MAXBUF);
1148 strncat(sparam,extparam.c_str(),MAXBUF);
1152 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1153 strncat(scratch,sparam,MAXMODES);
1157 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1158 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1159 * highest mode the user has must be returned. */
1161 int cstatus(userrec *user, chanrec *chan)
1163 if ((!chan) || (!user))
1165 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1170 for (i = 0; i != MAXCHANS; i++)
1172 if ((user->chans[i].channel == chan) && (chan != NULL))
1174 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1178 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1182 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1184 return STATUS_VOICE;
1186 return STATUS_NORMAL;
1192 /* compile a userlist of a channel into a string, each nick seperated by
1193 * spaces and op, voice etc status shown as @ and + */
1195 void userlist(userrec *user,chanrec *c)
1197 if ((!c) || (!user))
1199 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1203 sprintf(list,"353 %s = %s :", user->nick, c->name);
1204 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1206 if (has_channel(i->second,c))
1208 if (isnick(i->second->nick))
1210 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1212 /* user is +i, and source not on the channel, does not show
1213 * nick in NAMES list */
1216 strcat(list,cmode(i->second,c));
1217 strcat(list,i->second->nick);
1219 if (strlen(list)>(480-NICKMAX))
1221 /* list overflowed into
1222 * multiple numerics */
1223 WriteServ(user->fd,list);
1224 sprintf(list,"353 %s = %s :", user->nick, c->name);
1229 /* if whats left in the list isnt empty, send it */
1230 if (list[strlen(list)-1] != ':')
1232 WriteServ(user->fd,list);
1236 /* return a count of the users on a specific channel accounting for
1237 * invisible users who won't increase the count. e.g. for /LIST */
1239 int usercount_i(chanrec *c)
1246 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1251 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1255 if (has_channel(i->second,c))
1257 if (isnick(i->second->nick))
1259 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1261 /* user is +i, and source not on the channel, does not show
1262 * nick in NAMES list */
1270 log(DEBUG,"usercount_i: %s %d",c->name,count);
1275 int usercount(chanrec *c)
1282 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1287 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1291 if (has_channel(i->second,c))
1293 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1300 log(DEBUG,"usercount: %s %d",c->name,count);
1305 /* add a channel to a user, creating the record for it if needed and linking
1306 * it to the user record */
1308 chanrec* add_channel(userrec *user, const char* cn, const char* key)
1310 if ((!user) || (!cn))
1312 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1321 strncpy(cname,cn,MAXBUF);
1323 // we MUST declare this wherever we use FOREACH_RESULT
1326 if ((!cname) || (!user))
1330 if (strlen(cname) > CHANMAX-1)
1332 cname[CHANMAX-1] = '\0';
1335 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1337 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1339 return NULL; // already on the channel!
1343 if (!FindChan(cname))
1345 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1350 /* create a new one */
1351 log(DEBUG,"add_channel: creating: %s",cname);
1353 chanlist[cname] = new chanrec();
1355 strcpy(chanlist[cname]->name, cname);
1356 chanlist[cname]->topiclock = 1;
1357 chanlist[cname]->noexternal = 1;
1358 chanlist[cname]->created = time(NULL);
1359 strcpy(chanlist[cname]->topic, "");
1360 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1361 chanlist[cname]->topicset = 0;
1362 Ptr = chanlist[cname];
1363 log(DEBUG,"add_channel: created: %s",cname);
1364 /* set created to 2 to indicate user
1365 * is the first in the channel
1366 * and should be given ops */
1372 /* channel exists, just fish out a pointer to its struct */
1373 Ptr = FindChan(cname);
1376 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1381 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1382 if (strcmp(Ptr->key,""))
1384 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1387 log(DEBUG,"add_channel: no key given in JOIN");
1388 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1393 log(DEBUG,"key at %p is %s",key,key);
1394 if (strcasecmp(key,Ptr->key))
1396 log(DEBUG,"add_channel: bad key given in JOIN");
1397 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1402 log(DEBUG,"add_channel: no key");
1404 if (Ptr->inviteonly)
1406 log(DEBUG,"add_channel: channel is +i");
1407 if (user->IsInvited(Ptr->name))
1409 /* user was invited to channel */
1410 /* there may be an optional channel NOTICE here */
1414 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1418 log(DEBUG,"add_channel: channel is not +i");
1422 if (usercount(Ptr) == Ptr->limit)
1424 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1429 log(DEBUG,"add_channel: about to walk banlist");
1431 /* check user against the channel banlist */
1432 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1434 if (match(user->GetFullHost(),i->data))
1436 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1441 log(DEBUG,"add_channel: bans checked");
1443 user->RemoveInvite(Ptr->name);
1445 log(DEBUG,"add_channel: invites removed");
1451 log(DEBUG,"Passed channel checks");
1453 for (i =0; i != MAXCHANS; i++)
1455 if (user->chans[i].channel == NULL)
1457 log(DEBUG,"Adding into their channel list");
1461 /* first user in is given ops */
1462 user->chans[i].uc_modes = UCMODE_OP;
1466 user->chans[i].uc_modes = 0;
1468 user->chans[i].channel = Ptr;
1469 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1471 log(DEBUG,"Sent JOIN to client");
1475 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1476 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1479 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1480 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1481 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1482 FOREACH_MOD OnUserJoin(user,Ptr);
1486 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1487 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1491 /* remove a channel from a users record, and remove the record from memory
1492 * if the channel has become empty */
1494 chanrec* del_channel(userrec *user, const char* cname, const char* reason)
1496 if ((!user) || (!cname))
1498 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1506 if ((!cname) || (!user))
1511 Ptr = FindChan(cname);
1518 FOREACH_MOD OnUserPart(user,Ptr);
1519 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1521 for (i =0; i != MAXCHANS; i++)
1523 /* zap it from the channel list of the user */
1524 if (user->chans[i].channel == Ptr)
1528 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1532 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1534 user->chans[i].uc_modes = 0;
1535 user->chans[i].channel = NULL;
1536 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1541 /* if there are no users left on the channel */
1542 if (!usercount(Ptr))
1544 chan_hash::iterator iter = chanlist.find(Ptr->name);
1546 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1548 /* kill the record */
1549 if (iter != chanlist.end())
1551 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1552 delete iter->second;
1553 chanlist.erase(iter);
1559 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1561 if ((!src) || (!user) || (!Ptr) || (!reason))
1563 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1570 if ((!Ptr) || (!user) || (!src))
1575 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1577 if (!has_channel(user,Ptr))
1579 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1582 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1584 if (cstatus(src,Ptr) == STATUS_HOP)
1586 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1590 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1596 for (i =0; i != MAXCHANS; i++)
1598 /* zap it from the channel list of the user */
1599 if (user->chans[i].channel == Ptr)
1601 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1602 user->chans[i].uc_modes = 0;
1603 user->chans[i].channel = NULL;
1604 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1609 /* if there are no users left on the channel */
1610 if (!usercount(Ptr))
1612 chan_hash::iterator iter = chanlist.find(Ptr->name);
1614 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1616 /* kill the record */
1617 if (iter != chanlist.end())
1619 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1620 delete iter->second;
1621 chanlist.erase(iter);
1627 /* returns 1 if user u has channel c in their record, 0 if not */
1629 int has_channel(userrec *u, chanrec *c)
1635 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1638 for (i =0; i != MAXCHANS; i++)
1640 if (u->chans[i].channel == c)
1648 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1653 if ((!user) || (!dest) || (!chan))
1655 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1658 if (status != STATUS_OP)
1660 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1667 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1673 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1678 for (i = 0; i != MAXCHANS; i++)
1680 if ((d->chans[i].channel == chan) && (chan != NULL))
1682 if (d->chans[i].uc_modes & UCMODE_OP)
1684 /* mode already set on user, dont allow multiple */
1687 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1688 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1696 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1701 if ((!user) || (!dest) || (!chan))
1703 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1706 if (status != STATUS_OP)
1708 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1716 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1721 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1726 for (i = 0; i != MAXCHANS; i++)
1728 if ((d->chans[i].channel == chan) && (chan != NULL))
1730 if (d->chans[i].uc_modes & UCMODE_HOP)
1732 /* mode already set on user, dont allow multiple */
1735 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1736 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1744 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1749 if ((!user) || (!dest) || (!chan))
1751 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1754 if (status < STATUS_HOP)
1756 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1764 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1769 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1774 for (i = 0; i != MAXCHANS; i++)
1776 if ((d->chans[i].channel == chan) && (chan != NULL))
1778 if (d->chans[i].uc_modes & UCMODE_VOICE)
1780 /* mode already set on user, dont allow multiple */
1783 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1784 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1792 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1797 if ((!user) || (!dest) || (!chan))
1799 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1802 if (status != STATUS_OP)
1804 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1812 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1817 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1822 for (i = 0; i != MAXCHANS; i++)
1824 if ((d->chans[i].channel == chan) && (chan != NULL))
1826 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1828 /* mode already set on user, dont allow multiple */
1831 d->chans[i].uc_modes ^= UCMODE_OP;
1832 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1840 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1845 if ((!user) || (!dest) || (!chan))
1847 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1850 if (status != STATUS_OP)
1852 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1860 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1865 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1870 for (i = 0; i != MAXCHANS; i++)
1872 if ((d->chans[i].channel == chan) && (chan != NULL))
1874 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1876 /* mode already set on user, dont allow multiple */
1879 d->chans[i].uc_modes ^= UCMODE_HOP;
1880 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1888 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1893 if ((!user) || (!dest) || (!chan))
1895 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1898 if (status < STATUS_HOP)
1900 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1908 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1913 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1918 for (i = 0; i != MAXCHANS; i++)
1920 if ((d->chans[i].channel == chan) && (chan != NULL))
1922 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1924 /* mode already set on user, dont allow multiple */
1927 d->chans[i].uc_modes ^= UCMODE_VOICE;
1928 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1936 void TidyBan(char *ban)
1939 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1943 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1947 char* pos_of_pling = strchr(temp,'!');
1948 char* pos_of_at = strchr(temp,'@');
1950 pos_of_pling[0] = '\0';
1951 pos_of_at[0] = '\0';
1955 strncpy(NICK,temp,NICKMAX);
1956 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1957 strncpy(HOST,pos_of_at,160);
1959 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1962 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1964 if ((!user) || (!dest) || (!chan)) {
1965 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1970 if ((!user) || (!dest) || (!chan))
1972 if (strchr(dest,'!')==0)
1974 if (strchr(dest,'@')==0)
1976 for (int i = 0; i < strlen(dest); i++)
1979 for (int i = 0; i < strlen(dest); i++)
1983 for (int i = 0; i < strlen(dest); i++)
1989 for (int i = 0; i < strlen(dest); i++)
1994 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1997 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1999 if (!strcasecmp(i->data,dest))
2001 // dont allow a user to set the same ban twice
2006 b.set_time = time(NULL);
2007 strncpy(b.data,dest,MAXBUF);
2008 strncpy(b.set_by,user->nick,NICKMAX);
2009 chan->bans.push_back(b);
2013 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2015 if ((!user) || (!dest) || (!chan)) {
2016 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2020 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2021 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2023 if (!strcasecmp(i->data,dest))
2025 chan->bans.erase(i);
2032 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
2034 if ((!parameters) || (!user)) {
2035 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2040 char modelist[MAXBUF];
2041 char outlist[MAXBUF];
2042 char outstr[MAXBUF];
2043 char outpars[32][MAXBUF];
2049 bool k_set = false, l_set = false;
2056 log(DEBUG,"process_modes: start");
2058 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2059 /* parameters[2] onwards are parameters for
2060 * modes that require them :) */
2061 strcpy(outlist,"+");
2064 log(DEBUG,"process_modes: modelist: %s",modelist);
2066 for (ptr = 0; ptr < strlen(modelist); ptr++)
2071 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2072 char modechar = modelist[ptr];
2073 switch (modelist[ptr])
2078 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2080 outlist[strlen(outlist)-1] = '-';
2084 strcat(outlist,"-");
2094 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2096 outlist[strlen(outlist)-1] = '+';
2100 strcat(outlist,"+");
2107 if ((param >= pcnt)) break;
2110 r = give_ops(user,parameters[param++],chan,status);
2114 r = take_ops(user,parameters[param++],chan,status);
2118 strcat(outlist,"o");
2119 strcpy(outpars[pc++],parameters[param-1]);
2124 if ((param >= pcnt)) break;
2127 r = give_hops(user,parameters[param++],chan,status);
2131 r = take_hops(user,parameters[param++],chan,status);
2135 strcat(outlist,"h");
2136 strcpy(outpars[pc++],parameters[param-1]);
2142 if ((param >= pcnt)) break;
2145 r = give_voice(user,parameters[param++],chan,status);
2149 r = take_voice(user,parameters[param++],chan,status);
2153 strcat(outlist,"v");
2154 strcpy(outpars[pc++],parameters[param-1]);
2159 if ((param >= pcnt)) break;
2162 r = add_ban(user,parameters[param++],chan,status);
2166 r = take_ban(user,parameters[param++],chan,status);
2170 strcat(outlist,"b");
2171 strcpy(outpars[pc++],parameters[param-1]);
2177 if ((param >= pcnt))
2185 if (!strcmp(chan->key,""))
2187 strcat(outlist,"k");
2189 strcpy(key,parameters[param++]);
2190 if (strlen(key)>32) {
2193 strcpy(outpars[pc++],key);
2194 strcpy(chan->key,key);
2200 /* checks on -k are case sensitive and only accurate to the
2201 first 32 characters */
2203 strcpy(key,parameters[param++]);
2204 if (strlen(key)>32) {
2207 /* only allow -k if correct key given */
2208 if (!strcmp(chan->key,key))
2210 strcat(outlist,"k");
2211 strcpy(chan->key,"");
2212 strcpy(outpars[pc++],key);
2222 strcat(outlist,"l");
2227 if ((param >= pcnt)) break;
2233 bool invalid = false;
2234 for (int i = 0; i < strlen(parameters[param]); i++)
2236 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2241 if (atoi(parameters[param]) < 1)
2249 chan->limit = atoi(parameters[param]);
2252 strcat(outlist,"l");
2253 strcpy(outpars[pc++],parameters[param++]);
2260 if (chan->inviteonly != mdir)
2262 strcat(outlist,"i");
2264 chan->inviteonly = mdir;
2268 if (chan->topiclock != mdir)
2270 strcat(outlist,"t");
2272 chan->topiclock = mdir;
2276 if (chan->noexternal != mdir)
2278 strcat(outlist,"n");
2280 chan->noexternal = mdir;
2284 if (chan->moderated != mdir)
2286 strcat(outlist,"m");
2288 chan->moderated = mdir;
2292 if (chan->secret != mdir)
2294 strcat(outlist,"s");
2295 if (chan->c_private)
2297 chan->c_private = 0;
2300 strcat(outlist,"-p+");
2304 strcat(outlist,"+p-");
2308 chan->secret = mdir;
2312 if (chan->c_private != mdir)
2314 strcat(outlist,"p");
2320 strcat(outlist,"-s+");
2324 strcat(outlist,"+s-");
2328 chan->c_private = mdir;
2332 log(DEBUG,"Preprocessing custom mode %c",modechar);
2335 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2337 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2340 if (ModeDefined(modechar,MT_CHANNEL))
2342 log(DEBUG,"A module has claimed this mode");
2345 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2347 p.push_back(parameters[param]);
2349 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2351 p.push_back(parameters[param]);
2354 bool handled = false;
2357 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2358 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2359 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2365 for (int i = 0; i <= MODCOUNT; i++)
2369 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2371 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2372 char app[] = {modechar, 0};
2375 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2377 strcat(outlist, app);
2379 else if (!strchr(outlist,modechar))
2381 strcat(outlist, app);
2384 chan->SetCustomMode(modechar,mdir);
2385 // include parameters in output if mode has them
2386 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2388 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2389 strcpy(outpars[pc++],parameters[param++]);
2391 // break, because only one module can handle the mode.
2403 /* this ensures only the *valid* modes are sent out onto the network */
2404 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2406 outlist[strlen(outlist)-1] = '\0';
2408 if (strcmp(outlist,""))
2410 strcpy(outstr,outlist);
2411 for (ptr = 0; ptr < pc; ptr++)
2414 strcat(outstr,outpars[ptr]);
2418 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2422 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2427 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2429 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2431 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2432 // RFC1459 specified modes
2433 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2435 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2439 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2440 if ((strchr(sourcemodes,'o')) && (!adding))
2442 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2445 else if (umode == 'o')
2447 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2451 // process any module-defined modes that need oper
2452 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2454 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2458 if (ModeDefined(umode,MT_CLIENT))
2460 // process any module-defined modes that don't need oper
2461 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2462 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2464 // no, this mode needs oper, and this user 'aint got what it takes!
2470 // anything else - return false.
2471 log(DEBUG,"umode %c not known by any ruleset",umode);
2475 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2479 if (ModeDefined(umode,MT_CLIENT))
2481 for (int i = 0; i <= MODCOUNT; i++)
2483 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2485 log(DEBUG,"Module claims umode %c",umode);
2489 log(DEBUG,"No module claims umode %c",umode);
2494 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2499 void handle_mode(char **parameters, int pcnt, userrec *user)
2505 char outpars[MAXBUF];
2507 dest = Find(parameters[0]);
2509 if ((dest) && (pcnt == 1))
2511 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2515 if ((dest) && (pcnt > 1))
2517 char dmodes[MAXBUF];
2518 strncpy(dmodes,dest->modes,MAXBUF);
2519 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2524 if (strchr(user->modes,'o'))
2535 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2539 strcpy(outpars,"+");
2542 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2545 for (i = 0; i < strlen(parameters[1]); i++)
2547 if (parameters[1][i] == '+')
2551 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2553 outpars[strlen(outpars)-1] = '+';
2557 strcat(outpars,"+");
2563 if (parameters[1][i] == '-')
2567 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2569 outpars[strlen(outpars)-1] = '-';
2573 strcat(outpars,"-");
2581 if (strchr(user->modes,'o'))
2587 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2596 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2598 char umode = parameters[1][i];
2599 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2601 dmodes[strlen(dmodes)+1]='\0';
2602 dmodes[strlen(dmodes)] = parameters[1][i];
2603 outpars[strlen(outpars)+1]='\0';
2604 outpars[strlen(outpars)] = parameters[1][i];
2610 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2612 char umode = parameters[1][i];
2613 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2619 outpars[strlen(outpars)+1]='\0';
2620 outpars[strlen(outpars)] = parameters[1][i];
2623 for (q = 0; q < strlen(dmodes); q++)
2625 if (dmodes[q] != parameters[1][i])
2632 strcpy(dmodes,temp);
2639 if (strlen(outpars))
2645 while (i < strlen (outpars))
2647 b[z++] = outpars[i++];
2649 if (i<strlen(outpars)-1)
2651 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2653 // someones playing silly buggers and trying
2654 // to put a +- or -+ into the line...
2658 if (i == strlen(outpars)-1)
2660 if ((outpars[i] == '-') || (outpars[i] == '+'))
2668 if ((b[z] == '-') || (b[z] == '+'))
2671 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2674 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2676 if (strlen(dmodes)>MAXMODES)
2678 dmodes[MAXMODES-1] = '\0';
2680 log(DEBUG,"Stripped mode line");
2681 log(DEBUG,"Line dest is now %s",dmodes);
2682 strncpy(dest->modes,dmodes,MAXMODES);
2689 Ptr = FindChan(parameters[0]);
2694 /* just /modes #channel */
2695 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2696 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2702 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2705 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2707 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2709 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2713 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2715 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
2719 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2723 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2730 void server_mode(char **parameters, int pcnt, userrec *user)
2736 char outpars[MAXBUF];
2738 dest = Find(parameters[0]);
2740 // fix: ChroNiCk found this - we cant use this as debug if its null!
2743 log(DEBUG,"server_mode on %s",dest->nick);
2746 if ((dest) && (pcnt > 1))
2748 log(DEBUG,"params > 1");
2750 char dmodes[MAXBUF];
2751 strncpy(dmodes,dest->modes,MAXBUF);
2753 strcpy(outpars,"+");
2756 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2759 for (i = 0; i < strlen(parameters[1]); i++)
2761 if (parameters[1][i] == '+')
2765 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2767 outpars[strlen(outpars)-1] = '+';
2771 strcat(outpars,"+");
2777 if (parameters[1][i] == '-')
2781 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2783 outpars[strlen(outpars)-1] = '-';
2787 strcat(outpars,"-");
2794 log(DEBUG,"begin mode processing entry");
2800 log(DEBUG,"umode %c being added",parameters[1][i]);
2801 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2803 char umode = parameters[1][i];
2804 log(DEBUG,"umode %c is an allowed umode",umode);
2805 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2807 dmodes[strlen(dmodes)+1]='\0';
2808 dmodes[strlen(dmodes)] = parameters[1][i];
2809 outpars[strlen(outpars)+1]='\0';
2810 outpars[strlen(outpars)] = parameters[1][i];
2816 // can only remove a mode they already have
2817 log(DEBUG,"umode %c being removed",parameters[1][i]);
2818 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2820 char umode = parameters[1][i];
2821 log(DEBUG,"umode %c is an allowed umode",umode);
2822 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2828 outpars[strlen(outpars)+1]='\0';
2829 outpars[strlen(outpars)] = parameters[1][i];
2832 for (q = 0; q < strlen(dmodes); q++)
2834 if (dmodes[q] != parameters[1][i])
2841 strcpy(dmodes,temp);
2848 if (strlen(outpars))
2854 while (i < strlen (outpars))
2856 b[z++] = outpars[i++];
2858 if (i<strlen(outpars)-1)
2860 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2862 // someones playing silly buggers and trying
2863 // to put a +- or -+ into the line...
2867 if (i == strlen(outpars)-1)
2869 if ((outpars[i] == '-') || (outpars[i] == '+'))
2877 if ((b[z] == '-') || (b[z] == '+'))
2880 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2883 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2885 if (strlen(dmodes)>MAXMODES)
2887 dmodes[MAXMODES-1] = '\0';
2889 log(DEBUG,"Stripped mode line");
2890 log(DEBUG,"Line dest is now %s",dmodes);
2891 strncpy(dest->modes,dmodes,MAXMODES);
2898 Ptr = FindChan(parameters[0]);
2901 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2905 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2910 /* This function pokes and hacks at a parameter list like the following:
2912 * PART #winbot, #darkgalaxy :m00!
2914 * to turn it into a series of individual calls like this:
2916 * PART #winbot :m00!
2917 * PART #darkgalaxy :m00!
2919 * The seperate calls are sent to a callback function provided by the caller
2920 * (the caller will usually call itself recursively). The callback function
2921 * must be a command handler. Calling this function on a line with no list causes
2922 * no action to be taken. You must provide a starting and ending parameter number
2923 * where the range of the list can be found, useful if you have a terminating
2924 * parameter as above which is actually not part of the list, or parameters
2925 * before the actual list as well. This code is used by many functions which
2926 * can function as "one to list" (see the RFC) */
2928 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2933 char blog[32][MAXBUF];
2934 char blog2[32][MAXBUF];
2935 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2936 char keystr[MAXBUF];
2939 for (i = 0; i <32; i++)
2942 for (i = 0; i <32; i++)
2943 strcpy(blog2[i],"");
2946 for (i = 0; i <10; i++)
2950 parameters[i] = moo;
2955 if (pcnt > 1) /* we have a key to copy */
2957 strcpy(keystr,parameters[1]);
2961 if (!parameters[start])
2965 if (!strchr(parameters[start],','))
2970 for (i = start; i <= end; i++)
2974 strcat(plist,parameters[i]);
2982 for (i = 0; i < t; i++)
2984 if (plist[i] == ',')
2987 strcpy(blog[j++],param);
2991 strcpy(blog[j++],param);
2994 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2999 if ((joins) && (keystr))
3001 if (strchr(keystr,','))
3005 t2 = strlen(keystr);
3006 for (i = 0; i < t2; i++)
3008 if (keystr[i] == ',')
3011 strcpy(blog2[j++],param);
3015 strcpy(blog2[j++],param);
3020 for (j = 0; j < total; j++)
3026 for (q = end; q < pcnt-1; q++)
3028 if (parameters[q+1])
3030 pars[q-end+1] = parameters[q+1];
3033 if ((joins) && (parameters[1]))
3044 /* repeatedly call the function with the hacked parameter list */
3045 if ((joins) && (pcnt > 1))
3049 // pars[1] already set up and containing key from blog2[j]
3054 pars[1] = parameters[1];
3060 fn(pars,pcnt-(end-start),u);
3068 void handle_join(char **parameters, int pcnt, userrec *user)
3073 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3075 if (parameters[0][0] == '#')
3077 Ptr = add_channel(user,parameters[0],parameters[1]);
3082 void handle_part(char **parameters, int pcnt, userrec *user)
3088 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3090 del_channel(user,parameters[0],parameters[1]);
3094 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3096 del_channel(user,parameters[0],NULL);
3100 void handle_kick(char **parameters, int pcnt, userrec *user)
3102 chanrec* Ptr = FindChan(parameters[0]);
3103 userrec* u = Find(parameters[1]);
3107 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3111 if (!has_channel(u,Ptr))
3113 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3119 char reason[MAXBUF];
3120 strncpy(reason,parameters[2],MAXBUF);
3121 if (strlen(reason)>MAXKICK)
3123 reason[MAXKICK-1] = '\0';
3126 kick_channel(user,u,Ptr,reason);
3130 kick_channel(user,u,Ptr,user->nick);
3135 void handle_die(char **parameters, int pcnt, userrec *user)
3137 log(DEBUG,"die: %s",user->nick);
3138 if (!strcmp(parameters[0],diepass))
3140 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3146 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3150 void handle_restart(char **parameters, int pcnt, userrec *user)
3152 log(DEBUG,"restart: %s",user->nick);
3153 if (!strcmp(parameters[0],restartpass))
3155 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3158 /* Will finish this later when i can be arsed :) */
3162 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3167 void kill_link(userrec *user,const char* r)
3169 user_hash::iterator iter = clientlist.find(user->nick);
3171 char reason[MAXBUF];
3173 strncpy(reason,r,MAXBUF);
3175 if (strlen(reason)>MAXQUIT)
3177 reason[MAXQUIT-1] = '\0';
3180 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3181 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3182 log(DEBUG,"closing fd %d",user->fd);
3184 /* bugfix, cant close() a nonblocking socket (sux!) */
3185 if (user->registered == 7) {
3186 FOREACH_MOD OnUserQuit(user);
3187 WriteCommonExcept(user,"QUIT :%s",reason);
3190 /* push the socket on a stack of sockets due to be closed at the next opportunity
3191 * 'Client exited' is an exception to this as it means the client side has already
3192 * closed the socket, we don't need to do it.
3194 fd_reap.push_back(user->fd);
3196 bool do_purge = false;
3198 if (user->registered == 7) {
3199 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3203 if (iter != clientlist.end())
3205 log(DEBUG,"deleting user hash value %d",iter->second);
3206 if ((iter->second) && (user->registered == 7)) {
3207 delete iter->second;
3209 clientlist.erase(iter);
3212 if (user->registered == 7) {
3213 purge_empty_chans();
3218 void handle_kill(char **parameters, int pcnt, userrec *user)
3220 userrec *u = Find(parameters[0]);
3221 char killreason[MAXBUF];
3223 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3226 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3227 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3228 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3229 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3230 kill_link(u,killreason);
3234 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3238 void handle_summon(char **parameters, int pcnt, userrec *user)
3240 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3243 void handle_users(char **parameters, int pcnt, userrec *user)
3245 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3249 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3251 char* Passwd(userrec *user)
3253 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3255 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3263 bool IsDenied(userrec *user)
3265 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3267 if (match(user->host,i->host) && (i->type == CC_DENY))
3277 void handle_pass(char **parameters, int pcnt, userrec *user)
3279 // Check to make sure they havnt registered -- Fix by FCS
3280 if (user->registered == 7)
3282 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3285 if (!strcasecmp(parameters[0],Passwd(user)))
3287 user->haspassed = true;
3291 void handle_invite(char **parameters, int pcnt, userrec *user)
3293 userrec* u = Find(parameters[0]);
3294 chanrec* c = FindChan(parameters[1]);
3300 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3306 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3315 if (cstatus(user,c) < STATUS_HOP)
3317 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
3321 if (has_channel(u,c))
3323 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
3326 if (!has_channel(user,c))
3328 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
3331 u->InviteTo(c->name);
3332 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3333 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3336 void handle_topic(char **parameters, int pcnt, userrec *user)
3342 if (strlen(parameters[0]) <= CHANMAX)
3344 Ptr = FindChan(parameters[0]);
3349 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3350 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3354 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3359 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3366 if (strlen(parameters[0]) <= CHANMAX)
3368 Ptr = FindChan(parameters[0]);
3371 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3373 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
3378 strncpy(topic,parameters[1],MAXBUF);
3379 if (strlen(topic)>MAXTOPIC)
3381 topic[MAXTOPIC-1] = '\0';
3384 strcpy(Ptr->topic,topic);
3385 strcpy(Ptr->setby,user->nick);
3386 Ptr->topicset = time(NULL);
3387 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3391 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3397 /* sends out an error notice to all connected clients (not to be used
3400 void send_error(char *s)
3402 log(DEBUG,"send_error: %s",s);
3403 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3405 if (isnick(i->second->nick))
3407 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3411 // fix - unregistered connections receive ERROR, not NOTICE
3412 Write(i->second->fd,"ERROR :%s",s);
3417 void Error(int status)
3419 signal (SIGALRM, SIG_IGN);
3420 signal (SIGPIPE, SIG_IGN);
3421 signal (SIGTERM, SIG_IGN);
3422 signal (SIGABRT, SIG_IGN);
3423 signal (SIGSEGV, SIG_IGN);
3424 signal (SIGURG, SIG_IGN);
3425 signal (SIGKILL, SIG_IGN);
3426 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3427 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3432 int main (int argc, char *argv[])
3435 log(DEBUG,"*** InspIRCd starting up!");
3436 if (!FileExists(CONFIG_FILE))
3438 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3439 log(DEBUG,"main: no config");
3440 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3444 if (!strcmp(argv[1],"-nofork")) {
3448 if (InspIRCd() == ERROR)
3450 log(DEBUG,"main: daemon function bailed");
3451 printf("ERROR: could not initialise. Shutting down.\n");
3458 template<typename T> inline string ConvToStr(const T &in)
3461 if (!(tmp << in)) return string();
3465 /* re-allocates a nick in the user_hash after they change nicknames,
3466 * returns a pointer to the new user as it may have moved */
3468 userrec* ReHashNick(char* Old, char* New)
3470 user_hash::iterator newnick;
3471 user_hash::iterator oldnick = clientlist.find(Old);
3473 log(DEBUG,"ReHashNick: %s %s",Old,New);
3475 if (!strcasecmp(Old,New))
3477 log(DEBUG,"old nick is new nick, skipping");
3478 return oldnick->second;
3481 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3483 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3485 clientlist[New] = new userrec();
3486 clientlist[New] = oldnick->second;
3487 /*delete oldnick->second; */
3488 clientlist.erase(oldnick);
3490 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3492 return clientlist[New];
3495 /* adds or updates an entry in the whowas list */
3496 void AddWhoWas(userrec* u)
3498 user_hash::iterator iter = whowas.find(u->nick);
3499 userrec *a = new userrec();
3500 strcpy(a->nick,u->nick);
3501 strcpy(a->ident,u->ident);
3502 strcpy(a->dhost,u->dhost);
3503 strcpy(a->host,u->host);
3504 strcpy(a->fullname,u->fullname);
3505 strcpy(a->server,u->server);
3506 a->signon = u->signon;
3508 /* MAX_WHOWAS: max number of /WHOWAS items
3509 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3510 * can be replaced by a newer one
3513 if (iter == whowas.end())
3515 if (whowas.size() == WHOWAS_MAX)
3517 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3519 // 3600 seconds in an hour ;)
3520 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3524 log(DEBUG,"added WHOWAS entry, purged an old record");
3531 log(DEBUG,"added fresh WHOWAS entry");
3532 whowas[a->nick] = a;
3537 log(DEBUG,"updated WHOWAS entry");
3538 delete iter->second;
3544 /* add a client connection to the sockets list */
3545 void AddClient(int socket, char* host, int port, bool iscached)
3549 char resolved[MAXBUF];
3552 user_hash::iterator iter;
3554 tempnick = ConvToStr(socket) + "-unknown";
3555 sprintf(tn2,"%d-unknown",socket);
3557 iter = clientlist.find(tempnick);
3559 if (iter != clientlist.end()) return;
3562 * It is OK to access the value here this way since we know
3563 * it exists, we just created it above.
3565 * At NO other time should you access a value in a map or a
3566 * hash_map this way.
3568 clientlist[tempnick] = new userrec();
3570 NonBlocking(socket);
3571 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3573 clientlist[tempnick]->fd = socket;
3574 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3575 strncpy(clientlist[tempnick]->host, host,160);
3576 strncpy(clientlist[tempnick]->dhost, host,160);
3577 strncpy(clientlist[tempnick]->server, ServerName,256);
3578 strncpy(clientlist[tempnick]->ident, "unknown",9);
3579 clientlist[tempnick]->registered = 0;
3580 clientlist[tempnick]->signon = time(NULL);
3581 clientlist[tempnick]->nping = time(NULL)+240;
3582 clientlist[tempnick]->lastping = 1;
3583 clientlist[tempnick]->port = port;
3587 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3591 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3594 // set the registration timeout for this user
3595 unsigned long class_regtimeout = 90;
3596 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3598 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3600 class_regtimeout = (unsigned long)i->registration_timeout;
3604 log(DEBUG,"Client has a connection timeout value of %d",class_regtimeout);
3605 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3607 if (clientlist.size() == MAXCLIENTS)
3608 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3611 void handle_names(char **parameters, int pcnt, userrec *user)
3615 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3617 c = FindChan(parameters[0]);
3620 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3622 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3626 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3631 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3636 user->idle_lastmsg = time(NULL);
3638 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3640 if (parameters[0][0] == '#')
3642 chan = FindChan(parameters[0]);
3645 if ((chan->noexternal) && (!has_channel(user,chan)))
3647 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3650 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3652 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3658 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3663 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3667 /* no such nick/channel */
3668 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3673 dest = Find(parameters[0]);
3676 if (strcmp(dest->awaymsg,""))
3678 /* auto respond with aweh msg */
3679 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3684 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
3689 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3693 /* no such nick/channel */
3694 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3698 void handle_notice(char **parameters, int pcnt, userrec *user)
3703 user->idle_lastmsg = time(NULL);
3705 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3707 if (parameters[0][0] == '#')
3709 chan = FindChan(parameters[0]);
3712 if ((chan->noexternal) && (!has_channel(user,chan)))
3714 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3717 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3719 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3725 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3730 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3734 /* no such nick/channel */
3735 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3740 dest = Find(parameters[0]);
3745 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
3750 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3754 /* no such nick/channel */
3755 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3761 char* chlist(userrec *user)
3766 log(DEBUG,"chlist: %s",user->nick);
3772 for (i = 0; i != MAXCHANS; i++)
3774 if (user->chans[i].channel != NULL)
3776 if (user->chans[i].channel->name)
3778 strcpy(cmp,user->chans[i].channel->name);
3780 if (!strstr(lst,cmp))
3782 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3784 strcat(lst,cmode(user,user->chans[i].channel));
3785 strcat(lst,user->chans[i].channel->name);
3795 void handle_info(char **parameters, int pcnt, userrec *user)
3797 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3798 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3799 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3800 FOREACH_MOD OnInfo(user);
3801 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3804 void handle_time(char **parameters, int pcnt, userrec *user)
3807 struct tm * timeinfo;
3810 timeinfo = localtime ( &rawtime );
3811 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3815 void handle_whois(char **parameters, int pcnt, userrec *user)
3820 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3822 dest = Find(parameters[0]);
3825 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3826 if (dest->registered == 7)
3828 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3829 if ((user == dest) || (strchr(user->modes,'o')))
3831 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3833 if (strcmp(chlist(dest),""))
3835 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3837 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3838 if (strcmp(dest->awaymsg,""))
3840 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3842 if (strchr(dest->modes,'o'))
3844 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3846 FOREACH_MOD OnWhois(user,dest);
3847 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3848 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3850 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3854 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3859 /* no such nick/channel */
3860 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3864 void handle_quit(char **parameters, int pcnt, userrec *user)
3866 user_hash::iterator iter = clientlist.find(user->nick);
3869 if (user->registered == 7)
3871 /* theres more to do here, but for now just close the socket */
3874 if (parameters[0][0] == ':')
3878 reason = parameters[0];
3880 if (strlen(reason)>MAXQUIT)
3882 reason[MAXQUIT-1] = '\0';
3885 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3886 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3887 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3891 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3892 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3893 WriteCommonExcept(user,"QUIT :Client exited");
3895 FOREACH_MOD OnUserQuit(user);
3899 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3900 fd_reap.push_back(user->fd);
3902 if (iter != clientlist.end())
3904 log(DEBUG,"deleting user hash value %d",iter->second);
3905 if ((iter->second) && (user->registered == 7)) {
3906 delete iter->second;
3908 clientlist.erase(iter);
3911 if (user->registered == 7) {
3912 purge_empty_chans();
3916 void handle_who(char **parameters, int pcnt, userrec *user)
3918 chanrec* Ptr = NULL;
3920 /* theres more to do here, but for now just close the socket */
3923 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3925 if (user->chans[0].channel)
3927 Ptr = user->chans[0].channel;
3928 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3930 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3932 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);
3938 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3942 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3946 if (parameters[0][0] = '#')
3948 Ptr = FindChan(parameters[0]);
3951 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3953 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3955 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);
3958 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3962 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3968 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3970 Ptr = user->chans[0].channel;
3971 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3973 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3975 if (strchr(i->second->modes,'o'))
3977 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);
3981 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3987 void handle_wallops(char **parameters, int pcnt, userrec *user)
3989 WriteWallOps(user,"%s",parameters[0]);
3992 void handle_list(char **parameters, int pcnt, userrec *user)
3996 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3997 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3999 if ((!i->second->c_private) && (!i->second->secret))
4001 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4004 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4008 void handle_rehash(char **parameters, int pcnt, userrec *user)
4010 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
4012 FOREACH_MOD OnRehash();
4013 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
4019 return clientlist.size();
4022 int usercount_invisible(void)
4026 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4028 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4033 int usercount_opers(void)
4037 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4039 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4044 int usercount_unknown(void)
4048 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4050 if ((i->second->fd) && (i->second->registered != 7))
4058 return chanlist.size();
4061 int servercount(void)
4066 void handle_lusers(char **parameters, int pcnt, userrec *user)
4068 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4069 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4070 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4071 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4072 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4075 void handle_admin(char **parameters, int pcnt, userrec *user)
4077 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4078 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4079 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4080 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4083 void ShowMOTD(userrec *user)
4087 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4090 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4091 for (int i = 0; i != MOTD.size(); i++)
4093 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4095 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4098 void ShowRULES(userrec *user)
4102 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4105 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4106 for (int i = 0; i != RULES.size(); i++)
4108 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4110 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4113 /* shows the message of the day, and any other on-logon stuff */
4114 void ConnectUser(userrec *user)
4116 user->registered = 7;
4117 user->idle_lastmsg = time(NULL);
4118 log(DEBUG,"ConnectUser: %s",user->nick);
4120 if (strcmp(Passwd(user),"") && (!user->haspassed))
4122 kill_link(user,"Invalid password");
4127 kill_link(user,"Unauthorised connection");
4131 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4132 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4133 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4134 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4135 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4136 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);
4137 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);
4139 FOREACH_MOD OnUserConnect(user);
4140 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4143 void handle_version(char **parameters, int pcnt, userrec *user)
4145 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4148 void handle_ping(char **parameters, int pcnt, userrec *user)
4150 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4153 void handle_pong(char **parameters, int pcnt, userrec *user)
4155 // set the user as alive so they survive to next ping
4159 void handle_motd(char **parameters, int pcnt, userrec *user)
4164 void handle_rules(char **parameters, int pcnt, userrec *user)
4169 void handle_user(char **parameters, int pcnt, userrec *user)
4171 if (user->registered < 3)
4173 if (isident(parameters[0]) == 0) {
4174 // This kinda Sucks, According to the RFC thou, its either this,
4175 // or "You have already registered" :p -- Craig
4176 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4179 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4180 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4181 strncat(user->ident,parameters[0],IDENTMAX);
4182 strncpy(user->fullname,parameters[3],128);
4183 user->registered = (user->registered | 1);
4188 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4191 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4192 if (user->registered == 3)
4194 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4199 void handle_userhost(char **parameters, int pcnt, userrec *user)
4201 char Return[MAXBUF],junk[MAXBUF];
4202 sprintf(Return,"302 %s :",user->nick);
4203 for (int i = 0; i < pcnt; i++)
4205 userrec *u = Find(parameters[i]);
4208 if (strchr(u->modes,'o'))
4210 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4211 strcat(Return,junk);
4215 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4216 strcat(Return,junk);
4220 WriteServ(user->fd,Return);
4224 void handle_ison(char **parameters, int pcnt, userrec *user)
4226 char Return[MAXBUF];
4227 sprintf(Return,"303 %s :",user->nick);
4228 for (int i = 0; i < pcnt; i++)
4230 userrec *u = Find(parameters[i]);
4233 strcat(Return,u->nick);
4237 WriteServ(user->fd,Return);
4241 void handle_away(char **parameters, int pcnt, userrec *user)
4245 strcpy(user->awaymsg,parameters[0]);
4246 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4250 strcpy(user->awaymsg,"");
4251 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4255 void handle_whowas(char **parameters, int pcnt, userrec* user)
4257 user_hash::iterator i = whowas.find(parameters[0]);
4259 if (i == whowas.end())
4261 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4262 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4266 time_t rawtime = i->second->signon;
4270 timeinfo = localtime(&rawtime);
4271 strcpy(b,asctime(timeinfo));
4272 b[strlen(b)-1] = '\0';
4274 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4275 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4276 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4281 void handle_trace(char **parameters, int pcnt, userrec *user)
4283 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4287 if (isnick(i->second->nick))
4289 if (strchr(i->second->modes,'o'))
4291 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4295 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4300 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4306 void handle_modules(char **parameters, int pcnt, userrec *user)
4308 for (int i = 0; i < module_names.size(); i++)
4310 Version V = modules[i]->GetVersion();
4311 WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,module_names[i].c_str());
4315 void handle_stats(char **parameters, int pcnt, userrec *user)
4321 if (strlen(parameters[0])>1)
4323 /* make the stats query 1 character long */
4324 parameters[0][1] = '\0';
4327 /* stats m (list number of times each command has been used, plus bytecount) */
4328 if (!strcasecmp(parameters[0],"m"))
4330 for (int i = 0; i < cmdlist.size(); i++)
4332 if (cmdlist[i].handler_function)
4334 if (cmdlist[i].use_count)
4336 /* RPL_STATSCOMMANDS */
4337 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4344 /* stats z (debug and memory info) */
4345 if (!strcasecmp(parameters[0],"z"))
4347 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4348 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4349 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4350 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4351 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4352 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4353 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4354 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4358 if (!strcasecmp(parameters[0],"o"))
4360 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
4362 char LoginName[MAXBUF];
4363 char HostName[MAXBUF];
4364 char OperType[MAXBUF];
4365 ConfValue("oper","name",i,LoginName,&config_f);
4366 ConfValue("oper","host",i,HostName,&config_f);
4367 ConfValue("oper","type",i,OperType,&config_f);
4368 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4372 /* stats l (show user I/O stats) */
4373 if (!strcasecmp(parameters[0],"l"))
4375 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4376 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4378 if (isnick(i->second->nick))
4380 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);
4384 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);
4390 /* stats u (show server uptime) */
4391 if (!strcasecmp(parameters[0],"u"))
4393 time_t current_time = 0;
4394 current_time = time(NULL);
4395 time_t server_uptime = current_time - startup_time;
4397 stime = gmtime(&server_uptime);
4398 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4399 * Craig suggested this, and it seemed a good idea so in it went */
4400 if (stime->tm_year > 70)
4402 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);
4406 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);
4410 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4411 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4415 void handle_connect(char **parameters, int pcnt, userrec *user)
4417 char Link_ServerName[1024];
4418 char Link_IPAddr[1024];
4419 char Link_Port[1024];
4420 char Link_Pass[1024];
4424 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4426 ConfValue("link","name",i,Link_ServerName,&config_f);
4427 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4428 ConfValue("link","port",i,Link_Port,&config_f);
4429 ConfValue("link","sendpass",i,Link_Pass,&config_f);
4430 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4431 LinkPort = atoi(Link_Port);
4432 if (match(Link_ServerName,parameters[0])) {
4438 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4442 // TODO: Perform a check here to stop a server being linked twice!
4444 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4446 if (me[defaultRoute])
4449 // at this point parameters[0] is an ip in a string.
4450 // TODO: Look this up from the <link> blocks instead!
4451 for (int j = 0; j < 255; j++) {
4452 if (servers[j] == NULL) {
4453 servers[j] = new serverrec;
4454 strcpy(servers[j]->internal_addr,Link_IPAddr);
4455 strcpy(servers[j]->name,Link_ServerName);
4456 log(DEBUG,"Allocated new serverrec");
4457 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4459 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4464 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4468 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);
4472 void handle_squit(char **parameters, int pcnt, userrec *user)
4474 // send out an squit across the mesh and then clear the server list (for local squit)
4477 void handle_oper(char **parameters, int pcnt, userrec *user)
4479 char LoginName[MAXBUF];
4480 char Password[MAXBUF];
4481 char OperType[MAXBUF];
4482 char TypeName[MAXBUF];
4483 char Hostname[MAXBUF];
4486 for (i = 0; i < ConfValueEnum("oper",&config_f); i++)
4488 ConfValue("oper","name",i,LoginName,&config_f);
4489 ConfValue("oper","password",i,Password,&config_f);
4490 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4492 /* correct oper credentials */
4493 ConfValue("oper","type",i,OperType,&config_f);
4494 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4495 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4496 WriteServ(user->fd,"MODE %s :+o",user->nick);
4497 for (j =0; j < ConfValueEnum("type",&config_f); j++)
4499 ConfValue("type","name",j,TypeName,&config_f);
4500 if (!strcmp(TypeName,OperType))
4502 /* found this oper's opertype */
4503 ConfValue("type","host",j,Hostname,&config_f);
4504 strncpy(user->dhost,Hostname,256);
4507 if (!strchr(user->modes,'o'))
4509 strcat(user->modes,"o");
4511 FOREACH_MOD OnOper(user);
4516 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4517 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4520 void handle_nick(char **parameters, int pcnt, userrec *user)
4524 log(DEBUG,"not enough params for handle_nick");
4529 log(DEBUG,"invalid parameter passed to handle_nick");
4532 if (!strlen(parameters[0]))
4534 log(DEBUG,"zero length new nick passed to handle_nick");
4539 log(DEBUG,"invalid user passed to handle_nick");
4544 log(DEBUG,"invalid old nick passed to handle_nick");
4547 if (!strcasecmp(user->nick,parameters[0]))
4549 log(DEBUG,"old nick is new nick, skipping");
4554 if (strlen(parameters[0]) > 1)
4556 if (parameters[0][0] == ':')
4561 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4563 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4567 if (isnick(parameters[0]) == 0)
4569 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4573 if (user->registered == 7)
4575 WriteCommon(user,"NICK %s",parameters[0]);
4578 /* change the nick of the user in the users_hash */
4579 user = ReHashNick(user->nick, parameters[0]);
4580 /* actually change the nick within the record */
4582 if (!user->nick) return;
4584 strncpy(user->nick, parameters[0],NICKMAX);
4586 log(DEBUG,"new nick set: %s",user->nick);
4588 if (user->registered < 3)
4589 user->registered = (user->registered | 2);
4590 if (user->registered == 3)
4592 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4595 log(DEBUG,"exit nickchange: %s",user->nick);
4598 void force_nickchange(userrec* user,const char* newnick)
4607 strncpy(nick,newnick,MAXBUF);
4609 if (user->registered == 7)
4613 handle_nick(pars,1,user);
4619 int process_parameters(char **command_p,char *parameters)
4624 q = strlen(parameters);
4627 /* no parameters, command_p invalid! */
4630 if (parameters[0] == ':')
4632 command_p[0] = parameters+1;
4637 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4639 /* only one parameter */
4640 command_p[0] = parameters;
4641 if (parameters[0] == ':')
4643 if (strchr(parameters,' ') != NULL)
4651 command_p[j++] = parameters;
4652 for (i = 0; i <= q; i++)
4654 if (parameters[i] == ' ')
4656 command_p[j++] = parameters+i+1;
4657 parameters[i] = '\0';
4658 if (command_p[j-1][0] == ':')
4660 *command_p[j-1]++; /* remove dodgy ":" */
4662 /* parameter like this marks end of the sequence */
4666 return j; /* returns total number of items in the list */
4669 void process_command(userrec *user, char* cmd)
4673 char *command_p[127];
4674 char p[MAXBUF], temp[MAXBUF];
4675 int i, j, items, cmd_found;
4677 for (int i = 0; i < 127; i++)
4678 command_p[i] = NULL;
4688 if (!strcmp(cmd,""))
4693 int total_params = 0;
4696 for (int q = 0; q < strlen(cmd)-1; q++)
4698 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
4701 // found a 'trailing', we dont count them after this.
4709 // another phidjit bug...
4710 if (total_params > 126)
4712 kill_link(user,"Protocol violation");
4719 FOREACH_MOD OnServerRaw(tmp,true);
4720 const char* cmd2 = tmp.c_str();
4721 snprintf(cmd,512,"%s",cmd2);
4723 if (!strchr(cmd,' '))
4725 /* no parameters, lets skip the formalities and not chop up
4727 log(DEBUG,"About to preprocess command with no params");
4729 command_p[0] = NULL;
4731 for (int i = 0; i <= strlen(cmd); i++)
4733 cmd[i] = toupper(cmd[i]);
4735 log(DEBUG,"Preprocess done");
4741 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4742 for (i = 0; i < strlen(temp); i++)
4744 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4750 /* split the full string into a command plus parameters */
4754 if (strchr(cmd,' '))
4756 for (i = 0; i <= strlen(cmd); i++)
4758 /* capitalise the command ONLY, leave params intact */
4759 cmd[i] = toupper(cmd[i]);
4760 /* are we nearly there yet?! :P */
4764 parameters = cmd+i+1;
4772 for (i = 0; i <= strlen(cmd); i++)
4774 cmd[i] = toupper(cmd[i]);
4782 if (strlen(command)>MAXCOMMAND)
4784 kill_link(user,"Protocol violation");
4788 for (int x = 0; x < strlen(command); x++)
4790 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
4792 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
4794 kill_link(user,"Protocol violation");
4800 for (i = 0; i != cmdlist.size(); i++)
4802 if (strcmp(cmdlist[i].command,""))
4804 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
4806 log(DEBUG,"Found matching command");
4810 if (strcmp(parameters,""))
4812 items = process_parameters(command_p,parameters);
4817 command_p[0] = NULL;
4823 command_p[0] = NULL;
4828 log(DEBUG,"Processing command");
4830 /* activity resets the ping pending timer */
4831 user->nping = time(NULL) + 120;
4832 if ((items) < cmdlist[i].min_params)
4834 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4835 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4838 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4840 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4841 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4845 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4847 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
4849 if ((!isnick(user->nick)) || (user->registered != 7))
4851 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4852 WriteServ(user->fd,"451 %s :You have not registered",command);
4856 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4858 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4859 if (cmdlist[i].handler_function)
4861 /* ikky /stats counters */
4866 user->bytes_in += strlen(temp);
4869 cmdlist[i].use_count++;
4870 cmdlist[i].total_bytes+=strlen(temp);
4873 /* WARNING: nothing may come after the
4874 * command handler call, as the handler
4875 * may free the user structure! */
4877 cmdlist[i].handler_function(command_p,items,user);
4883 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4884 WriteServ(user->fd,"451 %s :You have not registered",command);
4892 if ((!cmd_found) && (user))
4894 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4895 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4900 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4903 /* create the command and push it onto the table */
4904 strcpy(comm.command,cmd);
4905 comm.handler_function = f;
4906 comm.flags_needed = flags;
4907 comm.min_params = minparams;
4909 comm.total_bytes = 0;
4910 cmdlist.push_back(comm);
4911 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4914 void SetupCommandTable(void)
4916 createcommand("USER",handle_user,0,4);
4917 createcommand("NICK",handle_nick,0,1);
4918 createcommand("QUIT",handle_quit,0,0);
4919 createcommand("VERSION",handle_version,0,0);
4920 createcommand("PING",handle_ping,0,1);
4921 createcommand("PONG",handle_pong,0,1);
4922 createcommand("ADMIN",handle_admin,0,0);
4923 createcommand("PRIVMSG",handle_privmsg,0,2);
4924 createcommand("INFO",handle_info,0,0);
4925 createcommand("TIME",handle_time,0,0);
4926 createcommand("WHOIS",handle_whois,0,1);
4927 createcommand("WALLOPS",handle_wallops,'o',1);
4928 createcommand("NOTICE",handle_notice,0,2);
4929 createcommand("JOIN",handle_join,0,1);
4930 createcommand("NAMES",handle_names,0,1);
4931 createcommand("PART",handle_part,0,1);
4932 createcommand("KICK",handle_kick,0,2);
4933 createcommand("MODE",handle_mode,0,1);
4934 createcommand("TOPIC",handle_topic,0,1);
4935 createcommand("WHO",handle_who,0,1);
4936 createcommand("MOTD",handle_motd,0,0);
4937 createcommand("RULES",handle_rules,0,0);
4938 createcommand("OPER",handle_oper,0,2);
4939 createcommand("LIST",handle_list,0,0);
4940 createcommand("DIE",handle_die,'o',1);
4941 createcommand("RESTART",handle_restart,'o',1);
4942 createcommand("KILL",handle_kill,'o',2);
4943 createcommand("REHASH",handle_rehash,'o',0);
4944 createcommand("LUSERS",handle_lusers,0,0);
4945 createcommand("STATS",handle_stats,0,1);
4946 createcommand("USERHOST",handle_userhost,0,1);
4947 createcommand("AWAY",handle_away,0,0);
4948 createcommand("ISON",handle_ison,0,0);
4949 createcommand("SUMMON",handle_summon,0,0);
4950 createcommand("USERS",handle_users,0,0);
4951 createcommand("INVITE",handle_invite,0,2);
4952 createcommand("PASS",handle_pass,0,1);
4953 createcommand("TRACE",handle_trace,'o',0);
4954 createcommand("WHOWAS",handle_whowas,0,1);
4955 createcommand("CONNECT",handle_connect,'o',1);
4956 createcommand("SQUIT",handle_squit,'o',1);
4957 createcommand("MODULES",handle_modules,'o',0);
4960 void process_buffer(userrec *user)
4964 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4971 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4974 if (!strcmp(user->inbuf,""))
4978 strncpy(cmd,user->inbuf,MAXBUF);
4979 if (!strcmp(cmd,""))
4983 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4985 cmd[strlen(cmd)-1] = '\0';
4987 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4989 cmd[strlen(cmd)-1] = '\0';
4991 strcpy(user->inbuf,"");
4992 if (!strcmp(cmd,""))
4996 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4998 if ((user) && (cmd))
5000 process_command(user,cmd);
5004 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5006 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
5010 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
5012 char response[10240];
5013 char token = udp_msg[0];
5014 char* params = udp_msg + 2;
5015 char finalparam[1024];
5016 strcpy(finalparam," :xxxx");
5017 if (strstr(params," :")) {
5018 strncpy(finalparam,strstr(params," :"),1024);
5021 // S test.chatspike.net password :ChatSpike InspIRCd test server
5022 char* servername = strtok(params," ");
5023 char* password = strtok(NULL," ");
5024 char* serverdesc = finalparam+2;
5025 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
5028 char Link_ServerName[1024];
5029 char Link_IPAddr[1024];
5030 char Link_Port[1024];
5031 char Link_Pass[1024];
5032 char Link_SendPass[1024];
5035 // search for a corresponding <link> block in the config files
5036 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5038 ConfValue("link","name",i,Link_ServerName,&config_f);
5039 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5040 ConfValue("link","port",i,Link_Port,&config_f);
5041 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5042 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5043 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5044 LinkPort = atoi(Link_Port);
5045 if (!strcasecmp(Link_ServerName,servername)) {
5046 if (!strcasecmp(Link_IPAddr,udp_host)) {
5047 if (LinkPort == udp_port) {
5048 // we have a matching link line -
5049 // send a 'diminutive' server message back...
5050 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
5051 serv->SendPacket(response,udp_host,udp_port,0);
5052 WriteOpers("CONNECT from %s accepted, authenticating",servername);
5053 for (int j = 0; j < 255; j++) {
5054 if (servers[j] == NULL) {
5055 servers[j] = new serverrec;
5056 strcpy(servers[j]->internal_addr,udp_host);
5057 strcpy(servers[j]->name,servername);
5058 // create a server record for this server
5059 snprintf(response,10240,"O %d",MyKey);
5060 serv->SendPacket(response,udp_host,udp_port,0);
5064 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
5068 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5072 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5076 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5079 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5080 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5085 // if this is received, this means the server-ip that sent it said "OK" to credentials.
5086 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
5087 // array, which is only added by an 'S' packet or BeginLink().
5088 for (int i = 0; i < 255; i++) {
5089 if (servers[i] != NULL) {
5090 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
5091 servers[i]->key = atoi(params);
5092 log(DEBUG,"Key for this server is now %d",servers[i]->key);
5093 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
5098 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
5102 // S test.chatspike.net password :ChatSpike InspIRCd test server
5103 char* servername = strtok(params," ");
5104 char* password = strtok(NULL," ");
5105 char* serverdesc = finalparam+2;
5107 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5108 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5109 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5110 // a connect, so put out an oper alert!
5115 // for now, just accept all, we'll fix that later.
5116 WriteOpers("%s accepted our link credentials ",servername);
5118 char Link_ServerName[1024];
5119 char Link_IPAddr[1024];
5120 char Link_Port[1024];
5121 char Link_Pass[1024];
5122 char Link_SendPass[1024];
5125 // search for a corresponding <link> block in the config files
5126 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5128 ConfValue("link","name",i,Link_ServerName,&config_f);
5129 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5130 ConfValue("link","port",i,Link_Port,&config_f);
5131 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5132 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5133 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5134 LinkPort = atoi(Link_Port);
5135 if (!strcasecmp(Link_ServerName,servername)) {
5136 if (!strcasecmp(Link_IPAddr,udp_host)) {
5137 if (LinkPort == udp_port) {
5138 // matching link at this end too, we're all done!
5139 // at this point we must begin key exchange and insert this
5140 // server into our 'active' table.
5141 for (int j = 0; j < 255; j++) {
5142 if (servers[j] != NULL) {
5143 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5144 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5145 snprintf(response,10240,"O %d",MyKey);
5146 serv->SendPacket(response,udp_host,udp_port,0);
5151 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5156 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5160 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5164 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5167 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5168 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5173 char* error_message = finalparam+2;
5174 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5175 // remove this server from any lists
5176 for (int j = 0; j < 255; j++) {
5177 if (servers[j] != NULL) {
5178 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5188 serverrec* source_server = NULL;
5190 for (int j = 0; j < 255; j++) {
5191 if (servers[j] != NULL) {
5192 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5193 if (servers[j]->key == theirkey) {
5194 // found a valid key for this server, can process restricted stuff here
5195 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5203 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5207 int reap_counter = 0;
5211 struct sockaddr_in client, server;
5212 char addrs[MAXBUF][255];
5213 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5215 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5216 int selectResult = 0;
5217 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5218 char resolvedHost[MAXBUF];
5222 log_file = fopen("ircd.log","a+");
5225 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5229 log(DEBUG,"InspIRCd: startup: begin");
5233 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5235 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5237 SetupCommandTable();
5238 log(DEBUG,"InspIRCd: startup: default command table set up");
5241 if (strcmp(DieValue,""))
5243 printf("WARNING: %s\n\n",DieValue);
5246 log(DEBUG,"InspIRCd: startup: read config");
5248 int count2 = 0, count3 = 0;
5250 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5252 ConfValue("bind","port",count,configToken,&config_f);
5253 ConfValue("bind","address",count,Addr,&config_f);
5254 ConfValue("bind","type",count,Type,&config_f);
5255 if (!strcmp(Type,"servers"))
5257 char Default[MAXBUF];
5258 strcpy(Default,"no");
5259 ConfValue("bind","default",count,Default,&config_f);
5260 if (strchr(Default,'y'))
5262 defaultRoute = count3;
5263 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5265 me[count3] = new serverrec(ServerName,100L,false);
5266 me[count3]->CreateListener(Addr,atoi(configToken));
5271 ports[count2] = atoi(configToken);
5272 strcpy(addrs[count2],Addr);
5275 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5278 UDPportCount = count3;
5280 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5282 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5286 /* BugFix By Craig! :p */
5288 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5290 char modfile[MAXBUF];
5291 ConfValue("module","name",count2,configToken,&config_f);
5292 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5293 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5294 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5295 /* If The File Doesnt exist, Trying to load it
5296 * Will Segfault the IRCd.. So, check to see if
5297 * it Exists, Before Proceeding. */
5298 if (FileExists(modfile))
5300 factory[count] = new ircd_module(modfile);
5301 if (factory[count]->LastError())
5303 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5304 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5307 if (factory[count]->factory)
5309 modules[count] = factory[count]->factory->CreateModule();
5310 /* save the module and the module's classfactory, if
5311 * this isnt done, random crashes can occur :/ */
5312 module_names.push_back(modfile);
5316 log(DEBUG,"Unable to load %s",modfile);
5317 sprintf("Unable to load %s\nExiting...\n",modfile);
5320 /* Increase the Count */
5325 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5326 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5329 MODCOUNT = count - 1;
5330 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5332 printf("\nInspIRCd is now running!\n");
5334 startup_time = time(NULL);
5338 log(VERBOSE,"Not forking as -nofork was specified");
5342 if (DaemonSeed() == ERROR)
5344 log(DEBUG,"InspIRCd: startup: can't daemonise");
5345 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5351 /* setup select call */
5352 FD_ZERO(&selectFds);
5353 log(DEBUG,"InspIRCd: startup: zero selects");
5354 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5356 for (count = 0; count < portCount; count++)
5358 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5360 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5363 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5365 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5367 else /* well we at least bound to one socket so we'll continue */
5373 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5375 /* if we didn't bind to anything then abort */
5376 if (boundPortCount == 0)
5378 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5382 length = sizeof (client);
5383 int flip_flop = 0, udp_port = 0;
5384 char udp_msg[MAXBUF], udp_host[MAXBUF];
5386 /* main loop for multiplexing/resetting */
5389 /* set up select call */
5390 for (count = 0; count < boundPortCount; count++)
5392 FD_SET (openSockfd[count], &selectFds);
5395 /* added timeout! select was waiting forever... wank... :/ */
5406 vector<int>::iterator niterator;
5409 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5410 // them in a list, then reap the list every second or so.
5411 if (reap_counter>5000) {
5412 if (fd_reap.size() > 0) {
5413 for( int n = 0; n < fd_reap.size(); n++)
5415 Blocking(fd_reap[n]);
5417 NonBlocking(fd_reap[n]);
5426 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5428 for (int x = 0; x != UDPportCount; x++)
5431 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5433 if (strlen(udp_msg)<1) {
5434 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5438 FOREACH_MOD OnPacketReceive(udp_msg);
5439 // Packets must go back via the route they arrived on :)
5440 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5445 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5449 if (!count2->second) break;
5452 if (count2->second->fd)
5454 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5455 // their connection class.
5456 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
5458 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5459 kill_link(count2->second,"Registration timeout");
5462 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5464 if (!count2->second->lastping)
5466 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5467 kill_link(count2->second,"Ping timeout");
5470 Write(count2->second->fd,"PING :%s",ServerName);
5471 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5472 count2->second->lastping = 0;
5473 count2->second->nping = time(NULL)+120;
5476 result = read(count2->second->fd, data, 1);
5477 // result EAGAIN means nothing read
5478 if (result == EAGAIN)
5486 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5487 kill_link(count2->second,"Client exited");
5488 // must bail here? kill_link removes the hash, corrupting the iterator
5489 log(DEBUG,"Bailing from client exit");
5493 else if (result > 0)
5498 // until the buffer is at 509 chars anything can be inserted into it.
5499 if ((strlen(count2->second->inbuf) < 509) && (data[0] != '\0')) {
5500 strncat(count2->second->inbuf, data, result);
5503 // once you reach 509 chars, only a \r or \n can be inserted,
5504 // completing the line.
5505 if ((strlen(count2->second->inbuf) >= 509) && ((data[0] == '\r') || (data[0] == '\n'))) {
5506 count2->second->inbuf[509] = '\r';
5507 count2->second->inbuf[510] = '\n';
5508 count2->second->inbuf[511] = '\0';
5509 process_buffer(count2->second);
5513 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5515 /* at least one complete line is waiting to be processed */
5516 if (!count2->second->fd)
5520 if (strlen(count2->second->inbuf)<512)
5522 // double check the length before processing!
5523 process_buffer(count2->second);
5527 strcpy(count2->second->inbuf,"");
5537 /* select is reporting a waiting socket. Poll them all to find out which */
5538 if (selectResult > 0)
5540 char target[MAXBUF], resolved[MAXBUF];
5541 for (count = 0; count < boundPortCount; count++)
5543 if (FD_ISSET (openSockfd[count], &selectFds))
5545 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5547 address_cache::iterator iter = IP.find(client.sin_addr);
5548 bool iscached = false;
5549 if (iter == IP.end())
5551 /* ip isn't in cache, add it */
5552 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5553 if(CleanAndResolve(resolved, target) != TRUE)
5555 strncpy(resolved,target,MAXBUF);
5557 /* hostname now in 'target' */
5558 IP[client.sin_addr] = new string(resolved);
5559 /* hostname in cache */
5563 /* found ip (cached) */
5564 strncpy(resolved, iter->second->c_str(), MAXBUF);
5568 if (incomingSockfd < 0)
5570 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5571 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5574 AddClient(incomingSockfd, resolved, ports[count], iscached);
5575 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5582 close (incomingSockfd);