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 WriteServ(user->fd,"407 %s :Too many targets in list, message not delivered.",blog[j-1]);
2996 strcpy(blog[j++],param);
2999 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3004 if ((joins) && (keystr))
3006 if (strchr(keystr,','))
3010 t2 = strlen(keystr);
3011 for (i = 0; i < t2; i++)
3013 if (keystr[i] == ',')
3016 strcpy(blog2[j++],param);
3020 strcpy(blog2[j++],param);
3027 // limit the total items in a comma seperated list
3028 // a phidjit bug... go figure.
3032 for (j = 0; j < total; j++)
3038 for (q = end; q < pcnt-1; q++)
3040 if (parameters[q+1])
3042 pars[q-end+1] = parameters[q+1];
3045 if ((joins) && (parameters[1]))
3056 /* repeatedly call the function with the hacked parameter list */
3057 if ((joins) && (pcnt > 1))
3061 // pars[1] already set up and containing key from blog2[j]
3066 pars[1] = parameters[1];
3072 fn(pars,pcnt-(end-start),u);
3080 void handle_join(char **parameters, int pcnt, userrec *user)
3085 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3087 if (parameters[0][0] == '#')
3089 Ptr = add_channel(user,parameters[0],parameters[1]);
3094 void handle_part(char **parameters, int pcnt, userrec *user)
3100 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3102 del_channel(user,parameters[0],parameters[1]);
3106 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3108 del_channel(user,parameters[0],NULL);
3112 void handle_kick(char **parameters, int pcnt, userrec *user)
3114 chanrec* Ptr = FindChan(parameters[0]);
3115 userrec* u = Find(parameters[1]);
3119 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3123 if (!has_channel(u,Ptr))
3125 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3131 char reason[MAXBUF];
3132 strncpy(reason,parameters[2],MAXBUF);
3133 if (strlen(reason)>MAXKICK)
3135 reason[MAXKICK-1] = '\0';
3138 kick_channel(user,u,Ptr,reason);
3142 kick_channel(user,u,Ptr,user->nick);
3147 void handle_die(char **parameters, int pcnt, userrec *user)
3149 log(DEBUG,"die: %s",user->nick);
3150 if (!strcmp(parameters[0],diepass))
3152 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3158 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3162 void handle_restart(char **parameters, int pcnt, userrec *user)
3164 log(DEBUG,"restart: %s",user->nick);
3165 if (!strcmp(parameters[0],restartpass))
3167 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3170 /* Will finish this later when i can be arsed :) */
3174 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3179 void kill_link(userrec *user,const char* r)
3181 user_hash::iterator iter = clientlist.find(user->nick);
3183 char reason[MAXBUF];
3185 strncpy(reason,r,MAXBUF);
3187 if (strlen(reason)>MAXQUIT)
3189 reason[MAXQUIT-1] = '\0';
3192 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3193 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3194 log(DEBUG,"closing fd %d",user->fd);
3196 /* bugfix, cant close() a nonblocking socket (sux!) */
3197 if (user->registered == 7) {
3198 FOREACH_MOD OnUserQuit(user);
3199 WriteCommonExcept(user,"QUIT :%s",reason);
3202 /* push the socket on a stack of sockets due to be closed at the next opportunity
3203 * 'Client exited' is an exception to this as it means the client side has already
3204 * closed the socket, we don't need to do it.
3206 fd_reap.push_back(user->fd);
3208 bool do_purge = false;
3210 if (user->registered == 7) {
3211 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3215 if (iter != clientlist.end())
3217 log(DEBUG,"deleting user hash value %d",iter->second);
3218 if ((iter->second) && (user->registered == 7)) {
3219 delete iter->second;
3221 clientlist.erase(iter);
3224 if (user->registered == 7) {
3225 purge_empty_chans();
3230 void handle_kill(char **parameters, int pcnt, userrec *user)
3232 userrec *u = Find(parameters[0]);
3233 char killreason[MAXBUF];
3235 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3238 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3239 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3240 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3241 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3242 kill_link(u,killreason);
3246 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3250 void handle_summon(char **parameters, int pcnt, userrec *user)
3252 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3255 void handle_users(char **parameters, int pcnt, userrec *user)
3257 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3261 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3263 char* Passwd(userrec *user)
3265 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3267 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3275 bool IsDenied(userrec *user)
3277 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3279 if (match(user->host,i->host) && (i->type == CC_DENY))
3289 void handle_pass(char **parameters, int pcnt, userrec *user)
3291 // Check to make sure they havnt registered -- Fix by FCS
3292 if (user->registered == 7)
3294 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3297 if (!strcasecmp(parameters[0],Passwd(user)))
3299 user->haspassed = true;
3303 void handle_invite(char **parameters, int pcnt, userrec *user)
3305 userrec* u = Find(parameters[0]);
3306 chanrec* c = FindChan(parameters[1]);
3312 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3318 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3327 if (cstatus(user,c) < STATUS_HOP)
3329 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
3333 if (has_channel(u,c))
3335 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
3338 if (!has_channel(user,c))
3340 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
3343 u->InviteTo(c->name);
3344 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3345 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3348 void handle_topic(char **parameters, int pcnt, userrec *user)
3354 if (strlen(parameters[0]) <= CHANMAX)
3356 Ptr = FindChan(parameters[0]);
3361 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3362 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3366 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3371 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3378 if (strlen(parameters[0]) <= CHANMAX)
3380 Ptr = FindChan(parameters[0]);
3383 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3385 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
3390 strncpy(topic,parameters[1],MAXBUF);
3391 if (strlen(topic)>MAXTOPIC)
3393 topic[MAXTOPIC-1] = '\0';
3396 strcpy(Ptr->topic,topic);
3397 strcpy(Ptr->setby,user->nick);
3398 Ptr->topicset = time(NULL);
3399 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3403 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3409 /* sends out an error notice to all connected clients (not to be used
3412 void send_error(char *s)
3414 log(DEBUG,"send_error: %s",s);
3415 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3417 if (isnick(i->second->nick))
3419 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3423 // fix - unregistered connections receive ERROR, not NOTICE
3424 Write(i->second->fd,"ERROR :%s",s);
3429 void Error(int status)
3431 signal (SIGALRM, SIG_IGN);
3432 signal (SIGPIPE, SIG_IGN);
3433 signal (SIGTERM, SIG_IGN);
3434 signal (SIGABRT, SIG_IGN);
3435 signal (SIGSEGV, SIG_IGN);
3436 signal (SIGURG, SIG_IGN);
3437 signal (SIGKILL, SIG_IGN);
3438 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3439 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3444 int main (int argc, char *argv[])
3447 log(DEBUG,"*** InspIRCd starting up!");
3448 if (!FileExists(CONFIG_FILE))
3450 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3451 log(DEBUG,"main: no config");
3452 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3456 if (!strcmp(argv[1],"-nofork")) {
3460 if (InspIRCd() == ERROR)
3462 log(DEBUG,"main: daemon function bailed");
3463 printf("ERROR: could not initialise. Shutting down.\n");
3470 template<typename T> inline string ConvToStr(const T &in)
3473 if (!(tmp << in)) return string();
3477 /* re-allocates a nick in the user_hash after they change nicknames,
3478 * returns a pointer to the new user as it may have moved */
3480 userrec* ReHashNick(char* Old, char* New)
3482 user_hash::iterator newnick;
3483 user_hash::iterator oldnick = clientlist.find(Old);
3485 log(DEBUG,"ReHashNick: %s %s",Old,New);
3487 if (!strcasecmp(Old,New))
3489 log(DEBUG,"old nick is new nick, skipping");
3490 return oldnick->second;
3493 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3495 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3497 clientlist[New] = new userrec();
3498 clientlist[New] = oldnick->second;
3499 /*delete oldnick->second; */
3500 clientlist.erase(oldnick);
3502 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3504 return clientlist[New];
3507 /* adds or updates an entry in the whowas list */
3508 void AddWhoWas(userrec* u)
3510 user_hash::iterator iter = whowas.find(u->nick);
3511 userrec *a = new userrec();
3512 strcpy(a->nick,u->nick);
3513 strcpy(a->ident,u->ident);
3514 strcpy(a->dhost,u->dhost);
3515 strcpy(a->host,u->host);
3516 strcpy(a->fullname,u->fullname);
3517 strcpy(a->server,u->server);
3518 a->signon = u->signon;
3520 /* MAX_WHOWAS: max number of /WHOWAS items
3521 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3522 * can be replaced by a newer one
3525 if (iter == whowas.end())
3527 if (whowas.size() == WHOWAS_MAX)
3529 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3531 // 3600 seconds in an hour ;)
3532 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3536 log(DEBUG,"added WHOWAS entry, purged an old record");
3543 log(DEBUG,"added fresh WHOWAS entry");
3544 whowas[a->nick] = a;
3549 log(DEBUG,"updated WHOWAS entry");
3550 delete iter->second;
3556 /* add a client connection to the sockets list */
3557 void AddClient(int socket, char* host, int port, bool iscached)
3561 char resolved[MAXBUF];
3564 user_hash::iterator iter;
3566 tempnick = ConvToStr(socket) + "-unknown";
3567 sprintf(tn2,"%d-unknown",socket);
3569 iter = clientlist.find(tempnick);
3571 if (iter != clientlist.end()) return;
3574 * It is OK to access the value here this way since we know
3575 * it exists, we just created it above.
3577 * At NO other time should you access a value in a map or a
3578 * hash_map this way.
3580 clientlist[tempnick] = new userrec();
3582 NonBlocking(socket);
3583 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3585 clientlist[tempnick]->fd = socket;
3586 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3587 strncpy(clientlist[tempnick]->host, host,160);
3588 strncpy(clientlist[tempnick]->dhost, host,160);
3589 strncpy(clientlist[tempnick]->server, ServerName,256);
3590 strncpy(clientlist[tempnick]->ident, "unknown",9);
3591 clientlist[tempnick]->registered = 0;
3592 clientlist[tempnick]->signon = time(NULL);
3593 clientlist[tempnick]->nping = time(NULL)+240;
3594 clientlist[tempnick]->lastping = 1;
3595 clientlist[tempnick]->port = port;
3599 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3603 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3606 // set the registration timeout for this user
3607 unsigned long class_regtimeout = 90;
3608 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3610 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3612 class_regtimeout = (unsigned long)i->registration_timeout;
3616 log(DEBUG,"Client has a connection timeout value of %d",class_regtimeout);
3617 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3619 if (clientlist.size() == MAXCLIENTS)
3620 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3623 void handle_names(char **parameters, int pcnt, userrec *user)
3627 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3629 c = FindChan(parameters[0]);
3632 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3634 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3638 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3643 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3648 user->idle_lastmsg = time(NULL);
3650 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3652 if (parameters[0][0] == '#')
3654 chan = FindChan(parameters[0]);
3657 if ((chan->noexternal) && (!has_channel(user,chan)))
3659 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3662 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3664 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3670 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3675 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3679 /* no such nick/channel */
3680 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3685 dest = Find(parameters[0]);
3688 if (strcmp(dest->awaymsg,""))
3690 /* auto respond with aweh msg */
3691 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3696 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
3701 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3705 /* no such nick/channel */
3706 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3710 void handle_notice(char **parameters, int pcnt, userrec *user)
3715 user->idle_lastmsg = time(NULL);
3717 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3719 if (parameters[0][0] == '#')
3721 chan = FindChan(parameters[0]);
3724 if ((chan->noexternal) && (!has_channel(user,chan)))
3726 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3729 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3731 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3737 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3742 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3746 /* no such nick/channel */
3747 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3752 dest = Find(parameters[0]);
3757 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
3762 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3766 /* no such nick/channel */
3767 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3773 char* chlist(userrec *user)
3778 log(DEBUG,"chlist: %s",user->nick);
3784 for (i = 0; i != MAXCHANS; i++)
3786 if (user->chans[i].channel != NULL)
3788 if (user->chans[i].channel->name)
3790 strcpy(cmp,user->chans[i].channel->name);
3792 if (!strstr(lst,cmp))
3794 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3796 strcat(lst,cmode(user,user->chans[i].channel));
3797 strcat(lst,user->chans[i].channel->name);
3807 void handle_info(char **parameters, int pcnt, userrec *user)
3809 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3810 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3811 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3812 FOREACH_MOD OnInfo(user);
3813 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3816 void handle_time(char **parameters, int pcnt, userrec *user)
3819 struct tm * timeinfo;
3822 timeinfo = localtime ( &rawtime );
3823 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3827 void handle_whois(char **parameters, int pcnt, userrec *user)
3832 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3834 dest = Find(parameters[0]);
3837 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3838 if (dest->registered == 7)
3840 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3841 if ((user == dest) || (strchr(user->modes,'o')))
3843 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3845 if (strcmp(chlist(dest),""))
3847 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3849 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3850 if (strcmp(dest->awaymsg,""))
3852 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3854 if (strchr(dest->modes,'o'))
3856 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3858 FOREACH_MOD OnWhois(user,dest);
3859 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3860 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3862 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3866 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3871 /* no such nick/channel */
3872 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3876 void handle_quit(char **parameters, int pcnt, userrec *user)
3878 user_hash::iterator iter = clientlist.find(user->nick);
3881 if (user->registered == 7)
3883 /* theres more to do here, but for now just close the socket */
3886 if (parameters[0][0] == ':')
3890 reason = parameters[0];
3892 if (strlen(reason)>MAXQUIT)
3894 reason[MAXQUIT-1] = '\0';
3897 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3898 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3899 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3903 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3904 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3905 WriteCommonExcept(user,"QUIT :Client exited");
3907 FOREACH_MOD OnUserQuit(user);
3911 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3912 fd_reap.push_back(user->fd);
3914 if (iter != clientlist.end())
3916 log(DEBUG,"deleting user hash value %d",iter->second);
3917 if ((iter->second) && (user->registered == 7)) {
3918 delete iter->second;
3920 clientlist.erase(iter);
3923 if (user->registered == 7) {
3924 purge_empty_chans();
3928 void handle_who(char **parameters, int pcnt, userrec *user)
3930 chanrec* Ptr = NULL;
3932 /* theres more to do here, but for now just close the socket */
3935 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3937 if (user->chans[0].channel)
3939 Ptr = user->chans[0].channel;
3940 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3942 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3944 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);
3950 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3954 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3958 if (parameters[0][0] = '#')
3960 Ptr = FindChan(parameters[0]);
3963 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3965 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3967 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);
3970 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3974 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3980 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3982 Ptr = user->chans[0].channel;
3983 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3985 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3987 if (strchr(i->second->modes,'o'))
3989 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);
3993 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3999 void handle_wallops(char **parameters, int pcnt, userrec *user)
4001 WriteWallOps(user,"%s",parameters[0]);
4004 void handle_list(char **parameters, int pcnt, userrec *user)
4008 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4009 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4011 if ((!i->second->c_private) && (!i->second->secret))
4013 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4016 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4020 void handle_rehash(char **parameters, int pcnt, userrec *user)
4022 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
4024 FOREACH_MOD OnRehash();
4025 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
4031 return clientlist.size();
4034 int usercount_invisible(void)
4038 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4040 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4045 int usercount_opers(void)
4049 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4051 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4056 int usercount_unknown(void)
4060 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4062 if ((i->second->fd) && (i->second->registered != 7))
4070 return chanlist.size();
4073 int servercount(void)
4078 void handle_lusers(char **parameters, int pcnt, userrec *user)
4080 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4081 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4082 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4083 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4084 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4087 void handle_admin(char **parameters, int pcnt, userrec *user)
4089 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4090 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4091 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4092 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4095 void ShowMOTD(userrec *user)
4099 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4102 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4103 for (int i = 0; i != MOTD.size(); i++)
4105 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4107 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4110 void ShowRULES(userrec *user)
4114 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4117 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4118 for (int i = 0; i != RULES.size(); i++)
4120 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4122 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4125 /* shows the message of the day, and any other on-logon stuff */
4126 void ConnectUser(userrec *user)
4128 user->registered = 7;
4129 user->idle_lastmsg = time(NULL);
4130 log(DEBUG,"ConnectUser: %s",user->nick);
4132 if (strcmp(Passwd(user),"") && (!user->haspassed))
4134 kill_link(user,"Invalid password");
4139 kill_link(user,"Unauthorised connection");
4143 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4144 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4145 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4146 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4147 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4148 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);
4149 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);
4151 FOREACH_MOD OnUserConnect(user);
4152 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4155 void handle_version(char **parameters, int pcnt, userrec *user)
4157 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4160 void handle_ping(char **parameters, int pcnt, userrec *user)
4162 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4165 void handle_pong(char **parameters, int pcnt, userrec *user)
4167 // set the user as alive so they survive to next ping
4171 void handle_motd(char **parameters, int pcnt, userrec *user)
4176 void handle_rules(char **parameters, int pcnt, userrec *user)
4181 void handle_user(char **parameters, int pcnt, userrec *user)
4183 if (user->registered < 3)
4185 if (isident(parameters[0]) == 0) {
4186 // This kinda Sucks, According to the RFC thou, its either this,
4187 // or "You have already registered" :p -- Craig
4188 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4191 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4192 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4193 strncat(user->ident,parameters[0],IDENTMAX);
4194 strncpy(user->fullname,parameters[3],128);
4195 user->registered = (user->registered | 1);
4200 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4203 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4204 if (user->registered == 3)
4206 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4211 void handle_userhost(char **parameters, int pcnt, userrec *user)
4213 char Return[MAXBUF],junk[MAXBUF];
4214 sprintf(Return,"302 %s :",user->nick);
4215 for (int i = 0; i < pcnt; i++)
4217 userrec *u = Find(parameters[i]);
4220 if (strchr(u->modes,'o'))
4222 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4223 strcat(Return,junk);
4227 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4228 strcat(Return,junk);
4232 WriteServ(user->fd,Return);
4236 void handle_ison(char **parameters, int pcnt, userrec *user)
4238 char Return[MAXBUF];
4239 sprintf(Return,"303 %s :",user->nick);
4240 for (int i = 0; i < pcnt; i++)
4242 userrec *u = Find(parameters[i]);
4245 strcat(Return,u->nick);
4249 WriteServ(user->fd,Return);
4253 void handle_away(char **parameters, int pcnt, userrec *user)
4257 strcpy(user->awaymsg,parameters[0]);
4258 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4262 strcpy(user->awaymsg,"");
4263 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4267 void handle_whowas(char **parameters, int pcnt, userrec* user)
4269 user_hash::iterator i = whowas.find(parameters[0]);
4271 if (i == whowas.end())
4273 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4274 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4278 time_t rawtime = i->second->signon;
4282 timeinfo = localtime(&rawtime);
4283 strcpy(b,asctime(timeinfo));
4284 b[strlen(b)-1] = '\0';
4286 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4287 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4288 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4293 void handle_trace(char **parameters, int pcnt, userrec *user)
4295 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4299 if (isnick(i->second->nick))
4301 if (strchr(i->second->modes,'o'))
4303 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4307 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4312 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4318 void handle_modules(char **parameters, int pcnt, userrec *user)
4320 for (int i = 0; i < module_names.size(); i++)
4322 Version V = modules[i]->GetVersion();
4323 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());
4327 void handle_stats(char **parameters, int pcnt, userrec *user)
4333 if (strlen(parameters[0])>1)
4335 /* make the stats query 1 character long */
4336 parameters[0][1] = '\0';
4339 /* stats m (list number of times each command has been used, plus bytecount) */
4340 if (!strcasecmp(parameters[0],"m"))
4342 for (int i = 0; i < cmdlist.size(); i++)
4344 if (cmdlist[i].handler_function)
4346 if (cmdlist[i].use_count)
4348 /* RPL_STATSCOMMANDS */
4349 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4356 /* stats z (debug and memory info) */
4357 if (!strcasecmp(parameters[0],"z"))
4359 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4360 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4361 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4362 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4363 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4364 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4365 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4366 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4370 if (!strcasecmp(parameters[0],"o"))
4372 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
4374 char LoginName[MAXBUF];
4375 char HostName[MAXBUF];
4376 char OperType[MAXBUF];
4377 ConfValue("oper","name",i,LoginName,&config_f);
4378 ConfValue("oper","host",i,HostName,&config_f);
4379 ConfValue("oper","type",i,OperType,&config_f);
4380 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4384 /* stats l (show user I/O stats) */
4385 if (!strcasecmp(parameters[0],"l"))
4387 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4388 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4390 if (isnick(i->second->nick))
4392 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);
4396 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);
4402 /* stats u (show server uptime) */
4403 if (!strcasecmp(parameters[0],"u"))
4405 time_t current_time = 0;
4406 current_time = time(NULL);
4407 time_t server_uptime = current_time - startup_time;
4409 stime = gmtime(&server_uptime);
4410 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4411 * Craig suggested this, and it seemed a good idea so in it went */
4412 if (stime->tm_year > 70)
4414 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);
4418 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);
4422 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4423 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4427 void handle_connect(char **parameters, int pcnt, userrec *user)
4429 char Link_ServerName[1024];
4430 char Link_IPAddr[1024];
4431 char Link_Port[1024];
4432 char Link_Pass[1024];
4436 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4438 ConfValue("link","name",i,Link_ServerName,&config_f);
4439 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4440 ConfValue("link","port",i,Link_Port,&config_f);
4441 ConfValue("link","sendpass",i,Link_Pass,&config_f);
4442 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4443 LinkPort = atoi(Link_Port);
4444 if (match(Link_ServerName,parameters[0])) {
4450 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4454 // TODO: Perform a check here to stop a server being linked twice!
4456 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4458 if (me[defaultRoute])
4461 // at this point parameters[0] is an ip in a string.
4462 // TODO: Look this up from the <link> blocks instead!
4463 for (int j = 0; j < 255; j++) {
4464 if (servers[j] == NULL) {
4465 servers[j] = new serverrec;
4466 strcpy(servers[j]->internal_addr,Link_IPAddr);
4467 strcpy(servers[j]->name,Link_ServerName);
4468 log(DEBUG,"Allocated new serverrec");
4469 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4471 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4476 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4480 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);
4484 void handle_squit(char **parameters, int pcnt, userrec *user)
4486 // send out an squit across the mesh and then clear the server list (for local squit)
4489 void handle_oper(char **parameters, int pcnt, userrec *user)
4491 char LoginName[MAXBUF];
4492 char Password[MAXBUF];
4493 char OperType[MAXBUF];
4494 char TypeName[MAXBUF];
4495 char Hostname[MAXBUF];
4498 for (i = 0; i < ConfValueEnum("oper",&config_f); i++)
4500 ConfValue("oper","name",i,LoginName,&config_f);
4501 ConfValue("oper","password",i,Password,&config_f);
4502 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4504 /* correct oper credentials */
4505 ConfValue("oper","type",i,OperType,&config_f);
4506 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4507 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4508 WriteServ(user->fd,"MODE %s :+o",user->nick);
4509 for (j =0; j < ConfValueEnum("type",&config_f); j++)
4511 ConfValue("type","name",j,TypeName,&config_f);
4512 if (!strcmp(TypeName,OperType))
4514 /* found this oper's opertype */
4515 ConfValue("type","host",j,Hostname,&config_f);
4516 strncpy(user->dhost,Hostname,256);
4519 if (!strchr(user->modes,'o'))
4521 strcat(user->modes,"o");
4523 FOREACH_MOD OnOper(user);
4528 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4529 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4532 void handle_nick(char **parameters, int pcnt, userrec *user)
4536 log(DEBUG,"not enough params for handle_nick");
4541 log(DEBUG,"invalid parameter passed to handle_nick");
4544 if (!strlen(parameters[0]))
4546 log(DEBUG,"zero length new nick passed to handle_nick");
4551 log(DEBUG,"invalid user passed to handle_nick");
4556 log(DEBUG,"invalid old nick passed to handle_nick");
4559 if (!strcasecmp(user->nick,parameters[0]))
4561 log(DEBUG,"old nick is new nick, skipping");
4566 if (strlen(parameters[0]) > 1)
4568 if (parameters[0][0] == ':')
4573 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4575 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4579 if (isnick(parameters[0]) == 0)
4581 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4585 if (user->registered == 7)
4587 WriteCommon(user,"NICK %s",parameters[0]);
4590 /* change the nick of the user in the users_hash */
4591 user = ReHashNick(user->nick, parameters[0]);
4592 /* actually change the nick within the record */
4594 if (!user->nick) return;
4596 strncpy(user->nick, parameters[0],NICKMAX);
4598 log(DEBUG,"new nick set: %s",user->nick);
4600 if (user->registered < 3)
4601 user->registered = (user->registered | 2);
4602 if (user->registered == 3)
4604 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4607 log(DEBUG,"exit nickchange: %s",user->nick);
4610 void force_nickchange(userrec* user,const char* newnick)
4619 strncpy(nick,newnick,MAXBUF);
4621 if (user->registered == 7)
4625 handle_nick(pars,1,user);
4631 int process_parameters(char **command_p,char *parameters)
4636 q = strlen(parameters);
4639 /* no parameters, command_p invalid! */
4642 if (parameters[0] == ':')
4644 command_p[0] = parameters+1;
4649 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4651 /* only one parameter */
4652 command_p[0] = parameters;
4653 if (parameters[0] == ':')
4655 if (strchr(parameters,' ') != NULL)
4663 command_p[j++] = parameters;
4664 for (i = 0; i <= q; i++)
4666 if (parameters[i] == ' ')
4668 command_p[j++] = parameters+i+1;
4669 parameters[i] = '\0';
4670 if (command_p[j-1][0] == ':')
4672 *command_p[j-1]++; /* remove dodgy ":" */
4674 /* parameter like this marks end of the sequence */
4678 return j; /* returns total number of items in the list */
4681 void process_command(userrec *user, char* cmd)
4685 char *command_p[127];
4686 char p[MAXBUF], temp[MAXBUF];
4687 int i, j, items, cmd_found;
4689 for (int i = 0; i < 127; i++)
4690 command_p[i] = NULL;
4700 if (!strcmp(cmd,""))
4705 int total_params = 0;
4708 for (int q = 0; q < strlen(cmd)-1; q++)
4710 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
4713 // found a 'trailing', we dont count them after this.
4721 // another phidjit bug...
4722 if (total_params > 126)
4724 kill_link(user,"Protocol violation");
4731 FOREACH_MOD OnServerRaw(tmp,true);
4732 const char* cmd2 = tmp.c_str();
4733 snprintf(cmd,512,"%s",cmd2);
4735 if (!strchr(cmd,' '))
4737 /* no parameters, lets skip the formalities and not chop up
4739 log(DEBUG,"About to preprocess command with no params");
4741 command_p[0] = NULL;
4743 for (int i = 0; i <= strlen(cmd); i++)
4745 cmd[i] = toupper(cmd[i]);
4747 log(DEBUG,"Preprocess done");
4753 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4754 for (i = 0; i < strlen(temp); i++)
4756 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4762 /* split the full string into a command plus parameters */
4766 if (strchr(cmd,' '))
4768 for (i = 0; i <= strlen(cmd); i++)
4770 /* capitalise the command ONLY, leave params intact */
4771 cmd[i] = toupper(cmd[i]);
4772 /* are we nearly there yet?! :P */
4776 parameters = cmd+i+1;
4784 for (i = 0; i <= strlen(cmd); i++)
4786 cmd[i] = toupper(cmd[i]);
4794 if (strlen(command)>MAXCOMMAND)
4796 kill_link(user,"Protocol violation");
4800 for (int x = 0; x < strlen(command); x++)
4802 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
4804 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
4806 kill_link(user,"Protocol violation");
4812 for (i = 0; i != cmdlist.size(); i++)
4814 if (strcmp(cmdlist[i].command,""))
4816 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
4818 log(DEBUG,"Found matching command");
4822 if (strcmp(parameters,""))
4824 items = process_parameters(command_p,parameters);
4829 command_p[0] = NULL;
4835 command_p[0] = NULL;
4840 log(DEBUG,"Processing command");
4842 /* activity resets the ping pending timer */
4843 user->nping = time(NULL) + 120;
4844 if ((items) < cmdlist[i].min_params)
4846 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4847 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4850 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4852 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4853 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4857 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4859 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
4861 if ((!isnick(user->nick)) || (user->registered != 7))
4863 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4864 WriteServ(user->fd,"451 %s :You have not registered",command);
4868 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4870 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4871 if (cmdlist[i].handler_function)
4873 /* ikky /stats counters */
4878 user->bytes_in += strlen(temp);
4881 cmdlist[i].use_count++;
4882 cmdlist[i].total_bytes+=strlen(temp);
4885 /* WARNING: nothing may come after the
4886 * command handler call, as the handler
4887 * may free the user structure! */
4889 cmdlist[i].handler_function(command_p,items,user);
4895 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4896 WriteServ(user->fd,"451 %s :You have not registered",command);
4904 if ((!cmd_found) && (user))
4906 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4907 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4912 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4915 /* create the command and push it onto the table */
4916 strcpy(comm.command,cmd);
4917 comm.handler_function = f;
4918 comm.flags_needed = flags;
4919 comm.min_params = minparams;
4921 comm.total_bytes = 0;
4922 cmdlist.push_back(comm);
4923 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4926 void SetupCommandTable(void)
4928 createcommand("USER",handle_user,0,4);
4929 createcommand("NICK",handle_nick,0,1);
4930 createcommand("QUIT",handle_quit,0,0);
4931 createcommand("VERSION",handle_version,0,0);
4932 createcommand("PING",handle_ping,0,1);
4933 createcommand("PONG",handle_pong,0,1);
4934 createcommand("ADMIN",handle_admin,0,0);
4935 createcommand("PRIVMSG",handle_privmsg,0,2);
4936 createcommand("INFO",handle_info,0,0);
4937 createcommand("TIME",handle_time,0,0);
4938 createcommand("WHOIS",handle_whois,0,1);
4939 createcommand("WALLOPS",handle_wallops,'o',1);
4940 createcommand("NOTICE",handle_notice,0,2);
4941 createcommand("JOIN",handle_join,0,1);
4942 createcommand("NAMES",handle_names,0,1);
4943 createcommand("PART",handle_part,0,1);
4944 createcommand("KICK",handle_kick,0,2);
4945 createcommand("MODE",handle_mode,0,1);
4946 createcommand("TOPIC",handle_topic,0,1);
4947 createcommand("WHO",handle_who,0,1);
4948 createcommand("MOTD",handle_motd,0,0);
4949 createcommand("RULES",handle_rules,0,0);
4950 createcommand("OPER",handle_oper,0,2);
4951 createcommand("LIST",handle_list,0,0);
4952 createcommand("DIE",handle_die,'o',1);
4953 createcommand("RESTART",handle_restart,'o',1);
4954 createcommand("KILL",handle_kill,'o',2);
4955 createcommand("REHASH",handle_rehash,'o',0);
4956 createcommand("LUSERS",handle_lusers,0,0);
4957 createcommand("STATS",handle_stats,0,1);
4958 createcommand("USERHOST",handle_userhost,0,1);
4959 createcommand("AWAY",handle_away,0,0);
4960 createcommand("ISON",handle_ison,0,0);
4961 createcommand("SUMMON",handle_summon,0,0);
4962 createcommand("USERS",handle_users,0,0);
4963 createcommand("INVITE",handle_invite,0,2);
4964 createcommand("PASS",handle_pass,0,1);
4965 createcommand("TRACE",handle_trace,'o',0);
4966 createcommand("WHOWAS",handle_whowas,0,1);
4967 createcommand("CONNECT",handle_connect,'o',1);
4968 createcommand("SQUIT",handle_squit,'o',1);
4969 createcommand("MODULES",handle_modules,'o',0);
4972 void process_buffer(userrec *user)
4976 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4983 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4986 if (!strcmp(user->inbuf,""))
4990 strncpy(cmd,user->inbuf,MAXBUF);
4991 if (!strcmp(cmd,""))
4995 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4997 cmd[strlen(cmd)-1] = '\0';
4999 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5001 cmd[strlen(cmd)-1] = '\0';
5003 strcpy(user->inbuf,"");
5004 if (!strcmp(cmd,""))
5008 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5010 if ((user) && (cmd))
5012 process_command(user,cmd);
5016 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5018 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
5022 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
5024 char response[10240];
5025 char token = udp_msg[0];
5026 char* params = udp_msg + 2;
5027 char finalparam[1024];
5028 strcpy(finalparam," :xxxx");
5029 if (strstr(params," :")) {
5030 strncpy(finalparam,strstr(params," :"),1024);
5033 // S test.chatspike.net password :ChatSpike InspIRCd test server
5034 char* servername = strtok(params," ");
5035 char* password = strtok(NULL," ");
5036 char* serverdesc = finalparam+2;
5037 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
5040 char Link_ServerName[1024];
5041 char Link_IPAddr[1024];
5042 char Link_Port[1024];
5043 char Link_Pass[1024];
5044 char Link_SendPass[1024];
5047 // search for a corresponding <link> block in the config files
5048 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5050 ConfValue("link","name",i,Link_ServerName,&config_f);
5051 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5052 ConfValue("link","port",i,Link_Port,&config_f);
5053 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5054 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5055 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5056 LinkPort = atoi(Link_Port);
5057 if (!strcasecmp(Link_ServerName,servername)) {
5058 if (!strcasecmp(Link_IPAddr,udp_host)) {
5059 if (LinkPort == udp_port) {
5060 // we have a matching link line -
5061 // send a 'diminutive' server message back...
5062 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
5063 serv->SendPacket(response,udp_host,udp_port,0);
5064 WriteOpers("CONNECT from %s accepted, authenticating",servername);
5065 for (int j = 0; j < 255; j++) {
5066 if (servers[j] == NULL) {
5067 servers[j] = new serverrec;
5068 strcpy(servers[j]->internal_addr,udp_host);
5069 strcpy(servers[j]->name,servername);
5070 // create a server record for this server
5071 snprintf(response,10240,"O %d",MyKey);
5072 serv->SendPacket(response,udp_host,udp_port,0);
5076 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
5080 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5084 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5088 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5091 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5092 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5097 // if this is received, this means the server-ip that sent it said "OK" to credentials.
5098 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
5099 // array, which is only added by an 'S' packet or BeginLink().
5100 for (int i = 0; i < 255; i++) {
5101 if (servers[i] != NULL) {
5102 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
5103 servers[i]->key = atoi(params);
5104 log(DEBUG,"Key for this server is now %d",servers[i]->key);
5105 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
5110 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
5114 // S test.chatspike.net password :ChatSpike InspIRCd test server
5115 char* servername = strtok(params," ");
5116 char* password = strtok(NULL," ");
5117 char* serverdesc = finalparam+2;
5119 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5120 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5121 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5122 // a connect, so put out an oper alert!
5127 // for now, just accept all, we'll fix that later.
5128 WriteOpers("%s accepted our link credentials ",servername);
5130 char Link_ServerName[1024];
5131 char Link_IPAddr[1024];
5132 char Link_Port[1024];
5133 char Link_Pass[1024];
5134 char Link_SendPass[1024];
5137 // search for a corresponding <link> block in the config files
5138 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5140 ConfValue("link","name",i,Link_ServerName,&config_f);
5141 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5142 ConfValue("link","port",i,Link_Port,&config_f);
5143 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5144 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5145 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5146 LinkPort = atoi(Link_Port);
5147 if (!strcasecmp(Link_ServerName,servername)) {
5148 if (!strcasecmp(Link_IPAddr,udp_host)) {
5149 if (LinkPort == udp_port) {
5150 // matching link at this end too, we're all done!
5151 // at this point we must begin key exchange and insert this
5152 // server into our 'active' table.
5153 for (int j = 0; j < 255; j++) {
5154 if (servers[j] != NULL) {
5155 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5156 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5157 snprintf(response,10240,"O %d",MyKey);
5158 serv->SendPacket(response,udp_host,udp_port,0);
5163 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5168 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5172 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5176 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5179 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5180 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5185 char* error_message = finalparam+2;
5186 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5187 // remove this server from any lists
5188 for (int j = 0; j < 255; j++) {
5189 if (servers[j] != NULL) {
5190 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5200 serverrec* source_server = NULL;
5202 for (int j = 0; j < 255; j++) {
5203 if (servers[j] != NULL) {
5204 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5205 if (servers[j]->key == theirkey) {
5206 // found a valid key for this server, can process restricted stuff here
5207 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5215 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5219 int reap_counter = 0;
5223 struct sockaddr_in client, server;
5224 char addrs[MAXBUF][255];
5225 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5227 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5228 int selectResult = 0;
5229 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5230 char resolvedHost[MAXBUF];
5234 log_file = fopen("ircd.log","a+");
5237 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5241 log(DEBUG,"InspIRCd: startup: begin");
5245 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5247 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5249 SetupCommandTable();
5250 log(DEBUG,"InspIRCd: startup: default command table set up");
5253 if (strcmp(DieValue,""))
5255 printf("WARNING: %s\n\n",DieValue);
5258 log(DEBUG,"InspIRCd: startup: read config");
5260 int count2 = 0, count3 = 0;
5262 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5264 ConfValue("bind","port",count,configToken,&config_f);
5265 ConfValue("bind","address",count,Addr,&config_f);
5266 ConfValue("bind","type",count,Type,&config_f);
5267 if (!strcmp(Type,"servers"))
5269 char Default[MAXBUF];
5270 strcpy(Default,"no");
5271 ConfValue("bind","default",count,Default,&config_f);
5272 if (strchr(Default,'y'))
5274 defaultRoute = count3;
5275 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5277 me[count3] = new serverrec(ServerName,100L,false);
5278 me[count3]->CreateListener(Addr,atoi(configToken));
5283 ports[count2] = atoi(configToken);
5284 strcpy(addrs[count2],Addr);
5287 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5290 UDPportCount = count3;
5292 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5294 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5298 /* BugFix By Craig! :p */
5300 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5302 char modfile[MAXBUF];
5303 ConfValue("module","name",count2,configToken,&config_f);
5304 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5305 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5306 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5307 /* If The File Doesnt exist, Trying to load it
5308 * Will Segfault the IRCd.. So, check to see if
5309 * it Exists, Before Proceeding. */
5310 if (FileExists(modfile))
5312 factory[count] = new ircd_module(modfile);
5313 if (factory[count]->LastError())
5315 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5316 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5319 if (factory[count]->factory)
5321 modules[count] = factory[count]->factory->CreateModule();
5322 /* save the module and the module's classfactory, if
5323 * this isnt done, random crashes can occur :/ */
5324 module_names.push_back(modfile);
5328 log(DEBUG,"Unable to load %s",modfile);
5329 sprintf("Unable to load %s\nExiting...\n",modfile);
5332 /* Increase the Count */
5337 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5338 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5341 MODCOUNT = count - 1;
5342 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5344 printf("\nInspIRCd is now running!\n");
5346 startup_time = time(NULL);
5350 log(VERBOSE,"Not forking as -nofork was specified");
5354 if (DaemonSeed() == ERROR)
5356 log(DEBUG,"InspIRCd: startup: can't daemonise");
5357 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5363 /* setup select call */
5364 FD_ZERO(&selectFds);
5365 log(DEBUG,"InspIRCd: startup: zero selects");
5366 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5368 for (count = 0; count < portCount; count++)
5370 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5372 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5375 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5377 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5379 else /* well we at least bound to one socket so we'll continue */
5385 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5387 /* if we didn't bind to anything then abort */
5388 if (boundPortCount == 0)
5390 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5394 length = sizeof (client);
5395 int flip_flop = 0, udp_port = 0;
5396 char udp_msg[MAXBUF], udp_host[MAXBUF];
5398 /* main loop for multiplexing/resetting */
5401 /* set up select call */
5402 for (count = 0; count < boundPortCount; count++)
5404 FD_SET (openSockfd[count], &selectFds);
5407 /* added timeout! select was waiting forever... wank... :/ */
5418 vector<int>::iterator niterator;
5421 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5422 // them in a list, then reap the list every second or so.
5423 if (reap_counter>5000) {
5424 if (fd_reap.size() > 0) {
5425 for( int n = 0; n < fd_reap.size(); n++)
5427 Blocking(fd_reap[n]);
5429 NonBlocking(fd_reap[n]);
5438 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5440 for (int x = 0; x != UDPportCount; x++)
5443 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5445 if (strlen(udp_msg)<1) {
5446 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5450 FOREACH_MOD OnPacketReceive(udp_msg);
5451 // Packets must go back via the route they arrived on :)
5452 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5457 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5461 if (!count2->second) break;
5464 if (count2->second->fd)
5466 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5467 // their connection class.
5468 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
5470 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5471 kill_link(count2->second,"Registration timeout");
5474 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5476 if (!count2->second->lastping)
5478 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5479 kill_link(count2->second,"Ping timeout");
5482 Write(count2->second->fd,"PING :%s",ServerName);
5483 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5484 count2->second->lastping = 0;
5485 count2->second->nping = time(NULL)+120;
5488 result = read(count2->second->fd, data, 1);
5489 // result EAGAIN means nothing read
5490 if (result == EAGAIN)
5498 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5499 kill_link(count2->second,"Client exited");
5500 // must bail here? kill_link removes the hash, corrupting the iterator
5501 log(DEBUG,"Bailing from client exit");
5505 else if (result > 0)
5510 // until the buffer is at 509 chars anything can be inserted into it.
5511 if ((strlen(count2->second->inbuf) < 509) && (data[0] != '\0')) {
5512 strncat(count2->second->inbuf, data, result);
5515 // once you reach 509 chars, only a \r or \n can be inserted,
5516 // completing the line.
5517 if ((strlen(count2->second->inbuf) >= 509) && ((data[0] == '\r') || (data[0] == '\n'))) {
5518 count2->second->inbuf[509] = '\r';
5519 count2->second->inbuf[510] = '\n';
5520 count2->second->inbuf[511] = '\0';
5521 process_buffer(count2->second);
5525 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5527 /* at least one complete line is waiting to be processed */
5528 if (!count2->second->fd)
5532 if (strlen(count2->second->inbuf)<512)
5534 // double check the length before processing!
5535 process_buffer(count2->second);
5539 strcpy(count2->second->inbuf,"");
5549 /* select is reporting a waiting socket. Poll them all to find out which */
5550 if (selectResult > 0)
5552 char target[MAXBUF], resolved[MAXBUF];
5553 for (count = 0; count < boundPortCount; count++)
5555 if (FD_ISSET (openSockfd[count], &selectFds))
5557 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5559 address_cache::iterator iter = IP.find(client.sin_addr);
5560 bool iscached = false;
5561 if (iter == IP.end())
5563 /* ip isn't in cache, add it */
5564 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5565 if(CleanAndResolve(resolved, target) != TRUE)
5567 strncpy(resolved,target,MAXBUF);
5569 /* hostname now in 'target' */
5570 IP[client.sin_addr] = new string(resolved);
5571 /* hostname in cache */
5575 /* found ip (cached) */
5576 strncpy(resolved, iter->second->c_str(), MAXBUF);
5580 if (incomingSockfd < 0)
5582 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5583 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5586 AddClient(incomingSockfd, resolved, ports[count], iscached);
5587 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5594 close (incomingSockfd);