1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
44 #include "connection.h"
54 #define nspace __gnu_cxx
59 int LogLevel = DEFAULT;
60 char ServerName[MAXBUF];
62 char ServerDesc[MAXBUF];
63 char AdminName[MAXBUF];
64 char AdminEmail[MAXBUF];
65 char AdminNick[MAXBUF];
67 char restartpass[MAXBUF];
71 char PrefixQuit[MAXBUF];
72 char DieValue[MAXBUF];
74 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
75 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
77 time_t startup_time = time(NULL);
78 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
79 time_t nb_start = time(NULL);
81 extern vector<Module*> modules;
82 std::vector<std::string> module_names;
83 extern vector<ircd_module*> factory;
84 std::vector<int> fd_reap;
94 template<> struct nspace::hash<in_addr>
96 size_t operator()(const struct in_addr &a) const
99 memcpy(&q,&a,sizeof(size_t));
104 template<> struct nspace::hash<string>
106 size_t operator()(const string &s) const
109 static struct hash<const char *> strhash;
121 bool operator()(const string& s1, const string& s2) const
123 char a[MAXBUF],b[MAXBUF];
124 strcpy(a,s1.c_str());
125 strcpy(b,s2.c_str());
126 return (strcasecmp(a,b) == 0);
131 struct InAddr_HashComp
134 bool operator()(const in_addr &s1, const in_addr &s2) const
139 memcpy(&q,&s1,sizeof(size_t));
140 memcpy(&p,&s2,sizeof(size_t));
148 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
149 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
150 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
151 typedef std::deque<command_t> command_table;
154 serverrec* servers[255];
158 user_hash clientlist;
161 command_table cmdlist;
168 struct linger linger = { 0 };
169 char bannerBuffer[MAXBUF];
170 int boundPortCount = 0;
171 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
172 int defaultRoute = 0;
176 long MyKey = C.GenKey();
180 int has_channel(userrec *u, chanrec *c);
181 int usercount(chanrec *c);
182 int usercount_i(chanrec *c);
183 void update_stats_l(int fd,int data_out);
184 char* Passwd(userrec *user);
185 bool IsDenied(userrec *user);
186 void AddWhoWas(userrec* u);
188 std::stringstream config_f(stringstream::in | stringstream::out);
190 void safedelete(userrec *p)
194 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
195 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
201 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
205 void safedelete(chanrec *p)
211 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
215 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
220 void tidystring(char* str)
222 // strips out double spaces before a : parameter
225 bool go_again = true;
232 while ((str[0] == ' ') && (strlen(str)>0))
239 bool noparse = false;
242 while (a < strlen(str))
244 if ((a<strlen(str)-1) && (noparse==false))
246 if ((str[a] == ' ') && (str[a+1] == ' '))
248 log(DEBUG,"Tidied extra space out of string: %s",str);
256 if ((str[a] == ' ') && (str[a+1] == ':'))
262 temp[t++] = str[a++];
265 strncpy(str,temp,MAXBUF);
269 /* chop a string down to 512 characters and preserve linefeed (irc max
276 log(DEBUG,"ERROR! Null string passed to chop()!");
280 FOREACH_MOD OnServerRaw(temp,false);
281 const char* str2 = temp.c_str();
282 sprintf(str,"%s",str2);
285 if (strlen(str) >= 512)
294 std::string getservername()
299 std::string getserverdesc()
304 std::string getnetworkname()
309 std::string getadminname()
314 std::string getadminemail()
319 std::string getadminnick()
324 void log(int level,char *text, ...)
326 char textbuffer[MAXBUF];
329 struct tm * timeinfo;
330 if (level < LogLevel)
334 timeinfo = localtime (&rawtime);
339 va_start (argsPtr, text);
340 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
342 strcpy(b,asctime(timeinfo));
343 b[strlen(b)-1] = ':';
344 fprintf(log_file,"%s %s\n",b,textbuffer);
347 // nofork enabled? display it on terminal too
348 printf("%s %s\n",b,textbuffer);
353 void readfile(file_cache &F, const char* fname)
356 char linebuf[MAXBUF];
358 log(DEBUG,"readfile: loading %s",fname);
360 file = fopen(fname,"r");
365 fgets(linebuf,sizeof(linebuf),file);
366 linebuf[strlen(linebuf)-1]='\0';
367 if (!strcmp(linebuf,""))
373 F.push_back(linebuf);
380 log(DEBUG,"readfile: failed to load file: %s",fname);
382 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
385 void ReadConfig(void)
387 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
390 LoadConf(CONFIG_FILE,&config_f);
392 ConfValue("server","name",0,ServerName,&config_f);
393 ConfValue("server","description",0,ServerDesc,&config_f);
394 ConfValue("server","network",0,Network,&config_f);
395 ConfValue("admin","name",0,AdminName,&config_f);
396 ConfValue("admin","email",0,AdminEmail,&config_f);
397 ConfValue("admin","nick",0,AdminNick,&config_f);
398 ConfValue("files","motd",0,motd,&config_f);
399 ConfValue("files","rules",0,rules,&config_f);
400 ConfValue("power","diepass",0,diepass,&config_f);
401 ConfValue("power","pause",0,pauseval,&config_f);
402 ConfValue("power","restartpass",0,restartpass,&config_f);
403 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
404 ConfValue("die","value",0,DieValue,&config_f);
405 ConfValue("options","loglevel",0,dbg,&config_f);
406 ConfValue("options","netbuffersize",0,NB,&config_f);
407 NetBufferSize = atoi(NB);
408 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
410 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
411 NetBufferSize = 10240;
413 if (!strcmp(dbg,"debug"))
415 if (!strcmp(dbg,"verbose"))
417 if (!strcmp(dbg,"default"))
419 if (!strcmp(dbg,"sparse"))
421 if (!strcmp(dbg,"none"))
424 log(DEBUG,"Reading message of the day");
425 readfile(RULES,rules);
426 log(DEBUG,"Reading connect classes");
428 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
431 ConfValue("connect","allow",i,Value,&config_f);
432 ConfValue("connect","timeout",i,timeout,&config_f);
433 ConfValue("connect","flood",i,flood,&config_f);
434 if (strcmp(Value,""))
436 strcpy(c.host,Value);
439 ConfValue("connect","password",i,Value,&config_f);
440 strcpy(c.pass,Value);
441 c.registration_timeout = 90; // default is 2 minutes
442 c.flood = atoi(flood);
445 c.registration_timeout = atoi(timeout);
447 Classes.push_back(c);
448 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
452 ConfValue("connect","deny",i,Value,&config_f);
453 strcpy(c.host,Value);
455 Classes.push_back(c);
456 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
465 log(DEBUG,"Blocking: %d",s);
466 flags = fcntl(s, F_GETFL, 0);
467 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
470 void NonBlocking(int s)
473 log(DEBUG,"NonBlocking: %d",s);
474 flags = fcntl(s, F_GETFL, 0);
475 //fcntl(s, F_SETFL, O_NONBLOCK);
476 fcntl(s, F_SETFL, flags | O_NONBLOCK);
480 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
482 struct hostent *hostPtr = NULL;
485 memset (resolvedHost, '\0',MAXBUF);
486 if(unresolvedHost == NULL)
488 if ((inet_aton(unresolvedHost,&addr)) == 0)
490 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
492 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
494 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
498 /* write formatted text to a socket, in same format as printf */
500 void Write(int sock,char *text, ...)
504 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
507 char textbuffer[MAXBUF];
511 va_start (argsPtr, text);
512 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
514 sprintf(tb,"%s\r\n",textbuffer);
518 write(sock,tb,strlen(tb));
519 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
523 /* write a server formatted numeric response to a single socket */
525 void WriteServ(int sock, char* text, ...)
529 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
532 char textbuffer[MAXBUF],tb[MAXBUF];
534 va_start (argsPtr, text);
536 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
538 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
542 write(sock,tb,strlen(tb));
543 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
547 /* write text from an originating user to originating user */
549 void WriteFrom(int sock, userrec *user,char* text, ...)
551 if ((!text) || (!user))
553 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
556 char textbuffer[MAXBUF],tb[MAXBUF];
558 va_start (argsPtr, text);
560 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
562 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
566 write(sock,tb,strlen(tb));
567 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
571 /* write text to an destination user from a source user (e.g. user privmsg) */
573 void WriteTo(userrec *source, userrec *dest,char *data, ...)
575 if ((!dest) || (!data))
577 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
580 char textbuffer[MAXBUF],tb[MAXBUF];
582 va_start (argsPtr, data);
583 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
587 // if no source given send it from the server.
590 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
594 WriteFrom(dest->fd,source,"%s",textbuffer);
598 /* write formatted text from a source user to all users on a channel
599 * including the sender (NOT for privmsg, notice etc!) */
601 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
603 if ((!Ptr) || (!user) || (!text))
605 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
608 char textbuffer[MAXBUF];
610 va_start (argsPtr, text);
611 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
613 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
615 if (has_channel(i->second,Ptr))
617 WriteTo(user,i->second,"%s",textbuffer);
622 /* write formatted text from a source user to all users on a channel
623 * including the sender (NOT for privmsg, notice etc!) doesnt send to
624 * users on remote servers */
626 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
628 if ((!Ptr) || (!text))
630 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
633 char textbuffer[MAXBUF];
635 va_start (argsPtr, text);
636 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
638 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
640 if (has_channel(i->second,Ptr))
642 if (i->second->fd != -1)
646 WriteServ(i->second->fd,"%s",textbuffer);
650 WriteTo(user,i->second,"%s",textbuffer);
658 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
660 if ((!Ptr) || (!user) || (!text))
662 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
665 char textbuffer[MAXBUF];
667 va_start (argsPtr, text);
668 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
670 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
674 if (has_channel(i->second,Ptr))
676 WriteServ(i->second->fd,"%s",textbuffer);
683 /* write formatted text from a source user to all users on a channel except
684 * for the sender (for privmsg etc) */
686 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
688 if ((!Ptr) || (!user) || (!text))
690 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
693 char textbuffer[MAXBUF];
695 va_start (argsPtr, text);
696 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
699 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
703 if (has_channel(i->second,Ptr) && (user != i->second))
705 WriteTo(user,i->second,"%s",textbuffer);
711 int c_count(userrec* u)
714 for (int i =0; i != MAXCHANS; i++)
715 if (u->chans[i].channel != NULL)
721 /* return 0 or 1 depending if users u and u2 share one or more common channels
722 * (used by QUIT, NICK etc which arent channel specific notices) */
724 int common_channels(userrec *u, userrec *u2)
731 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
734 for (i = 0; i != MAXCHANS; i++)
736 for (z = 0; z != MAXCHANS; z++)
738 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
740 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
742 if ((c_count(u)) && (c_count(u2)))
753 /* write a formatted string to all users who share at least one common
754 * channel, including the source user e.g. for use in NICK */
756 void WriteCommon(userrec *u, char* text, ...)
760 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
764 if (u->registered != 7) {
765 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
769 char textbuffer[MAXBUF];
771 va_start (argsPtr, text);
772 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
775 WriteFrom(u->fd,u,"%s",textbuffer);
777 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
781 if (common_channels(u,i->second) && (i->second != u))
783 WriteFrom(i->second->fd,u,"%s",textbuffer);
789 /* write a formatted string to all users who share at least one common
790 * channel, NOT including the source user e.g. for use in QUIT */
792 void WriteCommonExcept(userrec *u, char* text, ...)
796 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
800 if (u->registered != 7) {
801 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
805 char textbuffer[MAXBUF];
807 va_start (argsPtr, text);
808 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
811 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
815 if ((common_channels(u,i->second)) && (u != i->second))
817 WriteFrom(i->second->fd,u,"%s",textbuffer);
823 void WriteOpers(char* text, ...)
827 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
831 char textbuffer[MAXBUF];
833 va_start (argsPtr, text);
834 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
837 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
841 if (strchr(i->second->modes,'o'))
843 if (strchr(i->second->modes,'s'))
845 // send server notices to all with +s
846 // (TODO: needs SNOMASKs)
847 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
854 bool hasumode(userrec* user, char mode)
858 return (strchr(user->modes,mode)>0);
863 void WriteMode(const char* modes, int flags, const char* text, ...)
865 if ((!text) || (!modes) || (!flags))
867 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
871 char textbuffer[MAXBUF];
873 va_start (argsPtr, text);
874 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
877 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
881 bool send_to_user = false;
886 for (int n = 0; n < strlen(modes); n++)
888 if (!hasumode(i->second,modes[n]))
890 send_to_user = false;
895 else if (flags == WM_OR)
897 send_to_user = false;
898 for (int n = 0; n < strlen(modes); n++)
900 if (hasumode(i->second,modes[n]))
910 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
916 void WriteWallOps(userrec *source, char* text, ...)
918 if ((!text) || (!source))
920 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
925 char textbuffer[MAXBUF];
927 va_start (argsPtr, text);
928 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
931 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
935 if (strchr(i->second->modes,'w'))
937 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
943 /* convert a string to lowercase. Note following special circumstances
944 * taken from RFC 1459. Many "official" server branches still hold to this
945 * rule so i will too;
947 * Because of IRC's scandanavian origin, the characters {}| are
948 * considered to be the lower case equivalents of the characters []\,
949 * respectively. This is a critical issue when determining the
950 * equivalence of two nicknames.
953 void strlower(char *n)
959 for (int i = 0; i != strlen(n); i++)
961 n[i] = tolower(n[i]);
971 /* verify that a user's ident and nickname is valid */
973 int isident(const char* n)
986 for (i = 0; i != strlen(n); i++)
988 if ((n[i] < 33) || (n[i] > 125))
992 /* can't occur ANYWHERE in an Ident! */
993 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1002 int isnick(const char* n)
1014 if (strlen(n) > NICKMAX-1)
1018 for (i = 0; i != strlen(n); i++)
1020 if ((n[i] < 33) || (n[i] > 125))
1024 /* can't occur ANYWHERE in a nickname! */
1025 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1029 /* can't occur as the first char of a nickname... */
1030 if ((strchr("0123456789",n[i])) && (!i))
1038 /* Find a user record by nickname and return a pointer to it */
1040 userrec* Find(string nick)
1042 user_hash::iterator iter = clientlist.find(nick);
1044 if (iter == clientlist.end())
1045 /* Couldn't find it */
1048 return iter->second;
1051 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1053 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1057 if (i->second->fd == fd)
1059 i->second->bytes_out+=data_out;
1060 i->second->cmds_out++;
1067 /* find a channel record by channel name and return a pointer to it */
1069 chanrec* FindChan(const char* chan)
1073 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1077 chan_hash::iterator iter = chanlist.find(chan);
1079 if (iter == chanlist.end())
1080 /* Couldn't find it */
1083 return iter->second;
1087 void purge_empty_chans(void)
1089 int go_again = 1, purge = 0;
1094 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1097 if (!usercount(i->second))
1099 /* kill the record */
1100 if (i != chanlist.end())
1102 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1112 log(DEBUG,"skipped purge for %s",i->second->name);
1117 log(DEBUG,"completed channel purge, killed %d",purge);
1120 /* returns the status character for a given user on a channel, e.g. @ for op,
1121 * % for halfop etc. If the user has several modes set, the highest mode
1122 * the user has must be returned. */
1124 char* cmode(userrec *user, chanrec *chan)
1126 if ((!user) || (!chan))
1128 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1133 for (i = 0; i != MAXCHANS; i++)
1135 if ((user->chans[i].channel == chan) && (chan != NULL))
1137 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1141 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1145 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1154 char scratch[MAXBUF];
1155 char sparam[MAXBUF];
1157 char* chanmodes(chanrec *chan)
1161 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1168 if (chan->noexternal)
1170 strncat(scratch,"n",MAXMODES);
1172 if (chan->topiclock)
1174 strncat(scratch,"t",MAXMODES);
1176 if (strcmp(chan->key,""))
1178 strncat(scratch,"k",MAXMODES);
1182 strncat(scratch,"l",MAXMODES);
1184 if (chan->inviteonly)
1186 strncat(scratch,"i",MAXMODES);
1188 if (chan->moderated)
1190 strncat(scratch,"m",MAXMODES);
1194 strncat(scratch,"s",MAXMODES);
1196 if (chan->c_private)
1198 strncat(scratch,"p",MAXMODES);
1200 if (strcmp(chan->key,""))
1202 strncat(sparam,chan->key,MAXBUF);
1207 sprintf(foo," %d",chan->limit);
1208 strncat(sparam,foo,MAXBUF);
1210 if (strlen(chan->custom_modes))
1212 strncat(scratch,chan->custom_modes,MAXMODES);
1213 for (int z = 0; z < strlen(chan->custom_modes); z++)
1215 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1218 strncat(sparam," ",MAXBUF);
1219 strncat(sparam,extparam.c_str(),MAXBUF);
1223 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1224 strncat(scratch,sparam,MAXMODES);
1228 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1229 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1230 * highest mode the user has must be returned. */
1232 int cstatus(userrec *user, chanrec *chan)
1234 if ((!chan) || (!user))
1236 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1241 for (i = 0; i != MAXCHANS; i++)
1243 if ((user->chans[i].channel == chan) && (chan != NULL))
1245 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1249 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1253 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1255 return STATUS_VOICE;
1257 return STATUS_NORMAL;
1263 /* compile a userlist of a channel into a string, each nick seperated by
1264 * spaces and op, voice etc status shown as @ and + */
1266 void userlist(userrec *user,chanrec *c)
1268 if ((!c) || (!user))
1270 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1274 sprintf(list,"353 %s = %s :", user->nick, c->name);
1275 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1277 if (has_channel(i->second,c))
1279 if (isnick(i->second->nick))
1281 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1283 /* user is +i, and source not on the channel, does not show
1284 * nick in NAMES list */
1287 strcat(list,cmode(i->second,c));
1288 strcat(list,i->second->nick);
1290 if (strlen(list)>(480-NICKMAX))
1292 /* list overflowed into
1293 * multiple numerics */
1294 WriteServ(user->fd,list);
1295 sprintf(list,"353 %s = %s :", user->nick, c->name);
1300 /* if whats left in the list isnt empty, send it */
1301 if (list[strlen(list)-1] != ':')
1303 WriteServ(user->fd,list);
1307 /* return a count of the users on a specific channel accounting for
1308 * invisible users who won't increase the count. e.g. for /LIST */
1310 int usercount_i(chanrec *c)
1317 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1322 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1326 if (has_channel(i->second,c))
1328 if (isnick(i->second->nick))
1330 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1332 /* user is +i, and source not on the channel, does not show
1333 * nick in NAMES list */
1341 log(DEBUG,"usercount_i: %s %d",c->name,count);
1346 int usercount(chanrec *c)
1353 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1358 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1362 if (has_channel(i->second,c))
1364 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1371 log(DEBUG,"usercount: %s %d",c->name,count);
1376 /* add a channel to a user, creating the record for it if needed and linking
1377 * it to the user record */
1379 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1381 if ((!user) || (!cn))
1383 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1392 strncpy(cname,cn,MAXBUF);
1394 // we MUST declare this wherever we use FOREACH_RESULT
1397 if ((!cname) || (!user))
1401 if (strlen(cname) > CHANMAX-1)
1403 cname[CHANMAX-1] = '\0';
1406 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1408 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1410 return NULL; // already on the channel!
1414 if (!FindChan(cname))
1416 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1421 /* create a new one */
1422 log(DEBUG,"add_channel: creating: %s",cname);
1424 chanlist[cname] = new chanrec();
1426 strcpy(chanlist[cname]->name, cname);
1427 chanlist[cname]->topiclock = 1;
1428 chanlist[cname]->noexternal = 1;
1429 chanlist[cname]->created = time(NULL);
1430 strcpy(chanlist[cname]->topic, "");
1431 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1432 chanlist[cname]->topicset = 0;
1433 Ptr = chanlist[cname];
1434 log(DEBUG,"add_channel: created: %s",cname);
1435 /* set created to 2 to indicate user
1436 * is the first in the channel
1437 * and should be given ops */
1443 /* channel exists, just fish out a pointer to its struct */
1444 Ptr = FindChan(cname);
1447 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1452 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1454 // the override flag allows us to bypass channel modes
1455 // and bans (used by servers)
1459 if (strcmp(Ptr->key,""))
1461 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1464 log(DEBUG,"add_channel: no key given in JOIN");
1465 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1470 log(DEBUG,"key at %p is %s",key,key);
1471 if (strcasecmp(key,Ptr->key))
1473 log(DEBUG,"add_channel: bad key given in JOIN");
1474 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1479 log(DEBUG,"add_channel: no key");
1481 if (Ptr->inviteonly)
1483 log(DEBUG,"add_channel: channel is +i");
1484 if (user->IsInvited(Ptr->name))
1486 /* user was invited to channel */
1487 /* there may be an optional channel NOTICE here */
1491 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1495 log(DEBUG,"add_channel: channel is not +i");
1499 if (usercount(Ptr) == Ptr->limit)
1501 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1506 log(DEBUG,"add_channel: about to walk banlist");
1508 /* check user against the channel banlist */
1509 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1511 if (match(user->GetFullHost(),i->data))
1513 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1520 log(DEBUG,"add_channel: bans checked");
1522 user->RemoveInvite(Ptr->name);
1524 log(DEBUG,"add_channel: invites removed");
1530 log(DEBUG,"Passed channel checks");
1532 for (i =0; i != MAXCHANS; i++)
1534 if (user->chans[i].channel == NULL)
1536 log(DEBUG,"Adding into their channel list");
1540 /* first user in is given ops */
1541 user->chans[i].uc_modes = UCMODE_OP;
1545 user->chans[i].uc_modes = 0;
1547 user->chans[i].channel = Ptr;
1548 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1550 log(DEBUG,"Sent JOIN to client");
1554 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1555 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1558 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1559 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1560 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1561 FOREACH_MOD OnUserJoin(user,Ptr);
1565 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1566 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1570 /* remove a channel from a users record, and remove the record from memory
1571 * if the channel has become empty */
1573 chanrec* del_channel(userrec *user, const char* cname, const char* reason)
1575 if ((!user) || (!cname))
1577 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1585 if ((!cname) || (!user))
1590 Ptr = FindChan(cname);
1597 FOREACH_MOD OnUserPart(user,Ptr);
1598 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1600 for (i =0; i != MAXCHANS; i++)
1602 /* zap it from the channel list of the user */
1603 if (user->chans[i].channel == Ptr)
1607 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1611 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1613 user->chans[i].uc_modes = 0;
1614 user->chans[i].channel = NULL;
1615 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1620 /* if there are no users left on the channel */
1621 if (!usercount(Ptr))
1623 chan_hash::iterator iter = chanlist.find(Ptr->name);
1625 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1627 /* kill the record */
1628 if (iter != chanlist.end())
1630 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1631 delete iter->second;
1632 chanlist.erase(iter);
1638 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1640 if ((!src) || (!user) || (!Ptr) || (!reason))
1642 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1649 if ((!Ptr) || (!user) || (!src))
1654 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1656 if (!has_channel(user,Ptr))
1658 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1661 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1663 if (cstatus(src,Ptr) == STATUS_HOP)
1665 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1669 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1675 for (i =0; i != MAXCHANS; i++)
1677 /* zap it from the channel list of the user */
1678 if (user->chans[i].channel == Ptr)
1680 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1681 user->chans[i].uc_modes = 0;
1682 user->chans[i].channel = NULL;
1683 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1688 /* if there are no users left on the channel */
1689 if (!usercount(Ptr))
1691 chan_hash::iterator iter = chanlist.find(Ptr->name);
1693 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1695 /* kill the record */
1696 if (iter != chanlist.end())
1698 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1699 delete iter->second;
1700 chanlist.erase(iter);
1706 /* returns 1 if user u has channel c in their record, 0 if not */
1708 int has_channel(userrec *u, chanrec *c)
1714 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1717 for (i =0; i != MAXCHANS; i++)
1719 if (u->chans[i].channel == c)
1727 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1732 if ((!user) || (!dest) || (!chan))
1734 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1737 if (status != STATUS_OP)
1739 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1746 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1752 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1757 for (i = 0; i != MAXCHANS; i++)
1759 if ((d->chans[i].channel == chan) && (chan != NULL))
1761 if (d->chans[i].uc_modes & UCMODE_OP)
1763 /* mode already set on user, dont allow multiple */
1766 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1767 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1775 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1780 if ((!user) || (!dest) || (!chan))
1782 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1785 if (status != STATUS_OP)
1787 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1795 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1800 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1805 for (i = 0; i != MAXCHANS; i++)
1807 if ((d->chans[i].channel == chan) && (chan != NULL))
1809 if (d->chans[i].uc_modes & UCMODE_HOP)
1811 /* mode already set on user, dont allow multiple */
1814 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1815 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1823 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1828 if ((!user) || (!dest) || (!chan))
1830 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1833 if (status < STATUS_HOP)
1835 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1843 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1848 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1853 for (i = 0; i != MAXCHANS; i++)
1855 if ((d->chans[i].channel == chan) && (chan != NULL))
1857 if (d->chans[i].uc_modes & UCMODE_VOICE)
1859 /* mode already set on user, dont allow multiple */
1862 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1863 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1871 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1876 if ((!user) || (!dest) || (!chan))
1878 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1881 if (status != STATUS_OP)
1883 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1891 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1896 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1901 for (i = 0; i != MAXCHANS; i++)
1903 if ((d->chans[i].channel == chan) && (chan != NULL))
1905 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1907 /* mode already set on user, dont allow multiple */
1910 d->chans[i].uc_modes ^= UCMODE_OP;
1911 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1919 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1924 if ((!user) || (!dest) || (!chan))
1926 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1929 if (status != STATUS_OP)
1931 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1939 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1944 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1949 for (i = 0; i != MAXCHANS; i++)
1951 if ((d->chans[i].channel == chan) && (chan != NULL))
1953 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1955 /* mode already set on user, dont allow multiple */
1958 d->chans[i].uc_modes ^= UCMODE_HOP;
1959 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1967 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1972 if ((!user) || (!dest) || (!chan))
1974 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1977 if (status < STATUS_HOP)
1979 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
1987 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1992 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1997 for (i = 0; i != MAXCHANS; i++)
1999 if ((d->chans[i].channel == chan) && (chan != NULL))
2001 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
2003 /* mode already set on user, dont allow multiple */
2006 d->chans[i].uc_modes ^= UCMODE_VOICE;
2007 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
2015 void TidyBan(char *ban)
2018 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
2022 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
2026 char* pos_of_pling = strchr(temp,'!');
2027 char* pos_of_at = strchr(temp,'@');
2029 pos_of_pling[0] = '\0';
2030 pos_of_at[0] = '\0';
2034 strncpy(NICK,temp,NICKMAX);
2035 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
2036 strncpy(HOST,pos_of_at,160);
2038 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
2041 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
2043 if ((!user) || (!dest) || (!chan)) {
2044 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
2049 if ((!user) || (!dest) || (!chan))
2051 if (strchr(dest,'!')==0)
2053 if (strchr(dest,'@')==0)
2055 for (int i = 0; i < strlen(dest); i++)
2058 for (int i = 0; i < strlen(dest); i++)
2062 for (int i = 0; i < strlen(dest); i++)
2068 for (int i = 0; i < strlen(dest); i++)
2073 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2076 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2078 if (!strcasecmp(i->data,dest))
2080 // dont allow a user to set the same ban twice
2085 b.set_time = time(NULL);
2086 strncpy(b.data,dest,MAXBUF);
2087 strncpy(b.set_by,user->nick,NICKMAX);
2088 chan->bans.push_back(b);
2092 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2094 if ((!user) || (!dest) || (!chan)) {
2095 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2099 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2100 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2102 if (!strcasecmp(i->data,dest))
2104 chan->bans.erase(i);
2111 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode, bool silent)
2114 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2118 char modelist[MAXBUF];
2119 char outlist[MAXBUF];
2120 char outstr[MAXBUF];
2121 char outpars[32][MAXBUF];
2127 bool k_set = false, l_set = false;
2134 log(DEBUG,"process_modes: start");
2136 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2137 /* parameters[2] onwards are parameters for
2138 * modes that require them :) */
2139 strcpy(outlist,"+");
2142 log(DEBUG,"process_modes: modelist: %s",modelist);
2144 for (ptr = 0; ptr < strlen(modelist); ptr++)
2149 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2150 char modechar = modelist[ptr];
2151 switch (modelist[ptr])
2156 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2158 outlist[strlen(outlist)-1] = '-';
2162 strcat(outlist,"-");
2172 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2174 outlist[strlen(outlist)-1] = '+';
2178 strcat(outlist,"+");
2185 if ((param >= pcnt)) break;
2188 r = give_ops(user,parameters[param++],chan,status);
2192 r = take_ops(user,parameters[param++],chan,status);
2196 strcat(outlist,"o");
2197 strcpy(outpars[pc++],parameters[param-1]);
2202 if ((param >= pcnt)) break;
2205 r = give_hops(user,parameters[param++],chan,status);
2209 r = take_hops(user,parameters[param++],chan,status);
2213 strcat(outlist,"h");
2214 strcpy(outpars[pc++],parameters[param-1]);
2220 if ((param >= pcnt)) break;
2223 r = give_voice(user,parameters[param++],chan,status);
2227 r = take_voice(user,parameters[param++],chan,status);
2231 strcat(outlist,"v");
2232 strcpy(outpars[pc++],parameters[param-1]);
2237 if ((param >= pcnt)) break;
2240 r = add_ban(user,parameters[param++],chan,status);
2244 r = take_ban(user,parameters[param++],chan,status);
2248 strcat(outlist,"b");
2249 strcpy(outpars[pc++],parameters[param-1]);
2255 if ((param >= pcnt))
2263 if (!strcmp(chan->key,""))
2265 strcat(outlist,"k");
2267 strcpy(key,parameters[param++]);
2268 if (strlen(key)>32) {
2271 strcpy(outpars[pc++],key);
2272 strcpy(chan->key,key);
2278 /* checks on -k are case sensitive and only accurate to the
2279 first 32 characters */
2281 strcpy(key,parameters[param++]);
2282 if (strlen(key)>32) {
2285 /* only allow -k if correct key given */
2286 if (!strcmp(chan->key,key))
2288 strcat(outlist,"k");
2289 strcpy(chan->key,"");
2290 strcpy(outpars[pc++],key);
2300 strcat(outlist,"l");
2305 if ((param >= pcnt)) break;
2311 bool invalid = false;
2312 for (int i = 0; i < strlen(parameters[param]); i++)
2314 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2319 if (atoi(parameters[param]) < 1)
2327 chan->limit = atoi(parameters[param]);
2330 strcat(outlist,"l");
2331 strcpy(outpars[pc++],parameters[param++]);
2338 if (chan->inviteonly != mdir)
2340 strcat(outlist,"i");
2342 chan->inviteonly = mdir;
2346 if (chan->topiclock != mdir)
2348 strcat(outlist,"t");
2350 chan->topiclock = mdir;
2354 if (chan->noexternal != mdir)
2356 strcat(outlist,"n");
2358 chan->noexternal = mdir;
2362 if (chan->moderated != mdir)
2364 strcat(outlist,"m");
2366 chan->moderated = mdir;
2370 if (chan->secret != mdir)
2372 strcat(outlist,"s");
2373 if (chan->c_private)
2375 chan->c_private = 0;
2378 strcat(outlist,"-p+");
2382 strcat(outlist,"+p-");
2386 chan->secret = mdir;
2390 if (chan->c_private != mdir)
2392 strcat(outlist,"p");
2398 strcat(outlist,"-s+");
2402 strcat(outlist,"+s-");
2406 chan->c_private = mdir;
2410 log(DEBUG,"Preprocessing custom mode %c",modechar);
2413 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2415 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2418 if (ModeDefined(modechar,MT_CHANNEL))
2420 log(DEBUG,"A module has claimed this mode");
2423 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2425 p.push_back(parameters[param]);
2427 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2429 p.push_back(parameters[param]);
2432 bool handled = false;
2435 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2436 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2437 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2443 for (int i = 0; i <= MODCOUNT; i++)
2447 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2449 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2450 char app[] = {modechar, 0};
2453 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2455 strcat(outlist, app);
2457 else if (!strchr(outlist,modechar))
2459 strcat(outlist, app);
2462 chan->SetCustomMode(modechar,mdir);
2463 // include parameters in output if mode has them
2464 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2466 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2467 strcpy(outpars[pc++],parameters[param++]);
2469 // break, because only one module can handle the mode.
2481 /* this ensures only the *valid* modes are sent out onto the network */
2482 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2484 outlist[strlen(outlist)-1] = '\0';
2486 if (strcmp(outlist,""))
2488 strcpy(outstr,outlist);
2489 for (ptr = 0; ptr < pc; ptr++)
2492 strcat(outstr,outpars[ptr]);
2497 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2502 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2507 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2509 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2511 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2512 // RFC1459 specified modes
2513 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2515 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2519 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2520 if ((strchr(sourcemodes,'o')) && (!adding))
2522 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2525 else if (umode == 'o')
2527 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2531 // process any module-defined modes that need oper
2532 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2534 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2538 if (ModeDefined(umode,MT_CLIENT))
2540 // process any module-defined modes that don't need oper
2541 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2542 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2544 // no, this mode needs oper, and this user 'aint got what it takes!
2550 // anything else - return false.
2551 log(DEBUG,"umode %c not known by any ruleset",umode);
2555 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2561 strncpy(s2.nick,ServerName,NICKMAX);
2562 strcpy(s2.modes,"o");
2569 if (ModeDefined(umode,MT_CLIENT))
2571 for (int i = 0; i <= MODCOUNT; i++)
2573 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2575 log(DEBUG,"Module claims umode %c",umode);
2579 log(DEBUG,"No module claims umode %c",umode);
2586 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2593 void handle_mode(char **parameters, int pcnt, userrec *user)
2599 char outpars[MAXBUF];
2601 dest = Find(parameters[0]);
2603 if ((dest) && (pcnt == 1))
2605 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2609 if ((dest) && (pcnt > 1))
2611 char dmodes[MAXBUF];
2612 strncpy(dmodes,dest->modes,MAXBUF);
2613 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2618 if (strchr(user->modes,'o'))
2629 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2633 strcpy(outpars,"+");
2636 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2639 for (i = 0; i < strlen(parameters[1]); i++)
2641 if (parameters[1][i] == '+')
2645 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2647 outpars[strlen(outpars)-1] = '+';
2651 strcat(outpars,"+");
2657 if (parameters[1][i] == '-')
2661 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2663 outpars[strlen(outpars)-1] = '-';
2667 strcat(outpars,"-");
2675 if (strchr(user->modes,'o'))
2681 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2690 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2692 char umode = parameters[1][i];
2693 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2695 dmodes[strlen(dmodes)+1]='\0';
2696 dmodes[strlen(dmodes)] = parameters[1][i];
2697 outpars[strlen(outpars)+1]='\0';
2698 outpars[strlen(outpars)] = parameters[1][i];
2704 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2706 char umode = parameters[1][i];
2707 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2713 outpars[strlen(outpars)+1]='\0';
2714 outpars[strlen(outpars)] = parameters[1][i];
2717 for (q = 0; q < strlen(dmodes); q++)
2719 if (dmodes[q] != parameters[1][i])
2726 strcpy(dmodes,temp);
2733 if (strlen(outpars))
2739 while (i < strlen (outpars))
2741 b[z++] = outpars[i++];
2743 if (i<strlen(outpars)-1)
2745 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2747 // someones playing silly buggers and trying
2748 // to put a +- or -+ into the line...
2752 if (i == strlen(outpars)-1)
2754 if ((outpars[i] == '-') || (outpars[i] == '+'))
2762 if ((b[z] == '-') || (b[z] == '+'))
2765 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2768 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2770 if (strlen(dmodes)>MAXMODES)
2772 dmodes[MAXMODES-1] = '\0';
2774 log(DEBUG,"Stripped mode line");
2775 log(DEBUG,"Line dest is now %s",dmodes);
2776 strncpy(dest->modes,dmodes,MAXMODES);
2783 Ptr = FindChan(parameters[0]);
2788 /* just /modes #channel */
2789 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2790 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2796 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2799 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2801 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2803 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2807 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2809 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
2813 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false);
2817 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2824 void server_mode(char **parameters, int pcnt, userrec *user)
2830 char outpars[MAXBUF];
2832 dest = Find(parameters[0]);
2834 // fix: ChroNiCk found this - we cant use this as debug if its null!
2837 log(DEBUG,"server_mode on %s",dest->nick);
2840 if ((dest) && (pcnt > 1))
2842 log(DEBUG,"params > 1");
2844 char dmodes[MAXBUF];
2845 strncpy(dmodes,dest->modes,MAXBUF);
2847 strcpy(outpars,"+");
2850 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2853 for (i = 0; i < strlen(parameters[1]); i++)
2855 if (parameters[1][i] == '+')
2859 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2861 outpars[strlen(outpars)-1] = '+';
2865 strcat(outpars,"+");
2871 if (parameters[1][i] == '-')
2875 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2877 outpars[strlen(outpars)-1] = '-';
2881 strcat(outpars,"-");
2888 log(DEBUG,"begin mode processing entry");
2894 log(DEBUG,"umode %c being added",parameters[1][i]);
2895 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2897 char umode = parameters[1][i];
2898 log(DEBUG,"umode %c is an allowed umode",umode);
2899 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2901 dmodes[strlen(dmodes)+1]='\0';
2902 dmodes[strlen(dmodes)] = parameters[1][i];
2903 outpars[strlen(outpars)+1]='\0';
2904 outpars[strlen(outpars)] = parameters[1][i];
2910 // can only remove a mode they already have
2911 log(DEBUG,"umode %c being removed",parameters[1][i]);
2912 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2914 char umode = parameters[1][i];
2915 log(DEBUG,"umode %c is an allowed umode",umode);
2916 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2922 outpars[strlen(outpars)+1]='\0';
2923 outpars[strlen(outpars)] = parameters[1][i];
2926 for (q = 0; q < strlen(dmodes); q++)
2928 if (dmodes[q] != parameters[1][i])
2935 strcpy(dmodes,temp);
2942 if (strlen(outpars))
2948 while (i < strlen (outpars))
2950 b[z++] = outpars[i++];
2952 if (i<strlen(outpars)-1)
2954 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2956 // someones playing silly buggers and trying
2957 // to put a +- or -+ into the line...
2961 if (i == strlen(outpars)-1)
2963 if ((outpars[i] == '-') || (outpars[i] == '+'))
2971 if ((b[z] == '-') || (b[z] == '+'))
2974 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2977 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2979 if (strlen(dmodes)>MAXMODES)
2981 dmodes[MAXMODES-1] = '\0';
2983 log(DEBUG,"Stripped mode line");
2984 log(DEBUG,"Line dest is now %s",dmodes);
2985 strncpy(dest->modes,dmodes,MAXMODES);
2992 Ptr = FindChan(parameters[0]);
2995 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true,false);
2999 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3005 void merge_mode(char **parameters, int pcnt)
3011 char outpars[MAXBUF];
3013 dest = Find(parameters[0]);
3015 // fix: ChroNiCk found this - we cant use this as debug if its null!
3018 log(DEBUG,"merge_mode on %s",dest->nick);
3021 if ((dest) && (pcnt > 1))
3023 log(DEBUG,"params > 1");
3025 char dmodes[MAXBUF];
3026 strncpy(dmodes,dest->modes,MAXBUF);
3028 strcpy(outpars,"+");
3031 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3034 for (i = 0; i < strlen(parameters[1]); i++)
3036 if (parameters[1][i] == '+')
3040 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3042 outpars[strlen(outpars)-1] = '+';
3046 strcat(outpars,"+");
3052 if (parameters[1][i] == '-')
3056 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3058 outpars[strlen(outpars)-1] = '-';
3062 strcat(outpars,"-");
3069 log(DEBUG,"begin mode processing entry");
3075 log(DEBUG,"umode %c being added",parameters[1][i]);
3076 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],"o",true)))
3078 char umode = parameters[1][i];
3079 log(DEBUG,"umode %c is an allowed umode",umode);
3080 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3082 dmodes[strlen(dmodes)+1]='\0';
3083 dmodes[strlen(dmodes)] = parameters[1][i];
3084 outpars[strlen(outpars)+1]='\0';
3085 outpars[strlen(outpars)] = parameters[1][i];
3091 // can only remove a mode they already have
3092 log(DEBUG,"umode %c being removed",parameters[1][i]);
3093 if ((allowed_umode(parameters[1][i],"o",false)) && (strchr(dmodes,parameters[1][i])))
3095 char umode = parameters[1][i];
3096 log(DEBUG,"umode %c is an allowed umode",umode);
3097 if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3103 outpars[strlen(outpars)+1]='\0';
3104 outpars[strlen(outpars)] = parameters[1][i];
3107 for (q = 0; q < strlen(dmodes); q++)
3109 if (dmodes[q] != parameters[1][i])
3116 strcpy(dmodes,temp);
3123 if (strlen(outpars))
3129 while (i < strlen (outpars))
3131 b[z++] = outpars[i++];
3133 if (i<strlen(outpars)-1)
3135 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3137 // someones playing silly buggers and trying
3138 // to put a +- or -+ into the line...
3142 if (i == strlen(outpars)-1)
3144 if ((outpars[i] == '-') || (outpars[i] == '+'))
3152 if ((b[z] == '-') || (b[z] == '+'))
3155 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3158 if (strlen(dmodes)>MAXMODES)
3160 dmodes[MAXMODES-1] = '\0';
3162 log(DEBUG,"Stripped mode line");
3163 log(DEBUG,"Line dest is now %s",dmodes);
3164 strncpy(dest->modes,dmodes,MAXMODES);
3171 Ptr = FindChan(parameters[0]);
3175 strncpy(s2.nick,ServerName,NICKMAX);
3176 strcpy(s2.modes,"o");
3178 process_modes(parameters,&s2,Ptr,STATUS_OP,pcnt,true,true);
3183 /* This function pokes and hacks at a parameter list like the following:
3185 * PART #winbot, #darkgalaxy :m00!
3187 * to turn it into a series of individual calls like this:
3189 * PART #winbot :m00!
3190 * PART #darkgalaxy :m00!
3192 * The seperate calls are sent to a callback function provided by the caller
3193 * (the caller will usually call itself recursively). The callback function
3194 * must be a command handler. Calling this function on a line with no list causes
3195 * no action to be taken. You must provide a starting and ending parameter number
3196 * where the range of the list can be found, useful if you have a terminating
3197 * parameter as above which is actually not part of the list, or parameters
3198 * before the actual list as well. This code is used by many functions which
3199 * can function as "one to list" (see the RFC) */
3201 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
3206 char blog[32][MAXBUF];
3207 char blog2[32][MAXBUF];
3208 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
3209 char keystr[MAXBUF];
3212 for (i = 0; i <32; i++)
3215 for (i = 0; i <32; i++)
3216 strcpy(blog2[i],"");
3219 for (i = 0; i <10; i++)
3223 parameters[i] = moo;
3228 if (pcnt > 1) /* we have a key to copy */
3230 strcpy(keystr,parameters[1]);
3234 if (!parameters[start])
3238 if (!strchr(parameters[start],','))
3243 for (i = start; i <= end; i++)
3247 strcat(plist,parameters[i]);
3255 for (i = 0; i < t; i++)
3257 if (plist[i] == ',')
3260 strcpy(blog[j++],param);
3264 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3269 strcpy(blog[j++],param);
3272 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3277 if ((joins) && (keystr))
3279 if (strchr(keystr,','))
3283 t2 = strlen(keystr);
3284 for (i = 0; i < t2; i++)
3286 if (keystr[i] == ',')
3289 strcpy(blog2[j++],param);
3293 strcpy(blog2[j++],param);
3298 for (j = 0; j < total; j++)
3304 for (q = end; q < pcnt-1; q++)
3306 if (parameters[q+1])
3308 pars[q-end+1] = parameters[q+1];
3311 if ((joins) && (parameters[1]))
3322 /* repeatedly call the function with the hacked parameter list */
3323 if ((joins) && (pcnt > 1))
3327 // pars[1] already set up and containing key from blog2[j]
3332 pars[1] = parameters[1];
3338 fn(pars,pcnt-(end-start),u);
3346 void handle_join(char **parameters, int pcnt, userrec *user)
3351 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3353 if (parameters[0][0] == '#')
3355 Ptr = add_channel(user,parameters[0],parameters[1],false);
3360 void handle_part(char **parameters, int pcnt, userrec *user)
3366 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3368 del_channel(user,parameters[0],parameters[1]);
3372 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3374 del_channel(user,parameters[0],NULL);
3378 void handle_kick(char **parameters, int pcnt, userrec *user)
3380 chanrec* Ptr = FindChan(parameters[0]);
3381 userrec* u = Find(parameters[1]);
3385 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3389 if (!has_channel(u,Ptr))
3391 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3397 char reason[MAXBUF];
3398 strncpy(reason,parameters[2],MAXBUF);
3399 if (strlen(reason)>MAXKICK)
3401 reason[MAXKICK-1] = '\0';
3404 kick_channel(user,u,Ptr,reason);
3408 kick_channel(user,u,Ptr,user->nick);
3413 void handle_die(char **parameters, int pcnt, userrec *user)
3415 log(DEBUG,"die: %s",user->nick);
3416 if (!strcmp(parameters[0],diepass))
3418 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3424 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3428 void handle_restart(char **parameters, int pcnt, userrec *user)
3430 log(DEBUG,"restart: %s",user->nick);
3431 if (!strcmp(parameters[0],restartpass))
3433 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3436 /* Will finish this later when i can be arsed :) */
3440 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3445 void kill_link(userrec *user,const char* r)
3447 user_hash::iterator iter = clientlist.find(user->nick);
3449 char reason[MAXBUF];
3451 strncpy(reason,r,MAXBUF);
3453 if (strlen(reason)>MAXQUIT)
3455 reason[MAXQUIT-1] = '\0';
3458 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3459 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3460 log(DEBUG,"closing fd %d",user->fd);
3462 /* bugfix, cant close() a nonblocking socket (sux!) */
3463 if (user->registered == 7) {
3464 FOREACH_MOD OnUserQuit(user);
3465 WriteCommonExcept(user,"QUIT :%s",reason);
3468 /* push the socket on a stack of sockets due to be closed at the next opportunity
3469 * 'Client exited' is an exception to this as it means the client side has already
3470 * closed the socket, we don't need to do it.
3472 fd_reap.push_back(user->fd);
3474 bool do_purge = false;
3476 if (user->registered == 7) {
3477 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3481 if (iter != clientlist.end())
3483 log(DEBUG,"deleting user hash value %d",iter->second);
3484 if ((iter->second) && (user->registered == 7)) {
3485 delete iter->second;
3487 clientlist.erase(iter);
3490 if (user->registered == 7) {
3491 purge_empty_chans();
3498 void handle_kill(char **parameters, int pcnt, userrec *user)
3500 userrec *u = Find(parameters[0]);
3501 char killreason[MAXBUF];
3503 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3506 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3507 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3508 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3509 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3510 kill_link(u,killreason);
3514 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3518 void handle_summon(char **parameters, int pcnt, userrec *user)
3520 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3523 void handle_users(char **parameters, int pcnt, userrec *user)
3525 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3529 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3531 char* Passwd(userrec *user)
3533 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3535 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3543 bool IsDenied(userrec *user)
3545 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3547 if (match(user->host,i->host) && (i->type == CC_DENY))
3557 void handle_pass(char **parameters, int pcnt, userrec *user)
3559 // Check to make sure they havnt registered -- Fix by FCS
3560 if (user->registered == 7)
3562 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3565 if (!strcasecmp(parameters[0],Passwd(user)))
3567 user->haspassed = true;
3571 void handle_invite(char **parameters, int pcnt, userrec *user)
3573 userrec* u = Find(parameters[0]);
3574 chanrec* c = FindChan(parameters[1]);
3580 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3586 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3595 if (cstatus(user,c) < STATUS_HOP)
3597 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
3601 if (has_channel(u,c))
3603 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
3606 if (!has_channel(user,c))
3608 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
3611 u->InviteTo(c->name);
3612 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3613 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3616 void handle_topic(char **parameters, int pcnt, userrec *user)
3622 if (strlen(parameters[0]) <= CHANMAX)
3624 Ptr = FindChan(parameters[0]);
3629 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3630 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3634 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3639 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3646 if (strlen(parameters[0]) <= CHANMAX)
3648 Ptr = FindChan(parameters[0]);
3651 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3653 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
3658 strncpy(topic,parameters[1],MAXBUF);
3659 if (strlen(topic)>MAXTOPIC)
3661 topic[MAXTOPIC-1] = '\0';
3664 strcpy(Ptr->topic,topic);
3665 strcpy(Ptr->setby,user->nick);
3666 Ptr->topicset = time(NULL);
3667 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3671 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3677 /* sends out an error notice to all connected clients (not to be used
3680 void send_error(char *s)
3682 log(DEBUG,"send_error: %s",s);
3683 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3685 if (isnick(i->second->nick))
3687 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3691 // fix - unregistered connections receive ERROR, not NOTICE
3692 Write(i->second->fd,"ERROR :%s",s);
3697 void Error(int status)
3699 signal (SIGALRM, SIG_IGN);
3700 signal (SIGPIPE, SIG_IGN);
3701 signal (SIGTERM, SIG_IGN);
3702 signal (SIGABRT, SIG_IGN);
3703 signal (SIGSEGV, SIG_IGN);
3704 signal (SIGURG, SIG_IGN);
3705 signal (SIGKILL, SIG_IGN);
3706 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3707 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3712 int main (int argc, char *argv[])
3715 log(DEBUG,"*** InspIRCd starting up!");
3716 if (!FileExists(CONFIG_FILE))
3718 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3719 log(DEBUG,"main: no config");
3720 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3724 if (!strcmp(argv[1],"-nofork")) {
3728 if (InspIRCd() == ERROR)
3730 log(DEBUG,"main: daemon function bailed");
3731 printf("ERROR: could not initialise. Shutting down.\n");
3738 template<typename T> inline string ConvToStr(const T &in)
3741 if (!(tmp << in)) return string();
3745 /* re-allocates a nick in the user_hash after they change nicknames,
3746 * returns a pointer to the new user as it may have moved */
3748 userrec* ReHashNick(char* Old, char* New)
3750 user_hash::iterator newnick;
3751 user_hash::iterator oldnick = clientlist.find(Old);
3753 log(DEBUG,"ReHashNick: %s %s",Old,New);
3755 if (!strcasecmp(Old,New))
3757 log(DEBUG,"old nick is new nick, skipping");
3758 return oldnick->second;
3761 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3763 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3765 clientlist[New] = new userrec();
3766 clientlist[New] = oldnick->second;
3767 /*delete oldnick->second; */
3768 clientlist.erase(oldnick);
3770 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3772 return clientlist[New];
3775 /* adds or updates an entry in the whowas list */
3776 void AddWhoWas(userrec* u)
3778 user_hash::iterator iter = whowas.find(u->nick);
3779 userrec *a = new userrec();
3780 strcpy(a->nick,u->nick);
3781 strcpy(a->ident,u->ident);
3782 strcpy(a->dhost,u->dhost);
3783 strcpy(a->host,u->host);
3784 strcpy(a->fullname,u->fullname);
3785 strcpy(a->server,u->server);
3786 a->signon = u->signon;
3788 /* MAX_WHOWAS: max number of /WHOWAS items
3789 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3790 * can be replaced by a newer one
3793 if (iter == whowas.end())
3795 if (whowas.size() == WHOWAS_MAX)
3797 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3799 // 3600 seconds in an hour ;)
3800 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3804 log(DEBUG,"added WHOWAS entry, purged an old record");
3811 log(DEBUG,"added fresh WHOWAS entry");
3812 whowas[a->nick] = a;
3817 log(DEBUG,"updated WHOWAS entry");
3818 delete iter->second;
3824 /* add a client connection to the sockets list */
3825 void AddClient(int socket, char* host, int port, bool iscached)
3829 char resolved[MAXBUF];
3832 user_hash::iterator iter;
3834 tempnick = ConvToStr(socket) + "-unknown";
3835 sprintf(tn2,"%d-unknown",socket);
3837 iter = clientlist.find(tempnick);
3839 if (iter != clientlist.end()) return;
3842 * It is OK to access the value here this way since we know
3843 * it exists, we just created it above.
3845 * At NO other time should you access a value in a map or a
3846 * hash_map this way.
3848 clientlist[tempnick] = new userrec();
3850 NonBlocking(socket);
3851 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3853 clientlist[tempnick]->fd = socket;
3854 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3855 strncpy(clientlist[tempnick]->host, host,160);
3856 strncpy(clientlist[tempnick]->dhost, host,160);
3857 strncpy(clientlist[tempnick]->server, ServerName,256);
3858 strncpy(clientlist[tempnick]->ident, "unknown",9);
3859 clientlist[tempnick]->registered = 0;
3860 clientlist[tempnick]->signon = time(NULL);
3861 clientlist[tempnick]->nping = time(NULL)+240;
3862 clientlist[tempnick]->lastping = 1;
3863 clientlist[tempnick]->port = port;
3867 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3871 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3874 // set the registration timeout for this user
3875 unsigned long class_regtimeout = 90;
3876 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3878 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3880 class_regtimeout = (unsigned long)i->registration_timeout;
3885 int class_flood = 0;
3886 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3888 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
3890 class_flood = i->flood;
3895 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
3896 clientlist[tempnick]->flood = class_flood;
3898 if (clientlist.size() == MAXCLIENTS)
3899 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3902 void handle_names(char **parameters, int pcnt, userrec *user)
3906 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3908 c = FindChan(parameters[0]);
3911 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3913 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3917 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3921 // returns TRUE of any users on channel C occupy server 'servername'.
3923 bool ChanAnyOnThisServer(chanrec *c,char* servername)
3925 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3927 if (has_channel(i->second,c))
3929 if (!strcasecmp(i->second->server,servername))
3938 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3943 user->idle_lastmsg = time(NULL);
3945 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3947 if (parameters[0][0] == '#')
3949 chan = FindChan(parameters[0]);
3952 if ((chan->noexternal) && (!has_channel(user,chan)))
3954 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3957 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3959 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3965 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
3970 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3972 // if any users of this channel are on remote servers, broadcast the packet
3973 char buffer[MAXBUF];
3974 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
3975 for (int j = 0; j < 255; j++)
3977 if (servers[j] != NULL)
3979 if (ChanAnyOnThisServer(chan,servers[j]->name))
3981 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
3988 /* no such nick/channel */
3989 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3994 dest = Find(parameters[0]);
3997 if (strcmp(dest->awaymsg,""))
3999 /* auto respond with aweh msg */
4000 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
4005 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
4012 if (!strcmp(dest->server,user->server))
4014 // direct write, same server
4015 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
4019 for (int j = 0; j < 255; j++)
4021 if (servers[j] != NULL)
4023 if (!strcasecmp(servers[j]->name,dest->server))
4025 // direct write, same server
4026 char buffer[MAXBUF];
4027 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
4028 me[defaultRoute]->SendPacket(buffer,servers[j]->internal_addr,servers[j]->internal_port,MyKey);
4036 /* no such nick/channel */
4037 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4041 void handle_notice(char **parameters, int pcnt, userrec *user)
4046 user->idle_lastmsg = time(NULL);
4048 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
4050 if (parameters[0][0] == '#')
4052 chan = FindChan(parameters[0]);
4055 if ((chan->noexternal) && (!has_channel(user,chan)))
4057 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4060 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4062 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4068 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4073 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
4077 /* no such nick/channel */
4078 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4083 dest = Find(parameters[0]);
4088 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
4093 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
4097 /* no such nick/channel */
4098 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4104 char* chlist(userrec *user)
4109 log(DEBUG,"chlist: %s",user->nick);
4115 for (i = 0; i != MAXCHANS; i++)
4117 if (user->chans[i].channel != NULL)
4119 if (user->chans[i].channel->name)
4121 strcpy(cmp,user->chans[i].channel->name);
4123 if (!strstr(lst,cmp))
4125 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
4127 strcat(lst,cmode(user,user->chans[i].channel));
4128 strcat(lst,user->chans[i].channel->name);
4137 lst[strlen(lst)-1] = '\0'; // chop trailing space
4142 void handle_info(char **parameters, int pcnt, userrec *user)
4144 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
4145 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
4146 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
4147 FOREACH_MOD OnInfo(user);
4148 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
4151 void handle_time(char **parameters, int pcnt, userrec *user)
4154 struct tm * timeinfo;
4157 timeinfo = localtime ( &rawtime );
4158 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
4162 void handle_whois(char **parameters, int pcnt, userrec *user)
4167 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
4169 dest = Find(parameters[0]);
4172 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
4173 if (dest->registered == 7)
4175 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
4176 if ((user == dest) || (strchr(user->modes,'o')))
4178 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
4180 if (strcmp(chlist(dest),""))
4182 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
4184 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
4185 if (strcmp(dest->awaymsg,""))
4187 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
4189 if (strchr(dest->modes,'o'))
4191 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
4193 FOREACH_MOD OnWhois(user,dest);
4194 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
4195 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
4197 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
4201 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4206 /* no such nick/channel */
4207 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4211 void handle_quit(char **parameters, int pcnt, userrec *user)
4213 user_hash::iterator iter = clientlist.find(user->nick);
4216 if (user->registered == 7)
4218 /* theres more to do here, but for now just close the socket */
4221 if (parameters[0][0] == ':')
4225 reason = parameters[0];
4227 if (strlen(reason)>MAXQUIT)
4229 reason[MAXQUIT-1] = '\0';
4232 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
4233 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
4234 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
4238 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
4239 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
4240 WriteCommonExcept(user,"QUIT :Client exited");
4242 FOREACH_MOD OnUserQuit(user);
4246 /* push the socket on a stack of sockets due to be closed at the next opportunity */
4247 fd_reap.push_back(user->fd);
4249 if (iter != clientlist.end())
4251 log(DEBUG,"deleting user hash value %d",iter->second);
4252 if ((iter->second) && (user->registered == 7)) {
4253 delete iter->second;
4255 clientlist.erase(iter);
4258 if (user->registered == 7) {
4259 purge_empty_chans();
4265 void handle_who(char **parameters, int pcnt, userrec *user)
4267 chanrec* Ptr = NULL;
4269 /* theres more to do here, but for now just close the socket */
4272 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
4274 if (user->chans[0].channel)
4276 Ptr = user->chans[0].channel;
4277 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4279 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4281 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4287 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4291 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
4295 if (parameters[0][0] == '#')
4297 Ptr = FindChan(parameters[0]);
4300 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4302 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
4304 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4307 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4311 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4316 userrec* u = Find(parameters[0]);
4317 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, u->nick, u->ident, u->dhost, u->server, u->nick, u->fullname);
4322 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4324 Ptr = user->chans[0].channel;
4325 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4327 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4329 if (strchr(i->second->modes,'o'))
4331 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4335 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4341 void handle_wallops(char **parameters, int pcnt, userrec *user)
4343 WriteWallOps(user,"%s",parameters[0]);
4346 void handle_list(char **parameters, int pcnt, userrec *user)
4350 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4351 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4353 if ((!i->second->c_private) && (!i->second->secret))
4355 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4358 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4362 void handle_rehash(char **parameters, int pcnt, userrec *user)
4364 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4366 FOREACH_MOD OnRehash();
4367 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4373 return clientlist.size();
4377 int usercount_invisible(void)
4381 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4383 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4388 int usercount_opers(void)
4392 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4394 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4399 int usercount_unknown(void)
4403 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4405 if ((i->second->fd) && (i->second->registered != 7))
4413 return chanlist.size();
4416 int servercount(void)
4421 void handle_lusers(char **parameters, int pcnt, userrec *user)
4423 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4424 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4425 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4426 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4427 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
4430 void handle_admin(char **parameters, int pcnt, userrec *user)
4432 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4433 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
4434 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4435 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
4438 void ShowMOTD(userrec *user)
4442 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4445 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4446 for (int i = 0; i != MOTD.size(); i++)
4448 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4450 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4453 void ShowRULES(userrec *user)
4457 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4460 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4461 for (int i = 0; i != RULES.size(); i++)
4463 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4465 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4468 /* shows the message of the day, and any other on-logon stuff */
4469 void ConnectUser(userrec *user)
4471 user->registered = 7;
4472 user->idle_lastmsg = time(NULL);
4473 log(DEBUG,"ConnectUser: %s",user->nick);
4475 if (strcmp(Passwd(user),"") && (!user->haspassed))
4477 kill_link(user,"Invalid password");
4482 kill_link(user,"Unauthorised connection");
4486 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4487 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4488 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4489 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4490 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4491 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);
4492 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);
4494 FOREACH_MOD OnUserConnect(user);
4495 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
4498 void handle_version(char **parameters, int pcnt, userrec *user)
4500 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Revision$ $Date$",ServerName,SYSTEM);
4503 void handle_ping(char **parameters, int pcnt, userrec *user)
4505 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4508 void handle_pong(char **parameters, int pcnt, userrec *user)
4510 // set the user as alive so they survive to next ping
4514 void handle_motd(char **parameters, int pcnt, userrec *user)
4519 void handle_rules(char **parameters, int pcnt, userrec *user)
4524 void handle_user(char **parameters, int pcnt, userrec *user)
4526 if (user->registered < 3)
4528 if (isident(parameters[0]) == 0) {
4529 // This kinda Sucks, According to the RFC thou, its either this,
4530 // or "You have already registered" :p -- Craig
4531 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4534 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4535 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4536 strncat(user->ident,parameters[0],IDENTMAX);
4537 strncpy(user->fullname,parameters[3],128);
4538 user->registered = (user->registered | 1);
4543 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4546 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4547 if (user->registered == 3)
4549 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4554 void handle_userhost(char **parameters, int pcnt, userrec *user)
4556 char Return[MAXBUF],junk[MAXBUF];
4557 sprintf(Return,"302 %s :",user->nick);
4558 for (int i = 0; i < pcnt; i++)
4560 userrec *u = Find(parameters[i]);
4563 if (strchr(u->modes,'o'))
4565 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4566 strcat(Return,junk);
4570 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4571 strcat(Return,junk);
4575 WriteServ(user->fd,Return);
4579 void handle_ison(char **parameters, int pcnt, userrec *user)
4581 char Return[MAXBUF];
4582 sprintf(Return,"303 %s :",user->nick);
4583 for (int i = 0; i < pcnt; i++)
4585 userrec *u = Find(parameters[i]);
4588 strcat(Return,u->nick);
4592 WriteServ(user->fd,Return);
4596 void handle_away(char **parameters, int pcnt, userrec *user)
4600 strcpy(user->awaymsg,parameters[0]);
4601 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4605 strcpy(user->awaymsg,"");
4606 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4610 void handle_whowas(char **parameters, int pcnt, userrec* user)
4612 user_hash::iterator i = whowas.find(parameters[0]);
4614 if (i == whowas.end())
4616 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4617 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4621 time_t rawtime = i->second->signon;
4625 timeinfo = localtime(&rawtime);
4626 strcpy(b,asctime(timeinfo));
4627 b[strlen(b)-1] = '\0';
4629 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4630 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4631 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4636 void handle_trace(char **parameters, int pcnt, userrec *user)
4638 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4642 if (isnick(i->second->nick))
4644 if (strchr(i->second->modes,'o'))
4646 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4650 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4655 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4661 void handle_modules(char **parameters, int pcnt, userrec *user)
4663 for (int i = 0; i < module_names.size(); i++)
4665 Version V = modules[i]->GetVersion();
4666 char modulename[MAXBUF];
4667 strncpy(modulename,module_names[i].c_str(),256);
4668 WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,CleanFilename(modulename));
4672 void handle_stats(char **parameters, int pcnt, userrec *user)
4678 if (strlen(parameters[0])>1)
4680 /* make the stats query 1 character long */
4681 parameters[0][1] = '\0';
4684 /* stats m (list number of times each command has been used, plus bytecount) */
4685 if (!strcasecmp(parameters[0],"m"))
4687 for (int i = 0; i < cmdlist.size(); i++)
4689 if (cmdlist[i].handler_function)
4691 if (cmdlist[i].use_count)
4693 /* RPL_STATSCOMMANDS */
4694 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4701 /* stats z (debug and memory info) */
4702 if (!strcasecmp(parameters[0],"z"))
4704 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4705 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4706 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4707 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4708 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4709 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4710 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4711 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4715 if (!strcasecmp(parameters[0],"o"))
4717 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
4719 char LoginName[MAXBUF];
4720 char HostName[MAXBUF];
4721 char OperType[MAXBUF];
4722 ConfValue("oper","name",i,LoginName,&config_f);
4723 ConfValue("oper","host",i,HostName,&config_f);
4724 ConfValue("oper","type",i,OperType,&config_f);
4725 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4729 /* stats l (show user I/O stats) */
4730 if (!strcasecmp(parameters[0],"l"))
4732 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4733 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4735 if (isnick(i->second->nick))
4737 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);
4741 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);
4747 /* stats u (show server uptime) */
4748 if (!strcasecmp(parameters[0],"u"))
4750 time_t current_time = 0;
4751 current_time = time(NULL);
4752 time_t server_uptime = current_time - startup_time;
4754 stime = gmtime(&server_uptime);
4755 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4756 * Craig suggested this, and it seemed a good idea so in it went */
4757 if (stime->tm_year > 70)
4759 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);
4763 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);
4767 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4768 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4772 void handle_connect(char **parameters, int pcnt, userrec *user)
4774 char Link_ServerName[1024];
4775 char Link_IPAddr[1024];
4776 char Link_Port[1024];
4777 char Link_Pass[1024];
4781 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4783 ConfValue("link","name",i,Link_ServerName,&config_f);
4784 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4785 ConfValue("link","port",i,Link_Port,&config_f);
4786 ConfValue("link","sendpass",i,Link_Pass,&config_f);
4787 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4788 LinkPort = atoi(Link_Port);
4789 if (match(Link_ServerName,parameters[0])) {
4795 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4799 // TODO: Perform a check here to stop a server being linked twice!
4801 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4803 if (me[defaultRoute])
4806 // at this point parameters[0] is an ip in a string.
4807 // TODO: Look this up from the <link> blocks instead!
4808 for (int j = 0; j < 255; j++) {
4809 if (servers[j] == NULL) {
4810 servers[j] = new serverrec;
4811 strcpy(servers[j]->internal_addr,Link_IPAddr);
4812 servers[j]->internal_port = LinkPort;
4813 strcpy(servers[j]->name,Link_ServerName);
4814 log(DEBUG,"Allocated new serverrec");
4815 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4817 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4822 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4826 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);
4830 void handle_squit(char **parameters, int pcnt, userrec *user)
4832 // send out an squit across the mesh and then clear the server list (for local squit)
4835 char islast(serverrec* s)
4838 for (int j = 0; j < 255; j++)
4840 if (servers[j] != NULL)
4844 if (servers[j] == s)
4852 void handle_links(char **parameters, int pcnt, userrec *user)
4854 WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
4855 for (int j = 0; j < 255; j++)
4857 if (servers[j] != NULL)
4859 WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,servers[j]->name,ServerName,servers[j]->description);
4862 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
4865 void handle_map(char **parameters, int pcnt, userrec *user)
4867 WriteServ(user->fd,"006 %s :%s",user->nick,ServerName);
4868 for (int j = 0; j < 255; j++)
4870 if (servers[j] != NULL)
4872 WriteServ(user->fd,"006 %s :%c-%s",user->nick,islast(servers[j]),servers[j]->name);
4875 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
4879 void handle_oper(char **parameters, int pcnt, userrec *user)
4881 char LoginName[MAXBUF];
4882 char Password[MAXBUF];
4883 char OperType[MAXBUF];
4884 char TypeName[MAXBUF];
4885 char Hostname[MAXBUF];
4888 for (i = 0; i < ConfValueEnum("oper",&config_f); i++)
4890 ConfValue("oper","name",i,LoginName,&config_f);
4891 ConfValue("oper","password",i,Password,&config_f);
4892 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4894 /* correct oper credentials */
4895 ConfValue("oper","type",i,OperType,&config_f);
4896 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4897 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4898 WriteServ(user->fd,"MODE %s :+o",user->nick);
4899 for (j =0; j < ConfValueEnum("type",&config_f); j++)
4901 ConfValue("type","name",j,TypeName,&config_f);
4902 if (!strcmp(TypeName,OperType))
4904 /* found this oper's opertype */
4905 ConfValue("type","host",j,Hostname,&config_f);
4906 strncpy(user->dhost,Hostname,256);
4909 if (!strchr(user->modes,'o'))
4911 strcat(user->modes,"o");
4913 FOREACH_MOD OnOper(user);
4918 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4919 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4922 void handle_nick(char **parameters, int pcnt, userrec *user)
4926 log(DEBUG,"not enough params for handle_nick");
4931 log(DEBUG,"invalid parameter passed to handle_nick");
4934 if (!strlen(parameters[0]))
4936 log(DEBUG,"zero length new nick passed to handle_nick");
4941 log(DEBUG,"invalid user passed to handle_nick");
4946 log(DEBUG,"invalid old nick passed to handle_nick");
4949 if (!strcasecmp(user->nick,parameters[0]))
4951 log(DEBUG,"old nick is new nick, skipping");
4956 if (strlen(parameters[0]) > 1)
4958 if (parameters[0][0] == ':')
4963 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4965 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4969 if (isnick(parameters[0]) == 0)
4971 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4975 if (user->registered == 7)
4977 WriteCommon(user,"NICK %s",parameters[0]);
4980 /* change the nick of the user in the users_hash */
4981 user = ReHashNick(user->nick, parameters[0]);
4982 /* actually change the nick within the record */
4984 if (!user->nick) return;
4986 strncpy(user->nick, parameters[0],NICKMAX);
4988 log(DEBUG,"new nick set: %s",user->nick);
4990 if (user->registered < 3)
4991 user->registered = (user->registered | 2);
4992 if (user->registered == 3)
4994 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4997 log(DEBUG,"exit nickchange: %s",user->nick);
5000 void force_nickchange(userrec* user,const char* newnick)
5009 strncpy(nick,newnick,MAXBUF);
5011 if (user->registered == 7)
5015 handle_nick(pars,1,user);
5021 int process_parameters(char **command_p,char *parameters)
5026 q = strlen(parameters);
5029 /* no parameters, command_p invalid! */
5032 if (parameters[0] == ':')
5034 command_p[0] = parameters+1;
5039 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
5041 /* only one parameter */
5042 command_p[0] = parameters;
5043 if (parameters[0] == ':')
5045 if (strchr(parameters,' ') != NULL)
5053 command_p[j++] = parameters;
5054 for (i = 0; i <= q; i++)
5056 if (parameters[i] == ' ')
5058 command_p[j++] = parameters+i+1;
5059 parameters[i] = '\0';
5060 if (command_p[j-1][0] == ':')
5062 *command_p[j-1]++; /* remove dodgy ":" */
5064 /* parameter like this marks end of the sequence */
5068 return j; /* returns total number of items in the list */
5071 void process_command(userrec *user, char* cmd)
5075 char *command_p[127];
5076 char p[MAXBUF], temp[MAXBUF];
5077 int i, j, items, cmd_found;
5079 for (int i = 0; i < 127; i++)
5080 command_p[i] = NULL;
5090 if (!strcmp(cmd,""))
5095 int total_params = 0;
5098 for (int q = 0; q < strlen(cmd)-1; q++)
5100 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
5103 // found a 'trailing', we dont count them after this.
5111 // another phidjit bug...
5112 if (total_params > 126)
5114 kill_link(user,"Protocol violation (1)");
5121 FOREACH_MOD OnServerRaw(tmp,true);
5122 const char* cmd2 = tmp.c_str();
5123 snprintf(cmd,512,"%s",cmd2);
5125 if (!strchr(cmd,' '))
5127 /* no parameters, lets skip the formalities and not chop up
5129 log(DEBUG,"About to preprocess command with no params");
5131 command_p[0] = NULL;
5133 for (int i = 0; i <= strlen(cmd); i++)
5135 cmd[i] = toupper(cmd[i]);
5137 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
5144 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
5145 for (i = 0; i < strlen(temp); i++)
5147 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
5153 /* split the full string into a command plus parameters */
5157 if (strchr(cmd,' '))
5159 for (i = 0; i <= strlen(cmd); i++)
5161 /* capitalise the command ONLY, leave params intact */
5162 cmd[i] = toupper(cmd[i]);
5163 /* are we nearly there yet?! :P */
5167 parameters = cmd+i+1;
5175 for (i = 0; i <= strlen(cmd); i++)
5177 cmd[i] = toupper(cmd[i]);
5184 if (strlen(command)>MAXCOMMAND)
5186 kill_link(user,"Protocol violation (2)");
5190 for (int x = 0; x < strlen(command); x++)
5192 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
5194 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
5196 if (strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
5198 kill_link(user,"Protocol violation (3)");
5205 for (i = 0; i != cmdlist.size(); i++)
5207 if (strcmp(cmdlist[i].command,""))
5209 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
5211 log(DEBUG,"Found matching command");
5215 if (strcmp(parameters,""))
5217 items = process_parameters(command_p,parameters);
5222 command_p[0] = NULL;
5228 command_p[0] = NULL;
5233 log(DEBUG,"Processing command");
5235 /* activity resets the ping pending timer */
5236 user->nping = time(NULL) + 120;
5237 if ((items) < cmdlist[i].min_params)
5239 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
5240 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
5243 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
5245 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
5246 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
5250 /* if the command isnt USER, PASS, or NICK, and nick is empty,
5252 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
5254 if ((!isnick(user->nick)) || (user->registered != 7))
5256 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5257 WriteServ(user->fd,"451 %s :You have not registered",command);
5261 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
5263 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
5264 if (cmdlist[i].handler_function)
5266 /* ikky /stats counters */
5271 user->bytes_in += strlen(temp);
5274 cmdlist[i].use_count++;
5275 cmdlist[i].total_bytes+=strlen(temp);
5278 /* WARNING: nothing may come after the
5279 * command handler call, as the handler
5280 * may free the user structure! */
5282 cmdlist[i].handler_function(command_p,items,user);
5288 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5289 WriteServ(user->fd,"451 %s :You have not registered",command);
5297 if ((!cmd_found) && (user))
5299 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
5300 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
5305 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
5308 /* create the command and push it onto the table */
5309 strcpy(comm.command,cmd);
5310 comm.handler_function = f;
5311 comm.flags_needed = flags;
5312 comm.min_params = minparams;
5314 comm.total_bytes = 0;
5315 cmdlist.push_back(comm);
5316 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
5319 void SetupCommandTable(void)
5321 createcommand("USER",handle_user,0,4);
5322 createcommand("NICK",handle_nick,0,1);
5323 createcommand("QUIT",handle_quit,0,0);
5324 createcommand("VERSION",handle_version,0,0);
5325 createcommand("PING",handle_ping,0,1);
5326 createcommand("PONG",handle_pong,0,1);
5327 createcommand("ADMIN",handle_admin,0,0);
5328 createcommand("PRIVMSG",handle_privmsg,0,2);
5329 createcommand("INFO",handle_info,0,0);
5330 createcommand("TIME",handle_time,0,0);
5331 createcommand("WHOIS",handle_whois,0,1);
5332 createcommand("WALLOPS",handle_wallops,'o',1);
5333 createcommand("NOTICE",handle_notice,0,2);
5334 createcommand("JOIN",handle_join,0,1);
5335 createcommand("NAMES",handle_names,0,1);
5336 createcommand("PART",handle_part,0,1);
5337 createcommand("KICK",handle_kick,0,2);
5338 createcommand("MODE",handle_mode,0,1);
5339 createcommand("TOPIC",handle_topic,0,1);
5340 createcommand("WHO",handle_who,0,1);
5341 createcommand("MOTD",handle_motd,0,0);
5342 createcommand("RULES",handle_rules,0,0);
5343 createcommand("OPER",handle_oper,0,2);
5344 createcommand("LIST",handle_list,0,0);
5345 createcommand("DIE",handle_die,'o',1);
5346 createcommand("RESTART",handle_restart,'o',1);
5347 createcommand("KILL",handle_kill,'o',2);
5348 createcommand("REHASH",handle_rehash,'o',0);
5349 createcommand("LUSERS",handle_lusers,0,0);
5350 createcommand("STATS",handle_stats,0,1);
5351 createcommand("USERHOST",handle_userhost,0,1);
5352 createcommand("AWAY",handle_away,0,0);
5353 createcommand("ISON",handle_ison,0,0);
5354 createcommand("SUMMON",handle_summon,0,0);
5355 createcommand("USERS",handle_users,0,0);
5356 createcommand("INVITE",handle_invite,0,2);
5357 createcommand("PASS",handle_pass,0,1);
5358 createcommand("TRACE",handle_trace,'o',0);
5359 createcommand("WHOWAS",handle_whowas,0,1);
5360 createcommand("CONNECT",handle_connect,'o',1);
5361 createcommand("SQUIT",handle_squit,'o',1);
5362 createcommand("MODULES",handle_modules,'o',0);
5363 createcommand("LINKS",handle_links,0,0);
5364 createcommand("MAP",handle_map,0,0);
5367 void process_buffer(const char* cmdbuf,userrec *user)
5371 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5378 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5381 if (!strcmp(cmdbuf,""))
5385 strncpy(cmd,cmdbuf,MAXBUF);
5386 if (!strcmp(cmd,""))
5390 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5392 cmd[strlen(cmd)-1] = '\0';
5394 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5396 cmd[strlen(cmd)-1] = '\0';
5398 if (!strcmp(cmd,""))
5402 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5404 if ((user) && (cmd))
5406 process_command(user,cmd);
5410 void DoSync(serverrec* serv, char* udp_host,int udp_port, long MyKey)
5413 // send start of sync marker: Y <timestamp>
5414 snprintf(data,MAXBUF,"Y %d",time(NULL));
5415 serv->SendPacket(data,udp_host,udp_port,MyKey);
5416 // send users and channels
5417 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
5419 snprintf(data,MAXBUF,"N %d %s %s %s %s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->server,u->second->fullname);
5420 serv->SendPacket(data,udp_host,udp_port,MyKey);
5421 if (strcmp(chlist(u->second),""))
5423 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
5424 serv->SendPacket(data,udp_host,udp_port,MyKey);
5427 // send channel modes, topics etc...
5428 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
5430 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
5431 serv->SendPacket(data,udp_host,udp_port,MyKey);
5432 if (strcmp(c->second->topic,""))
5434 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
5435 serv->SendPacket(data,udp_host,udp_port,MyKey);
5437 // send current banlist
5439 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
5441 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
5442 serv->SendPacket(data,udp_host,udp_port,MyKey);
5445 // send end of sync marker: E <timestamp>
5446 snprintf(data,MAXBUF,"F %d",time(NULL));
5447 serv->SendPacket(data,udp_host,udp_port,MyKey);
5450 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5452 char* src = strtok(NULL," ");
5453 char* dest = strtok(NULL," :");
5454 char* text = strtok(NULL,"\r\n");
5457 userrec* user = Find(src);
5460 userrec* dst = Find(dest);
5464 WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
5468 chanrec* d = FindChan(dest);
5471 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
5479 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5481 char* tm = strtok(params," ");
5482 char* setby = strtok(NULL," ");
5483 char* channel = strtok(NULL," :");
5484 char* topic = strtok(NULL,"\r\n");
5486 time_t TS = atoi(tm);
5487 chanrec* c = FindChan(channel);
5490 // in the case of topics and TS, the *NEWER*
5491 if (TS <= c->topicset)
5493 WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
5494 strncpy(c->topic,topic,MAXTOPIC);
5495 strncpy(c->setby,setby,NICKMAX);
5500 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5503 char original[MAXBUF],target[MAXBUF];
5504 strncpy(original,params,MAXBUF);
5506 char* parameter = strtok(params," ");
5507 strncpy(target,parameter,MAXBUF);
5510 pars[index++] = parameter;
5511 parameter = strtok(NULL," ");
5513 merge_mode(pars,--index);
5514 if (FindChan(target))
5516 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
5520 WriteTo(NULL,Find(target),"MODE %s",original);
5524 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5526 char* tm = strtok(params," ");
5527 char* nick = strtok(NULL," ");
5528 char* host = strtok(NULL," ");
5529 char* dhost = strtok(NULL," ");
5530 char* ident = strtok(NULL," ");
5531 char* modes = strtok(NULL," ");
5532 char* server = strtok(NULL," :");
5533 char* gecos = strtok(NULL,"\r\n");
5535 time_t TS = atoi(tm);
5536 user_hash::iterator iter = clientlist.find(nick);
5537 if (iter != clientlist.end())
5540 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
5541 if (TS >= iter->second->age)
5544 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
5545 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
5546 // client on remote server is older than the local user, kill the local user
5547 kill_link(iter->second,str);
5550 clientlist[nick] = new userrec();
5551 // remote users have an fd of -1. This is so that our Write abstraction
5552 // routines know to route any messages to this record away to whatever server
5554 clientlist[nick]->fd = -1;
5555 strncpy(clientlist[nick]->nick, nick,NICKMAX);
5556 strncpy(clientlist[nick]->host, host,160);
5557 strncpy(clientlist[nick]->dhost, dhost,160);
5558 strncpy(clientlist[nick]->server, server,256);
5559 strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for '~'
5560 strncpy(clientlist[nick]->fullname, gecos,128);
5561 clientlist[nick]->signon = TS;
5562 clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
5563 clientlist[nick]->lastping = 1;
5564 clientlist[nick]->port = 0; // so is this...
5565 clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
5566 clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
5569 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5571 long tdiff = time(NULL) - atoi(params);
5573 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
5576 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5579 // The J token currently has no timestamp - this needs looking at
5580 // because it will allow splitriding.
5581 char* nick = strtok(params," ");
5582 char* channel = strtok(NULL," ");
5583 userrec* user = Find(nick);
5586 if ((user != NULL) && (strcmp(channel,"")))
5588 char privilage = '\0';
5589 if (channel[0] != '#')
5591 privilage = channel[0];
5594 add_channel(user,channel,"",true);
5596 // now work out the privilages they should have on each channel
5597 // and send the appropriate servermodes.
5598 for (int i = 0; i != MAXCHANS; i++)
5600 if (user->chans[i].channel)
5602 if (!strcasecmp(user->chans[i].channel->name,channel))
5604 if (privilage == '@')
5606 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
5607 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
5609 if (privilage == '%')
5611 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
5612 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
5614 if (privilage == '+')
5616 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
5617 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
5624 channel = strtok(NULL," ");
5628 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
5635 nb_start = time(NULL);
5636 WriteOpers("Server %s is starting netburst.",source->name);
5638 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
5639 // introduce remote client
5641 handle_N(token,params,source,reply,udp_host,udp_port);
5643 // J <NICK> <CHANLIST>
5644 // Join user to channel list, merge channel permissions
5646 handle_J(token,params,source,reply,udp_host,udp_port);
5648 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
5649 // change channel topic (netburst only)
5651 handle_T(token,params,source,reply,udp_host,udp_port);
5653 // M <TS> <TARGET> <MODES> [MODE-PARAMETERS]
5654 // Set modes on an object
5656 handle_M(token,params,source,reply,udp_host,udp_port);
5658 // P <SOURCE> <TARGET> :<TEXT>
5659 // Send a private/channel message
5661 handle_P(token,params,source,reply,udp_host,udp_port);
5666 WriteOpers("Server %s has completed netburst. (%d secs)",source->name,time(NULL)-nb_start);
5667 handle_F(token,params,source,reply,udp_host,udp_port);
5671 WriteOpers("WARNING! Unknown datagram type '%c'",token);
5677 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
5679 char response[10240];
5680 char token = udp_msg[0];
5681 char* params = udp_msg + 2;
5682 char finalparam[1024];
5683 strcpy(finalparam," :xxxx");
5684 if (strstr(params," :")) {
5685 strncpy(finalparam,strstr(params," :"),1024);
5688 // S test.chatspike.net password :ChatSpike InspIRCd test server
5689 char* servername = strtok(params," ");
5690 char* password = strtok(NULL," ");
5691 char* serverdesc = finalparam+2;
5692 WriteOpers("CONNECT from %s (%s)",servername,udp_host);
5695 char Link_ServerName[1024];
5696 char Link_IPAddr[1024];
5697 char Link_Port[1024];
5698 char Link_Pass[1024];
5699 char Link_SendPass[1024];
5702 // search for a corresponding <link> block in the config files
5703 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5705 ConfValue("link","name",i,Link_ServerName,&config_f);
5706 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5707 ConfValue("link","port",i,Link_Port,&config_f);
5708 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5709 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5710 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5711 LinkPort = atoi(Link_Port);
5712 if (!strcasecmp(Link_ServerName,servername)) {
5713 if (!strcasecmp(Link_IPAddr,udp_host)) {
5714 if (LinkPort == udp_port) {
5715 // we have a matching link line -
5716 // send a 'diminutive' server message back...
5717 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
5718 serv->SendPacket(response,udp_host,udp_port,0);
5719 WriteOpers("CONNECT from %s accepted, authenticating",servername);
5720 for (int j = 0; j < 255; j++) {
5721 if (servers[j] == NULL) {
5722 servers[j] = new serverrec;
5723 strcpy(servers[j]->internal_addr,udp_host);
5724 strcpy(servers[j]->name,servername);
5725 strcpy(servers[j]->description,serverdesc);
5726 servers[j]->internal_port = udp_port;
5727 // create a server record for this server
5728 snprintf(response,10240,"O %d",MyKey);
5729 serv->SendPacket(response,udp_host,udp_port,0);
5733 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
5737 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5741 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5745 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5748 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5749 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5754 // if this is received, this means the server-ip that sent it said "OK" to credentials.
5755 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
5756 // array, which is only added by an 'S' packet or BeginLink().
5757 for (int i = 0; i < 255; i++) {
5758 if (servers[i] != NULL) {
5759 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
5760 servers[i]->key = atoi(params);
5761 log(DEBUG,"Key for this server is now %d",servers[i]->key);
5762 DoSync(serv,udp_host,udp_port,MyKey);
5767 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
5771 // S test.chatspike.net password :ChatSpike InspIRCd test server
5772 char* servername = strtok(params," ");
5773 char* password = strtok(NULL," ");
5774 char* serverdesc = finalparam+2;
5776 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5777 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5778 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5779 // a connect, so put out an oper alert!
5784 // for now, just accept all, we'll fix that later.
5785 WriteOpers("%s accepted our link credentials ",servername);
5787 char Link_ServerName[1024];
5788 char Link_IPAddr[1024];
5789 char Link_Port[1024];
5790 char Link_Pass[1024];
5791 char Link_SendPass[1024];
5794 // search for a corresponding <link> block in the config files
5795 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5797 ConfValue("link","name",i,Link_ServerName,&config_f);
5798 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5799 ConfValue("link","port",i,Link_Port,&config_f);
5800 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5801 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5802 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5803 LinkPort = atoi(Link_Port);
5804 if (!strcasecmp(Link_ServerName,servername)) {
5805 if (!strcasecmp(Link_IPAddr,udp_host)) {
5806 if (LinkPort == udp_port) {
5807 // matching link at this end too, we're all done!
5808 // at this point we must begin key exchange and insert this
5809 // server into our 'active' table.
5810 for (int j = 0; j < 255; j++) {
5811 if (servers[j] != NULL) {
5812 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5813 strcpy(servers[j]->description,serverdesc);
5814 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
5815 snprintf(response,10240,"O %d",MyKey);
5816 serv->SendPacket(response,udp_host,udp_port,0);
5821 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5826 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
5830 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
5834 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5837 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
5838 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5843 char* error_message = finalparam+2;
5844 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5845 // remove this server from any lists
5846 for (int j = 0; j < 255; j++) {
5847 if (servers[j] != NULL) {
5848 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5858 serverrec* source_server = NULL;
5860 for (int j = 0; j < 255; j++) {
5861 if (servers[j] != NULL) {
5862 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
5863 if (servers[j]->key == theirkey) {
5864 // found a valid key for this server, can process restricted stuff here
5865 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
5872 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
5876 int reap_counter = 0;
5880 struct sockaddr_in client, server;
5881 char addrs[MAXBUF][255];
5882 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5884 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5885 int selectResult = 0, selectResult2 = 0;
5886 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5887 char resolvedHost[MAXBUF];
5891 log_file = fopen("ircd.log","a+");
5894 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5898 log(DEBUG,"InspIRCd: startup: begin");
5902 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5904 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5906 SetupCommandTable();
5907 log(DEBUG,"InspIRCd: startup: default command table set up");
5910 if (strcmp(DieValue,""))
5912 printf("WARNING: %s\n\n",DieValue);
5915 log(DEBUG,"InspIRCd: startup: read config");
5917 int count2 = 0, count3 = 0;
5919 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5921 ConfValue("bind","port",count,configToken,&config_f);
5922 ConfValue("bind","address",count,Addr,&config_f);
5923 ConfValue("bind","type",count,Type,&config_f);
5924 if (!strcmp(Type,"servers"))
5926 char Default[MAXBUF];
5927 strcpy(Default,"no");
5928 ConfValue("bind","default",count,Default,&config_f);
5929 if (strchr(Default,'y'))
5931 defaultRoute = count3;
5932 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5934 me[count3] = new serverrec(ServerName,100L,false);
5935 me[count3]->CreateListener(Addr,atoi(configToken));
5940 ports[count2] = atoi(configToken);
5941 strcpy(addrs[count2],Addr);
5944 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5947 UDPportCount = count3;
5949 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5951 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5955 /* BugFix By Craig! :p */
5957 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5959 char modfile[MAXBUF];
5960 ConfValue("module","name",count2,configToken,&config_f);
5961 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5962 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5963 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5964 /* If The File Doesnt exist, Trying to load it
5965 * Will Segfault the IRCd.. So, check to see if
5966 * it Exists, Before Proceeding. */
5967 if (FileExists(modfile))
5969 factory[count] = new ircd_module(modfile);
5970 if (factory[count]->LastError())
5972 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5973 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5976 if (factory[count]->factory)
5978 modules[count] = factory[count]->factory->CreateModule();
5979 /* save the module and the module's classfactory, if
5980 * this isnt done, random crashes can occur :/ */
5981 module_names.push_back(modfile);
5985 log(DEBUG,"Unable to load %s",modfile);
5986 sprintf("Unable to load %s\nExiting...\n",modfile);
5989 /* Increase the Count */
5994 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5995 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5998 MODCOUNT = count - 1;
5999 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
6001 printf("\nInspIRCd is now running!\n");
6003 startup_time = time(NULL);
6007 log(VERBOSE,"Not forking as -nofork was specified");
6011 if (DaemonSeed() == ERROR)
6013 log(DEBUG,"InspIRCd: startup: can't daemonise");
6014 printf("ERROR: could not go into daemon mode. Shutting down.\n");
6020 /* setup select call */
6021 FD_ZERO(&selectFds);
6022 log(DEBUG,"InspIRCd: startup: zero selects");
6023 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
6025 for (count = 0; count < portCount; count++)
6027 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
6029 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
6032 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
6034 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
6036 else /* well we at least bound to one socket so we'll continue */
6042 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
6044 /* if we didn't bind to anything then abort */
6045 if (boundPortCount == 0)
6047 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
6051 length = sizeof (client);
6052 int flip_flop = 0, udp_port = 0;
6053 char udp_msg[MAXBUF], udp_host[MAXBUF];
6055 /* main loop, this never returns */
6060 struct timeval tval;
6063 user_hash::iterator count2 = clientlist.begin();
6065 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
6066 // them in a list, then reap the list every second or so.
6067 if (reap_counter>5000)
6069 if (fd_reap.size() > 0)
6071 for( int n = 0; n < fd_reap.size(); n++)
6073 Blocking(fd_reap[n]);
6075 NonBlocking(fd_reap[n]);
6083 for (int x = 0; x != UDPportCount; x++)
6086 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
6088 if (strlen(udp_msg)<1) {
6089 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
6093 FOREACH_MOD OnPacketReceive(udp_msg);
6094 // Packets must go back via the route they arrived on :)
6095 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
6096 // link packets can manipulate the usertable so beware of
6097 // any loops here watching the user or channels hash
6098 log(DEBUG,"Sync: exit 3");
6105 while (count2 != clientlist.end())
6108 tval.tv_usec = tval.tv_sec = 0;
6110 int total_in_this_set = 0;
6112 user_hash::iterator xcount = count2;
6113 user_hash::iterator endingiter = count2;
6115 if (!count2->second) break;
6118 if (count2->second->fd != 0)
6120 // assemble up to 64 sockets into an fd_set
6121 // to implement a pooling mechanism.
6123 // This should be up to 64x faster than the
6124 // old implementation.
6125 while (total_in_this_set < 64)
6127 if (count2 != clientlist.end())
6129 // we don't check the state of remote users.
6130 if (count2->second->fd > 0)
6132 FD_SET (count2->second->fd, &sfd);
6134 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
6135 // their connection class.
6136 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
6138 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
6139 kill_link(count2->second,"Registration timeout");
6142 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
6144 if ((!count2->second->lastping) && (count2->second->registered == 7))
6146 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
6147 kill_link(count2->second,"Ping timeout");
6150 Write(count2->second->fd,"PING :%s",ServerName);
6151 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
6152 count2->second->lastping = 0;
6153 count2->second->nping = time(NULL)+120;
6157 total_in_this_set++;
6162 endingiter = count2;
6163 count2 = xcount; // roll back to where we were
6169 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
6171 // now loop through all of the items in this pool if any are waiting
6172 //if (selectResult2 > 0)
6173 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
6176 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
6178 log(DEBUG,"Reading fd %d",count2a->second->fd);
6179 memset(data, 0, 10240);
6180 result = read(count2a->second->fd, data, 10240);
6184 log(DEBUG,"Read %d characters from socket",result);
6185 userrec* current = count2a->second;
6186 int currfd = current->fd;
6187 char* l = strtok(data,"\n");
6192 if ((floodlines > current->flood) && (current->flood != 0))
6194 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
6195 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
6196 kill_link(current,"Excess flood");
6199 char sanitized[NetBufferSize];
6200 memset(sanitized, 0, NetBufferSize);
6202 for (int pt = 0; pt < strlen(l); pt++)
6206 sanitized[ptt++] = l[pt];
6209 sanitized[ptt] = '\0';
6210 if (strlen(sanitized))
6214 // we're gonna re-scan to check if the nick is gone, after every
6215 // command - if it has, we're gonna bail
6216 bool find_again = false;
6217 process_buffer(sanitized,current);
6219 // look for the user's record in case it's changed
6220 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
6222 if (c2->second->fd == currfd)
6224 // found again, update pointer
6225 current == c2->second;
6234 l = strtok(NULL,"\n");
6239 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
6241 log(DEBUG,"killing: %s",count2a->second->nick);
6242 kill_link(count2a->second,strerror(errno));
6246 // result EAGAIN means nothing read
6247 if (result == EAGAIN)
6255 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
6256 kill_link(count2a->second,"Client exited");
6257 // must bail here? kill_link removes the hash, corrupting the iterator
6258 log(DEBUG,"Bailing from client exit");
6262 else if (result > 0)
6267 for (int q = 0; q < total_in_this_set; q++)
6269 // there is no iterator += operator :(
6270 //if (count2 != clientlist.end())
6277 // set up select call
6278 for (count = 0; count < boundPortCount; count++)
6280 FD_SET (openSockfd[count], &selectFds);
6283 /* added timeout! select was waiting forever... wank... :/ */
6295 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
6297 /* select is reporting a waiting socket. Poll them all to find out which */
6298 if (selectResult > 0)
6300 char target[MAXBUF], resolved[MAXBUF];
6301 for (count = 0; count < boundPortCount; count++)
6303 if (FD_ISSET (openSockfd[count], &selectFds))
6305 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
6307 address_cache::iterator iter = IP.find(client.sin_addr);
6308 bool iscached = false;
6309 if (iter == IP.end())
6311 /* ip isn't in cache, add it */
6312 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
6313 if(CleanAndResolve(resolved, target) != TRUE)
6315 strncpy(resolved,target,MAXBUF);
6317 /* hostname now in 'target' */
6318 IP[client.sin_addr] = new string(resolved);
6319 /* hostname in cache */
6323 /* found ip (cached) */
6324 strncpy(resolved, iter->second->c_str(), MAXBUF);
6328 if (incomingSockfd < 0)
6330 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
6331 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
6335 AddClient(incomingSockfd, resolved, ports[count], iscached);
6336 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
6343 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
6346 close (incomingSockfd);