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 FOREACH_MOD OnServerRaw(temp,false);
270 const char* str2 = temp.c_str();
271 sprintf(str,"%s",str2);
274 if (strlen(str) >= 512)
283 std::string getservername()
288 std::string getserverdesc()
293 std::string getnetworkname()
298 std::string getadminname()
303 std::string getadminemail()
308 std::string getadminnick()
313 void log(int level,char *text, ...)
315 char textbuffer[MAXBUF];
318 struct tm * timeinfo;
319 if (level < LogLevel)
323 timeinfo = localtime (&rawtime);
328 va_start (argsPtr, text);
329 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
331 strcpy(b,asctime(timeinfo));
332 b[strlen(b)-1] = ':';
333 fprintf(log_file,"%s %s\n",b,textbuffer);
336 // nofork enabled? display it on terminal too
337 printf("%s %s\n",b,textbuffer);
342 void readfile(file_cache &F, const char* fname)
345 char linebuf[MAXBUF];
347 log(DEBUG,"readfile: loading %s",fname);
349 file = fopen(fname,"r");
354 fgets(linebuf,sizeof(linebuf),file);
355 linebuf[strlen(linebuf)-1]='\0';
356 if (!strcmp(linebuf,""))
362 F.push_back(linebuf);
369 log(DEBUG,"readfile: failed to load file: %s",fname);
371 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
374 void ReadConfig(void)
376 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF];
379 LoadConf(CONFIG_FILE,&config_f);
381 ConfValue("server","name",0,ServerName,&config_f);
382 ConfValue("server","description",0,ServerDesc,&config_f);
383 ConfValue("server","network",0,Network,&config_f);
384 ConfValue("admin","name",0,AdminName,&config_f);
385 ConfValue("admin","email",0,AdminEmail,&config_f);
386 ConfValue("admin","nick",0,AdminNick,&config_f);
387 ConfValue("files","motd",0,motd,&config_f);
388 ConfValue("files","rules",0,rules,&config_f);
389 ConfValue("power","diepass",0,diepass,&config_f);
390 ConfValue("power","pause",0,pauseval,&config_f);
391 ConfValue("power","restartpass",0,restartpass,&config_f);
392 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
393 ConfValue("die","value",0,DieValue,&config_f);
394 ConfValue("options","loglevel",0,dbg,&config_f);
395 if (!strcmp(dbg,"debug"))
397 if (!strcmp(dbg,"verbose"))
399 if (!strcmp(dbg,"default"))
401 if (!strcmp(dbg,"sparse"))
403 if (!strcmp(dbg,"none"))
406 log(DEBUG,"Reading message of the day");
407 readfile(RULES,rules);
408 log(DEBUG,"Reading connect classes");
410 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
413 ConfValue("connect","allow",i,Value,&config_f);
414 ConfValue("connect","timeout",i,timeout,&config_f);
415 if (strcmp(Value,""))
417 strcpy(c.host,Value);
420 ConfValue("connect","password",i,Value,&config_f);
421 strcpy(c.pass,Value);
422 c.registration_timeout = 90; // default is 2 minutes
425 c.registration_timeout = atoi(timeout);
427 Classes.push_back(c);
428 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
432 ConfValue("connect","deny",i,Value,&config_f);
433 strcpy(c.host,Value);
435 Classes.push_back(c);
436 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
445 log(DEBUG,"Blocking: %d",s);
446 flags = fcntl(s, F_GETFL, 0);
447 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
450 void NonBlocking(int s)
453 log(DEBUG,"NonBlocking: %d",s);
454 flags = fcntl(s, F_GETFL, 0);
455 fcntl(s, F_SETFL, flags | O_NONBLOCK);
459 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
461 struct hostent *hostPtr = NULL;
464 memset (resolvedHost, '\0',MAXBUF);
465 if(unresolvedHost == NULL)
467 if ((inet_aton(unresolvedHost,&addr)) == 0)
469 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
471 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
473 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
477 /* write formatted text to a socket, in same format as printf */
479 void Write(int sock,char *text, ...)
483 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
486 char textbuffer[MAXBUF];
490 va_start (argsPtr, text);
491 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
493 sprintf(tb,"%s\r\n",textbuffer);
495 write(sock,tb,strlen(tb));
496 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
499 /* write a server formatted numeric response to a single socket */
501 void WriteServ(int sock, char* text, ...)
505 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
508 char textbuffer[MAXBUF],tb[MAXBUF];
510 va_start (argsPtr, text);
512 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
514 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
516 write(sock,tb,strlen(tb));
517 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
520 /* write text from an originating user to originating user */
522 void WriteFrom(int sock, userrec *user,char* text, ...)
524 if ((!text) || (!user))
526 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
529 char textbuffer[MAXBUF],tb[MAXBUF];
531 va_start (argsPtr, text);
533 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
535 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
537 write(sock,tb,strlen(tb));
538 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
541 /* write text to an destination user from a source user (e.g. user privmsg) */
543 void WriteTo(userrec *source, userrec *dest,char *data, ...)
545 if ((!source) || (!dest) || (!data))
547 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
550 char textbuffer[MAXBUF],tb[MAXBUF];
552 va_start (argsPtr, data);
553 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
556 WriteFrom(dest->fd,source,"%s",textbuffer);
559 /* write formatted text from a source user to all users on a channel
560 * including the sender (NOT for privmsg, notice etc!) */
562 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
564 if ((!Ptr) || (!user) || (!text))
566 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
569 char textbuffer[MAXBUF];
571 va_start (argsPtr, text);
572 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
574 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
576 if (has_channel(i->second,Ptr))
578 WriteTo(user,i->second,"%s",textbuffer);
583 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
585 if ((!Ptr) || (!user) || (!text))
587 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
590 char textbuffer[MAXBUF];
592 va_start (argsPtr, text);
593 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
595 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
599 if (has_channel(i->second,Ptr))
601 WriteServ(i->second->fd,"%s",textbuffer);
608 /* write formatted text from a source user to all users on a channel except
609 * for the sender (for privmsg etc) */
611 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
613 if ((!Ptr) || (!user) || (!text))
615 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
618 char textbuffer[MAXBUF];
620 va_start (argsPtr, text);
621 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
624 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
628 if (has_channel(i->second,Ptr) && (user != i->second))
630 WriteTo(user,i->second,"%s",textbuffer);
636 int c_count(userrec* u)
639 for (int i =0; i != MAXCHANS; i++)
640 if (u->chans[i].channel != NULL)
646 /* return 0 or 1 depending if users u and u2 share one or more common channels
647 * (used by QUIT, NICK etc which arent channel specific notices) */
649 int common_channels(userrec *u, userrec *u2)
656 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
659 for (i = 0; i != MAXCHANS; i++)
661 for (z = 0; z != MAXCHANS; z++)
663 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
665 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
667 if ((c_count(u)) && (c_count(u2)))
678 /* write a formatted string to all users who share at least one common
679 * channel, including the source user e.g. for use in NICK */
681 void WriteCommon(userrec *u, char* text, ...)
685 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
689 if (u->registered != 7) {
690 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
694 char textbuffer[MAXBUF];
696 va_start (argsPtr, text);
697 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
700 WriteFrom(u->fd,u,"%s",textbuffer);
702 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
706 if (common_channels(u,i->second) && (i->second != u))
708 WriteFrom(i->second->fd,u,"%s",textbuffer);
714 /* write a formatted string to all users who share at least one common
715 * channel, NOT including the source user e.g. for use in QUIT */
717 void WriteCommonExcept(userrec *u, char* text, ...)
721 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
725 if (u->registered != 7) {
726 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
730 char textbuffer[MAXBUF];
732 va_start (argsPtr, text);
733 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
736 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
740 if ((common_channels(u,i->second)) && (u != i->second))
742 WriteFrom(i->second->fd,u,"%s",textbuffer);
748 void WriteOpers(char* text, ...)
752 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
756 char textbuffer[MAXBUF];
758 va_start (argsPtr, text);
759 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
762 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
766 if (strchr(i->second->modes,'o'))
768 if (strchr(i->second->modes,'s'))
770 // send server notices to all with +s
771 // (TODO: needs SNOMASKs)
772 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
779 bool hasumode(userrec* user, char mode)
783 return (strchr(user->modes,mode)>0);
788 void WriteMode(const char* modes, int flags, const char* text, ...)
790 if ((!text) || (!modes) || (!flags))
792 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
796 char textbuffer[MAXBUF];
798 va_start (argsPtr, text);
799 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
802 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
806 bool send_to_user = false;
811 for (int n = 0; n < strlen(modes); n++)
813 if (!hasumode(i->second,modes[n]))
815 send_to_user = false;
820 else if (flags == WM_OR)
822 send_to_user = false;
823 for (int n = 0; n < strlen(modes); n++)
825 if (hasumode(i->second,modes[n]))
835 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
841 void WriteWallOps(userrec *source, char* text, ...)
843 if ((!text) || (!source))
845 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
850 char textbuffer[MAXBUF];
852 va_start (argsPtr, text);
853 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
856 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
860 if (strchr(i->second->modes,'w'))
862 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
868 /* convert a string to lowercase. Note following special circumstances
869 * taken from RFC 1459. Many "official" server branches still hold to this
870 * rule so i will too;
872 * Because of IRC's scandanavian origin, the characters {}| are
873 * considered to be the lower case equivalents of the characters []\,
874 * respectively. This is a critical issue when determining the
875 * equivalence of two nicknames.
878 void strlower(char *n)
884 for (int i = 0; i != strlen(n); i++)
886 n[i] = tolower(n[i]);
896 /* verify that a user's ident and nickname is valid */
898 int isident(const char* n)
911 for (i = 0; i != strlen(n); i++)
913 if ((n[i] < 33) || (n[i] > 125))
917 /* can't occur ANYWHERE in an Ident! */
918 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
927 int isnick(const char* n)
939 if (strlen(n) > NICKMAX-1)
943 for (i = 0; i != strlen(n); i++)
945 if ((n[i] < 33) || (n[i] > 125))
949 /* can't occur ANYWHERE in a nickname! */
950 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
954 /* can't occur as the first char of a nickname... */
955 if ((strchr("0123456789",n[i])) && (!i))
963 /* Find a user record by nickname and return a pointer to it */
965 userrec* Find(string nick)
967 user_hash::iterator iter = clientlist.find(nick);
969 if (iter == clientlist.end())
970 /* Couldn't find it */
976 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
978 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
982 if (i->second->fd == fd)
984 i->second->bytes_out+=data_out;
985 i->second->cmds_out++;
992 /* find a channel record by channel name and return a pointer to it */
994 chanrec* FindChan(const char* chan)
998 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1002 chan_hash::iterator iter = chanlist.find(chan);
1004 if (iter == chanlist.end())
1005 /* Couldn't find it */
1008 return iter->second;
1012 void purge_empty_chans(void)
1014 int go_again = 1, purge = 0;
1019 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1022 if (!usercount(i->second))
1024 /* kill the record */
1025 if (i != chanlist.end())
1027 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1037 log(DEBUG,"skipped purge for %s",i->second->name);
1042 log(DEBUG,"completed channel purge, killed %d",purge);
1045 /* returns the status character for a given user on a channel, e.g. @ for op,
1046 * % for halfop etc. If the user has several modes set, the highest mode
1047 * the user has must be returned. */
1049 char* cmode(userrec *user, chanrec *chan)
1051 if ((!user) || (!chan))
1053 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1058 for (i = 0; i != MAXCHANS; i++)
1060 if ((user->chans[i].channel == chan) && (chan != NULL))
1062 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1066 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1070 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1079 char scratch[MAXBUF];
1080 char sparam[MAXBUF];
1082 char* chanmodes(chanrec *chan)
1086 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1093 if (chan->noexternal)
1095 strncat(scratch,"n",MAXMODES);
1097 if (chan->topiclock)
1099 strncat(scratch,"t",MAXMODES);
1101 if (strcmp(chan->key,""))
1103 strncat(scratch,"k",MAXMODES);
1107 strncat(scratch,"l",MAXMODES);
1109 if (chan->inviteonly)
1111 strncat(scratch,"i",MAXMODES);
1113 if (chan->moderated)
1115 strncat(scratch,"m",MAXMODES);
1119 strncat(scratch,"s",MAXMODES);
1121 if (chan->c_private)
1123 strncat(scratch,"p",MAXMODES);
1125 if (strcmp(chan->key,""))
1127 strncat(sparam,chan->key,MAXBUF);
1132 sprintf(foo," %d",chan->limit);
1133 strncat(sparam,foo,MAXBUF);
1135 if (strlen(chan->custom_modes))
1137 strncat(scratch,chan->custom_modes,MAXMODES);
1138 for (int z = 0; z < strlen(chan->custom_modes); z++)
1140 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1143 strncat(sparam," ",MAXBUF);
1144 strncat(sparam,extparam.c_str(),MAXBUF);
1148 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1149 strncat(scratch,sparam,MAXMODES);
1153 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1154 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1155 * highest mode the user has must be returned. */
1157 int cstatus(userrec *user, chanrec *chan)
1159 if ((!chan) || (!user))
1161 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1166 for (i = 0; i != MAXCHANS; i++)
1168 if ((user->chans[i].channel == chan) && (chan != NULL))
1170 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1174 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1178 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1180 return STATUS_VOICE;
1182 return STATUS_NORMAL;
1188 /* compile a userlist of a channel into a string, each nick seperated by
1189 * spaces and op, voice etc status shown as @ and + */
1191 void userlist(userrec *user,chanrec *c)
1193 if ((!c) || (!user))
1195 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1199 sprintf(list,"353 %s = %s :", user->nick, c->name);
1200 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1202 if (has_channel(i->second,c))
1204 if (isnick(i->second->nick))
1206 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1208 /* user is +i, and source not on the channel, does not show
1209 * nick in NAMES list */
1212 strcat(list,cmode(i->second,c));
1213 strcat(list,i->second->nick);
1215 if (strlen(list)>(480-NICKMAX))
1217 /* list overflowed into
1218 * multiple numerics */
1219 WriteServ(user->fd,list);
1220 sprintf(list,"353 %s = %s :", user->nick, c->name);
1225 /* if whats left in the list isnt empty, send it */
1226 if (list[strlen(list)-1] != ':')
1228 WriteServ(user->fd,list);
1232 /* return a count of the users on a specific channel accounting for
1233 * invisible users who won't increase the count. e.g. for /LIST */
1235 int usercount_i(chanrec *c)
1242 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1247 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1251 if (has_channel(i->second,c))
1253 if (isnick(i->second->nick))
1255 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1257 /* user is +i, and source not on the channel, does not show
1258 * nick in NAMES list */
1266 log(DEBUG,"usercount_i: %s %d",c->name,count);
1271 int usercount(chanrec *c)
1278 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1283 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1287 if (has_channel(i->second,c))
1289 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1296 log(DEBUG,"usercount: %s %d",c->name,count);
1301 /* add a channel to a user, creating the record for it if needed and linking
1302 * it to the user record */
1304 chanrec* add_channel(userrec *user, const char* cn, const char* key)
1306 if ((!user) || (!cn))
1308 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1317 strncpy(cname,cn,MAXBUF);
1319 // we MUST declare this wherever we use FOREACH_RESULT
1322 if ((!cname) || (!user))
1326 if (strlen(cname) > CHANMAX-1)
1328 cname[CHANMAX-1] = '\0';
1331 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1333 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1335 return NULL; // already on the channel!
1339 if (!FindChan(cname))
1341 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1346 /* create a new one */
1347 log(DEBUG,"add_channel: creating: %s",cname);
1349 chanlist[cname] = new chanrec();
1351 strcpy(chanlist[cname]->name, cname);
1352 chanlist[cname]->topiclock = 1;
1353 chanlist[cname]->noexternal = 1;
1354 chanlist[cname]->created = time(NULL);
1355 strcpy(chanlist[cname]->topic, "");
1356 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1357 chanlist[cname]->topicset = 0;
1358 Ptr = chanlist[cname];
1359 log(DEBUG,"add_channel: created: %s",cname);
1360 /* set created to 2 to indicate user
1361 * is the first in the channel
1362 * and should be given ops */
1368 /* channel exists, just fish out a pointer to its struct */
1369 Ptr = FindChan(cname);
1372 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1377 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1378 if (strcmp(Ptr->key,""))
1380 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1383 log(DEBUG,"add_channel: no key given in JOIN");
1384 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1389 log(DEBUG,"key at %p is %s",key,key);
1390 if (strcasecmp(key,Ptr->key))
1392 log(DEBUG,"add_channel: bad key given in JOIN");
1393 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1398 log(DEBUG,"add_channel: no key");
1400 if (Ptr->inviteonly)
1402 log(DEBUG,"add_channel: channel is +i");
1403 if (user->IsInvited(Ptr->name))
1405 /* user was invited to channel */
1406 /* there may be an optional channel NOTICE here */
1410 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1414 log(DEBUG,"add_channel: channel is not +i");
1418 if (usercount(Ptr) == Ptr->limit)
1420 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1425 log(DEBUG,"add_channel: about to walk banlist");
1427 /* check user against the channel banlist */
1428 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1430 if (match(user->GetFullHost(),i->data))
1432 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1437 log(DEBUG,"add_channel: bans checked");
1439 user->RemoveInvite(Ptr->name);
1441 log(DEBUG,"add_channel: invites removed");
1447 log(DEBUG,"Passed channel checks");
1449 for (i =0; i != MAXCHANS; i++)
1451 if (user->chans[i].channel == NULL)
1453 log(DEBUG,"Adding into their channel list");
1457 /* first user in is given ops */
1458 user->chans[i].uc_modes = UCMODE_OP;
1462 user->chans[i].uc_modes = 0;
1464 user->chans[i].channel = Ptr;
1465 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1467 log(DEBUG,"Sent JOIN to client");
1471 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1472 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1475 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1476 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1477 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1478 FOREACH_MOD OnUserJoin(user,Ptr);
1482 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1483 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1487 /* remove a channel from a users record, and remove the record from memory
1488 * if the channel has become empty */
1490 chanrec* del_channel(userrec *user, const char* cname, const char* reason)
1492 if ((!user) || (!cname))
1494 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1502 if ((!cname) || (!user))
1507 Ptr = FindChan(cname);
1514 FOREACH_MOD OnUserPart(user,Ptr);
1515 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1517 for (i =0; i != MAXCHANS; i++)
1519 /* zap it from the channel list of the user */
1520 if (user->chans[i].channel == Ptr)
1524 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1528 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1530 user->chans[i].uc_modes = 0;
1531 user->chans[i].channel = NULL;
1532 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1537 /* if there are no users left on the channel */
1538 if (!usercount(Ptr))
1540 chan_hash::iterator iter = chanlist.find(Ptr->name);
1542 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1544 /* kill the record */
1545 if (iter != chanlist.end())
1547 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1548 delete iter->second;
1549 chanlist.erase(iter);
1555 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1557 if ((!src) || (!user) || (!Ptr) || (!reason))
1559 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1566 if ((!Ptr) || (!user) || (!src))
1571 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1573 if (!has_channel(user,Ptr))
1575 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1578 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1580 if (cstatus(src,Ptr) == STATUS_HOP)
1582 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1586 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1592 for (i =0; i != MAXCHANS; i++)
1594 /* zap it from the channel list of the user */
1595 if (user->chans[i].channel == Ptr)
1597 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1598 user->chans[i].uc_modes = 0;
1599 user->chans[i].channel = NULL;
1600 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1605 /* if there are no users left on the channel */
1606 if (!usercount(Ptr))
1608 chan_hash::iterator iter = chanlist.find(Ptr->name);
1610 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1612 /* kill the record */
1613 if (iter != chanlist.end())
1615 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1616 delete iter->second;
1617 chanlist.erase(iter);
1623 /* returns 1 if user u has channel c in their record, 0 if not */
1625 int has_channel(userrec *u, chanrec *c)
1631 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1634 for (i =0; i != MAXCHANS; i++)
1636 if (u->chans[i].channel == c)
1644 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1649 if ((!user) || (!dest) || (!chan))
1651 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1654 if (status != STATUS_OP)
1656 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1663 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1669 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1674 for (i = 0; i != MAXCHANS; i++)
1676 if ((d->chans[i].channel == chan) && (chan != NULL))
1678 if (d->chans[i].uc_modes & UCMODE_OP)
1680 /* mode already set on user, dont allow multiple */
1683 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1684 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1692 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1697 if ((!user) || (!dest) || (!chan))
1699 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1702 if (status != STATUS_OP)
1704 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1712 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1717 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1722 for (i = 0; i != MAXCHANS; i++)
1724 if ((d->chans[i].channel == chan) && (chan != NULL))
1726 if (d->chans[i].uc_modes & UCMODE_HOP)
1728 /* mode already set on user, dont allow multiple */
1731 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1732 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1740 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1745 if ((!user) || (!dest) || (!chan))
1747 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1750 if (status < STATUS_HOP)
1752 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1760 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1765 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1770 for (i = 0; i != MAXCHANS; i++)
1772 if ((d->chans[i].channel == chan) && (chan != NULL))
1774 if (d->chans[i].uc_modes & UCMODE_VOICE)
1776 /* mode already set on user, dont allow multiple */
1779 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1780 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1788 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1793 if ((!user) || (!dest) || (!chan))
1795 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1798 if (status != STATUS_OP)
1800 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1808 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1813 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1818 for (i = 0; i != MAXCHANS; i++)
1820 if ((d->chans[i].channel == chan) && (chan != NULL))
1822 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1824 /* mode already set on user, dont allow multiple */
1827 d->chans[i].uc_modes ^= UCMODE_OP;
1828 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1836 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1841 if ((!user) || (!dest) || (!chan))
1843 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1846 if (status != STATUS_OP)
1848 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1856 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1861 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1866 for (i = 0; i != MAXCHANS; i++)
1868 if ((d->chans[i].channel == chan) && (chan != NULL))
1870 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1872 /* mode already set on user, dont allow multiple */
1875 d->chans[i].uc_modes ^= UCMODE_HOP;
1876 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1884 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1889 if ((!user) || (!dest) || (!chan))
1891 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1894 if (status < STATUS_HOP)
1896 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1904 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1909 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1914 for (i = 0; i != MAXCHANS; i++)
1916 if ((d->chans[i].channel == chan) && (chan != NULL))
1918 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1920 /* mode already set on user, dont allow multiple */
1923 d->chans[i].uc_modes ^= UCMODE_VOICE;
1924 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1932 void TidyBan(char *ban)
1935 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1939 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1943 char* pos_of_pling = strchr(temp,'!');
1944 char* pos_of_at = strchr(temp,'@');
1946 pos_of_pling[0] = '\0';
1947 pos_of_at[0] = '\0';
1951 strncpy(NICK,temp,NICKMAX);
1952 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1953 strncpy(HOST,pos_of_at,160);
1955 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1958 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1960 if ((!user) || (!dest) || (!chan)) {
1961 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1966 if ((!user) || (!dest) || (!chan))
1968 if (strchr(dest,'!')==0)
1970 if (strchr(dest,'@')==0)
1972 for (int i = 0; i < strlen(dest); i++)
1975 for (int i = 0; i < strlen(dest); i++)
1979 for (int i = 0; i < strlen(dest); i++)
1985 for (int i = 0; i < strlen(dest); i++)
1990 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1993 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1995 if (!strcasecmp(i->data,dest))
1997 // dont allow a user to set the same ban twice
2002 b.set_time = time(NULL);
2003 strncpy(b.data,dest,MAXBUF);
2004 strncpy(b.set_by,user->nick,NICKMAX);
2005 chan->bans.push_back(b);
2009 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2011 if ((!user) || (!dest) || (!chan)) {
2012 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2016 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2017 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2019 if (!strcasecmp(i->data,dest))
2021 chan->bans.erase(i);
2028 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
2030 if ((!parameters) || (!user)) {
2031 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2036 char modelist[MAXBUF];
2037 char outlist[MAXBUF];
2038 char outstr[MAXBUF];
2039 char outpars[32][MAXBUF];
2045 bool k_set = false, l_set = false;
2052 log(DEBUG,"process_modes: start");
2054 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2055 /* parameters[2] onwards are parameters for
2056 * modes that require them :) */
2057 strcpy(outlist,"+");
2060 log(DEBUG,"process_modes: modelist: %s",modelist);
2062 for (ptr = 0; ptr < strlen(modelist); ptr++)
2067 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2068 char modechar = modelist[ptr];
2069 switch (modelist[ptr])
2074 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2076 outlist[strlen(outlist)-1] = '-';
2080 strcat(outlist,"-");
2090 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2092 outlist[strlen(outlist)-1] = '+';
2096 strcat(outlist,"+");
2103 if ((param >= pcnt)) break;
2106 r = give_ops(user,parameters[param++],chan,status);
2110 r = take_ops(user,parameters[param++],chan,status);
2114 strcat(outlist,"o");
2115 strcpy(outpars[pc++],parameters[param-1]);
2120 if ((param >= pcnt)) break;
2123 r = give_hops(user,parameters[param++],chan,status);
2127 r = take_hops(user,parameters[param++],chan,status);
2131 strcat(outlist,"h");
2132 strcpy(outpars[pc++],parameters[param-1]);
2138 if ((param >= pcnt)) break;
2141 r = give_voice(user,parameters[param++],chan,status);
2145 r = take_voice(user,parameters[param++],chan,status);
2149 strcat(outlist,"v");
2150 strcpy(outpars[pc++],parameters[param-1]);
2155 if ((param >= pcnt)) break;
2158 r = add_ban(user,parameters[param++],chan,status);
2162 r = take_ban(user,parameters[param++],chan,status);
2166 strcat(outlist,"b");
2167 strcpy(outpars[pc++],parameters[param-1]);
2173 if ((param >= pcnt))
2181 if (!strcmp(chan->key,""))
2183 strcat(outlist,"k");
2185 strcpy(key,parameters[param++]);
2186 if (strlen(key)>32) {
2189 strcpy(outpars[pc++],key);
2190 strcpy(chan->key,key);
2196 /* checks on -k are case sensitive and only accurate to the
2197 first 32 characters */
2199 strcpy(key,parameters[param++]);
2200 if (strlen(key)>32) {
2203 /* only allow -k if correct key given */
2204 if (!strcmp(chan->key,key))
2206 strcat(outlist,"k");
2207 strcpy(chan->key,"");
2208 strcpy(outpars[pc++],key);
2218 strcat(outlist,"l");
2223 if ((param >= pcnt)) break;
2229 bool invalid = false;
2230 for (int i = 0; i < strlen(parameters[param]); i++)
2232 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2237 if (atoi(parameters[param]) < 1)
2245 chan->limit = atoi(parameters[param]);
2248 strcat(outlist,"l");
2249 strcpy(outpars[pc++],parameters[param++]);
2256 if (chan->inviteonly != mdir)
2258 strcat(outlist,"i");
2260 chan->inviteonly = mdir;
2264 if (chan->topiclock != mdir)
2266 strcat(outlist,"t");
2268 chan->topiclock = mdir;
2272 if (chan->noexternal != mdir)
2274 strcat(outlist,"n");
2276 chan->noexternal = mdir;
2280 if (chan->moderated != mdir)
2282 strcat(outlist,"m");
2284 chan->moderated = mdir;
2288 if (chan->secret != mdir)
2290 strcat(outlist,"s");
2291 if (chan->c_private)
2293 chan->c_private = 0;
2296 strcat(outlist,"-p+");
2300 strcat(outlist,"+p-");
2304 chan->secret = mdir;
2308 if (chan->c_private != mdir)
2310 strcat(outlist,"p");
2316 strcat(outlist,"-s+");
2320 strcat(outlist,"+s-");
2324 chan->c_private = mdir;
2328 log(DEBUG,"Preprocessing custom mode %c",modechar);
2331 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2333 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2336 if (ModeDefined(modechar,MT_CHANNEL))
2338 log(DEBUG,"A module has claimed this mode");
2341 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2343 p.push_back(parameters[param]);
2345 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2347 p.push_back(parameters[param]);
2350 bool handled = false;
2353 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2354 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2355 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2361 for (int i = 0; i <= MODCOUNT; i++)
2365 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2367 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2368 char app[] = {modechar, 0};
2371 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2373 strcat(outlist, app);
2375 else if (!strchr(outlist,modechar))
2377 strcat(outlist, app);
2380 chan->SetCustomMode(modechar,mdir);
2381 // include parameters in output if mode has them
2382 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2384 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2385 strcpy(outpars[pc++],parameters[param++]);
2387 // break, because only one module can handle the mode.
2399 /* this ensures only the *valid* modes are sent out onto the network */
2400 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2402 outlist[strlen(outlist)-1] = '\0';
2404 if (strcmp(outlist,""))
2406 strcpy(outstr,outlist);
2407 for (ptr = 0; ptr < pc; ptr++)
2410 strcat(outstr,outpars[ptr]);
2414 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2418 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2423 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2425 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2427 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2428 // RFC1459 specified modes
2429 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2431 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2435 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2436 if ((strchr(sourcemodes,'o')) && (!adding))
2438 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2441 else if (umode == 'o')
2443 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2447 // process any module-defined modes that need oper
2448 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2450 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2454 if (ModeDefined(umode,MT_CLIENT))
2456 // process any module-defined modes that don't need oper
2457 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2458 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2460 // no, this mode needs oper, and this user 'aint got what it takes!
2466 // anything else - return false.
2467 log(DEBUG,"umode %c not known by any ruleset",umode);
2471 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2475 if (ModeDefined(umode,MT_CLIENT))
2477 for (int i = 0; i <= MODCOUNT; i++)
2479 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2481 log(DEBUG,"Module claims umode %c",umode);
2485 log(DEBUG,"No module claims umode %c",umode);
2490 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2495 void handle_mode(char **parameters, int pcnt, userrec *user)
2501 char outpars[MAXBUF];
2503 dest = Find(parameters[0]);
2505 if ((dest) && (pcnt == 1))
2507 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2511 if ((dest) && (pcnt > 1))
2513 char dmodes[MAXBUF];
2514 strncpy(dmodes,dest->modes,MAXBUF);
2515 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2520 if (strchr(user->modes,'o'))
2531 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2535 strcpy(outpars,"+");
2538 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2541 for (i = 0; i < strlen(parameters[1]); i++)
2543 if (parameters[1][i] == '+')
2547 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2549 outpars[strlen(outpars)-1] = '+';
2553 strcat(outpars,"+");
2559 if (parameters[1][i] == '-')
2563 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2565 outpars[strlen(outpars)-1] = '-';
2569 strcat(outpars,"-");
2577 if (strchr(user->modes,'o'))
2583 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2592 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2594 char umode = parameters[1][i];
2595 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2597 dmodes[strlen(dmodes)+1]='\0';
2598 dmodes[strlen(dmodes)] = parameters[1][i];
2599 outpars[strlen(outpars)+1]='\0';
2600 outpars[strlen(outpars)] = parameters[1][i];
2606 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2608 char umode = parameters[1][i];
2609 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2615 outpars[strlen(outpars)+1]='\0';
2616 outpars[strlen(outpars)] = parameters[1][i];
2619 for (q = 0; q < strlen(dmodes); q++)
2621 if (dmodes[q] != parameters[1][i])
2628 strcpy(dmodes,temp);
2635 if (strlen(outpars))
2641 while (i < strlen (outpars))
2643 b[z++] = outpars[i++];
2645 if (i<strlen(outpars)-1)
2647 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2649 // someones playing silly buggers and trying
2650 // to put a +- or -+ into the line...
2654 if (i == strlen(outpars)-1)
2656 if ((outpars[i] == '-') || (outpars[i] == '+'))
2664 if ((b[z] == '-') || (b[z] == '+'))
2667 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2670 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2672 if (strlen(dmodes)>MAXMODES)
2674 dmodes[MAXMODES-1] = '\0';
2676 log(DEBUG,"Stripped mode line");
2677 log(DEBUG,"Line dest is now %s",dmodes);
2678 strncpy(dest->modes,dmodes,MAXMODES);
2685 Ptr = FindChan(parameters[0]);
2690 /* just /modes #channel */
2691 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2692 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2698 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2701 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2703 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2705 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2709 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2711 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
2715 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2719 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2726 void server_mode(char **parameters, int pcnt, userrec *user)
2732 char outpars[MAXBUF];
2734 dest = Find(parameters[0]);
2736 // fix: ChroNiCk found this - we cant use this as debug if its null!
2739 log(DEBUG,"server_mode on %s",dest->nick);
2742 if ((dest) && (pcnt > 1))
2744 log(DEBUG,"params > 1");
2746 char dmodes[MAXBUF];
2747 strncpy(dmodes,dest->modes,MAXBUF);
2749 strcpy(outpars,"+");
2752 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2755 for (i = 0; i < strlen(parameters[1]); i++)
2757 if (parameters[1][i] == '+')
2761 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2763 outpars[strlen(outpars)-1] = '+';
2767 strcat(outpars,"+");
2773 if (parameters[1][i] == '-')
2777 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2779 outpars[strlen(outpars)-1] = '-';
2783 strcat(outpars,"-");
2790 log(DEBUG,"begin mode processing entry");
2796 log(DEBUG,"umode %c being added",parameters[1][i]);
2797 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2799 char umode = parameters[1][i];
2800 log(DEBUG,"umode %c is an allowed umode",umode);
2801 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2803 dmodes[strlen(dmodes)+1]='\0';
2804 dmodes[strlen(dmodes)] = parameters[1][i];
2805 outpars[strlen(outpars)+1]='\0';
2806 outpars[strlen(outpars)] = parameters[1][i];
2812 // can only remove a mode they already have
2813 log(DEBUG,"umode %c being removed",parameters[1][i]);
2814 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2816 char umode = parameters[1][i];
2817 log(DEBUG,"umode %c is an allowed umode",umode);
2818 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2824 outpars[strlen(outpars)+1]='\0';
2825 outpars[strlen(outpars)] = parameters[1][i];
2828 for (q = 0; q < strlen(dmodes); q++)
2830 if (dmodes[q] != parameters[1][i])
2837 strcpy(dmodes,temp);
2844 if (strlen(outpars))
2850 while (i < strlen (outpars))
2852 b[z++] = outpars[i++];
2854 if (i<strlen(outpars)-1)
2856 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2858 // someones playing silly buggers and trying
2859 // to put a +- or -+ into the line...
2863 if (i == strlen(outpars)-1)
2865 if ((outpars[i] == '-') || (outpars[i] == '+'))
2873 if ((b[z] == '-') || (b[z] == '+'))
2876 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2879 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2881 if (strlen(dmodes)>MAXMODES)
2883 dmodes[MAXMODES-1] = '\0';
2885 log(DEBUG,"Stripped mode line");
2886 log(DEBUG,"Line dest is now %s",dmodes);
2887 strncpy(dest->modes,dmodes,MAXMODES);
2894 Ptr = FindChan(parameters[0]);
2897 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2901 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2906 /* This function pokes and hacks at a parameter list like the following:
2908 * PART #winbot, #darkgalaxy :m00!
2910 * to turn it into a series of individual calls like this:
2912 * PART #winbot :m00!
2913 * PART #darkgalaxy :m00!
2915 * The seperate calls are sent to a callback function provided by the caller
2916 * (the caller will usually call itself recursively). The callback function
2917 * must be a command handler. Calling this function on a line with no list causes
2918 * no action to be taken. You must provide a starting and ending parameter number
2919 * where the range of the list can be found, useful if you have a terminating
2920 * parameter as above which is actually not part of the list, or parameters
2921 * before the actual list as well. This code is used by many functions which
2922 * can function as "one to list" (see the RFC) */
2924 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2929 char blog[32][MAXBUF];
2930 char blog2[32][MAXBUF];
2931 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2932 char keystr[MAXBUF];
2935 for (i = 0; i <32; i++)
2938 for (i = 0; i <32; i++)
2939 strcpy(blog2[i],"");
2942 for (i = 0; i <10; i++)
2946 parameters[i] = moo;
2951 if (pcnt > 1) /* we have a key to copy */
2953 strcpy(keystr,parameters[1]);
2957 if (!parameters[start])
2961 if (!strchr(parameters[start],','))
2966 for (i = start; i <= end; i++)
2970 strcat(plist,parameters[i]);
2978 for (i = 0; i < t; i++)
2980 if (plist[i] == ',')
2983 strcpy(blog[j++],param);
2987 strcpy(blog[j++],param);
2990 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2995 if ((joins) && (keystr))
2997 if (strchr(keystr,','))
3001 t2 = strlen(keystr);
3002 for (i = 0; i < t2; i++)
3004 if (keystr[i] == ',')
3007 strcpy(blog2[j++],param);
3011 strcpy(blog2[j++],param);
3016 for (j = 0; j < total; j++)
3022 for (q = end; q < pcnt-1; q++)
3024 if (parameters[q+1])
3026 pars[q-end+1] = parameters[q+1];
3029 if ((joins) && (parameters[1]))
3040 /* repeatedly call the function with the hacked parameter list */
3041 if ((joins) && (pcnt > 1))
3045 // pars[1] already set up and containing key from blog2[j]
3050 pars[1] = parameters[1];
3056 fn(pars,pcnt-(end-start),u);
3064 void handle_join(char **parameters, int pcnt, userrec *user)
3069 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3071 if (parameters[0][0] == '#')
3073 Ptr = add_channel(user,parameters[0],parameters[1]);
3078 void handle_part(char **parameters, int pcnt, userrec *user)
3084 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3086 del_channel(user,parameters[0],parameters[1]);
3090 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3092 del_channel(user,parameters[0],NULL);
3096 void handle_kick(char **parameters, int pcnt, userrec *user)
3098 chanrec* Ptr = FindChan(parameters[0]);
3099 userrec* u = Find(parameters[1]);
3103 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3107 if (!has_channel(u,Ptr))
3109 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3115 char reason[MAXBUF];
3116 strncpy(reason,parameters[2],MAXBUF);
3117 if (strlen(reason)>MAXKICK)
3119 reason[MAXKICK-1] = '\0';
3122 kick_channel(user,u,Ptr,reason);
3126 kick_channel(user,u,Ptr,user->nick);
3131 void handle_die(char **parameters, int pcnt, userrec *user)
3133 log(DEBUG,"die: %s",user->nick);
3134 if (!strcmp(parameters[0],diepass))
3136 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3142 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3146 void handle_restart(char **parameters, int pcnt, userrec *user)
3148 log(DEBUG,"restart: %s",user->nick);
3149 if (!strcmp(parameters[0],restartpass))
3151 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3154 /* Will finish this later when i can be arsed :) */
3158 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3163 void kill_link(userrec *user,const char* r)
3165 user_hash::iterator iter = clientlist.find(user->nick);
3167 char reason[MAXBUF];
3169 strncpy(reason,r,MAXBUF);
3171 if (strlen(reason)>MAXQUIT)
3173 reason[MAXQUIT-1] = '\0';
3176 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3177 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3178 log(DEBUG,"closing fd %d",user->fd);
3180 /* bugfix, cant close() a nonblocking socket (sux!) */
3181 if (user->registered == 7) {
3182 FOREACH_MOD OnUserQuit(user);
3183 WriteCommonExcept(user,"QUIT :%s",reason);
3186 /* push the socket on a stack of sockets due to be closed at the next opportunity
3187 * 'Client exited' is an exception to this as it means the client side has already
3188 * closed the socket, we don't need to do it.
3190 fd_reap.push_back(user->fd);
3192 bool do_purge = false;
3194 if (user->registered == 7) {
3195 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3199 if (iter != clientlist.end())
3201 log(DEBUG,"deleting user hash value %d",iter->second);
3202 if ((iter->second) && (user->registered == 7)) {
3203 delete iter->second;
3205 clientlist.erase(iter);
3208 if (user->registered == 7) {
3209 purge_empty_chans();
3214 void handle_kill(char **parameters, int pcnt, userrec *user)
3216 userrec *u = Find(parameters[0]);
3217 char killreason[MAXBUF];
3219 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3222 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3223 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3224 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3225 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3226 kill_link(u,killreason);
3230 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3234 void handle_summon(char **parameters, int pcnt, userrec *user)
3236 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3239 void handle_users(char **parameters, int pcnt, userrec *user)
3241 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3245 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3247 char* Passwd(userrec *user)
3249 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3251 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3259 bool IsDenied(userrec *user)
3261 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3263 if (match(user->host,i->host) && (i->type == CC_DENY))
3273 void handle_pass(char **parameters, int pcnt, userrec *user)
3275 // Check to make sure they havnt registered -- Fix by FCS
3276 if (user->registered == 7)
3278 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3281 if (!strcasecmp(parameters[0],Passwd(user)))
3283 user->haspassed = true;
3287 void handle_invite(char **parameters, int pcnt, userrec *user)
3289 userrec* u = Find(parameters[0]);
3290 chanrec* c = FindChan(parameters[1]);
3296 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3302 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3311 if (cstatus(user,c) < STATUS_HOP)
3313 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
3317 if (has_channel(u,c))
3319 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
3322 u->InviteTo(c->name);
3323 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3324 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3327 void handle_topic(char **parameters, int pcnt, userrec *user)
3333 if (strlen(parameters[0]) <= CHANMAX)
3335 Ptr = FindChan(parameters[0]);
3340 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3341 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3345 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3350 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3357 if (strlen(parameters[0]) <= CHANMAX)
3359 Ptr = FindChan(parameters[0]);
3362 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3364 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
3369 strncpy(topic,parameters[1],MAXBUF);
3370 if (strlen(topic)>MAXTOPIC)
3372 topic[MAXTOPIC-1] = '\0';
3375 strcpy(Ptr->topic,topic);
3376 strcpy(Ptr->setby,user->nick);
3377 Ptr->topicset = time(NULL);
3378 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3382 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3388 /* sends out an error notice to all connected clients (not to be used
3391 void send_error(char *s)
3393 log(DEBUG,"send_error: %s",s);
3394 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3396 if (isnick(i->second->nick))
3398 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3402 // fix - unregistered connections receive ERROR, not NOTICE
3403 Write(i->second->fd,"ERROR :%s",s);
3408 void Error(int status)
3410 signal (SIGALRM, SIG_IGN);
3411 signal (SIGPIPE, SIG_IGN);
3412 signal (SIGTERM, SIG_IGN);
3413 signal (SIGABRT, SIG_IGN);
3414 signal (SIGSEGV, SIG_IGN);
3415 signal (SIGURG, SIG_IGN);
3416 signal (SIGKILL, SIG_IGN);
3417 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3418 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3423 int main (int argc, char *argv[])
3426 log(DEBUG,"*** InspIRCd starting up!");
3427 if (!FileExists(CONFIG_FILE))
3429 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3430 log(DEBUG,"main: no config");
3431 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3435 if (!strcmp(argv[1],"-nofork")) {
3439 if (InspIRCd() == ERROR)
3441 log(DEBUG,"main: daemon function bailed");
3442 printf("ERROR: could not initialise. Shutting down.\n");
3449 template<typename T> inline string ConvToStr(const T &in)
3452 if (!(tmp << in)) return string();
3456 /* re-allocates a nick in the user_hash after they change nicknames,
3457 * returns a pointer to the new user as it may have moved */
3459 userrec* ReHashNick(char* Old, char* New)
3461 user_hash::iterator newnick;
3462 user_hash::iterator oldnick = clientlist.find(Old);
3464 log(DEBUG,"ReHashNick: %s %s",Old,New);
3466 if (!strcasecmp(Old,New))
3468 log(DEBUG,"old nick is new nick, skipping");
3469 return oldnick->second;
3472 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3474 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3476 clientlist[New] = new userrec();
3477 clientlist[New] = oldnick->second;
3478 /*delete oldnick->second; */
3479 clientlist.erase(oldnick);
3481 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3483 return clientlist[New];
3486 /* adds or updates an entry in the whowas list */
3487 void AddWhoWas(userrec* u)
3489 user_hash::iterator iter = whowas.find(u->nick);
3490 userrec *a = new userrec();
3491 strcpy(a->nick,u->nick);
3492 strcpy(a->ident,u->ident);
3493 strcpy(a->dhost,u->dhost);
3494 strcpy(a->host,u->host);
3495 strcpy(a->fullname,u->fullname);
3496 strcpy(a->server,u->server);
3497 a->signon = u->signon;
3499 /* MAX_WHOWAS: max number of /WHOWAS items
3500 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3501 * can be replaced by a newer one
3504 if (iter == whowas.end())
3506 if (whowas.size() == WHOWAS_MAX)
3508 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3510 // 3600 seconds in an hour ;)
3511 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3515 log(DEBUG,"added WHOWAS entry, purged an old record");
3522 log(DEBUG,"added fresh WHOWAS entry");
3523 whowas[a->nick] = a;
3528 log(DEBUG,"updated WHOWAS entry");
3529 delete iter->second;
3535 /* add a client connection to the sockets list */
3536 void AddClient(int socket, char* host, int port, bool iscached)
3540 char resolved[MAXBUF];
3543 user_hash::iterator iter;
3545 tempnick = ConvToStr(socket) + "-unknown";
3546 sprintf(tn2,"%d-unknown",socket);
3548 iter = clientlist.find(tempnick);
3550 if (iter != clientlist.end()) return;
3553 * It is OK to access the value here this way since we know
3554 * it exists, we just created it above.
3556 * At NO other time should you access a value in a map or a
3557 * hash_map this way.
3559 clientlist[tempnick] = new userrec();
3561 NonBlocking(socket);
3562 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3564 clientlist[tempnick]->fd = socket;
3565 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3566 strncpy(clientlist[tempnick]->host, host,160);
3567 strncpy(clientlist[tempnick]->dhost, host,160);
3568 strncpy(clientlist[tempnick]->server, ServerName,256);
3569 strncpy(clientlist[tempnick]->ident, "unknown",9);
3570 clientlist[tempnick]->registered = 0;
3571 clientlist[tempnick]->signon = time(NULL);
3572 clientlist[tempnick]->nping = time(NULL)+240;
3573 clientlist[tempnick]->lastping = 1;
3574 clientlist[tempnick]->port = port;
3578 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3582 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3585 // set the registration timeout for this user
3586 unsigned long class_regtimeout = 90;
3587 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3589 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3591 class_regtimeout = (unsigned long)i->registration_timeout;
3595 log(DEBUG,"Client has a connection timeout value of %d",class_regtimeout);
3596 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3598 if (clientlist.size() == MAXCLIENTS)
3599 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3602 void handle_names(char **parameters, int pcnt, userrec *user)
3606 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3608 c = FindChan(parameters[0]);
3611 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3613 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3617 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3622 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3627 user->idle_lastmsg = time(NULL);
3629 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3631 if (parameters[0][0] == '#')
3633 chan = FindChan(parameters[0]);
3636 if ((chan->noexternal) && (!has_channel(user,chan)))
3638 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3641 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3643 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3649 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3654 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3658 /* no such nick/channel */
3659 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3664 dest = Find(parameters[0]);
3667 if (strcmp(dest->awaymsg,""))
3669 /* auto respond with aweh msg */
3670 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3675 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
3680 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3684 /* no such nick/channel */
3685 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3689 void handle_notice(char **parameters, int pcnt, userrec *user)
3694 user->idle_lastmsg = time(NULL);
3696 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3698 if (parameters[0][0] == '#')
3700 chan = FindChan(parameters[0]);
3703 if ((chan->noexternal) && (!has_channel(user,chan)))
3705 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3708 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3710 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3716 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3721 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3725 /* no such nick/channel */
3726 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3731 dest = Find(parameters[0]);
3736 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
3741 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3745 /* no such nick/channel */
3746 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3752 char* chlist(userrec *user)
3757 log(DEBUG,"chlist: %s",user->nick);
3763 for (i = 0; i != MAXCHANS; i++)
3765 if (user->chans[i].channel != NULL)
3767 if (user->chans[i].channel->name)
3769 strcpy(cmp,user->chans[i].channel->name);
3771 if (!strstr(lst,cmp))
3773 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3775 strcat(lst,cmode(user,user->chans[i].channel));
3776 strcat(lst,user->chans[i].channel->name);
3786 void handle_info(char **parameters, int pcnt, userrec *user)
3788 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3789 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3790 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3791 FOREACH_MOD OnInfo(user);
3792 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3795 void handle_time(char **parameters, int pcnt, userrec *user)
3798 struct tm * timeinfo;
3801 timeinfo = localtime ( &rawtime );
3802 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3806 void handle_whois(char **parameters, int pcnt, userrec *user)
3811 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3813 dest = Find(parameters[0]);
3816 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3817 if (dest->registered == 7)
3819 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3820 if ((user == dest) || (strchr(user->modes,'o')))
3822 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3824 if (strcmp(chlist(dest),""))
3826 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3828 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3829 if (strcmp(dest->awaymsg,""))
3831 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3833 if (strchr(dest->modes,'o'))
3835 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3837 FOREACH_MOD OnWhois(user,dest);
3838 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3839 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3841 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3845 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3850 /* no such nick/channel */
3851 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3855 void handle_quit(char **parameters, int pcnt, userrec *user)
3857 user_hash::iterator iter = clientlist.find(user->nick);
3860 if (user->registered == 7)
3862 /* theres more to do here, but for now just close the socket */
3865 if (parameters[0][0] == ':')
3869 reason = parameters[0];
3871 if (strlen(reason)>MAXQUIT)
3873 reason[MAXQUIT-1] = '\0';
3876 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3877 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3878 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3882 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3883 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3884 WriteCommonExcept(user,"QUIT :Client exited");
3886 FOREACH_MOD OnUserQuit(user);
3890 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3891 fd_reap.push_back(user->fd);
3893 if (iter != clientlist.end())
3895 log(DEBUG,"deleting user hash value %d",iter->second);
3896 if ((iter->second) && (user->registered == 7)) {
3897 delete iter->second;
3899 clientlist.erase(iter);
3902 if (user->registered == 7) {
3903 purge_empty_chans();
3907 void handle_who(char **parameters, int pcnt, userrec *user)
3909 chanrec* Ptr = NULL;
3911 /* theres more to do here, but for now just close the socket */
3914 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3916 if (user->chans[0].channel)
3918 Ptr = user->chans[0].channel;
3919 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3921 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3923 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);
3929 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3933 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3937 if (parameters[0][0] = '#')
3939 Ptr = FindChan(parameters[0]);
3942 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3944 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3946 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);
3949 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3953 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3959 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3961 Ptr = user->chans[0].channel;
3962 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3964 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3966 if (strchr(i->second->modes,'o'))
3968 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3972 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3978 void handle_wallops(char **parameters, int pcnt, userrec *user)
3980 WriteWallOps(user,"%s",parameters[0]);
3983 void handle_list(char **parameters, int pcnt, userrec *user)
3987 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3988 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3990 if ((!i->second->c_private) && (!i->second->secret))
3992 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3995 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3999 void handle_rehash(char **parameters, int pcnt, userrec *user)
4001 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
4003 FOREACH_MOD OnRehash();
4004 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
4010 return clientlist.size();
4013 int usercount_invisible(void)
4017 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4019 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4024 int usercount_opers(void)
4028 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4030 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4035 int usercount_unknown(void)
4039 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4041 if ((i->second->fd) && (i->second->registered != 7))
4049 return chanlist.size();
4052 int servercount(void)
4057 void handle_lusers(char **parameters, int pcnt, userrec *user)
4059 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4060 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4061 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4062 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4063 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4066 void handle_admin(char **parameters, int pcnt, userrec *user)
4068 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4069 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4070 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4071 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4074 void ShowMOTD(userrec *user)
4078 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4081 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4082 for (int i = 0; i != MOTD.size(); i++)
4084 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4086 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4089 void ShowRULES(userrec *user)
4093 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4096 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4097 for (int i = 0; i != RULES.size(); i++)
4099 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4101 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4104 /* shows the message of the day, and any other on-logon stuff */
4105 void ConnectUser(userrec *user)
4107 user->registered = 7;
4108 user->idle_lastmsg = time(NULL);
4109 log(DEBUG,"ConnectUser: %s",user->nick);
4111 if (strcmp(Passwd(user),"") && (!user->haspassed))
4113 kill_link(user,"Invalid password");
4118 kill_link(user,"Unauthorised connection");
4122 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4123 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4124 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4125 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4126 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4127 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);
4128 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);
4130 FOREACH_MOD OnUserConnect(user);
4131 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4134 void handle_version(char **parameters, int pcnt, userrec *user)
4136 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4139 void handle_ping(char **parameters, int pcnt, userrec *user)
4141 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4144 void handle_pong(char **parameters, int pcnt, userrec *user)
4146 // set the user as alive so they survive to next ping
4150 void handle_motd(char **parameters, int pcnt, userrec *user)
4155 void handle_rules(char **parameters, int pcnt, userrec *user)
4160 void handle_user(char **parameters, int pcnt, userrec *user)
4162 if (user->registered < 3)
4164 if (isident(parameters[0]) == 0) {
4165 // This kinda Sucks, According to the RFC thou, its either this,
4166 // or "You have already registered" :p -- Craig
4167 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4170 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4171 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4172 strncat(user->ident,parameters[0],IDENTMAX);
4173 strncpy(user->fullname,parameters[3],128);
4174 user->registered = (user->registered | 1);
4179 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4182 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4183 if (user->registered == 3)
4185 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4190 void handle_userhost(char **parameters, int pcnt, userrec *user)
4192 char Return[MAXBUF],junk[MAXBUF];
4193 sprintf(Return,"302 %s :",user->nick);
4194 for (int i = 0; i < pcnt; i++)
4196 userrec *u = Find(parameters[i]);
4199 if (strchr(u->modes,'o'))
4201 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4202 strcat(Return,junk);
4206 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4207 strcat(Return,junk);
4211 WriteServ(user->fd,Return);
4215 void handle_ison(char **parameters, int pcnt, userrec *user)
4217 char Return[MAXBUF];
4218 sprintf(Return,"303 %s :",user->nick);
4219 for (int i = 0; i < pcnt; i++)
4221 userrec *u = Find(parameters[i]);
4224 strcat(Return,u->nick);
4228 WriteServ(user->fd,Return);
4232 void handle_away(char **parameters, int pcnt, userrec *user)
4236 strcpy(user->awaymsg,parameters[0]);
4237 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4241 strcpy(user->awaymsg,"");
4242 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4246 void handle_whowas(char **parameters, int pcnt, userrec* user)
4248 user_hash::iterator i = whowas.find(parameters[0]);
4250 if (i == whowas.end())
4252 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4253 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4257 time_t rawtime = i->second->signon;
4261 timeinfo = localtime(&rawtime);
4262 strcpy(b,asctime(timeinfo));
4263 b[strlen(b)-1] = '\0';
4265 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4266 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4267 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4272 void handle_trace(char **parameters, int pcnt, userrec *user)
4274 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4278 if (isnick(i->second->nick))
4280 if (strchr(i->second->modes,'o'))
4282 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4286 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4291 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4297 void handle_modules(char **parameters, int pcnt, userrec *user)
4299 for (int i = 0; i < module_names.size(); i++)
4301 Version V = modules[i]->GetVersion();
4302 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());
4306 void handle_stats(char **parameters, int pcnt, userrec *user)
4312 if (strlen(parameters[0])>1)
4314 /* make the stats query 1 character long */
4315 parameters[0][1] = '\0';
4318 /* stats m (list number of times each command has been used, plus bytecount) */
4319 if (!strcasecmp(parameters[0],"m"))
4321 for (int i = 0; i < cmdlist.size(); i++)
4323 if (cmdlist[i].handler_function)
4325 if (cmdlist[i].use_count)
4327 /* RPL_STATSCOMMANDS */
4328 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4335 /* stats z (debug and memory info) */
4336 if (!strcasecmp(parameters[0],"z"))
4338 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4339 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4340 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4341 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4342 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4343 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4344 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4345 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4349 if (!strcasecmp(parameters[0],"o"))
4351 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
4353 char LoginName[MAXBUF];
4354 char HostName[MAXBUF];
4355 char OperType[MAXBUF];
4356 ConfValue("oper","name",i,LoginName,&config_f);
4357 ConfValue("oper","host",i,HostName,&config_f);
4358 ConfValue("oper","type",i,OperType,&config_f);
4359 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4363 /* stats l (show user I/O stats) */
4364 if (!strcasecmp(parameters[0],"l"))
4366 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4367 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4369 if (isnick(i->second->nick))
4371 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);
4375 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);
4381 /* stats u (show server uptime) */
4382 if (!strcasecmp(parameters[0],"u"))
4384 time_t current_time = 0;
4385 current_time = time(NULL);
4386 time_t server_uptime = current_time - startup_time;
4388 stime = gmtime(&server_uptime);
4389 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4390 * Craig suggested this, and it seemed a good idea so in it went */
4391 if (stime->tm_year > 70)
4393 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);
4397 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);
4401 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4402 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4406 void handle_connect(char **parameters, int pcnt, userrec *user)
4408 char Link_ServerName[1024];
4409 char Link_IPAddr[1024];
4410 char Link_Port[1024];
4411 char Link_Pass[1024];
4415 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4417 ConfValue("link","name",i,Link_ServerName,&config_f);
4418 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4419 ConfValue("link","port",i,Link_Port,&config_f);
4420 ConfValue("link","sendpass",i,Link_Pass,&config_f);
4421 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4422 LinkPort = atoi(Link_Port);
4423 if (match(Link_ServerName,parameters[0])) {
4429 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4433 // TODO: Perform a check here to stop a server being linked twice!
4435 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4437 if (me[defaultRoute])
4440 // at this point parameters[0] is an ip in a string.
4441 // TODO: Look this up from the <link> blocks instead!
4442 for (int j = 0; j < 255; j++) {
4443 if (servers[j] == NULL) {
4444 servers[j] = new serverrec;
4445 strcpy(servers[j]->internal_addr,Link_IPAddr);
4446 strcpy(servers[j]->name,Link_ServerName);
4447 log(DEBUG,"Allocated new serverrec");
4448 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4450 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4455 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4459 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);
4463 void handle_squit(char **parameters, int pcnt, userrec *user)
4465 // send out an squit across the mesh and then clear the server list (for local squit)
4468 void handle_oper(char **parameters, int pcnt, userrec *user)
4470 char LoginName[MAXBUF];
4471 char Password[MAXBUF];
4472 char OperType[MAXBUF];
4473 char TypeName[MAXBUF];
4474 char Hostname[MAXBUF];
4477 for (i = 0; i < ConfValueEnum("oper",&config_f); i++)
4479 ConfValue("oper","name",i,LoginName,&config_f);
4480 ConfValue("oper","password",i,Password,&config_f);
4481 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4483 /* correct oper credentials */
4484 ConfValue("oper","type",i,OperType,&config_f);
4485 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4486 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4487 WriteServ(user->fd,"MODE %s :+o",user->nick);
4488 for (j =0; j < ConfValueEnum("type",&config_f); j++)
4490 ConfValue("type","name",j,TypeName,&config_f);
4491 if (!strcmp(TypeName,OperType))
4493 /* found this oper's opertype */
4494 ConfValue("type","host",j,Hostname,&config_f);
4495 strncpy(user->dhost,Hostname,256);
4498 if (!strchr(user->modes,'o'))
4500 strcat(user->modes,"o");
4502 FOREACH_MOD OnOper(user);
4507 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4508 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4511 void handle_nick(char **parameters, int pcnt, userrec *user)
4515 log(DEBUG,"not enough params for handle_nick");
4520 log(DEBUG,"invalid parameter passed to handle_nick");
4523 if (!strlen(parameters[0]))
4525 log(DEBUG,"zero length new nick passed to handle_nick");
4530 log(DEBUG,"invalid user passed to handle_nick");
4535 log(DEBUG,"invalid old nick passed to handle_nick");
4538 if (!strcasecmp(user->nick,parameters[0]))
4540 log(DEBUG,"old nick is new nick, skipping");
4545 if (strlen(parameters[0]) > 1)
4547 if (parameters[0][0] == ':')
4552 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4554 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4558 if (isnick(parameters[0]) == 0)
4560 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4564 if (user->registered == 7)
4566 WriteCommon(user,"NICK %s",parameters[0]);
4569 /* change the nick of the user in the users_hash */
4570 user = ReHashNick(user->nick, parameters[0]);
4571 /* actually change the nick within the record */
4573 if (!user->nick) return;
4575 strncpy(user->nick, parameters[0],NICKMAX);
4577 log(DEBUG,"new nick set: %s",user->nick);
4579 if (user->registered < 3)
4580 user->registered = (user->registered | 2);
4581 if (user->registered == 3)
4583 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4586 log(DEBUG,"exit nickchange: %s",user->nick);
4589 void force_nickchange(userrec* user,const char* newnick)
4598 strncpy(nick,newnick,MAXBUF);
4600 if (user->registered == 7)
4604 handle_nick(pars,1,user);
4610 int process_parameters(char **command_p,char *parameters)
4615 q = strlen(parameters);
4618 /* no parameters, command_p invalid! */
4621 if (parameters[0] == ':')
4623 command_p[0] = parameters+1;
4628 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4630 /* only one parameter */
4631 command_p[0] = parameters;
4632 if (parameters[0] == ':')
4634 if (strchr(parameters,' ') != NULL)
4642 command_p[j++] = parameters;
4643 for (i = 0; i <= q; i++)
4645 if (parameters[i] == ' ')
4647 command_p[j++] = parameters+i+1;
4648 parameters[i] = '\0';
4649 if (command_p[j-1][0] == ':')
4651 *command_p[j-1]++; /* remove dodgy ":" */
4653 /* parameter like this marks end of the sequence */
4657 return j; /* returns total number of items in the list */
4660 void process_command(userrec *user, char* cmd)
4664 char *command_p[127];
4665 char p[MAXBUF], temp[MAXBUF];
4666 int i, j, items, cmd_found;
4668 for (int i = 0; i < 127; i++)
4669 command_p[i] = NULL;
4679 if (!strcmp(cmd,""))
4684 int total_params = 0;
4687 for (int q = 0; q < strlen(cmd)-1; q++)
4689 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
4692 // found a 'trailing', we dont count them after this.
4700 // another phidjit bug...
4701 if (total_params > 126)
4703 kill_link(user,"Protocol violation");
4710 FOREACH_MOD OnServerRaw(tmp,true);
4711 const char* cmd2 = tmp.c_str();
4712 snprintf(cmd,512,"%s",cmd2);
4714 if (!strchr(cmd,' '))
4716 /* no parameters, lets skip the formalities and not chop up
4718 log(DEBUG,"About to preprocess command with no params");
4720 command_p[0] = NULL;
4722 for (int i = 0; i <= strlen(cmd); i++)
4724 cmd[i] = toupper(cmd[i]);
4726 log(DEBUG,"Preprocess done");
4732 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4733 for (i = 0; i < strlen(temp); i++)
4735 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4741 /* split the full string into a command plus parameters */
4745 if (strchr(cmd,' '))
4747 for (i = 0; i <= strlen(cmd); i++)
4749 /* capitalise the command ONLY, leave params intact */
4750 cmd[i] = toupper(cmd[i]);
4751 /* are we nearly there yet?! :P */
4755 parameters = cmd+i+1;
4763 for (i = 0; i <= strlen(cmd); i++)
4765 cmd[i] = toupper(cmd[i]);
4773 if (strlen(command)>MAXCOMMAND)
4775 kill_link(user,"Protocol violation");
4779 for (int x = 0; x < strlen(command); x++)
4781 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
4783 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
4785 kill_link(user,"Protocol violation");
4791 for (i = 0; i != cmdlist.size(); i++)
4793 if (strcmp(cmdlist[i].command,""))
4795 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
4797 log(DEBUG,"Found matching command");
4801 if (strcmp(parameters,""))
4803 items = process_parameters(command_p,parameters);
4808 command_p[0] = NULL;
4814 command_p[0] = NULL;
4819 log(DEBUG,"Processing command");
4821 /* activity resets the ping pending timer */
4822 user->nping = time(NULL) + 120;
4823 if ((items) < cmdlist[i].min_params)
4825 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4826 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4829 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4831 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4832 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4836 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4838 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
4840 if ((!isnick(user->nick)) || (user->registered != 7))
4842 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4843 WriteServ(user->fd,"451 %s :You have not registered",command);
4847 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4849 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4850 if (cmdlist[i].handler_function)
4852 /* ikky /stats counters */
4857 user->bytes_in += strlen(temp);
4860 cmdlist[i].use_count++;
4861 cmdlist[i].total_bytes+=strlen(temp);
4864 /* WARNING: nothing may come after the
4865 * command handler call, as the handler
4866 * may free the user structure! */
4868 cmdlist[i].handler_function(command_p,items,user);
4874 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4875 WriteServ(user->fd,"451 %s :You have not registered",command);
4883 if ((!cmd_found) && (user))
4885 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4886 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4891 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4894 /* create the command and push it onto the table */
4895 strcpy(comm.command,cmd);
4896 comm.handler_function = f;
4897 comm.flags_needed = flags;
4898 comm.min_params = minparams;
4900 comm.total_bytes = 0;
4901 cmdlist.push_back(comm);
4902 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4905 void SetupCommandTable(void)
4907 createcommand("USER",handle_user,0,4);
4908 createcommand("NICK",handle_nick,0,1);
4909 createcommand("QUIT",handle_quit,0,0);
4910 createcommand("VERSION",handle_version,0,0);
4911 createcommand("PING",handle_ping,0,1);
4912 createcommand("PONG",handle_pong,0,1);
4913 createcommand("ADMIN",handle_admin,0,0);
4914 createcommand("PRIVMSG",handle_privmsg,0,2);
4915 createcommand("INFO",handle_info,0,0);
4916 createcommand("TIME",handle_time,0,0);
4917 createcommand("WHOIS",handle_whois,0,1);
4918 createcommand("WALLOPS",handle_wallops,'o',1);
4919 createcommand("NOTICE",handle_notice,0,2);
4920 createcommand("JOIN",handle_join,0,1);
4921 createcommand("NAMES",handle_names,0,1);
4922 createcommand("PART",handle_part,0,1);
4923 createcommand("KICK",handle_kick,0,2);
4924 createcommand("MODE",handle_mode,0,1);
4925 createcommand("TOPIC",handle_topic,0,1);
4926 createcommand("WHO",handle_who,0,1);
4927 createcommand("MOTD",handle_motd,0,0);
4928 createcommand("RULES",handle_rules,0,0);
4929 createcommand("OPER",handle_oper,0,2);
4930 createcommand("LIST",handle_list,0,0);
4931 createcommand("DIE",handle_die,'o',1);
4932 createcommand("RESTART",handle_restart,'o',1);
4933 createcommand("KILL",handle_kill,'o',2);
4934 createcommand("REHASH",handle_rehash,'o',0);
4935 createcommand("LUSERS",handle_lusers,0,0);
4936 createcommand("STATS",handle_stats,0,1);
4937 createcommand("USERHOST",handle_userhost,0,1);
4938 createcommand("AWAY",handle_away,0,0);
4939 createcommand("ISON",handle_ison,0,0);
4940 createcommand("SUMMON",handle_summon,0,0);
4941 createcommand("USERS",handle_users,0,0);
4942 createcommand("INVITE",handle_invite,0,2);
4943 createcommand("PASS",handle_pass,0,1);
4944 createcommand("TRACE",handle_trace,'o',0);
4945 createcommand("WHOWAS",handle_whowas,0,1);
4946 createcommand("CONNECT",handle_connect,'o',1);
4947 createcommand("SQUIT",handle_squit,'o',1);
4948 createcommand("MODULES",handle_modules,'o',0);
4951 void process_buffer(userrec *user)
4955 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4962 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4965 if (!strcmp(user->inbuf,""))
4969 strncpy(cmd,user->inbuf,MAXBUF);
4970 if (!strcmp(cmd,""))
4974 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4976 cmd[strlen(cmd)-1] = '\0';
4978 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4980 cmd[strlen(cmd)-1] = '\0';
4982 strcpy(user->inbuf,"");
4983 if (!strcmp(cmd,""))
4987 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4989 if ((user) && (cmd))
4991 process_command(user,cmd);
4995 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4997 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
5001 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
5003 char response[10240];
5004 char token = udp_msg[0];
5005 char* params = udp_msg + 2;
5006 char finalparam[1024];
5007 strcpy(finalparam," :xxxx");
5008 if (strstr(params," :")) {
5009 strncpy(finalparam,strstr(params," :"),1024);
5012 // S test.chatspike.net password :ChatSpike InspIRCd test server
5013 char* servername = strtok(params," ");
5014 char* password = strtok(NULL," ");
5015 char* serverdesc = finalparam+2;
5016 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
5019 char Link_ServerName[1024];
5020 char Link_IPAddr[1024];
5021 char Link_Port[1024];
5022 char Link_Pass[1024];
5023 char Link_SendPass[1024];
5026 // search for a corresponding <link> block in the config files
5027 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5029 ConfValue("link","name",i,Link_ServerName,&config_f);
5030 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5031 ConfValue("link","port",i,Link_Port,&config_f);
5032 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5033 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5034 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5035 LinkPort = atoi(Link_Port);
5036 if (!strcasecmp(Link_ServerName,servername)) {
5037 if (!strcasecmp(Link_IPAddr,udp_host)) {
5038 if (LinkPort == udp_port) {
5039 // we have a matching link line -
5040 // send a 'diminutive' server message back...
5041 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
5042 serv->SendPacket(response,udp_host,udp_port,0);
5043 WriteOpers("CONNECT from %s accepted, authenticating",servername);
5044 for (int j = 0; j < 255; j++) {
5045 if (servers[j] == NULL) {
5046 servers[j] = new serverrec;
5047 strcpy(servers[j]->internal_addr,udp_host);
5048 strcpy(servers[j]->name,servername);
5049 // create a server record for this server
5050 snprintf(response,10240,"O %d",MyKey);
5051 serv->SendPacket(response,udp_host,udp_port,0);
5055 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
5059 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5063 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5067 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5070 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5071 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5076 // if this is received, this means the server-ip that sent it said "OK" to credentials.
5077 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
5078 // array, which is only added by an 'S' packet or BeginLink().
5079 for (int i = 0; i < 255; i++) {
5080 if (servers[i] != NULL) {
5081 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
5082 servers[i]->key = atoi(params);
5083 log(DEBUG,"Key for this server is now %d",servers[i]->key);
5084 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
5089 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
5093 // S test.chatspike.net password :ChatSpike InspIRCd test server
5094 char* servername = strtok(params," ");
5095 char* password = strtok(NULL," ");
5096 char* serverdesc = finalparam+2;
5098 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5099 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5100 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5101 // a connect, so put out an oper alert!
5106 // for now, just accept all, we'll fix that later.
5107 WriteOpers("%s accepted our link credentials ",servername);
5109 char Link_ServerName[1024];
5110 char Link_IPAddr[1024];
5111 char Link_Port[1024];
5112 char Link_Pass[1024];
5113 char Link_SendPass[1024];
5116 // search for a corresponding <link> block in the config files
5117 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5119 ConfValue("link","name",i,Link_ServerName,&config_f);
5120 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5121 ConfValue("link","port",i,Link_Port,&config_f);
5122 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5123 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5124 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5125 LinkPort = atoi(Link_Port);
5126 if (!strcasecmp(Link_ServerName,servername)) {
5127 if (!strcasecmp(Link_IPAddr,udp_host)) {
5128 if (LinkPort == udp_port) {
5129 // matching link at this end too, we're all done!
5130 // at this point we must begin key exchange and insert this
5131 // server into our 'active' table.
5132 for (int j = 0; j < 255; j++) {
5133 if (servers[j] != NULL) {
5134 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5135 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5136 snprintf(response,10240,"O %d",MyKey);
5137 serv->SendPacket(response,udp_host,udp_port,0);
5142 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5147 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5151 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5155 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5158 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5159 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5164 char* error_message = finalparam+2;
5165 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5166 // remove this server from any lists
5167 for (int j = 0; j < 255; j++) {
5168 if (servers[j] != NULL) {
5169 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5179 serverrec* source_server = NULL;
5181 for (int j = 0; j < 255; j++) {
5182 if (servers[j] != NULL) {
5183 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5184 if (servers[j]->key == theirkey) {
5185 // found a valid key for this server, can process restricted stuff here
5186 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5194 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5198 int reap_counter = 0;
5202 struct sockaddr_in client, server;
5203 char addrs[MAXBUF][255];
5204 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5206 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5207 int selectResult = 0;
5208 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5209 char resolvedHost[MAXBUF];
5213 log_file = fopen("ircd.log","a+");
5216 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5220 log(DEBUG,"InspIRCd: startup: begin");
5224 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5226 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5228 SetupCommandTable();
5229 log(DEBUG,"InspIRCd: startup: default command table set up");
5232 if (strcmp(DieValue,""))
5234 printf("WARNING: %s\n\n",DieValue);
5237 log(DEBUG,"InspIRCd: startup: read config");
5239 int count2 = 0, count3 = 0;
5241 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5243 ConfValue("bind","port",count,configToken,&config_f);
5244 ConfValue("bind","address",count,Addr,&config_f);
5245 ConfValue("bind","type",count,Type,&config_f);
5246 if (!strcmp(Type,"servers"))
5248 char Default[MAXBUF];
5249 strcpy(Default,"no");
5250 ConfValue("bind","default",count,Default,&config_f);
5251 if (strchr(Default,'y'))
5253 defaultRoute = count3;
5254 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5256 me[count3] = new serverrec(ServerName,100L,false);
5257 me[count3]->CreateListener(Addr,atoi(configToken));
5262 ports[count2] = atoi(configToken);
5263 strcpy(addrs[count2],Addr);
5266 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5269 UDPportCount = count3;
5271 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5273 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5277 /* BugFix By Craig! :p */
5279 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5281 char modfile[MAXBUF];
5282 ConfValue("module","name",count,configToken,&config_f);
5283 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5284 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5285 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5286 /* If The File Doesnt exist, Trying to load it
5287 * Will Segfault the IRCd.. So, check to see if
5288 * it Exists, Before Proceeding. */
5289 if (FileExists(modfile))
5291 factory[count] = new ircd_module(modfile);
5292 if (factory[count]->LastError())
5294 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5295 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5298 if (factory[count]->factory)
5300 modules[count] = factory[count]->factory->CreateModule();
5301 /* save the module and the module's classfactory, if
5302 * this isnt done, random crashes can occur :/ */
5303 module_names.push_back(modfile);
5307 log(DEBUG,"Unable to load %s",modfile);
5308 sprintf("Unable to load %s\nExiting...\n",modfile);
5311 /* Increase the Count */
5316 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5317 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5320 MODCOUNT = count - 1;
5321 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5323 printf("\nInspIRCd is now running!\n");
5325 startup_time = time(NULL);
5329 log(VERBOSE,"Not forking as -nofork was specified");
5333 if (DaemonSeed() == ERROR)
5335 log(DEBUG,"InspIRCd: startup: can't daemonise");
5336 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5342 /* setup select call */
5343 FD_ZERO(&selectFds);
5344 log(DEBUG,"InspIRCd: startup: zero selects");
5345 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5347 for (count = 0; count < portCount; count++)
5349 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5351 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5354 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5356 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5358 else /* well we at least bound to one socket so we'll continue */
5364 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5366 /* if we didn't bind to anything then abort */
5367 if (boundPortCount == 0)
5369 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5373 length = sizeof (client);
5374 int flip_flop = 0, udp_port = 0;
5375 char udp_msg[MAXBUF], udp_host[MAXBUF];
5377 /* main loop for multiplexing/resetting */
5380 /* set up select call */
5381 for (count = 0; count < boundPortCount; count++)
5383 FD_SET (openSockfd[count], &selectFds);
5386 /* added timeout! select was waiting forever... wank... :/ */
5397 vector<int>::iterator niterator;
5400 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5401 // them in a list, then reap the list every second or so.
5402 if (reap_counter>5000) {
5403 if (fd_reap.size() > 0) {
5404 for( int n = 0; n < fd_reap.size(); n++)
5406 Blocking(fd_reap[n]);
5408 NonBlocking(fd_reap[n]);
5417 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5419 for (int x = 0; x != UDPportCount; x++)
5422 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5424 if (strlen(udp_msg)<1) {
5425 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5429 FOREACH_MOD OnPacketReceive(udp_msg);
5430 // Packets must go back via the route they arrived on :)
5431 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5436 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5440 if (!count2->second) break;
5443 if (count2->second->fd)
5445 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5446 // their connection class.
5447 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
5449 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5450 kill_link(count2->second,"Registration timeout");
5453 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5455 if (!count2->second->lastping)
5457 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5458 kill_link(count2->second,"Ping timeout");
5461 Write(count2->second->fd,"PING :%s",ServerName);
5462 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5463 count2->second->lastping = 0;
5464 count2->second->nping = time(NULL)+120;
5467 result = read(count2->second->fd, data, 1);
5468 // result EAGAIN means nothing read
5469 if (result == EAGAIN)
5477 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5478 kill_link(count2->second,"Client exited");
5479 // must bail here? kill_link removes the hash, corrupting the iterator
5480 log(DEBUG,"Bailing from client exit");
5484 else if (result > 0)
5489 // until the buffer is at 509 chars anything can be inserted into it.
5490 if ((strlen(count2->second->inbuf) < 509) && (data[0] != '\0')) {
5491 strncat(count2->second->inbuf, data, result);
5494 // once you reach 509 chars, only a \r or \n can be inserted,
5495 // completing the line.
5496 if ((strlen(count2->second->inbuf) >= 509) && ((data[0] == '\r') || (data[0] == '\n'))) {
5497 count2->second->inbuf[509] = '\r';
5498 count2->second->inbuf[510] = '\n';
5499 count2->second->inbuf[511] = '\0';
5500 process_buffer(count2->second);
5504 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5506 /* at least one complete line is waiting to be processed */
5507 if (!count2->second->fd)
5511 if (strlen(count2->second->inbuf)<512)
5513 // double check the length before processing!
5514 process_buffer(count2->second);
5518 strcpy(count2->second->inbuf,"");
5528 /* select is reporting a waiting socket. Poll them all to find out which */
5529 if (selectResult > 0)
5531 char target[MAXBUF], resolved[MAXBUF];
5532 for (count = 0; count < boundPortCount; count++)
5534 if (FD_ISSET (openSockfd[count], &selectFds))
5536 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5538 address_cache::iterator iter = IP.find(client.sin_addr);
5539 bool iscached = false;
5540 if (iter == IP.end())
5542 /* ip isn't in cache, add it */
5543 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5544 if(CleanAndResolve(resolved, target) != TRUE)
5546 strncpy(resolved,target,MAXBUF);
5548 /* hostname now in 'target' */
5549 IP[client.sin_addr] = new string(resolved);
5550 /* hostname in cache */
5554 /* found ip (cached) */
5555 strncpy(resolved, iter->second->c_str(), MAXBUF);
5559 if (incomingSockfd < 0)
5561 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5562 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5565 AddClient(incomingSockfd, resolved, ports[count], iscached);
5566 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5573 close (incomingSockfd);