1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
43 #include "connection.h"
53 #define nspace __gnu_cxx
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
66 char restartpass[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 time_t startup_time = time(NULL);
78 extern vector<Module*> modules;
79 vector<string> module_names;
80 extern vector<ircd_module*> factory;
89 template<> struct nspace::hash<in_addr>
91 size_t operator()(const struct in_addr &a) const
94 memcpy(&q,&a,sizeof(size_t));
99 template<> struct nspace::hash<string>
101 size_t operator()(const string &s) const
104 static struct hash<const char *> strhash;
116 bool operator()(const string& s1, const string& s2) const
118 char a[MAXBUF],b[MAXBUF];
119 strcpy(a,s1.c_str());
120 strcpy(b,s2.c_str());
121 return (strcasecmp(a,b) == 0);
126 struct InAddr_HashComp
129 bool operator()(const in_addr &s1, const in_addr &s2) const
134 memcpy(&q,&s1,sizeof(size_t));
135 memcpy(&p,&s2,sizeof(size_t));
143 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
144 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
145 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
146 typedef std::deque<command_t> command_table;
149 serverrec* servers[255];
153 user_hash clientlist;
156 command_table cmdlist;
163 struct linger linger = { 0 };
164 char bannerBuffer[MAXBUF];
165 int boundPortCount = 0;
166 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
167 int defaultRoute = 0;
171 long MyKey = C.GenKey();
175 int has_channel(userrec *u, chanrec *c);
176 int usercount(chanrec *c);
177 int usercount_i(chanrec *c);
178 void update_stats_l(int fd,int data_out);
179 char* Passwd(userrec *user);
180 bool IsDenied(userrec *user);
181 void AddWhoWas(userrec* u);
183 std::stringstream config_f(stringstream::in | stringstream::out);
185 void safedelete(userrec *p)
189 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
190 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
195 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
199 void safedelete(chanrec *p)
204 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
208 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
213 void tidystring(char* str)
215 // strips out double spaces before a : parameter
218 bool go_again = true;
225 while ((str[0] == ' ') && (strlen(str)>0))
232 bool noparse = false;
235 while (a < strlen(str))
237 if ((a<strlen(str)-1) && (noparse==false))
239 if ((str[a] == ' ') && (str[a+1] == ' '))
241 log(DEBUG,"Tidied extra space out of string: %s",str);
249 if ((str[a] == ' ') && (str[a+1] == ':'))
255 temp[t++] = str[a++];
258 strncpy(str,temp,MAXBUF);
262 /* chop a string down to 512 characters and preserve linefeed (irc max
269 log(DEBUG,"ERROR! Null string passed to chop()!");
273 FOREACH_MOD OnServerRaw(temp,false);
274 const char* str2 = temp.c_str();
275 sprintf(str,"%s",str2);
278 if (strlen(str) >= 512)
287 std::string getservername()
292 std::string getserverdesc()
297 std::string getnetworkname()
302 std::string getadminname()
307 std::string getadminemail()
312 std::string getadminnick()
317 void log(int level,char *text, ...)
319 char textbuffer[MAXBUF];
322 struct tm * timeinfo;
323 if (level < LogLevel)
327 timeinfo = localtime (&rawtime);
332 va_start (argsPtr, text);
333 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
335 strcpy(b,asctime(timeinfo));
336 b[strlen(b)-1] = ':';
337 fprintf(log_file,"%s %s\n",b,textbuffer);
340 // nofork enabled? display it on terminal too
341 printf("%s %s\n",b,textbuffer);
346 void readfile(file_cache &F, const char* fname)
349 char linebuf[MAXBUF];
351 log(DEBUG,"readfile: loading %s",fname);
353 file = fopen(fname,"r");
358 fgets(linebuf,sizeof(linebuf),file);
359 linebuf[strlen(linebuf)-1]='\0';
360 if (!strcmp(linebuf,""))
366 F.push_back(linebuf);
373 log(DEBUG,"readfile: failed to load file: %s",fname);
375 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
378 void ReadConfig(void)
380 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF];
383 LoadConf(CONFIG_FILE,&config_f);
385 ConfValue("server","name",0,ServerName,&config_f);
386 ConfValue("server","description",0,ServerDesc,&config_f);
387 ConfValue("server","network",0,Network,&config_f);
388 ConfValue("admin","name",0,AdminName,&config_f);
389 ConfValue("admin","email",0,AdminEmail,&config_f);
390 ConfValue("admin","nick",0,AdminNick,&config_f);
391 ConfValue("files","motd",0,motd,&config_f);
392 ConfValue("files","rules",0,rules,&config_f);
393 ConfValue("power","diepass",0,diepass,&config_f);
394 ConfValue("power","pause",0,pauseval,&config_f);
395 ConfValue("power","restartpass",0,restartpass,&config_f);
396 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
397 ConfValue("die","value",0,DieValue,&config_f);
398 ConfValue("options","loglevel",0,dbg,&config_f);
399 if (!strcmp(dbg,"debug"))
401 if (!strcmp(dbg,"verbose"))
403 if (!strcmp(dbg,"default"))
405 if (!strcmp(dbg,"sparse"))
407 if (!strcmp(dbg,"none"))
410 log(DEBUG,"Reading message of the day");
411 readfile(RULES,rules);
412 log(DEBUG,"Reading connect classes");
414 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
417 ConfValue("connect","allow",i,Value,&config_f);
418 ConfValue("connect","timeout",i,timeout,&config_f);
419 if (strcmp(Value,""))
421 strcpy(c.host,Value);
424 ConfValue("connect","password",i,Value,&config_f);
425 strcpy(c.pass,Value);
426 c.registration_timeout = 90; // default is 2 minutes
429 c.registration_timeout = atoi(timeout);
431 Classes.push_back(c);
432 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
436 ConfValue("connect","deny",i,Value,&config_f);
437 strcpy(c.host,Value);
439 Classes.push_back(c);
440 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
449 log(DEBUG,"Blocking: %d",s);
450 flags = fcntl(s, F_GETFL, 0);
451 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
454 void NonBlocking(int s)
457 log(DEBUG,"NonBlocking: %d",s);
458 flags = fcntl(s, F_GETFL, 0);
459 fcntl(s, F_SETFL, flags | O_NONBLOCK);
463 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
465 struct hostent *hostPtr = NULL;
468 memset (resolvedHost, '\0',MAXBUF);
469 if(unresolvedHost == NULL)
471 if ((inet_aton(unresolvedHost,&addr)) == 0)
473 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
475 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
477 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
481 /* write formatted text to a socket, in same format as printf */
483 void Write(int sock,char *text, ...)
487 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
490 char textbuffer[MAXBUF];
494 va_start (argsPtr, text);
495 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
497 sprintf(tb,"%s\r\n",textbuffer);
499 write(sock,tb,strlen(tb));
500 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
503 /* write a server formatted numeric response to a single socket */
505 void WriteServ(int sock, char* text, ...)
509 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
512 char textbuffer[MAXBUF],tb[MAXBUF];
514 va_start (argsPtr, text);
516 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
518 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
520 write(sock,tb,strlen(tb));
521 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
524 /* write text from an originating user to originating user */
526 void WriteFrom(int sock, userrec *user,char* text, ...)
528 if ((!text) || (!user))
530 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
533 char textbuffer[MAXBUF],tb[MAXBUF];
535 va_start (argsPtr, text);
537 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
539 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
541 write(sock,tb,strlen(tb));
542 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
545 /* write text to an destination user from a source user (e.g. user privmsg) */
547 void WriteTo(userrec *source, userrec *dest,char *data, ...)
549 if ((!source) || (!dest) || (!data))
551 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
554 char textbuffer[MAXBUF],tb[MAXBUF];
556 va_start (argsPtr, data);
557 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
560 WriteFrom(dest->fd,source,"%s",textbuffer);
563 /* write formatted text from a source user to all users on a channel
564 * including the sender (NOT for privmsg, notice etc!) */
566 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
568 if ((!Ptr) || (!user) || (!text))
570 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
573 char textbuffer[MAXBUF];
575 va_start (argsPtr, text);
576 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
578 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
580 if (has_channel(i->second,Ptr))
582 WriteTo(user,i->second,"%s",textbuffer);
587 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
589 if ((!Ptr) || (!user) || (!text))
591 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
594 char textbuffer[MAXBUF];
596 va_start (argsPtr, text);
597 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
599 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
603 if (has_channel(i->second,Ptr))
605 WriteServ(i->second->fd,"%s",textbuffer);
612 /* write formatted text from a source user to all users on a channel except
613 * for the sender (for privmsg etc) */
615 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
617 if ((!Ptr) || (!user) || (!text))
619 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
622 char textbuffer[MAXBUF];
624 va_start (argsPtr, text);
625 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
628 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
632 if (has_channel(i->second,Ptr) && (user != i->second))
634 WriteTo(user,i->second,"%s",textbuffer);
640 int c_count(userrec* u)
643 for (int i =0; i != MAXCHANS; i++)
644 if (u->chans[i].channel != NULL)
650 /* return 0 or 1 depending if users u and u2 share one or more common channels
651 * (used by QUIT, NICK etc which arent channel specific notices) */
653 int common_channels(userrec *u, userrec *u2)
660 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
663 for (i = 0; i != MAXCHANS; i++)
665 for (z = 0; z != MAXCHANS; z++)
667 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
669 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
671 if ((c_count(u)) && (c_count(u2)))
682 /* write a formatted string to all users who share at least one common
683 * channel, including the source user e.g. for use in NICK */
685 void WriteCommon(userrec *u, char* text, ...)
689 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
693 if (u->registered != 7) {
694 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
698 char textbuffer[MAXBUF];
700 va_start (argsPtr, text);
701 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
704 WriteFrom(u->fd,u,"%s",textbuffer);
706 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
710 if (common_channels(u,i->second) && (i->second != u))
712 WriteFrom(i->second->fd,u,"%s",textbuffer);
718 /* write a formatted string to all users who share at least one common
719 * channel, NOT including the source user e.g. for use in QUIT */
721 void WriteCommonExcept(userrec *u, char* text, ...)
725 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
729 if (u->registered != 7) {
730 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
734 char textbuffer[MAXBUF];
736 va_start (argsPtr, text);
737 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
740 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
744 if ((common_channels(u,i->second)) && (u != i->second))
746 WriteFrom(i->second->fd,u,"%s",textbuffer);
752 void WriteOpers(char* text, ...)
756 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
760 char textbuffer[MAXBUF];
762 va_start (argsPtr, text);
763 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
766 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
770 if (strchr(i->second->modes,'o'))
772 if (strchr(i->second->modes,'s'))
774 // send server notices to all with +s
775 // (TODO: needs SNOMASKs)
776 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
783 bool hasumode(userrec* user, char mode)
787 return (strchr(user->modes,mode)>0);
792 void WriteMode(const char* modes, int flags, const char* text, ...)
794 if ((!text) || (!modes) || (!flags))
796 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
800 char textbuffer[MAXBUF];
802 va_start (argsPtr, text);
803 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
806 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
810 bool send_to_user = false;
815 for (int n = 0; n < strlen(modes); n++)
817 if (!hasumode(i->second,modes[n]))
819 send_to_user = false;
824 else if (flags == WM_OR)
826 send_to_user = false;
827 for (int n = 0; n < strlen(modes); n++)
829 if (hasumode(i->second,modes[n]))
839 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
845 void WriteWallOps(userrec *source, char* text, ...)
847 if ((!text) || (!source))
849 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
854 char textbuffer[MAXBUF];
856 va_start (argsPtr, text);
857 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
860 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
864 if (strchr(i->second->modes,'w'))
866 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
872 /* convert a string to lowercase. Note following special circumstances
873 * taken from RFC 1459. Many "official" server branches still hold to this
874 * rule so i will too;
876 * Because of IRC's scandanavian origin, the characters {}| are
877 * considered to be the lower case equivalents of the characters []\,
878 * respectively. This is a critical issue when determining the
879 * equivalence of two nicknames.
882 void strlower(char *n)
888 for (int i = 0; i != strlen(n); i++)
890 n[i] = tolower(n[i]);
900 /* verify that a user's ident and nickname is valid */
902 int isident(const char* n)
915 for (i = 0; i != strlen(n); i++)
917 if ((n[i] < 33) || (n[i] > 125))
921 /* can't occur ANYWHERE in an Ident! */
922 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
931 int isnick(const char* n)
943 if (strlen(n) > NICKMAX-1)
947 for (i = 0; i != strlen(n); i++)
949 if ((n[i] < 33) || (n[i] > 125))
953 /* can't occur ANYWHERE in a nickname! */
954 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
958 /* can't occur as the first char of a nickname... */
959 if ((strchr("0123456789",n[i])) && (!i))
967 /* Find a user record by nickname and return a pointer to it */
969 userrec* Find(string nick)
971 user_hash::iterator iter = clientlist.find(nick);
973 if (iter == clientlist.end())
974 /* Couldn't find it */
980 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
982 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
986 if (i->second->fd == fd)
988 i->second->bytes_out+=data_out;
989 i->second->cmds_out++;
996 /* find a channel record by channel name and return a pointer to it */
998 chanrec* FindChan(const char* chan)
1002 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1006 chan_hash::iterator iter = chanlist.find(chan);
1008 if (iter == chanlist.end())
1009 /* Couldn't find it */
1012 return iter->second;
1016 void purge_empty_chans(void)
1018 int go_again = 1, purge = 0;
1023 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1026 if (!usercount(i->second))
1028 /* kill the record */
1029 if (i != chanlist.end())
1031 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1041 log(DEBUG,"skipped purge for %s",i->second->name);
1046 log(DEBUG,"completed channel purge, killed %d",purge);
1049 /* returns the status character for a given user on a channel, e.g. @ for op,
1050 * % for halfop etc. If the user has several modes set, the highest mode
1051 * the user has must be returned. */
1053 char* cmode(userrec *user, chanrec *chan)
1055 if ((!user) || (!chan))
1057 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1062 for (i = 0; i != MAXCHANS; i++)
1064 if ((user->chans[i].channel == chan) && (chan != NULL))
1066 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1070 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1074 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1083 char scratch[MAXBUF];
1084 char sparam[MAXBUF];
1086 char* chanmodes(chanrec *chan)
1090 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1097 if (chan->noexternal)
1099 strncat(scratch,"n",MAXMODES);
1101 if (chan->topiclock)
1103 strncat(scratch,"t",MAXMODES);
1105 if (strcmp(chan->key,""))
1107 strncat(scratch,"k",MAXMODES);
1111 strncat(scratch,"l",MAXMODES);
1113 if (chan->inviteonly)
1115 strncat(scratch,"i",MAXMODES);
1117 if (chan->moderated)
1119 strncat(scratch,"m",MAXMODES);
1123 strncat(scratch,"s",MAXMODES);
1125 if (chan->c_private)
1127 strncat(scratch,"p",MAXMODES);
1129 if (strcmp(chan->key,""))
1131 strncat(sparam,chan->key,MAXBUF);
1136 sprintf(foo," %d",chan->limit);
1137 strncat(sparam,foo,MAXBUF);
1139 if (strlen(chan->custom_modes))
1141 strncat(scratch,chan->custom_modes,MAXMODES);
1142 for (int z = 0; z < strlen(chan->custom_modes); z++)
1144 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1147 strncat(sparam," ",MAXBUF);
1148 strncat(sparam,extparam.c_str(),MAXBUF);
1152 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1153 strncat(scratch,sparam,MAXMODES);
1157 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1158 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1159 * highest mode the user has must be returned. */
1161 int cstatus(userrec *user, chanrec *chan)
1163 if ((!chan) || (!user))
1165 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1170 for (i = 0; i != MAXCHANS; i++)
1172 if ((user->chans[i].channel == chan) && (chan != NULL))
1174 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1178 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1182 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1184 return STATUS_VOICE;
1186 return STATUS_NORMAL;
1192 /* compile a userlist of a channel into a string, each nick seperated by
1193 * spaces and op, voice etc status shown as @ and + */
1195 void userlist(userrec *user,chanrec *c)
1197 if ((!c) || (!user))
1199 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1203 sprintf(list,"353 %s = %s :", user->nick, c->name);
1204 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1206 if (has_channel(i->second,c))
1208 if (isnick(i->second->nick))
1210 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1212 /* user is +i, and source not on the channel, does not show
1213 * nick in NAMES list */
1216 strcat(list,cmode(i->second,c));
1217 strcat(list,i->second->nick);
1219 if (strlen(list)>(480-NICKMAX))
1221 /* list overflowed into
1222 * multiple numerics */
1223 WriteServ(user->fd,list);
1224 sprintf(list,"353 %s = %s :", user->nick, c->name);
1229 /* if whats left in the list isnt empty, send it */
1230 if (list[strlen(list)-1] != ':')
1232 WriteServ(user->fd,list);
1236 /* return a count of the users on a specific channel accounting for
1237 * invisible users who won't increase the count. e.g. for /LIST */
1239 int usercount_i(chanrec *c)
1246 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1251 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1255 if (has_channel(i->second,c))
1257 if (isnick(i->second->nick))
1259 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1261 /* user is +i, and source not on the channel, does not show
1262 * nick in NAMES list */
1270 log(DEBUG,"usercount_i: %s %d",c->name,count);
1275 int usercount(chanrec *c)
1282 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1287 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1291 if (has_channel(i->second,c))
1293 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1300 log(DEBUG,"usercount: %s %d",c->name,count);
1305 /* add a channel to a user, creating the record for it if needed and linking
1306 * it to the user record */
1308 chanrec* add_channel(userrec *user, const char* cn, const char* key)
1310 if ((!user) || (!cn))
1312 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1321 strncpy(cname,cn,MAXBUF);
1323 // we MUST declare this wherever we use FOREACH_RESULT
1326 if ((!cname) || (!user))
1330 if (strlen(cname) > CHANMAX-1)
1332 cname[CHANMAX-1] = '\0';
1335 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1337 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1339 return NULL; // already on the channel!
1343 if (!FindChan(cname))
1345 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1350 /* create a new one */
1351 log(DEBUG,"add_channel: creating: %s",cname);
1353 chanlist[cname] = new chanrec();
1355 strcpy(chanlist[cname]->name, cname);
1356 chanlist[cname]->topiclock = 1;
1357 chanlist[cname]->noexternal = 1;
1358 chanlist[cname]->created = time(NULL);
1359 strcpy(chanlist[cname]->topic, "");
1360 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1361 chanlist[cname]->topicset = 0;
1362 Ptr = chanlist[cname];
1363 log(DEBUG,"add_channel: created: %s",cname);
1364 /* set created to 2 to indicate user
1365 * is the first in the channel
1366 * and should be given ops */
1372 /* channel exists, just fish out a pointer to its struct */
1373 Ptr = FindChan(cname);
1376 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1381 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1382 if (strcmp(Ptr->key,""))
1384 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1387 log(DEBUG,"add_channel: no key given in JOIN");
1388 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1393 log(DEBUG,"key at %p is %s",key,key);
1394 if (strcasecmp(key,Ptr->key))
1396 log(DEBUG,"add_channel: bad key given in JOIN");
1397 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1402 log(DEBUG,"add_channel: no key");
1404 if (Ptr->inviteonly)
1406 log(DEBUG,"add_channel: channel is +i");
1407 if (user->IsInvited(Ptr->name))
1409 /* user was invited to channel */
1410 /* there may be an optional channel NOTICE here */
1414 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1418 log(DEBUG,"add_channel: channel is not +i");
1422 if (usercount(Ptr) == Ptr->limit)
1424 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1429 log(DEBUG,"add_channel: about to walk banlist");
1431 /* check user against the channel banlist */
1432 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1434 if (match(user->GetFullHost(),i->data))
1436 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1441 log(DEBUG,"add_channel: bans checked");
1443 user->RemoveInvite(Ptr->name);
1445 log(DEBUG,"add_channel: invites removed");
1451 log(DEBUG,"Passed channel checks");
1453 for (i =0; i != MAXCHANS; i++)
1455 if (user->chans[i].channel == NULL)
1457 log(DEBUG,"Adding into their channel list");
1461 /* first user in is given ops */
1462 user->chans[i].uc_modes = UCMODE_OP;
1466 user->chans[i].uc_modes = 0;
1468 user->chans[i].channel = Ptr;
1469 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1471 log(DEBUG,"Sent JOIN to client");
1475 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1476 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1479 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1480 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1481 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1482 FOREACH_MOD OnUserJoin(user,Ptr);
1486 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1487 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1491 /* remove a channel from a users record, and remove the record from memory
1492 * if the channel has become empty */
1494 chanrec* del_channel(userrec *user, const char* cname, const char* reason)
1496 if ((!user) || (!cname))
1498 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1506 if ((!cname) || (!user))
1511 Ptr = FindChan(cname);
1518 FOREACH_MOD OnUserPart(user,Ptr);
1519 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1521 for (i =0; i != MAXCHANS; i++)
1523 /* zap it from the channel list of the user */
1524 if (user->chans[i].channel == Ptr)
1528 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1532 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1534 user->chans[i].uc_modes = 0;
1535 user->chans[i].channel = NULL;
1536 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1541 /* if there are no users left on the channel */
1542 if (!usercount(Ptr))
1544 chan_hash::iterator iter = chanlist.find(Ptr->name);
1546 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1548 /* kill the record */
1549 if (iter != chanlist.end())
1551 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1552 delete iter->second;
1553 chanlist.erase(iter);
1559 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1561 if ((!src) || (!user) || (!Ptr) || (!reason))
1563 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1570 if ((!Ptr) || (!user) || (!src))
1575 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1577 if (!has_channel(user,Ptr))
1579 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1582 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1584 if (cstatus(src,Ptr) == STATUS_HOP)
1586 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1590 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1596 for (i =0; i != MAXCHANS; i++)
1598 /* zap it from the channel list of the user */
1599 if (user->chans[i].channel == Ptr)
1601 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1602 user->chans[i].uc_modes = 0;
1603 user->chans[i].channel = NULL;
1604 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1609 /* if there are no users left on the channel */
1610 if (!usercount(Ptr))
1612 chan_hash::iterator iter = chanlist.find(Ptr->name);
1614 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1616 /* kill the record */
1617 if (iter != chanlist.end())
1619 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1620 delete iter->second;
1621 chanlist.erase(iter);
1627 /* returns 1 if user u has channel c in their record, 0 if not */
1629 int has_channel(userrec *u, chanrec *c)
1635 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1638 for (i =0; i != MAXCHANS; i++)
1640 if (u->chans[i].channel == c)
1648 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1653 if ((!user) || (!dest) || (!chan))
1655 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1658 if (status != STATUS_OP)
1660 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1667 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1673 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1678 for (i = 0; i != MAXCHANS; i++)
1680 if ((d->chans[i].channel == chan) && (chan != NULL))
1682 if (d->chans[i].uc_modes & UCMODE_OP)
1684 /* mode already set on user, dont allow multiple */
1687 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1688 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1696 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1701 if ((!user) || (!dest) || (!chan))
1703 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1706 if (status != STATUS_OP)
1708 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1716 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1721 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1726 for (i = 0; i != MAXCHANS; i++)
1728 if ((d->chans[i].channel == chan) && (chan != NULL))
1730 if (d->chans[i].uc_modes & UCMODE_HOP)
1732 /* mode already set on user, dont allow multiple */
1735 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1736 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1744 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1749 if ((!user) || (!dest) || (!chan))
1751 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1754 if (status < STATUS_HOP)
1756 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1764 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1769 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1774 for (i = 0; i != MAXCHANS; i++)
1776 if ((d->chans[i].channel == chan) && (chan != NULL))
1778 if (d->chans[i].uc_modes & UCMODE_VOICE)
1780 /* mode already set on user, dont allow multiple */
1783 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1784 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1792 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1797 if ((!user) || (!dest) || (!chan))
1799 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1802 if (status != STATUS_OP)
1804 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1812 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1817 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1822 for (i = 0; i != MAXCHANS; i++)
1824 if ((d->chans[i].channel == chan) && (chan != NULL))
1826 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1828 /* mode already set on user, dont allow multiple */
1831 d->chans[i].uc_modes ^= UCMODE_OP;
1832 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1840 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1845 if ((!user) || (!dest) || (!chan))
1847 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1850 if (status != STATUS_OP)
1852 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1860 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1865 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1870 for (i = 0; i != MAXCHANS; i++)
1872 if ((d->chans[i].channel == chan) && (chan != NULL))
1874 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1876 /* mode already set on user, dont allow multiple */
1879 d->chans[i].uc_modes ^= UCMODE_HOP;
1880 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1888 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1893 if ((!user) || (!dest) || (!chan))
1895 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1898 if (status < STATUS_HOP)
1900 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1908 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1913 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1918 for (i = 0; i != MAXCHANS; i++)
1920 if ((d->chans[i].channel == chan) && (chan != NULL))
1922 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1924 /* mode already set on user, dont allow multiple */
1927 d->chans[i].uc_modes ^= UCMODE_VOICE;
1928 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1936 void TidyBan(char *ban)
1939 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1943 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1947 char* pos_of_pling = strchr(temp,'!');
1948 char* pos_of_at = strchr(temp,'@');
1950 pos_of_pling[0] = '\0';
1951 pos_of_at[0] = '\0';
1955 strncpy(NICK,temp,NICKMAX);
1956 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1957 strncpy(HOST,pos_of_at,160);
1959 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1962 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1964 if ((!user) || (!dest) || (!chan)) {
1965 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1970 if ((!user) || (!dest) || (!chan))
1972 if (strchr(dest,'!')==0)
1974 if (strchr(dest,'@')==0)
1976 for (int i = 0; i < strlen(dest); i++)
1979 for (int i = 0; i < strlen(dest); i++)
1983 for (int i = 0; i < strlen(dest); i++)
1989 for (int i = 0; i < strlen(dest); i++)
1994 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1997 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1999 if (!strcasecmp(i->data,dest))
2001 // dont allow a user to set the same ban twice
2006 b.set_time = time(NULL);
2007 strncpy(b.data,dest,MAXBUF);
2008 strncpy(b.set_by,user->nick,NICKMAX);
2009 chan->bans.push_back(b);
2013 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2015 if ((!user) || (!dest) || (!chan)) {
2016 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2020 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2021 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2023 if (!strcasecmp(i->data,dest))
2025 chan->bans.erase(i);
2032 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
2034 if ((!parameters) || (!user)) {
2035 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2040 char modelist[MAXBUF];
2041 char outlist[MAXBUF];
2042 char outstr[MAXBUF];
2043 char outpars[32][MAXBUF];
2049 bool k_set = false, l_set = false;
2056 log(DEBUG,"process_modes: start");
2058 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2059 /* parameters[2] onwards are parameters for
2060 * modes that require them :) */
2061 strcpy(outlist,"+");
2064 log(DEBUG,"process_modes: modelist: %s",modelist);
2066 for (ptr = 0; ptr < strlen(modelist); ptr++)
2071 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2072 char modechar = modelist[ptr];
2073 switch (modelist[ptr])
2078 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2080 outlist[strlen(outlist)-1] = '-';
2084 strcat(outlist,"-");
2094 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2096 outlist[strlen(outlist)-1] = '+';
2100 strcat(outlist,"+");
2107 if ((param >= pcnt)) break;
2110 r = give_ops(user,parameters[param++],chan,status);
2114 r = take_ops(user,parameters[param++],chan,status);
2118 strcat(outlist,"o");
2119 strcpy(outpars[pc++],parameters[param-1]);
2124 if ((param >= pcnt)) break;
2127 r = give_hops(user,parameters[param++],chan,status);
2131 r = take_hops(user,parameters[param++],chan,status);
2135 strcat(outlist,"h");
2136 strcpy(outpars[pc++],parameters[param-1]);
2142 if ((param >= pcnt)) break;
2145 r = give_voice(user,parameters[param++],chan,status);
2149 r = take_voice(user,parameters[param++],chan,status);
2153 strcat(outlist,"v");
2154 strcpy(outpars[pc++],parameters[param-1]);
2159 if ((param >= pcnt)) break;
2162 r = add_ban(user,parameters[param++],chan,status);
2166 r = take_ban(user,parameters[param++],chan,status);
2170 strcat(outlist,"b");
2171 strcpy(outpars[pc++],parameters[param-1]);
2177 if ((param >= pcnt))
2185 if (!strcmp(chan->key,""))
2187 strcat(outlist,"k");
2189 strcpy(key,parameters[param++]);
2190 if (strlen(key)>32) {
2193 strcpy(outpars[pc++],key);
2194 strcpy(chan->key,key);
2200 /* checks on -k are case sensitive and only accurate to the
2201 first 32 characters */
2203 strcpy(key,parameters[param++]);
2204 if (strlen(key)>32) {
2207 /* only allow -k if correct key given */
2208 if (!strcmp(chan->key,key))
2210 strcat(outlist,"k");
2211 strcpy(chan->key,"");
2212 strcpy(outpars[pc++],key);
2222 strcat(outlist,"l");
2227 if ((param >= pcnt)) break;
2233 bool invalid = false;
2234 for (int i = 0; i < strlen(parameters[param]); i++)
2236 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2241 if (atoi(parameters[param]) < 1)
2249 chan->limit = atoi(parameters[param]);
2252 strcat(outlist,"l");
2253 strcpy(outpars[pc++],parameters[param++]);
2260 if (chan->inviteonly != mdir)
2262 strcat(outlist,"i");
2264 chan->inviteonly = mdir;
2268 if (chan->topiclock != mdir)
2270 strcat(outlist,"t");
2272 chan->topiclock = mdir;
2276 if (chan->noexternal != mdir)
2278 strcat(outlist,"n");
2280 chan->noexternal = mdir;
2284 if (chan->moderated != mdir)
2286 strcat(outlist,"m");
2288 chan->moderated = mdir;
2292 if (chan->secret != mdir)
2294 strcat(outlist,"s");
2295 if (chan->c_private)
2297 chan->c_private = 0;
2300 strcat(outlist,"-p+");
2304 strcat(outlist,"+p-");
2308 chan->secret = mdir;
2312 if (chan->c_private != mdir)
2314 strcat(outlist,"p");
2320 strcat(outlist,"-s+");
2324 strcat(outlist,"+s-");
2328 chan->c_private = mdir;
2332 log(DEBUG,"Preprocessing custom mode %c",modechar);
2335 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2337 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2340 if (ModeDefined(modechar,MT_CHANNEL))
2342 log(DEBUG,"A module has claimed this mode");
2345 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2347 p.push_back(parameters[param]);
2349 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2351 p.push_back(parameters[param]);
2354 bool handled = false;
2357 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2358 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2359 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2365 for (int i = 0; i <= MODCOUNT; i++)
2369 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2371 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2372 char app[] = {modechar, 0};
2375 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2377 strcat(outlist, app);
2379 else if (!strchr(outlist,modechar))
2381 strcat(outlist, app);
2384 chan->SetCustomMode(modechar,mdir);
2385 // include parameters in output if mode has them
2386 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2388 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2389 strcpy(outpars[pc++],parameters[param++]);
2391 // break, because only one module can handle the mode.
2403 /* this ensures only the *valid* modes are sent out onto the network */
2404 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2406 outlist[strlen(outlist)-1] = '\0';
2408 if (strcmp(outlist,""))
2410 strcpy(outstr,outlist);
2411 for (ptr = 0; ptr < pc; ptr++)
2414 strcat(outstr,outpars[ptr]);
2418 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2422 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2427 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2429 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2431 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2432 // RFC1459 specified modes
2433 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2435 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2439 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2440 if ((strchr(sourcemodes,'o')) && (!adding))
2442 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2445 else if (umode == 'o')
2447 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2451 // process any module-defined modes that need oper
2452 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2454 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2458 if (ModeDefined(umode,MT_CLIENT))
2460 // process any module-defined modes that don't need oper
2461 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2462 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2464 // no, this mode needs oper, and this user 'aint got what it takes!
2470 // anything else - return false.
2471 log(DEBUG,"umode %c not known by any ruleset",umode);
2475 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2479 if (ModeDefined(umode,MT_CLIENT))
2481 for (int i = 0; i <= MODCOUNT; i++)
2483 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2485 log(DEBUG,"Module claims umode %c",umode);
2489 log(DEBUG,"No module claims umode %c",umode);
2494 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2499 void handle_mode(char **parameters, int pcnt, userrec *user)
2505 char outpars[MAXBUF];
2507 dest = Find(parameters[0]);
2509 if ((dest) && (pcnt == 1))
2511 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2515 if ((dest) && (pcnt > 1))
2517 char dmodes[MAXBUF];
2518 strncpy(dmodes,dest->modes,MAXBUF);
2519 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2524 if (strchr(user->modes,'o'))
2535 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2539 strcpy(outpars,"+");
2542 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2545 for (i = 0; i < strlen(parameters[1]); i++)
2547 if (parameters[1][i] == '+')
2551 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2553 outpars[strlen(outpars)-1] = '+';
2557 strcat(outpars,"+");
2563 if (parameters[1][i] == '-')
2567 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2569 outpars[strlen(outpars)-1] = '-';
2573 strcat(outpars,"-");
2581 if (strchr(user->modes,'o'))
2587 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2596 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2598 char umode = parameters[1][i];
2599 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2601 dmodes[strlen(dmodes)+1]='\0';
2602 dmodes[strlen(dmodes)] = parameters[1][i];
2603 outpars[strlen(outpars)+1]='\0';
2604 outpars[strlen(outpars)] = parameters[1][i];
2610 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2612 char umode = parameters[1][i];
2613 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2619 outpars[strlen(outpars)+1]='\0';
2620 outpars[strlen(outpars)] = parameters[1][i];
2623 for (q = 0; q < strlen(dmodes); q++)
2625 if (dmodes[q] != parameters[1][i])
2632 strcpy(dmodes,temp);
2639 if (strlen(outpars))
2645 while (i < strlen (outpars))
2647 b[z++] = outpars[i++];
2649 if (i<strlen(outpars)-1)
2651 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2653 // someones playing silly buggers and trying
2654 // to put a +- or -+ into the line...
2658 if (i == strlen(outpars)-1)
2660 if ((outpars[i] == '-') || (outpars[i] == '+'))
2668 if ((b[z] == '-') || (b[z] == '+'))
2671 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2674 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2676 if (strlen(dmodes)>MAXMODES)
2678 dmodes[MAXMODES-1] = '\0';
2680 log(DEBUG,"Stripped mode line");
2681 log(DEBUG,"Line dest is now %s",dmodes);
2682 strncpy(dest->modes,dmodes,MAXMODES);
2689 Ptr = FindChan(parameters[0]);
2694 /* just /modes #channel */
2695 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2696 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2702 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2705 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2707 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2709 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2713 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2715 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
2719 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2723 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2730 void server_mode(char **parameters, int pcnt, userrec *user)
2736 char outpars[MAXBUF];
2738 dest = Find(parameters[0]);
2740 // fix: ChroNiCk found this - we cant use this as debug if its null!
2743 log(DEBUG,"server_mode on %s",dest->nick);
2746 if ((dest) && (pcnt > 1))
2748 log(DEBUG,"params > 1");
2750 char dmodes[MAXBUF];
2751 strncpy(dmodes,dest->modes,MAXBUF);
2753 strcpy(outpars,"+");
2756 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2759 for (i = 0; i < strlen(parameters[1]); i++)
2761 if (parameters[1][i] == '+')
2765 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2767 outpars[strlen(outpars)-1] = '+';
2771 strcat(outpars,"+");
2777 if (parameters[1][i] == '-')
2781 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2783 outpars[strlen(outpars)-1] = '-';
2787 strcat(outpars,"-");
2794 log(DEBUG,"begin mode processing entry");
2800 log(DEBUG,"umode %c being added",parameters[1][i]);
2801 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2803 char umode = parameters[1][i];
2804 log(DEBUG,"umode %c is an allowed umode",umode);
2805 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2807 dmodes[strlen(dmodes)+1]='\0';
2808 dmodes[strlen(dmodes)] = parameters[1][i];
2809 outpars[strlen(outpars)+1]='\0';
2810 outpars[strlen(outpars)] = parameters[1][i];
2816 // can only remove a mode they already have
2817 log(DEBUG,"umode %c being removed",parameters[1][i]);
2818 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2820 char umode = parameters[1][i];
2821 log(DEBUG,"umode %c is an allowed umode",umode);
2822 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2828 outpars[strlen(outpars)+1]='\0';
2829 outpars[strlen(outpars)] = parameters[1][i];
2832 for (q = 0; q < strlen(dmodes); q++)
2834 if (dmodes[q] != parameters[1][i])
2841 strcpy(dmodes,temp);
2848 if (strlen(outpars))
2854 while (i < strlen (outpars))
2856 b[z++] = outpars[i++];
2858 if (i<strlen(outpars)-1)
2860 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2862 // someones playing silly buggers and trying
2863 // to put a +- or -+ into the line...
2867 if (i == strlen(outpars)-1)
2869 if ((outpars[i] == '-') || (outpars[i] == '+'))
2877 if ((b[z] == '-') || (b[z] == '+'))
2880 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2883 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2885 if (strlen(dmodes)>MAXMODES)
2887 dmodes[MAXMODES-1] = '\0';
2889 log(DEBUG,"Stripped mode line");
2890 log(DEBUG,"Line dest is now %s",dmodes);
2891 strncpy(dest->modes,dmodes,MAXMODES);
2898 Ptr = FindChan(parameters[0]);
2901 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2905 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2910 /* This function pokes and hacks at a parameter list like the following:
2912 * PART #winbot, #darkgalaxy :m00!
2914 * to turn it into a series of individual calls like this:
2916 * PART #winbot :m00!
2917 * PART #darkgalaxy :m00!
2919 * The seperate calls are sent to a callback function provided by the caller
2920 * (the caller will usually call itself recursively). The callback function
2921 * must be a command handler. Calling this function on a line with no list causes
2922 * no action to be taken. You must provide a starting and ending parameter number
2923 * where the range of the list can be found, useful if you have a terminating
2924 * parameter as above which is actually not part of the list, or parameters
2925 * before the actual list as well. This code is used by many functions which
2926 * can function as "one to list" (see the RFC) */
2928 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2933 char blog[32][MAXBUF];
2934 char blog2[32][MAXBUF];
2935 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2936 char keystr[MAXBUF];
2939 for (i = 0; i <32; i++)
2942 for (i = 0; i <32; i++)
2943 strcpy(blog2[i],"");
2946 for (i = 0; i <10; i++)
2950 parameters[i] = moo;
2955 if (pcnt > 1) /* we have a key to copy */
2957 strcpy(keystr,parameters[1]);
2961 if (!parameters[start])
2965 if (!strchr(parameters[start],','))
2970 for (i = start; i <= end; i++)
2974 strcat(plist,parameters[i]);
2982 for (i = 0; i < t; i++)
2984 if (plist[i] == ',')
2987 strcpy(blog[j++],param);
2991 strcpy(blog[j++],param);
2994 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2999 if ((joins) && (keystr))
3001 if (strchr(keystr,','))
3005 t2 = strlen(keystr);
3006 for (i = 0; i < t2; i++)
3008 if (keystr[i] == ',')
3011 strcpy(blog2[j++],param);
3015 strcpy(blog2[j++],param);
3022 // limit the total items in a comma seperated list
3023 // a phidjit bug... go figure.
3027 for (j = 0; j < total; j++)
3033 for (q = end; q < pcnt-1; q++)
3035 if (parameters[q+1])
3037 pars[q-end+1] = parameters[q+1];
3040 if ((joins) && (parameters[1]))
3051 /* repeatedly call the function with the hacked parameter list */
3052 if ((joins) && (pcnt > 1))
3056 // pars[1] already set up and containing key from blog2[j]
3061 pars[1] = parameters[1];
3067 fn(pars,pcnt-(end-start),u);
3075 void handle_join(char **parameters, int pcnt, userrec *user)
3080 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3082 if (parameters[0][0] == '#')
3084 Ptr = add_channel(user,parameters[0],parameters[1]);
3089 void handle_part(char **parameters, int pcnt, userrec *user)
3095 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3097 del_channel(user,parameters[0],parameters[1]);
3101 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3103 del_channel(user,parameters[0],NULL);
3107 void handle_kick(char **parameters, int pcnt, userrec *user)
3109 chanrec* Ptr = FindChan(parameters[0]);
3110 userrec* u = Find(parameters[1]);
3114 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3118 if (!has_channel(u,Ptr))
3120 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3126 char reason[MAXBUF];
3127 strncpy(reason,parameters[2],MAXBUF);
3128 if (strlen(reason)>MAXKICK)
3130 reason[MAXKICK-1] = '\0';
3133 kick_channel(user,u,Ptr,reason);
3137 kick_channel(user,u,Ptr,user->nick);
3142 void handle_die(char **parameters, int pcnt, userrec *user)
3144 log(DEBUG,"die: %s",user->nick);
3145 if (!strcmp(parameters[0],diepass))
3147 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3153 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3157 void handle_restart(char **parameters, int pcnt, userrec *user)
3159 log(DEBUG,"restart: %s",user->nick);
3160 if (!strcmp(parameters[0],restartpass))
3162 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3165 /* Will finish this later when i can be arsed :) */
3169 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3174 void kill_link(userrec *user,const char* r)
3176 user_hash::iterator iter = clientlist.find(user->nick);
3178 char reason[MAXBUF];
3180 strncpy(reason,r,MAXBUF);
3182 if (strlen(reason)>MAXQUIT)
3184 reason[MAXQUIT-1] = '\0';
3187 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3188 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3189 log(DEBUG,"closing fd %d",user->fd);
3191 /* bugfix, cant close() a nonblocking socket (sux!) */
3192 if (user->registered == 7) {
3193 FOREACH_MOD OnUserQuit(user);
3194 WriteCommonExcept(user,"QUIT :%s",reason);
3197 /* push the socket on a stack of sockets due to be closed at the next opportunity
3198 * 'Client exited' is an exception to this as it means the client side has already
3199 * closed the socket, we don't need to do it.
3201 fd_reap.push_back(user->fd);
3203 bool do_purge = false;
3205 if (user->registered == 7) {
3206 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3210 if (iter != clientlist.end())
3212 log(DEBUG,"deleting user hash value %d",iter->second);
3213 if ((iter->second) && (user->registered == 7)) {
3214 delete iter->second;
3216 clientlist.erase(iter);
3219 if (user->registered == 7) {
3220 purge_empty_chans();
3225 void handle_kill(char **parameters, int pcnt, userrec *user)
3227 userrec *u = Find(parameters[0]);
3228 char killreason[MAXBUF];
3230 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3233 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3234 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3235 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3236 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3237 kill_link(u,killreason);
3241 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3245 void handle_summon(char **parameters, int pcnt, userrec *user)
3247 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3250 void handle_users(char **parameters, int pcnt, userrec *user)
3252 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3256 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3258 char* Passwd(userrec *user)
3260 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3262 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3270 bool IsDenied(userrec *user)
3272 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3274 if (match(user->host,i->host) && (i->type == CC_DENY))
3284 void handle_pass(char **parameters, int pcnt, userrec *user)
3286 // Check to make sure they havnt registered -- Fix by FCS
3287 if (user->registered == 7)
3289 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3292 if (!strcasecmp(parameters[0],Passwd(user)))
3294 user->haspassed = true;
3298 void handle_invite(char **parameters, int pcnt, userrec *user)
3300 userrec* u = Find(parameters[0]);
3301 chanrec* c = FindChan(parameters[1]);
3307 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3313 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3322 if (cstatus(user,c) < STATUS_HOP)
3324 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
3328 if (has_channel(u,c))
3330 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
3333 if (!has_channel(user,c))
3335 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
3338 u->InviteTo(c->name);
3339 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3340 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3343 void handle_topic(char **parameters, int pcnt, userrec *user)
3349 if (strlen(parameters[0]) <= CHANMAX)
3351 Ptr = FindChan(parameters[0]);
3356 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3357 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3361 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3366 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3373 if (strlen(parameters[0]) <= CHANMAX)
3375 Ptr = FindChan(parameters[0]);
3378 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3380 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
3385 strncpy(topic,parameters[1],MAXBUF);
3386 if (strlen(topic)>MAXTOPIC)
3388 topic[MAXTOPIC-1] = '\0';
3391 strcpy(Ptr->topic,topic);
3392 strcpy(Ptr->setby,user->nick);
3393 Ptr->topicset = time(NULL);
3394 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3398 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3404 /* sends out an error notice to all connected clients (not to be used
3407 void send_error(char *s)
3409 log(DEBUG,"send_error: %s",s);
3410 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3412 if (isnick(i->second->nick))
3414 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3418 // fix - unregistered connections receive ERROR, not NOTICE
3419 Write(i->second->fd,"ERROR :%s",s);
3424 void Error(int status)
3426 signal (SIGALRM, SIG_IGN);
3427 signal (SIGPIPE, SIG_IGN);
3428 signal (SIGTERM, SIG_IGN);
3429 signal (SIGABRT, SIG_IGN);
3430 signal (SIGSEGV, SIG_IGN);
3431 signal (SIGURG, SIG_IGN);
3432 signal (SIGKILL, SIG_IGN);
3433 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3434 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3439 int main (int argc, char *argv[])
3442 log(DEBUG,"*** InspIRCd starting up!");
3443 if (!FileExists(CONFIG_FILE))
3445 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3446 log(DEBUG,"main: no config");
3447 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3451 if (!strcmp(argv[1],"-nofork")) {
3455 if (InspIRCd() == ERROR)
3457 log(DEBUG,"main: daemon function bailed");
3458 printf("ERROR: could not initialise. Shutting down.\n");
3465 template<typename T> inline string ConvToStr(const T &in)
3468 if (!(tmp << in)) return string();
3472 /* re-allocates a nick in the user_hash after they change nicknames,
3473 * returns a pointer to the new user as it may have moved */
3475 userrec* ReHashNick(char* Old, char* New)
3477 user_hash::iterator newnick;
3478 user_hash::iterator oldnick = clientlist.find(Old);
3480 log(DEBUG,"ReHashNick: %s %s",Old,New);
3482 if (!strcasecmp(Old,New))
3484 log(DEBUG,"old nick is new nick, skipping");
3485 return oldnick->second;
3488 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3490 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3492 clientlist[New] = new userrec();
3493 clientlist[New] = oldnick->second;
3494 /*delete oldnick->second; */
3495 clientlist.erase(oldnick);
3497 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3499 return clientlist[New];
3502 /* adds or updates an entry in the whowas list */
3503 void AddWhoWas(userrec* u)
3505 user_hash::iterator iter = whowas.find(u->nick);
3506 userrec *a = new userrec();
3507 strcpy(a->nick,u->nick);
3508 strcpy(a->ident,u->ident);
3509 strcpy(a->dhost,u->dhost);
3510 strcpy(a->host,u->host);
3511 strcpy(a->fullname,u->fullname);
3512 strcpy(a->server,u->server);
3513 a->signon = u->signon;
3515 /* MAX_WHOWAS: max number of /WHOWAS items
3516 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3517 * can be replaced by a newer one
3520 if (iter == whowas.end())
3522 if (whowas.size() == WHOWAS_MAX)
3524 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3526 // 3600 seconds in an hour ;)
3527 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3531 log(DEBUG,"added WHOWAS entry, purged an old record");
3538 log(DEBUG,"added fresh WHOWAS entry");
3539 whowas[a->nick] = a;
3544 log(DEBUG,"updated WHOWAS entry");
3545 delete iter->second;
3551 /* add a client connection to the sockets list */
3552 void AddClient(int socket, char* host, int port, bool iscached)
3556 char resolved[MAXBUF];
3559 user_hash::iterator iter;
3561 tempnick = ConvToStr(socket) + "-unknown";
3562 sprintf(tn2,"%d-unknown",socket);
3564 iter = clientlist.find(tempnick);
3566 if (iter != clientlist.end()) return;
3569 * It is OK to access the value here this way since we know
3570 * it exists, we just created it above.
3572 * At NO other time should you access a value in a map or a
3573 * hash_map this way.
3575 clientlist[tempnick] = new userrec();
3577 NonBlocking(socket);
3578 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3580 clientlist[tempnick]->fd = socket;
3581 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3582 strncpy(clientlist[tempnick]->host, host,160);
3583 strncpy(clientlist[tempnick]->dhost, host,160);
3584 strncpy(clientlist[tempnick]->server, ServerName,256);
3585 strncpy(clientlist[tempnick]->ident, "unknown",9);
3586 clientlist[tempnick]->registered = 0;
3587 clientlist[tempnick]->signon = time(NULL);
3588 clientlist[tempnick]->nping = time(NULL)+240;
3589 clientlist[tempnick]->lastping = 1;
3590 clientlist[tempnick]->port = port;
3594 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3598 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3601 // set the registration timeout for this user
3602 unsigned long class_regtimeout = 90;
3603 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3605 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3607 class_regtimeout = (unsigned long)i->registration_timeout;
3611 log(DEBUG,"Client has a connection timeout value of %d",class_regtimeout);
3612 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3614 if (clientlist.size() == MAXCLIENTS)
3615 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3618 void handle_names(char **parameters, int pcnt, userrec *user)
3622 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3624 c = FindChan(parameters[0]);
3627 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3629 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3633 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3638 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3643 user->idle_lastmsg = time(NULL);
3645 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3647 if (parameters[0][0] == '#')
3649 chan = FindChan(parameters[0]);
3652 if ((chan->noexternal) && (!has_channel(user,chan)))
3654 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3657 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3659 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3665 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3670 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3674 /* no such nick/channel */
3675 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3680 dest = Find(parameters[0]);
3683 if (strcmp(dest->awaymsg,""))
3685 /* auto respond with aweh msg */
3686 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3691 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
3696 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3700 /* no such nick/channel */
3701 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3705 void handle_notice(char **parameters, int pcnt, userrec *user)
3710 user->idle_lastmsg = time(NULL);
3712 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3714 if (parameters[0][0] == '#')
3716 chan = FindChan(parameters[0]);
3719 if ((chan->noexternal) && (!has_channel(user,chan)))
3721 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3724 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3726 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3732 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3737 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3741 /* no such nick/channel */
3742 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3747 dest = Find(parameters[0]);
3752 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
3757 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3761 /* no such nick/channel */
3762 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3768 char* chlist(userrec *user)
3773 log(DEBUG,"chlist: %s",user->nick);
3779 for (i = 0; i != MAXCHANS; i++)
3781 if (user->chans[i].channel != NULL)
3783 if (user->chans[i].channel->name)
3785 strcpy(cmp,user->chans[i].channel->name);
3787 if (!strstr(lst,cmp))
3789 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3791 strcat(lst,cmode(user,user->chans[i].channel));
3792 strcat(lst,user->chans[i].channel->name);
3802 void handle_info(char **parameters, int pcnt, userrec *user)
3804 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3805 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3806 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3807 FOREACH_MOD OnInfo(user);
3808 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3811 void handle_time(char **parameters, int pcnt, userrec *user)
3814 struct tm * timeinfo;
3817 timeinfo = localtime ( &rawtime );
3818 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3822 void handle_whois(char **parameters, int pcnt, userrec *user)
3827 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3829 dest = Find(parameters[0]);
3832 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3833 if (dest->registered == 7)
3835 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3836 if ((user == dest) || (strchr(user->modes,'o')))
3838 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3840 if (strcmp(chlist(dest),""))
3842 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3844 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3845 if (strcmp(dest->awaymsg,""))
3847 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3849 if (strchr(dest->modes,'o'))
3851 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3853 FOREACH_MOD OnWhois(user,dest);
3854 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3855 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3857 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3861 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3866 /* no such nick/channel */
3867 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3871 void handle_quit(char **parameters, int pcnt, userrec *user)
3873 user_hash::iterator iter = clientlist.find(user->nick);
3876 if (user->registered == 7)
3878 /* theres more to do here, but for now just close the socket */
3881 if (parameters[0][0] == ':')
3885 reason = parameters[0];
3887 if (strlen(reason)>MAXQUIT)
3889 reason[MAXQUIT-1] = '\0';
3892 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3893 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3894 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3898 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3899 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3900 WriteCommonExcept(user,"QUIT :Client exited");
3902 FOREACH_MOD OnUserQuit(user);
3906 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3907 fd_reap.push_back(user->fd);
3909 if (iter != clientlist.end())
3911 log(DEBUG,"deleting user hash value %d",iter->second);
3912 if ((iter->second) && (user->registered == 7)) {
3913 delete iter->second;
3915 clientlist.erase(iter);
3918 if (user->registered == 7) {
3919 purge_empty_chans();
3923 void handle_who(char **parameters, int pcnt, userrec *user)
3925 chanrec* Ptr = NULL;
3927 /* theres more to do here, but for now just close the socket */
3930 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3932 if (user->chans[0].channel)
3934 Ptr = user->chans[0].channel;
3935 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3937 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3939 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);
3945 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3949 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3953 if (parameters[0][0] = '#')
3955 Ptr = FindChan(parameters[0]);
3958 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3960 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3962 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);
3965 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3969 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3975 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3977 Ptr = user->chans[0].channel;
3978 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3980 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3982 if (strchr(i->second->modes,'o'))
3984 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);
3988 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3994 void handle_wallops(char **parameters, int pcnt, userrec *user)
3996 WriteWallOps(user,"%s",parameters[0]);
3999 void handle_list(char **parameters, int pcnt, userrec *user)
4003 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4004 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4006 if ((!i->second->c_private) && (!i->second->secret))
4008 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4011 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4015 void handle_rehash(char **parameters, int pcnt, userrec *user)
4017 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
4019 FOREACH_MOD OnRehash();
4020 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
4026 return clientlist.size();
4029 int usercount_invisible(void)
4033 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4035 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4040 int usercount_opers(void)
4044 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4046 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4051 int usercount_unknown(void)
4055 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4057 if ((i->second->fd) && (i->second->registered != 7))
4065 return chanlist.size();
4068 int servercount(void)
4073 void handle_lusers(char **parameters, int pcnt, userrec *user)
4075 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4076 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4077 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4078 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4079 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4082 void handle_admin(char **parameters, int pcnt, userrec *user)
4084 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4085 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4086 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4087 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4090 void ShowMOTD(userrec *user)
4094 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4097 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4098 for (int i = 0; i != MOTD.size(); i++)
4100 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4102 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4105 void ShowRULES(userrec *user)
4109 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4112 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4113 for (int i = 0; i != RULES.size(); i++)
4115 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4117 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4120 /* shows the message of the day, and any other on-logon stuff */
4121 void ConnectUser(userrec *user)
4123 user->registered = 7;
4124 user->idle_lastmsg = time(NULL);
4125 log(DEBUG,"ConnectUser: %s",user->nick);
4127 if (strcmp(Passwd(user),"") && (!user->haspassed))
4129 kill_link(user,"Invalid password");
4134 kill_link(user,"Unauthorised connection");
4138 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4139 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4140 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4141 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4142 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4143 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);
4144 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);
4146 FOREACH_MOD OnUserConnect(user);
4147 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4150 void handle_version(char **parameters, int pcnt, userrec *user)
4152 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4155 void handle_ping(char **parameters, int pcnt, userrec *user)
4157 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4160 void handle_pong(char **parameters, int pcnt, userrec *user)
4162 // set the user as alive so they survive to next ping
4166 void handle_motd(char **parameters, int pcnt, userrec *user)
4171 void handle_rules(char **parameters, int pcnt, userrec *user)
4176 void handle_user(char **parameters, int pcnt, userrec *user)
4178 if (user->registered < 3)
4180 if (isident(parameters[0]) == 0) {
4181 // This kinda Sucks, According to the RFC thou, its either this,
4182 // or "You have already registered" :p -- Craig
4183 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4186 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4187 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4188 strncat(user->ident,parameters[0],IDENTMAX);
4189 strncpy(user->fullname,parameters[3],128);
4190 user->registered = (user->registered | 1);
4195 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4198 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4199 if (user->registered == 3)
4201 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4206 void handle_userhost(char **parameters, int pcnt, userrec *user)
4208 char Return[MAXBUF],junk[MAXBUF];
4209 sprintf(Return,"302 %s :",user->nick);
4210 for (int i = 0; i < pcnt; i++)
4212 userrec *u = Find(parameters[i]);
4215 if (strchr(u->modes,'o'))
4217 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4218 strcat(Return,junk);
4222 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4223 strcat(Return,junk);
4227 WriteServ(user->fd,Return);
4231 void handle_ison(char **parameters, int pcnt, userrec *user)
4233 char Return[MAXBUF];
4234 sprintf(Return,"303 %s :",user->nick);
4235 for (int i = 0; i < pcnt; i++)
4237 userrec *u = Find(parameters[i]);
4240 strcat(Return,u->nick);
4244 WriteServ(user->fd,Return);
4248 void handle_away(char **parameters, int pcnt, userrec *user)
4252 strcpy(user->awaymsg,parameters[0]);
4253 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4257 strcpy(user->awaymsg,"");
4258 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4262 void handle_whowas(char **parameters, int pcnt, userrec* user)
4264 user_hash::iterator i = whowas.find(parameters[0]);
4266 if (i == whowas.end())
4268 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4269 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4273 time_t rawtime = i->second->signon;
4277 timeinfo = localtime(&rawtime);
4278 strcpy(b,asctime(timeinfo));
4279 b[strlen(b)-1] = '\0';
4281 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4282 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4283 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4288 void handle_trace(char **parameters, int pcnt, userrec *user)
4290 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4294 if (isnick(i->second->nick))
4296 if (strchr(i->second->modes,'o'))
4298 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4302 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4307 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4313 void handle_modules(char **parameters, int pcnt, userrec *user)
4315 for (int i = 0; i < module_names.size(); i++)
4317 Version V = modules[i]->GetVersion();
4318 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());
4322 void handle_stats(char **parameters, int pcnt, userrec *user)
4328 if (strlen(parameters[0])>1)
4330 /* make the stats query 1 character long */
4331 parameters[0][1] = '\0';
4334 /* stats m (list number of times each command has been used, plus bytecount) */
4335 if (!strcasecmp(parameters[0],"m"))
4337 for (int i = 0; i < cmdlist.size(); i++)
4339 if (cmdlist[i].handler_function)
4341 if (cmdlist[i].use_count)
4343 /* RPL_STATSCOMMANDS */
4344 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4351 /* stats z (debug and memory info) */
4352 if (!strcasecmp(parameters[0],"z"))
4354 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4355 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4356 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4357 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4358 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4359 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4360 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4361 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4365 if (!strcasecmp(parameters[0],"o"))
4367 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
4369 char LoginName[MAXBUF];
4370 char HostName[MAXBUF];
4371 char OperType[MAXBUF];
4372 ConfValue("oper","name",i,LoginName,&config_f);
4373 ConfValue("oper","host",i,HostName,&config_f);
4374 ConfValue("oper","type",i,OperType,&config_f);
4375 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4379 /* stats l (show user I/O stats) */
4380 if (!strcasecmp(parameters[0],"l"))
4382 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4383 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4385 if (isnick(i->second->nick))
4387 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);
4391 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);
4397 /* stats u (show server uptime) */
4398 if (!strcasecmp(parameters[0],"u"))
4400 time_t current_time = 0;
4401 current_time = time(NULL);
4402 time_t server_uptime = current_time - startup_time;
4404 stime = gmtime(&server_uptime);
4405 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4406 * Craig suggested this, and it seemed a good idea so in it went */
4407 if (stime->tm_year > 70)
4409 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);
4413 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);
4417 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4418 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4422 void handle_connect(char **parameters, int pcnt, userrec *user)
4424 char Link_ServerName[1024];
4425 char Link_IPAddr[1024];
4426 char Link_Port[1024];
4427 char Link_Pass[1024];
4431 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4433 ConfValue("link","name",i,Link_ServerName,&config_f);
4434 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4435 ConfValue("link","port",i,Link_Port,&config_f);
4436 ConfValue("link","sendpass",i,Link_Pass,&config_f);
4437 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4438 LinkPort = atoi(Link_Port);
4439 if (match(Link_ServerName,parameters[0])) {
4445 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4449 // TODO: Perform a check here to stop a server being linked twice!
4451 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4453 if (me[defaultRoute])
4456 // at this point parameters[0] is an ip in a string.
4457 // TODO: Look this up from the <link> blocks instead!
4458 for (int j = 0; j < 255; j++) {
4459 if (servers[j] == NULL) {
4460 servers[j] = new serverrec;
4461 strcpy(servers[j]->internal_addr,Link_IPAddr);
4462 strcpy(servers[j]->name,Link_ServerName);
4463 log(DEBUG,"Allocated new serverrec");
4464 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4466 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4471 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4475 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);
4479 void handle_squit(char **parameters, int pcnt, userrec *user)
4481 // send out an squit across the mesh and then clear the server list (for local squit)
4484 void handle_oper(char **parameters, int pcnt, userrec *user)
4486 char LoginName[MAXBUF];
4487 char Password[MAXBUF];
4488 char OperType[MAXBUF];
4489 char TypeName[MAXBUF];
4490 char Hostname[MAXBUF];
4493 for (i = 0; i < ConfValueEnum("oper",&config_f); i++)
4495 ConfValue("oper","name",i,LoginName,&config_f);
4496 ConfValue("oper","password",i,Password,&config_f);
4497 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4499 /* correct oper credentials */
4500 ConfValue("oper","type",i,OperType,&config_f);
4501 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4502 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4503 WriteServ(user->fd,"MODE %s :+o",user->nick);
4504 for (j =0; j < ConfValueEnum("type",&config_f); j++)
4506 ConfValue("type","name",j,TypeName,&config_f);
4507 if (!strcmp(TypeName,OperType))
4509 /* found this oper's opertype */
4510 ConfValue("type","host",j,Hostname,&config_f);
4511 strncpy(user->dhost,Hostname,256);
4514 if (!strchr(user->modes,'o'))
4516 strcat(user->modes,"o");
4518 FOREACH_MOD OnOper(user);
4523 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4524 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4527 void handle_nick(char **parameters, int pcnt, userrec *user)
4531 log(DEBUG,"not enough params for handle_nick");
4536 log(DEBUG,"invalid parameter passed to handle_nick");
4539 if (!strlen(parameters[0]))
4541 log(DEBUG,"zero length new nick passed to handle_nick");
4546 log(DEBUG,"invalid user passed to handle_nick");
4551 log(DEBUG,"invalid old nick passed to handle_nick");
4554 if (!strcasecmp(user->nick,parameters[0]))
4556 log(DEBUG,"old nick is new nick, skipping");
4561 if (strlen(parameters[0]) > 1)
4563 if (parameters[0][0] == ':')
4568 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4570 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4574 if (isnick(parameters[0]) == 0)
4576 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4580 if (user->registered == 7)
4582 WriteCommon(user,"NICK %s",parameters[0]);
4585 /* change the nick of the user in the users_hash */
4586 user = ReHashNick(user->nick, parameters[0]);
4587 /* actually change the nick within the record */
4589 if (!user->nick) return;
4591 strncpy(user->nick, parameters[0],NICKMAX);
4593 log(DEBUG,"new nick set: %s",user->nick);
4595 if (user->registered < 3)
4596 user->registered = (user->registered | 2);
4597 if (user->registered == 3)
4599 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4602 log(DEBUG,"exit nickchange: %s",user->nick);
4605 void force_nickchange(userrec* user,const char* newnick)
4614 strncpy(nick,newnick,MAXBUF);
4616 if (user->registered == 7)
4620 handle_nick(pars,1,user);
4626 int process_parameters(char **command_p,char *parameters)
4631 q = strlen(parameters);
4634 /* no parameters, command_p invalid! */
4637 if (parameters[0] == ':')
4639 command_p[0] = parameters+1;
4644 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4646 /* only one parameter */
4647 command_p[0] = parameters;
4648 if (parameters[0] == ':')
4650 if (strchr(parameters,' ') != NULL)
4658 command_p[j++] = parameters;
4659 for (i = 0; i <= q; i++)
4661 if (parameters[i] == ' ')
4663 command_p[j++] = parameters+i+1;
4664 parameters[i] = '\0';
4665 if (command_p[j-1][0] == ':')
4667 *command_p[j-1]++; /* remove dodgy ":" */
4669 /* parameter like this marks end of the sequence */
4673 return j; /* returns total number of items in the list */
4676 void process_command(userrec *user, char* cmd)
4680 char *command_p[127];
4681 char p[MAXBUF], temp[MAXBUF];
4682 int i, j, items, cmd_found;
4684 for (int i = 0; i < 127; i++)
4685 command_p[i] = NULL;
4695 if (!strcmp(cmd,""))
4700 int total_params = 0;
4703 for (int q = 0; q < strlen(cmd)-1; q++)
4705 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
4708 // found a 'trailing', we dont count them after this.
4716 // another phidjit bug...
4717 if (total_params > 126)
4719 kill_link(user,"Protocol violation");
4726 FOREACH_MOD OnServerRaw(tmp,true);
4727 const char* cmd2 = tmp.c_str();
4728 snprintf(cmd,512,"%s",cmd2);
4730 if (!strchr(cmd,' '))
4732 /* no parameters, lets skip the formalities and not chop up
4734 log(DEBUG,"About to preprocess command with no params");
4736 command_p[0] = NULL;
4738 for (int i = 0; i <= strlen(cmd); i++)
4740 cmd[i] = toupper(cmd[i]);
4742 log(DEBUG,"Preprocess done");
4748 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4749 for (i = 0; i < strlen(temp); i++)
4751 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4757 /* split the full string into a command plus parameters */
4761 if (strchr(cmd,' '))
4763 for (i = 0; i <= strlen(cmd); i++)
4765 /* capitalise the command ONLY, leave params intact */
4766 cmd[i] = toupper(cmd[i]);
4767 /* are we nearly there yet?! :P */
4771 parameters = cmd+i+1;
4779 for (i = 0; i <= strlen(cmd); i++)
4781 cmd[i] = toupper(cmd[i]);
4789 if (strlen(command)>MAXCOMMAND)
4791 kill_link(user,"Protocol violation");
4795 for (int x = 0; x < strlen(command); x++)
4797 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
4799 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
4801 kill_link(user,"Protocol violation");
4807 for (i = 0; i != cmdlist.size(); i++)
4809 if (strcmp(cmdlist[i].command,""))
4811 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
4813 log(DEBUG,"Found matching command");
4817 if (strcmp(parameters,""))
4819 items = process_parameters(command_p,parameters);
4824 command_p[0] = NULL;
4830 command_p[0] = NULL;
4835 log(DEBUG,"Processing command");
4837 /* activity resets the ping pending timer */
4838 user->nping = time(NULL) + 120;
4839 if ((items) < cmdlist[i].min_params)
4841 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4842 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4845 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4847 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4848 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4852 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4854 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
4856 if ((!isnick(user->nick)) || (user->registered != 7))
4858 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4859 WriteServ(user->fd,"451 %s :You have not registered",command);
4863 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4865 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4866 if (cmdlist[i].handler_function)
4868 /* ikky /stats counters */
4873 user->bytes_in += strlen(temp);
4876 cmdlist[i].use_count++;
4877 cmdlist[i].total_bytes+=strlen(temp);
4880 /* WARNING: nothing may come after the
4881 * command handler call, as the handler
4882 * may free the user structure! */
4884 cmdlist[i].handler_function(command_p,items,user);
4890 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4891 WriteServ(user->fd,"451 %s :You have not registered",command);
4899 if ((!cmd_found) && (user))
4901 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4902 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4907 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4910 /* create the command and push it onto the table */
4911 strcpy(comm.command,cmd);
4912 comm.handler_function = f;
4913 comm.flags_needed = flags;
4914 comm.min_params = minparams;
4916 comm.total_bytes = 0;
4917 cmdlist.push_back(comm);
4918 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4921 void SetupCommandTable(void)
4923 createcommand("USER",handle_user,0,4);
4924 createcommand("NICK",handle_nick,0,1);
4925 createcommand("QUIT",handle_quit,0,0);
4926 createcommand("VERSION",handle_version,0,0);
4927 createcommand("PING",handle_ping,0,1);
4928 createcommand("PONG",handle_pong,0,1);
4929 createcommand("ADMIN",handle_admin,0,0);
4930 createcommand("PRIVMSG",handle_privmsg,0,2);
4931 createcommand("INFO",handle_info,0,0);
4932 createcommand("TIME",handle_time,0,0);
4933 createcommand("WHOIS",handle_whois,0,1);
4934 createcommand("WALLOPS",handle_wallops,'o',1);
4935 createcommand("NOTICE",handle_notice,0,2);
4936 createcommand("JOIN",handle_join,0,1);
4937 createcommand("NAMES",handle_names,0,1);
4938 createcommand("PART",handle_part,0,1);
4939 createcommand("KICK",handle_kick,0,2);
4940 createcommand("MODE",handle_mode,0,1);
4941 createcommand("TOPIC",handle_topic,0,1);
4942 createcommand("WHO",handle_who,0,1);
4943 createcommand("MOTD",handle_motd,0,0);
4944 createcommand("RULES",handle_rules,0,0);
4945 createcommand("OPER",handle_oper,0,2);
4946 createcommand("LIST",handle_list,0,0);
4947 createcommand("DIE",handle_die,'o',1);
4948 createcommand("RESTART",handle_restart,'o',1);
4949 createcommand("KILL",handle_kill,'o',2);
4950 createcommand("REHASH",handle_rehash,'o',0);
4951 createcommand("LUSERS",handle_lusers,0,0);
4952 createcommand("STATS",handle_stats,0,1);
4953 createcommand("USERHOST",handle_userhost,0,1);
4954 createcommand("AWAY",handle_away,0,0);
4955 createcommand("ISON",handle_ison,0,0);
4956 createcommand("SUMMON",handle_summon,0,0);
4957 createcommand("USERS",handle_users,0,0);
4958 createcommand("INVITE",handle_invite,0,2);
4959 createcommand("PASS",handle_pass,0,1);
4960 createcommand("TRACE",handle_trace,'o',0);
4961 createcommand("WHOWAS",handle_whowas,0,1);
4962 createcommand("CONNECT",handle_connect,'o',1);
4963 createcommand("SQUIT",handle_squit,'o',1);
4964 createcommand("MODULES",handle_modules,'o',0);
4967 void process_buffer(userrec *user)
4971 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4978 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4981 if (!strcmp(user->inbuf,""))
4985 strncpy(cmd,user->inbuf,MAXBUF);
4986 if (!strcmp(cmd,""))
4990 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4992 cmd[strlen(cmd)-1] = '\0';
4994 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4996 cmd[strlen(cmd)-1] = '\0';
4998 strcpy(user->inbuf,"");
4999 if (!strcmp(cmd,""))
5003 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5005 if ((user) && (cmd))
5007 process_command(user,cmd);
5011 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5013 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
5017 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
5019 char response[10240];
5020 char token = udp_msg[0];
5021 char* params = udp_msg + 2;
5022 char finalparam[1024];
5023 strcpy(finalparam," :xxxx");
5024 if (strstr(params," :")) {
5025 strncpy(finalparam,strstr(params," :"),1024);
5028 // S test.chatspike.net password :ChatSpike InspIRCd test server
5029 char* servername = strtok(params," ");
5030 char* password = strtok(NULL," ");
5031 char* serverdesc = finalparam+2;
5032 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
5035 char Link_ServerName[1024];
5036 char Link_IPAddr[1024];
5037 char Link_Port[1024];
5038 char Link_Pass[1024];
5039 char Link_SendPass[1024];
5042 // search for a corresponding <link> block in the config files
5043 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5045 ConfValue("link","name",i,Link_ServerName,&config_f);
5046 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5047 ConfValue("link","port",i,Link_Port,&config_f);
5048 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5049 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5050 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5051 LinkPort = atoi(Link_Port);
5052 if (!strcasecmp(Link_ServerName,servername)) {
5053 if (!strcasecmp(Link_IPAddr,udp_host)) {
5054 if (LinkPort == udp_port) {
5055 // we have a matching link line -
5056 // send a 'diminutive' server message back...
5057 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
5058 serv->SendPacket(response,udp_host,udp_port,0);
5059 WriteOpers("CONNECT from %s accepted, authenticating",servername);
5060 for (int j = 0; j < 255; j++) {
5061 if (servers[j] == NULL) {
5062 servers[j] = new serverrec;
5063 strcpy(servers[j]->internal_addr,udp_host);
5064 strcpy(servers[j]->name,servername);
5065 // create a server record for this server
5066 snprintf(response,10240,"O %d",MyKey);
5067 serv->SendPacket(response,udp_host,udp_port,0);
5071 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
5075 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5079 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5083 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5086 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5087 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5092 // if this is received, this means the server-ip that sent it said "OK" to credentials.
5093 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
5094 // array, which is only added by an 'S' packet or BeginLink().
5095 for (int i = 0; i < 255; i++) {
5096 if (servers[i] != NULL) {
5097 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
5098 servers[i]->key = atoi(params);
5099 log(DEBUG,"Key for this server is now %d",servers[i]->key);
5100 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
5105 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
5109 // S test.chatspike.net password :ChatSpike InspIRCd test server
5110 char* servername = strtok(params," ");
5111 char* password = strtok(NULL," ");
5112 char* serverdesc = finalparam+2;
5114 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5115 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5116 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5117 // a connect, so put out an oper alert!
5122 // for now, just accept all, we'll fix that later.
5123 WriteOpers("%s accepted our link credentials ",servername);
5125 char Link_ServerName[1024];
5126 char Link_IPAddr[1024];
5127 char Link_Port[1024];
5128 char Link_Pass[1024];
5129 char Link_SendPass[1024];
5132 // search for a corresponding <link> block in the config files
5133 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5135 ConfValue("link","name",i,Link_ServerName,&config_f);
5136 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5137 ConfValue("link","port",i,Link_Port,&config_f);
5138 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5139 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5140 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5141 LinkPort = atoi(Link_Port);
5142 if (!strcasecmp(Link_ServerName,servername)) {
5143 if (!strcasecmp(Link_IPAddr,udp_host)) {
5144 if (LinkPort == udp_port) {
5145 // matching link at this end too, we're all done!
5146 // at this point we must begin key exchange and insert this
5147 // server into our 'active' table.
5148 for (int j = 0; j < 255; j++) {
5149 if (servers[j] != NULL) {
5150 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5151 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5152 snprintf(response,10240,"O %d",MyKey);
5153 serv->SendPacket(response,udp_host,udp_port,0);
5158 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5163 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5167 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5171 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5174 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5175 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5180 char* error_message = finalparam+2;
5181 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5182 // remove this server from any lists
5183 for (int j = 0; j < 255; j++) {
5184 if (servers[j] != NULL) {
5185 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5195 serverrec* source_server = NULL;
5197 for (int j = 0; j < 255; j++) {
5198 if (servers[j] != NULL) {
5199 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5200 if (servers[j]->key == theirkey) {
5201 // found a valid key for this server, can process restricted stuff here
5202 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5210 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5214 int reap_counter = 0;
5218 struct sockaddr_in client, server;
5219 char addrs[MAXBUF][255];
5220 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5222 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5223 int selectResult = 0;
5224 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5225 char resolvedHost[MAXBUF];
5229 log_file = fopen("ircd.log","a+");
5232 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5236 log(DEBUG,"InspIRCd: startup: begin");
5240 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5242 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5244 SetupCommandTable();
5245 log(DEBUG,"InspIRCd: startup: default command table set up");
5248 if (strcmp(DieValue,""))
5250 printf("WARNING: %s\n\n",DieValue);
5253 log(DEBUG,"InspIRCd: startup: read config");
5255 int count2 = 0, count3 = 0;
5257 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5259 ConfValue("bind","port",count,configToken,&config_f);
5260 ConfValue("bind","address",count,Addr,&config_f);
5261 ConfValue("bind","type",count,Type,&config_f);
5262 if (!strcmp(Type,"servers"))
5264 char Default[MAXBUF];
5265 strcpy(Default,"no");
5266 ConfValue("bind","default",count,Default,&config_f);
5267 if (strchr(Default,'y'))
5269 defaultRoute = count3;
5270 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5272 me[count3] = new serverrec(ServerName,100L,false);
5273 me[count3]->CreateListener(Addr,atoi(configToken));
5278 ports[count2] = atoi(configToken);
5279 strcpy(addrs[count2],Addr);
5282 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5285 UDPportCount = count3;
5287 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5289 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5293 /* BugFix By Craig! :p */
5295 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5297 char modfile[MAXBUF];
5298 ConfValue("module","name",count2,configToken,&config_f);
5299 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5300 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5301 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5302 /* If The File Doesnt exist, Trying to load it
5303 * Will Segfault the IRCd.. So, check to see if
5304 * it Exists, Before Proceeding. */
5305 if (FileExists(modfile))
5307 factory[count] = new ircd_module(modfile);
5308 if (factory[count]->LastError())
5310 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5311 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5314 if (factory[count]->factory)
5316 modules[count] = factory[count]->factory->CreateModule();
5317 /* save the module and the module's classfactory, if
5318 * this isnt done, random crashes can occur :/ */
5319 module_names.push_back(modfile);
5323 log(DEBUG,"Unable to load %s",modfile);
5324 sprintf("Unable to load %s\nExiting...\n",modfile);
5327 /* Increase the Count */
5332 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5333 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5336 MODCOUNT = count - 1;
5337 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5339 printf("\nInspIRCd is now running!\n");
5341 startup_time = time(NULL);
5345 log(VERBOSE,"Not forking as -nofork was specified");
5349 if (DaemonSeed() == ERROR)
5351 log(DEBUG,"InspIRCd: startup: can't daemonise");
5352 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5358 /* setup select call */
5359 FD_ZERO(&selectFds);
5360 log(DEBUG,"InspIRCd: startup: zero selects");
5361 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5363 for (count = 0; count < portCount; count++)
5365 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5367 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5370 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5372 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5374 else /* well we at least bound to one socket so we'll continue */
5380 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5382 /* if we didn't bind to anything then abort */
5383 if (boundPortCount == 0)
5385 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5389 length = sizeof (client);
5390 int flip_flop = 0, udp_port = 0;
5391 char udp_msg[MAXBUF], udp_host[MAXBUF];
5393 /* main loop for multiplexing/resetting */
5396 /* set up select call */
5397 for (count = 0; count < boundPortCount; count++)
5399 FD_SET (openSockfd[count], &selectFds);
5402 /* added timeout! select was waiting forever... wank... :/ */
5413 vector<int>::iterator niterator;
5416 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5417 // them in a list, then reap the list every second or so.
5418 if (reap_counter>5000) {
5419 if (fd_reap.size() > 0) {
5420 for( int n = 0; n < fd_reap.size(); n++)
5422 Blocking(fd_reap[n]);
5424 NonBlocking(fd_reap[n]);
5433 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5435 for (int x = 0; x != UDPportCount; x++)
5438 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5440 if (strlen(udp_msg)<1) {
5441 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5445 FOREACH_MOD OnPacketReceive(udp_msg);
5446 // Packets must go back via the route they arrived on :)
5447 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5452 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5456 if (!count2->second) break;
5459 if (count2->second->fd)
5461 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5462 // their connection class.
5463 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
5465 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5466 kill_link(count2->second,"Registration timeout");
5469 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5471 if (!count2->second->lastping)
5473 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5474 kill_link(count2->second,"Ping timeout");
5477 Write(count2->second->fd,"PING :%s",ServerName);
5478 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5479 count2->second->lastping = 0;
5480 count2->second->nping = time(NULL)+120;
5483 result = read(count2->second->fd, data, 1);
5484 // result EAGAIN means nothing read
5485 if (result == EAGAIN)
5493 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5494 kill_link(count2->second,"Client exited");
5495 // must bail here? kill_link removes the hash, corrupting the iterator
5496 log(DEBUG,"Bailing from client exit");
5500 else if (result > 0)
5505 // until the buffer is at 509 chars anything can be inserted into it.
5506 if ((strlen(count2->second->inbuf) < 509) && (data[0] != '\0')) {
5507 strncat(count2->second->inbuf, data, result);
5510 // once you reach 509 chars, only a \r or \n can be inserted,
5511 // completing the line.
5512 if ((strlen(count2->second->inbuf) >= 509) && ((data[0] == '\r') || (data[0] == '\n'))) {
5513 count2->second->inbuf[509] = '\r';
5514 count2->second->inbuf[510] = '\n';
5515 count2->second->inbuf[511] = '\0';
5516 process_buffer(count2->second);
5520 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5522 /* at least one complete line is waiting to be processed */
5523 if (!count2->second->fd)
5527 if (strlen(count2->second->inbuf)<512)
5529 // double check the length before processing!
5530 process_buffer(count2->second);
5534 strcpy(count2->second->inbuf,"");
5544 /* select is reporting a waiting socket. Poll them all to find out which */
5545 if (selectResult > 0)
5547 char target[MAXBUF], resolved[MAXBUF];
5548 for (count = 0; count < boundPortCount; count++)
5550 if (FD_ISSET (openSockfd[count], &selectFds))
5552 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5554 address_cache::iterator iter = IP.find(client.sin_addr);
5555 bool iscached = false;
5556 if (iter == IP.end())
5558 /* ip isn't in cache, add it */
5559 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5560 if(CleanAndResolve(resolved, target) != TRUE)
5562 strncpy(resolved,target,MAXBUF);
5564 /* hostname now in 'target' */
5565 IP[client.sin_addr] = new string(resolved);
5566 /* hostname in cache */
5570 /* found ip (cached) */
5571 strncpy(resolved, iter->second->c_str(), MAXBUF);
5575 if (incomingSockfd < 0)
5577 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5578 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5581 AddClient(incomingSockfd, resolved, ports[count], iscached);
5582 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5589 close (incomingSockfd);