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! ;) */
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
32 #include <ext/hash_map>
41 #include "connection.h"
53 #define nspace __gnu_cxx
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
66 char restartpass[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 time_t startup_time = time(NULL);
78 extern vector<Module*> modules;
79 vector<string> module_names;
80 extern vector<ircd_module*> factory;
89 template<> struct nspace::hash<in_addr>
91 size_t operator()(const struct in_addr &a) const
94 memcpy(&q,&a,sizeof(size_t));
99 template<> struct nspace::hash<string>
101 size_t operator()(const string &s) const
104 static struct hash<const char *> strhash;
116 bool operator()(const string& s1, const string& s2) const
118 char a[MAXBUF],b[MAXBUF];
119 strcpy(a,s1.c_str());
120 strcpy(b,s2.c_str());
121 return (strcasecmp(a,b) == 0);
126 struct InAddr_HashComp
129 bool operator()(const in_addr &s1, const in_addr &s2) const
134 memcpy(&q,&s1,sizeof(size_t));
135 memcpy(&p,&s2,sizeof(size_t));
143 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
144 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
145 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
146 typedef std::deque<command_t> command_table;
149 serverrec* servers[255];
153 user_hash clientlist;
156 command_table cmdlist;
163 struct linger linger = { 0 };
164 char bannerBuffer[MAXBUF];
165 int boundPortCount = 0;
166 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
167 int defaultRoute = 0;
171 long MyKey = C.GenKey();
175 int has_channel(userrec *u, chanrec *c);
176 int usercount(chanrec *c);
177 int usercount_i(chanrec *c);
178 void update_stats_l(int fd,int data_out);
179 char* Passwd(userrec *user);
180 bool IsDenied(userrec *user);
181 void AddWhoWas(userrec* u);
184 void safedelete(userrec *p)
188 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
189 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
194 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
198 void safedelete(chanrec *p)
203 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
207 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
212 void tidystring(char* str)
214 // strips out double spaces before a : parameter
217 bool go_again = true;
224 while ((str[0] == ' ') && (strlen(str)>0))
231 bool noparse = false;
234 while (a < strlen(str))
236 if ((a<strlen(str)-1) && (noparse==false))
238 if ((str[a] == ' ') && (str[a+1] == ' '))
240 log(DEBUG,"Tidied extra space out of string: %s",str);
248 if ((str[a] == ' ') && (str[a+1] == ':'))
254 temp[t++] = str[a++];
257 strncpy(str,temp,MAXBUF);
261 /* chop a string down to 512 characters and preserve linefeed (irc max
268 FOREACH_MOD OnServerRaw(temp,false);
269 const char* str2 = temp.c_str();
270 sprintf(str,"%s",str2);
273 if (strlen(str) >= 512)
282 std::string getservername()
287 std::string getserverdesc()
292 std::string getnetworkname()
297 std::string getadminname()
302 std::string getadminemail()
307 std::string getadminnick()
312 void log(int level,char *text, ...)
314 char textbuffer[MAXBUF];
317 struct tm * timeinfo;
318 if (level < LogLevel)
322 timeinfo = localtime (&rawtime);
327 va_start (argsPtr, text);
328 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
330 strcpy(b,asctime(timeinfo));
331 b[strlen(b)-1] = ':';
332 fprintf(log_file,"%s %s\n",b,textbuffer);
335 // nofork enabled? display it on terminal too
336 printf("%s %s\n",b,textbuffer);
341 void readfile(file_cache &F, const char* fname)
344 char linebuf[MAXBUF];
346 log(DEBUG,"readfile: loading %s",fname);
348 file = fopen(fname,"r");
353 fgets(linebuf,sizeof(linebuf),file);
354 linebuf[strlen(linebuf)-1]='\0';
355 if (!strcmp(linebuf,""))
361 F.push_back(linebuf);
368 log(DEBUG,"readfile: failed to load file: %s",fname);
370 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
373 void ReadConfig(void)
375 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF];
378 ConfValue("server","name",0,ServerName);
379 ConfValue("server","description",0,ServerDesc);
380 ConfValue("server","network",0,Network);
381 ConfValue("admin","name",0,AdminName);
382 ConfValue("admin","email",0,AdminEmail);
383 ConfValue("admin","nick",0,AdminNick);
384 ConfValue("files","motd",0,motd);
385 ConfValue("files","rules",0,rules);
386 ConfValue("power","diepass",0,diepass);
387 ConfValue("power","pause",0,pauseval);
388 ConfValue("power","restartpass",0,restartpass);
389 ConfValue("options","prefixquit",0,PrefixQuit);
390 ConfValue("die","value",0,DieValue);
391 ConfValue("options","loglevel",0,dbg);
392 if (!strcmp(dbg,"debug"))
394 if (!strcmp(dbg,"verbose"))
396 if (!strcmp(dbg,"default"))
398 if (!strcmp(dbg,"sparse"))
400 if (!strcmp(dbg,"none"))
403 log(DEBUG,"Reading message of the day");
404 readfile(RULES,rules);
405 log(DEBUG,"Reading connect classes");
407 for (int i = 0; i < ConfValueEnum("connect"); i++)
410 ConfValue("connect","allow",i,Value);
411 ConfValue("connect","timeout",i,timeout);
412 if (strcmp(Value,""))
414 strcpy(c.host,Value);
417 ConfValue("connect","password",i,Value);
418 strcpy(c.pass,Value);
419 c.registration_timeout = 90; // default is 2 minutes
422 c.registration_timeout = atoi(timeout);
424 Classes.push_back(c);
425 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
429 ConfValue("connect","deny",i,Value);
430 strcpy(c.host,Value);
432 Classes.push_back(c);
433 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
442 log(DEBUG,"Blocking: %d",s);
443 flags = fcntl(s, F_GETFL, 0);
444 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
447 void NonBlocking(int s)
450 log(DEBUG,"NonBlocking: %d",s);
451 flags = fcntl(s, F_GETFL, 0);
452 fcntl(s, F_SETFL, flags | O_NONBLOCK);
456 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
458 struct hostent *hostPtr = NULL;
461 memset (resolvedHost, '\0',MAXBUF);
462 if(unresolvedHost == NULL)
464 if ((inet_aton(unresolvedHost,&addr)) == 0)
466 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
468 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
470 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
474 /* write formatted text to a socket, in same format as printf */
476 void Write(int sock,char *text, ...)
480 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
483 char textbuffer[MAXBUF];
487 va_start (argsPtr, text);
488 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
490 sprintf(tb,"%s\r\n",textbuffer);
492 write(sock,tb,strlen(tb));
493 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
496 /* write a server formatted numeric response to a single socket */
498 void WriteServ(int sock, char* text, ...)
502 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
505 char textbuffer[MAXBUF],tb[MAXBUF];
507 va_start (argsPtr, text);
509 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
511 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
513 write(sock,tb,strlen(tb));
514 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
517 /* write text from an originating user to originating user */
519 void WriteFrom(int sock, userrec *user,char* text, ...)
521 if ((!text) || (!user))
523 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
526 char textbuffer[MAXBUF],tb[MAXBUF];
528 va_start (argsPtr, text);
530 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
532 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
534 write(sock,tb,strlen(tb));
535 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
538 /* write text to an destination user from a source user (e.g. user privmsg) */
540 void WriteTo(userrec *source, userrec *dest,char *data, ...)
542 if ((!source) || (!dest) || (!data))
544 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
547 char textbuffer[MAXBUF],tb[MAXBUF];
549 va_start (argsPtr, data);
550 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
553 WriteFrom(dest->fd,source,"%s",textbuffer);
556 /* write formatted text from a source user to all users on a channel
557 * including the sender (NOT for privmsg, notice etc!) */
559 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
561 if ((!Ptr) || (!user) || (!text))
563 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
566 char textbuffer[MAXBUF];
568 va_start (argsPtr, text);
569 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
571 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
573 if (has_channel(i->second,Ptr))
575 WriteTo(user,i->second,"%s",textbuffer);
580 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
582 if ((!Ptr) || (!user) || (!text))
584 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
587 char textbuffer[MAXBUF];
589 va_start (argsPtr, text);
590 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
592 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
596 if (has_channel(i->second,Ptr))
598 WriteServ(i->second->fd,"%s",textbuffer);
605 /* write formatted text from a source user to all users on a channel except
606 * for the sender (for privmsg etc) */
608 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
610 if ((!Ptr) || (!user) || (!text))
612 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
615 char textbuffer[MAXBUF];
617 va_start (argsPtr, text);
618 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
621 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
625 if (has_channel(i->second,Ptr) && (user != i->second))
627 WriteTo(user,i->second,"%s",textbuffer);
633 int c_count(userrec* u)
636 for (int i =0; i != MAXCHANS; i++)
637 if (u->chans[i].channel != NULL)
643 /* return 0 or 1 depending if users u and u2 share one or more common channels
644 * (used by QUIT, NICK etc which arent channel specific notices) */
646 int common_channels(userrec *u, userrec *u2)
653 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
656 for (i = 0; i != MAXCHANS; i++)
658 for (z = 0; z != MAXCHANS; z++)
660 if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
662 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
664 if ((c_count(u)) && (c_count(u2)))
675 /* write a formatted string to all users who share at least one common
676 * channel, including the source user e.g. for use in NICK */
678 void WriteCommon(userrec *u, char* text, ...)
682 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
686 if (u->registered != 7) {
687 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
691 char textbuffer[MAXBUF];
693 va_start (argsPtr, text);
694 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
697 WriteFrom(u->fd,u,"%s",textbuffer);
699 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
703 if (common_channels(u,i->second) && (i->second != u))
705 WriteFrom(i->second->fd,u,"%s",textbuffer);
711 /* write a formatted string to all users who share at least one common
712 * channel, NOT including the source user e.g. for use in QUIT */
714 void WriteCommonExcept(userrec *u, char* text, ...)
718 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
722 if (u->registered != 7) {
723 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
727 char textbuffer[MAXBUF];
729 va_start (argsPtr, text);
730 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
733 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
737 if ((common_channels(u,i->second)) && (u != i->second))
739 WriteFrom(i->second->fd,u,"%s",textbuffer);
745 void WriteOpers(char* text, ...)
749 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
753 char textbuffer[MAXBUF];
755 va_start (argsPtr, text);
756 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
759 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
763 if (strchr(i->second->modes,'o'))
765 if (strchr(i->second->modes,'s'))
767 // send server notices to all with +s
768 // (TODO: needs SNOMASKs)
769 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
776 void WriteWallOps(userrec *source, char* text, ...)
778 if ((!text) || (!source))
780 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
785 char textbuffer[MAXBUF];
787 va_start (argsPtr, text);
788 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
791 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
795 if (strchr(i->second->modes,'w'))
797 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
803 /* convert a string to lowercase. Note following special circumstances
804 * taken from RFC 1459. Many "official" server branches still hold to this
805 * rule so i will too;
807 * Because of IRC's scandanavian origin, the characters {}| are
808 * considered to be the lower case equivalents of the characters []\,
809 * respectively. This is a critical issue when determining the
810 * equivalence of two nicknames.
813 void strlower(char *n)
819 for (int i = 0; i != strlen(n); i++)
821 n[i] = tolower(n[i]);
831 /* verify that a user's ident and nickname is valid */
833 int isident(const char* n)
846 for (i = 0; i != strlen(n); i++)
848 if ((n[i] < 33) || (n[i] > 125))
852 /* can't occur ANYWHERE in an Ident! */
853 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
862 int isnick(const char* n)
874 if (strlen(n) > NICKMAX-1)
878 for (i = 0; i != strlen(n); i++)
880 if ((n[i] < 33) || (n[i] > 125))
884 /* can't occur ANYWHERE in a nickname! */
885 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
889 /* can't occur as the first char of a nickname... */
890 if ((strchr("0123456789",n[i])) && (!i))
898 /* Find a user record by nickname and return a pointer to it */
900 userrec* Find(string nick)
902 user_hash::iterator iter = clientlist.find(nick);
904 if (iter == clientlist.end())
905 /* Couldn't find it */
911 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
913 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
917 if (i->second->fd == fd)
919 i->second->bytes_out+=data_out;
920 i->second->cmds_out++;
927 /* find a channel record by channel name and return a pointer to it */
929 chanrec* FindChan(const char* chan)
933 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
937 chan_hash::iterator iter = chanlist.find(chan);
939 if (iter == chanlist.end())
940 /* Couldn't find it */
947 void purge_empty_chans(void)
949 int go_again = 1, purge = 0;
954 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
957 if (!usercount(i->second))
959 /* kill the record */
960 if (i != chanlist.end())
962 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
972 log(DEBUG,"skipped purge for %s",i->second->name);
977 log(DEBUG,"completed channel purge, killed %d",purge);
980 /* returns the status character for a given user on a channel, e.g. @ for op,
981 * % for halfop etc. If the user has several modes set, the highest mode
982 * the user has must be returned. */
984 char* cmode(userrec *user, chanrec *chan)
986 if ((!user) || (!chan))
988 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
993 for (i = 0; i != MAXCHANS; i++)
995 if ((user->chans[i].channel == chan) && (chan != NULL))
997 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1001 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1005 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1014 char scratch[MAXBUF];
1015 char sparam[MAXBUF];
1017 char* chanmodes(chanrec *chan)
1021 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1028 if (chan->noexternal)
1030 strncat(scratch,"n",MAXMODES);
1032 if (chan->topiclock)
1034 strncat(scratch,"t",MAXMODES);
1036 if (strcmp(chan->key,""))
1038 strncat(scratch,"k",MAXMODES);
1042 strncat(scratch,"l",MAXMODES);
1044 if (chan->inviteonly)
1046 strncat(scratch,"i",MAXMODES);
1048 if (chan->moderated)
1050 strncat(scratch,"m",MAXMODES);
1054 strncat(scratch,"s",MAXMODES);
1056 if (chan->c_private)
1058 strncat(scratch,"p",MAXMODES);
1060 if (strcmp(chan->key,""))
1062 strncat(sparam,chan->key,MAXBUF);
1067 sprintf(foo," %d",chan->limit);
1068 strncat(sparam,foo,MAXBUF);
1070 if (strlen(chan->custom_modes))
1072 strncat(scratch,chan->custom_modes,MAXMODES);
1073 for (int z = 0; z < strlen(chan->custom_modes); z++)
1075 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1078 strncat(sparam," ",MAXBUF);
1079 strncat(sparam,extparam.c_str(),MAXBUF);
1083 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1084 strncat(scratch,sparam,MAXMODES);
1088 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1089 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1090 * highest mode the user has must be returned. */
1092 int cstatus(userrec *user, chanrec *chan)
1094 if ((!chan) || (!user))
1096 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1101 for (i = 0; i != MAXCHANS; i++)
1103 if ((user->chans[i].channel == chan) && (chan != NULL))
1105 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1109 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1113 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1115 return STATUS_VOICE;
1117 return STATUS_NORMAL;
1123 /* compile a userlist of a channel into a string, each nick seperated by
1124 * spaces and op, voice etc status shown as @ and + */
1126 void userlist(userrec *user,chanrec *c)
1128 if ((!c) || (!user))
1130 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1134 sprintf(list,"353 %s = %s :", user->nick, c->name);
1135 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1137 if (has_channel(i->second,c))
1139 if (isnick(i->second->nick))
1141 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1143 /* user is +i, and source not on the channel, does not show
1144 * nick in NAMES list */
1147 strcat(list,cmode(i->second,c));
1148 strcat(list,i->second->nick);
1150 if (strlen(list)>(480-NICKMAX))
1152 /* list overflowed into
1153 * multiple numerics */
1154 WriteServ(user->fd,list);
1155 sprintf(list,"353 %s = %s :", user->nick, c->name);
1160 /* if whats left in the list isnt empty, send it */
1161 if (list[strlen(list)-1] != ':')
1163 WriteServ(user->fd,list);
1167 /* return a count of the users on a specific channel accounting for
1168 * invisible users who won't increase the count. e.g. for /LIST */
1170 int usercount_i(chanrec *c)
1177 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1182 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1186 if (has_channel(i->second,c))
1188 if (isnick(i->second->nick))
1190 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1192 /* user is +i, and source not on the channel, does not show
1193 * nick in NAMES list */
1201 log(DEBUG,"usercount_i: %s %d",c->name,count);
1206 int usercount(chanrec *c)
1213 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1218 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1222 if (has_channel(i->second,c))
1224 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1231 log(DEBUG,"usercount: %s %d",c->name,count);
1236 /* add a channel to a user, creating the record for it if needed and linking
1237 * it to the user record */
1239 chanrec* add_channel(userrec *user, char* cname, char* key)
1242 if ((!user) || (!cname))
1244 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1252 // we MUST declare this wherever we use FOREACH_RESULT
1255 if ((!cname) || (!user))
1259 if (strlen(cname) > CHANMAX-1)
1261 cname[CHANMAX-1] = '\0';
1264 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1266 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1268 return NULL; // already on the channel!
1272 if (!FindChan(cname))
1274 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1279 /* create a new one */
1280 log(DEBUG,"add_channel: creating: %s",cname);
1282 chanlist[cname] = new chanrec();
1284 strcpy(chanlist[cname]->name, cname);
1285 chanlist[cname]->topiclock = 1;
1286 chanlist[cname]->noexternal = 1;
1287 chanlist[cname]->created = time(NULL);
1288 strcpy(chanlist[cname]->topic, "");
1289 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1290 chanlist[cname]->topicset = 0;
1291 Ptr = chanlist[cname];
1292 log(DEBUG,"add_channel: created: %s",cname);
1293 /* set created to 2 to indicate user
1294 * is the first in the channel
1295 * and should be given ops */
1301 /* channel exists, just fish out a pointer to its struct */
1302 Ptr = FindChan(cname);
1305 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1310 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1311 if (strcmp(Ptr->key,""))
1313 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1316 log(DEBUG,"add_channel: no key given in JOIN");
1317 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1322 log(DEBUG,"key at %p is %s",key,key);
1323 if (strcasecmp(key,Ptr->key))
1325 log(DEBUG,"add_channel: bad key given in JOIN");
1326 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1331 log(DEBUG,"add_channel: no key");
1333 if (Ptr->inviteonly)
1335 log(DEBUG,"add_channel: channel is +i");
1336 if (user->IsInvited(Ptr->name))
1338 /* user was invited to channel */
1339 /* there may be an optional channel NOTICE here */
1343 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1347 log(DEBUG,"add_channel: channel is not +i");
1351 if (usercount(Ptr) == Ptr->limit)
1353 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1358 log(DEBUG,"add_channel: about to walk banlist");
1360 /* check user against the channel banlist */
1361 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1363 if (match(user->GetFullHost(),i->data))
1365 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1370 log(DEBUG,"add_channel: bans checked");
1372 user->RemoveInvite(Ptr->name);
1374 log(DEBUG,"add_channel: invites removed");
1380 log(DEBUG,"Passed channel checks");
1382 for (i =0; i != MAXCHANS; i++)
1384 if (user->chans[i].channel == NULL)
1386 log(DEBUG,"Adding into their channel list");
1390 /* first user in is given ops */
1391 user->chans[i].uc_modes = UCMODE_OP;
1395 user->chans[i].uc_modes = 0;
1397 user->chans[i].channel = Ptr;
1398 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1400 log(DEBUG,"Sent JOIN to client");
1404 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1405 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1408 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1409 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1410 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1411 FOREACH_MOD OnUserJoin(user,Ptr);
1415 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1416 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1420 /* remove a channel from a users record, and remove the record from memory
1421 * if the channel has become empty */
1423 chanrec* del_channel(userrec *user, char* cname, char* reason)
1425 if ((!user) || (!cname))
1427 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1435 if ((!cname) || (!user))
1440 Ptr = FindChan(cname);
1447 FOREACH_MOD OnUserPart(user,Ptr);
1448 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1450 for (i =0; i != MAXCHANS; i++)
1452 /* zap it from the channel list of the user */
1453 if (user->chans[i].channel == Ptr)
1457 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1461 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1463 user->chans[i].uc_modes = 0;
1464 user->chans[i].channel = NULL;
1465 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1470 /* if there are no users left on the channel */
1471 if (!usercount(Ptr))
1473 chan_hash::iterator iter = chanlist.find(Ptr->name);
1475 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1477 /* kill the record */
1478 if (iter != chanlist.end())
1480 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1481 delete iter->second;
1482 chanlist.erase(iter);
1488 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1490 if ((!src) || (!user) || (!Ptr) || (!reason))
1492 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1499 if ((!Ptr) || (!user) || (!src))
1504 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1506 if (!has_channel(user,Ptr))
1508 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1511 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1513 if (cstatus(src,Ptr) == STATUS_HOP)
1515 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1519 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1525 for (i =0; i != MAXCHANS; i++)
1527 /* zap it from the channel list of the user */
1528 if (user->chans[i].channel == Ptr)
1530 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1531 user->chans[i].uc_modes = 0;
1532 user->chans[i].channel = NULL;
1533 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1538 /* if there are no users left on the channel */
1539 if (!usercount(Ptr))
1541 chan_hash::iterator iter = chanlist.find(Ptr->name);
1543 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1545 /* kill the record */
1546 if (iter != chanlist.end())
1548 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1549 delete iter->second;
1550 chanlist.erase(iter);
1556 /* returns 1 if user u has channel c in their record, 0 if not */
1558 int has_channel(userrec *u, chanrec *c)
1564 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1567 for (i =0; i != MAXCHANS; i++)
1569 if (u->chans[i].channel == c)
1577 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1582 if ((!user) || (!dest) || (!chan))
1584 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1587 if (status != STATUS_OP)
1589 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1596 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1602 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1607 for (i = 0; i != MAXCHANS; i++)
1609 if ((d->chans[i].channel == chan) && (chan != NULL))
1611 if (d->chans[i].uc_modes & UCMODE_OP)
1613 /* mode already set on user, dont allow multiple */
1616 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1617 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1625 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1630 if ((!user) || (!dest) || (!chan))
1632 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1635 if (status != STATUS_OP)
1637 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1645 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1650 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1655 for (i = 0; i != MAXCHANS; i++)
1657 if ((d->chans[i].channel == chan) && (chan != NULL))
1659 if (d->chans[i].uc_modes & UCMODE_HOP)
1661 /* mode already set on user, dont allow multiple */
1664 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1665 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1673 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1678 if ((!user) || (!dest) || (!chan))
1680 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1683 if (status < STATUS_HOP)
1685 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1693 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1698 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1703 for (i = 0; i != MAXCHANS; i++)
1705 if ((d->chans[i].channel == chan) && (chan != NULL))
1707 if (d->chans[i].uc_modes & UCMODE_VOICE)
1709 /* mode already set on user, dont allow multiple */
1712 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1713 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1721 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1726 if ((!user) || (!dest) || (!chan))
1728 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1731 if (status != STATUS_OP)
1733 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1741 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1746 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1751 for (i = 0; i != MAXCHANS; i++)
1753 if ((d->chans[i].channel == chan) && (chan != NULL))
1755 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1757 /* mode already set on user, dont allow multiple */
1760 d->chans[i].uc_modes ^= UCMODE_OP;
1761 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1769 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1774 if ((!user) || (!dest) || (!chan))
1776 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1779 if (status != STATUS_OP)
1781 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1789 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1794 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1799 for (i = 0; i != MAXCHANS; i++)
1801 if ((d->chans[i].channel == chan) && (chan != NULL))
1803 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1805 /* mode already set on user, dont allow multiple */
1808 d->chans[i].uc_modes ^= UCMODE_HOP;
1809 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1817 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1822 if ((!user) || (!dest) || (!chan))
1824 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1827 if (status < STATUS_HOP)
1829 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1837 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1842 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1847 for (i = 0; i != MAXCHANS; i++)
1849 if ((d->chans[i].channel == chan) && (chan != NULL))
1851 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1853 /* mode already set on user, dont allow multiple */
1856 d->chans[i].uc_modes ^= UCMODE_VOICE;
1857 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1865 void TidyBan(char *ban)
1868 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1872 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1876 char* pos_of_pling = strchr(temp,'!');
1877 char* pos_of_at = strchr(temp,'@');
1879 pos_of_pling[0] = '\0';
1880 pos_of_at[0] = '\0';
1884 strncpy(NICK,temp,NICKMAX);
1885 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1886 strncpy(HOST,pos_of_at,160);
1888 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1891 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1893 if ((!user) || (!dest) || (!chan)) {
1894 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1899 if ((!user) || (!dest) || (!chan))
1901 if (strchr(dest,'!')==0)
1903 if (strchr(dest,'@')==0)
1905 for (int i = 0; i < strlen(dest); i++)
1908 for (int i = 0; i < strlen(dest); i++)
1912 for (int i = 0; i < strlen(dest); i++)
1918 for (int i = 0; i < strlen(dest); i++)
1923 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1926 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1928 if (!strcasecmp(i->data,dest))
1930 // dont allow a user to set the same ban twice
1935 b.set_time = time(NULL);
1936 strncpy(b.data,dest,MAXBUF);
1937 strncpy(b.set_by,user->nick,NICKMAX);
1938 chan->bans.push_back(b);
1942 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1944 if ((!user) || (!dest) || (!chan)) {
1945 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
1949 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1950 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1952 if (!strcasecmp(i->data,dest))
1954 chan->bans.erase(i);
1961 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1963 if ((!parameters) || (!user)) {
1964 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
1969 char modelist[MAXBUF];
1970 char outlist[MAXBUF];
1971 char outstr[MAXBUF];
1972 char outpars[32][MAXBUF];
1978 bool k_set = false, l_set = false;
1985 log(DEBUG,"process_modes: start");
1987 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1988 /* parameters[2] onwards are parameters for
1989 * modes that require them :) */
1990 strcpy(outlist,"+");
1993 log(DEBUG,"process_modes: modelist: %s",modelist);
1995 for (ptr = 0; ptr < strlen(modelist); ptr++)
2000 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2001 char modechar = modelist[ptr];
2002 switch (modelist[ptr])
2007 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2009 outlist[strlen(outlist)-1] = '-';
2013 strcat(outlist,"-");
2023 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2025 outlist[strlen(outlist)-1] = '+';
2029 strcat(outlist,"+");
2036 if ((param >= pcnt)) break;
2039 r = give_ops(user,parameters[param++],chan,status);
2043 r = take_ops(user,parameters[param++],chan,status);
2047 strcat(outlist,"o");
2048 strcpy(outpars[pc++],parameters[param-1]);
2053 if ((param >= pcnt)) break;
2056 r = give_hops(user,parameters[param++],chan,status);
2060 r = take_hops(user,parameters[param++],chan,status);
2064 strcat(outlist,"h");
2065 strcpy(outpars[pc++],parameters[param-1]);
2071 if ((param >= pcnt)) break;
2074 r = give_voice(user,parameters[param++],chan,status);
2078 r = take_voice(user,parameters[param++],chan,status);
2082 strcat(outlist,"v");
2083 strcpy(outpars[pc++],parameters[param-1]);
2088 if ((param >= pcnt)) break;
2091 r = add_ban(user,parameters[param++],chan,status);
2095 r = take_ban(user,parameters[param++],chan,status);
2099 strcat(outlist,"b");
2100 strcpy(outpars[pc++],parameters[param-1]);
2106 if ((param >= pcnt))
2114 if (!strcmp(chan->key,""))
2116 strcat(outlist,"k");
2118 strcpy(key,parameters[param++]);
2119 if (strlen(key)>32) {
2122 strcpy(outpars[pc++],key);
2123 strcpy(chan->key,key);
2129 /* checks on -k are case sensitive and only accurate to the
2130 first 32 characters */
2132 strcpy(key,parameters[param++]);
2133 if (strlen(key)>32) {
2136 /* only allow -k if correct key given */
2137 if (!strcmp(chan->key,key))
2139 strcat(outlist,"k");
2140 strcpy(chan->key,"");
2141 strcpy(outpars[pc++],key);
2151 strcat(outlist,"l");
2156 if ((param >= pcnt)) break;
2162 bool invalid = false;
2163 for (int i = 0; i < strlen(parameters[param]); i++)
2165 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2170 if (atoi(parameters[param]) < 1)
2178 chan->limit = atoi(parameters[param]);
2181 strcat(outlist,"l");
2182 strcpy(outpars[pc++],parameters[param++]);
2189 if (chan->inviteonly != mdir)
2191 strcat(outlist,"i");
2193 chan->inviteonly = mdir;
2197 if (chan->topiclock != mdir)
2199 strcat(outlist,"t");
2201 chan->topiclock = mdir;
2205 if (chan->noexternal != mdir)
2207 strcat(outlist,"n");
2209 chan->noexternal = mdir;
2213 if (chan->moderated != mdir)
2215 strcat(outlist,"m");
2217 chan->moderated = mdir;
2221 if (chan->secret != mdir)
2223 strcat(outlist,"s");
2224 if (chan->c_private)
2226 chan->c_private = 0;
2229 strcat(outlist,"-p+");
2233 strcat(outlist,"+p-");
2237 chan->secret = mdir;
2241 if (chan->c_private != mdir)
2243 strcat(outlist,"p");
2249 strcat(outlist,"-s+");
2253 strcat(outlist,"+s-");
2257 chan->c_private = mdir;
2261 log(DEBUG,"Preprocessing custom mode %c",modechar);
2264 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2266 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2269 if (ModeDefined(modechar,MT_CHANNEL))
2271 log(DEBUG,"A module has claimed this mode");
2274 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2276 p.push_back(parameters[param]);
2278 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2280 p.push_back(parameters[param]);
2283 bool handled = false;
2286 log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2287 // we're supposed to have a parameter, but none was given... so dont handle the mode.
2288 if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir)))
2294 for (int i = 0; i <= MODCOUNT; i++)
2298 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2300 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2301 char app[] = {modechar, 0};
2304 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2306 strcat(outlist, app);
2308 else if (!strchr(outlist,modechar))
2310 strcat(outlist, app);
2313 chan->SetCustomMode(modechar,mdir);
2314 // include parameters in output if mode has them
2315 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2317 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2318 strcpy(outpars[pc++],parameters[param++]);
2320 // break, because only one module can handle the mode.
2332 /* this ensures only the *valid* modes are sent out onto the network */
2333 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2335 outlist[strlen(outlist)-1] = '\0';
2337 if (strcmp(outlist,""))
2339 strcpy(outstr,outlist);
2340 for (ptr = 0; ptr < pc; ptr++)
2343 strcat(outstr,outpars[ptr]);
2347 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2351 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2356 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2358 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2360 log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2361 // RFC1459 specified modes
2362 if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2364 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2368 // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2369 if ((strchr(sourcemodes,'o')) && (!adding))
2371 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2374 else if (umode == 'o')
2376 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2380 // process any module-defined modes that need oper
2381 if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2383 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2387 if (ModeDefined(umode,MT_CLIENT))
2389 // process any module-defined modes that don't need oper
2390 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2391 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2393 // no, this mode needs oper, and this user 'aint got what it takes!
2399 // anything else - return false.
2400 log(DEBUG,"umode %c not known by any ruleset",umode);
2404 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2408 if (ModeDefined(umode,MT_CLIENT))
2410 for (int i = 0; i <= MODCOUNT; i++)
2412 if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2414 log(DEBUG,"Module claims umode %c",umode);
2418 log(DEBUG,"No module claims umode %c",umode);
2423 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2428 void handle_mode(char **parameters, int pcnt, userrec *user)
2434 char outpars[MAXBUF];
2436 dest = Find(parameters[0]);
2438 if ((dest) && (pcnt == 1))
2440 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2444 if ((dest) && (pcnt > 1))
2446 char dmodes[MAXBUF];
2447 strncpy(dmodes,dest->modes,MAXBUF);
2448 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2453 if (strchr(user->modes,'o'))
2464 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2468 strcpy(outpars,"+");
2471 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2474 for (i = 0; i < strlen(parameters[1]); i++)
2476 if (parameters[1][i] == '+')
2480 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2482 outpars[strlen(outpars)-1] = '+';
2486 strcat(outpars,"+");
2492 if (parameters[1][i] == '-')
2496 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2498 outpars[strlen(outpars)-1] = '-';
2502 strcat(outpars,"-");
2510 if (strchr(user->modes,'o'))
2516 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2525 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2527 char umode = parameters[1][i];
2528 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2530 dmodes[strlen(dmodes)+1]='\0';
2531 dmodes[strlen(dmodes)] = parameters[1][i];
2532 outpars[strlen(outpars)+1]='\0';
2533 outpars[strlen(outpars)] = parameters[1][i];
2539 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2541 char umode = parameters[1][i];
2542 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2548 outpars[strlen(outpars)+1]='\0';
2549 outpars[strlen(outpars)] = parameters[1][i];
2552 for (q = 0; q < strlen(dmodes); q++)
2554 if (dmodes[q] != parameters[1][i])
2561 strcpy(dmodes,temp);
2568 if (strlen(outpars))
2574 while (i < strlen (outpars))
2576 b[z++] = outpars[i++];
2578 if (i<strlen(outpars)-1)
2580 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2582 // someones playing silly buggers and trying
2583 // to put a +- or -+ into the line...
2587 if (i == strlen(outpars)-1)
2589 if ((outpars[i] == '-') || (outpars[i] == '+'))
2597 if ((b[z] == '-') || (b[z] == '+'))
2600 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2603 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2605 if (strlen(dmodes)>MAXMODES)
2607 dmodes[MAXMODES-1] = '\0';
2609 log(DEBUG,"Stripped mode line");
2610 log(DEBUG,"Line dest is now %s",dmodes);
2611 strncpy(dest->modes,dmodes,MAXMODES);
2618 Ptr = FindChan(parameters[0]);
2623 /* just /modes #channel */
2624 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2625 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2631 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2634 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2636 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2638 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2642 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2644 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2648 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2652 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2659 void server_mode(char **parameters, int pcnt, userrec *user)
2665 char outpars[MAXBUF];
2667 dest = Find(parameters[0]);
2669 // fix: ChroNiCk found this - we cant use this as debug if its null!
2672 log(DEBUG,"server_mode on %s",dest->nick);
2675 if ((dest) && (pcnt > 1))
2677 log(DEBUG,"params > 1");
2679 char dmodes[MAXBUF];
2680 strncpy(dmodes,dest->modes,MAXBUF);
2682 strcpy(outpars,"+");
2685 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2688 for (i = 0; i < strlen(parameters[1]); i++)
2690 if (parameters[1][i] == '+')
2694 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2696 outpars[strlen(outpars)-1] = '+';
2700 strcat(outpars,"+");
2706 if (parameters[1][i] == '-')
2710 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2712 outpars[strlen(outpars)-1] = '-';
2716 strcat(outpars,"-");
2723 log(DEBUG,"begin mode processing entry");
2729 log(DEBUG,"umode %c being added",parameters[1][i]);
2730 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2732 char umode = parameters[1][i];
2733 log(DEBUG,"umode %c is an allowed umode",umode);
2734 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2736 dmodes[strlen(dmodes)+1]='\0';
2737 dmodes[strlen(dmodes)] = parameters[1][i];
2738 outpars[strlen(outpars)+1]='\0';
2739 outpars[strlen(outpars)] = parameters[1][i];
2745 // can only remove a mode they already have
2746 log(DEBUG,"umode %c being removed",parameters[1][i]);
2747 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2749 char umode = parameters[1][i];
2750 log(DEBUG,"umode %c is an allowed umode",umode);
2751 if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2757 outpars[strlen(outpars)+1]='\0';
2758 outpars[strlen(outpars)] = parameters[1][i];
2761 for (q = 0; q < strlen(dmodes); q++)
2763 if (dmodes[q] != parameters[1][i])
2770 strcpy(dmodes,temp);
2777 if (strlen(outpars))
2783 while (i < strlen (outpars))
2785 b[z++] = outpars[i++];
2787 if (i<strlen(outpars)-1)
2789 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2791 // someones playing silly buggers and trying
2792 // to put a +- or -+ into the line...
2796 if (i == strlen(outpars)-1)
2798 if ((outpars[i] == '-') || (outpars[i] == '+'))
2806 if ((b[z] == '-') || (b[z] == '+'))
2809 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2812 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2814 if (strlen(dmodes)>MAXMODES)
2816 dmodes[MAXMODES-1] = '\0';
2818 log(DEBUG,"Stripped mode line");
2819 log(DEBUG,"Line dest is now %s",dmodes);
2820 strncpy(dest->modes,dmodes,MAXMODES);
2827 Ptr = FindChan(parameters[0]);
2830 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2834 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2839 /* This function pokes and hacks at a parameter list like the following:
2841 * PART #winbot, #darkgalaxy :m00!
2843 * to turn it into a series of individual calls like this:
2845 * PART #winbot :m00!
2846 * PART #darkgalaxy :m00!
2848 * The seperate calls are sent to a callback function provided by the caller
2849 * (the caller will usually call itself recursively). The callback function
2850 * must be a command handler. Calling this function on a line with no list causes
2851 * no action to be taken. You must provide a starting and ending parameter number
2852 * where the range of the list can be found, useful if you have a terminating
2853 * parameter as above which is actually not part of the list, or parameters
2854 * before the actual list as well. This code is used by many functions which
2855 * can function as "one to list" (see the RFC) */
2857 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2862 char blog[32][MAXBUF];
2863 char blog2[32][MAXBUF];
2864 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2865 char keystr[MAXBUF];
2868 for (i = 0; i <32; i++)
2871 for (i = 0; i <32; i++)
2872 strcpy(blog2[i],"");
2875 for (i = 0; i <10; i++)
2879 parameters[i] = moo;
2884 if (pcnt > 1) /* we have a key to copy */
2886 strcpy(keystr,parameters[1]);
2890 if (!parameters[start])
2894 if (!strchr(parameters[start],','))
2899 for (i = start; i <= end; i++)
2903 strcat(plist,parameters[i]);
2911 for (i = 0; i < t; i++)
2913 if (plist[i] == ',')
2916 strcpy(blog[j++],param);
2920 strcpy(blog[j++],param);
2923 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2928 if ((joins) && (keystr))
2930 if (strchr(keystr,','))
2934 t2 = strlen(keystr);
2935 for (i = 0; i < t2; i++)
2937 if (keystr[i] == ',')
2940 strcpy(blog2[j++],param);
2944 strcpy(blog2[j++],param);
2949 for (j = 0; j < total; j++)
2955 for (q = end; q < pcnt-1; q++)
2957 if (parameters[q+1])
2959 pars[q-end+1] = parameters[q+1];
2962 if ((joins) && (parameters[1]))
2973 /* repeatedly call the function with the hacked parameter list */
2974 if ((joins) && (pcnt > 1))
2978 // pars[1] already set up and containing key from blog2[j]
2983 pars[1] = parameters[1];
2989 fn(pars,pcnt-(end-start),u);
2997 void handle_join(char **parameters, int pcnt, userrec *user)
3002 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3004 if (parameters[0][0] == '#')
3006 Ptr = add_channel(user,parameters[0],parameters[1]);
3011 void handle_part(char **parameters, int pcnt, userrec *user)
3017 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3019 del_channel(user,parameters[0],parameters[1]);
3023 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3025 del_channel(user,parameters[0],NULL);
3029 void handle_kick(char **parameters, int pcnt, userrec *user)
3031 chanrec* Ptr = FindChan(parameters[0]);
3032 userrec* u = Find(parameters[1]);
3036 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3040 if (!has_channel(u,Ptr))
3042 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3048 char reason[MAXBUF];
3049 strncpy(reason,parameters[2],MAXBUF);
3050 if (strlen(reason)>MAXKICK)
3052 reason[MAXKICK-1] = '\0';
3055 kick_channel(user,u,Ptr,reason);
3059 kick_channel(user,u,Ptr,user->nick);
3064 void handle_die(char **parameters, int pcnt, userrec *user)
3066 log(DEBUG,"die: %s",user->nick);
3067 if (!strcmp(parameters[0],diepass))
3069 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3075 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3079 void handle_restart(char **parameters, int pcnt, userrec *user)
3081 log(DEBUG,"restart: %s",user->nick);
3082 if (!strcmp(parameters[0],restartpass))
3084 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3087 /* Will finish this later when i can be arsed :) */
3091 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3096 void kill_link(userrec *user,char* reason)
3098 user_hash::iterator iter = clientlist.find(user->nick);
3100 if (strlen(reason)>MAXQUIT)
3102 reason[MAXQUIT-1] = '\0';
3105 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3106 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3107 log(DEBUG,"closing fd %d",user->fd);
3109 /* bugfix, cant close() a nonblocking socket (sux!) */
3110 if (user->registered == 7) {
3111 FOREACH_MOD OnUserQuit(user);
3112 WriteCommonExcept(user,"QUIT :%s",reason);
3115 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3116 fd_reap.push_back(user->fd);
3118 bool do_purge = false;
3120 if (user->registered == 7) {
3121 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3125 if (iter != clientlist.end())
3127 log(DEBUG,"deleting user hash value %d",iter->second);
3128 if ((iter->second) && (user->registered == 7)) {
3129 delete iter->second;
3131 clientlist.erase(iter);
3134 if (user->registered == 7) {
3135 purge_empty_chans();
3140 void handle_kill(char **parameters, int pcnt, userrec *user)
3142 userrec *u = Find(parameters[0]);
3143 char killreason[MAXBUF];
3145 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3148 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3149 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3150 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3151 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3152 kill_link(u,killreason);
3156 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3160 void handle_summon(char **parameters, int pcnt, userrec *user)
3162 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3165 void handle_users(char **parameters, int pcnt, userrec *user)
3167 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3171 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3173 char* Passwd(userrec *user)
3175 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3177 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3185 bool IsDenied(userrec *user)
3187 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3189 if (match(user->host,i->host) && (i->type == CC_DENY))
3198 void handle_pass(char **parameters, int pcnt, userrec *user)
3200 if (!strcasecmp(parameters[0],Passwd(user)))
3202 user->haspassed = true;
3206 void handle_invite(char **parameters, int pcnt, userrec *user)
3208 userrec* u = Find(parameters[0]);
3209 chanrec* c = FindChan(parameters[1]);
3215 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
3221 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3230 if (cstatus(user,c) < STATUS_HOP)
3232 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
3236 u->InviteTo(c->name);
3237 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3238 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3242 void handle_topic(char **parameters, int pcnt, userrec *user)
3248 if (strlen(parameters[0]) <= CHANMAX)
3250 Ptr = FindChan(parameters[0]);
3255 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3256 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3260 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3265 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3272 if (strlen(parameters[0]) <= CHANMAX)
3274 Ptr = FindChan(parameters[0]);
3277 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3279 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
3284 strncpy(topic,parameters[1],MAXBUF);
3285 if (strlen(topic)>MAXTOPIC)
3287 topic[MAXTOPIC-1] = '\0';
3290 strcpy(Ptr->topic,topic);
3291 strcpy(Ptr->setby,user->nick);
3292 Ptr->topicset = time(NULL);
3293 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3297 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3303 /* sends out an error notice to all connected clients (not to be used
3306 void send_error(char *s)
3308 log(DEBUG,"send_error: %s",s);
3309 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3311 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3315 void Error(int status)
3317 signal (SIGALRM, SIG_IGN);
3318 signal (SIGPIPE, SIG_IGN);
3319 signal (SIGTERM, SIG_IGN);
3320 signal (SIGABRT, SIG_IGN);
3321 signal (SIGSEGV, SIG_IGN);
3322 signal (SIGURG, SIG_IGN);
3323 signal (SIGKILL, SIG_IGN);
3324 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3325 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3329 int main (int argc, char *argv[])
3332 log(DEBUG,"*** InspIRCd starting up!");
3333 if (!FileExists(CONFIG_FILE))
3335 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3336 log(DEBUG,"main: no config");
3337 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3341 if (!strcmp(argv[1],"-nofork")) {
3345 if (InspIRCd() == ERROR)
3347 log(DEBUG,"main: daemon function bailed");
3348 printf("ERROR: could not initialise. Shutting down.\n");
3355 template<typename T> inline string ConvToStr(const T &in)
3358 if (!(tmp << in)) return string();
3362 /* re-allocates a nick in the user_hash after they change nicknames,
3363 * returns a pointer to the new user as it may have moved */
3365 userrec* ReHashNick(char* Old, char* New)
3367 user_hash::iterator newnick;
3368 user_hash::iterator oldnick = clientlist.find(Old);
3370 log(DEBUG,"ReHashNick: %s %s",Old,New);
3372 if (!strcasecmp(Old,New))
3374 log(DEBUG,"old nick is new nick, skipping");
3375 return oldnick->second;
3378 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3380 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3382 clientlist[New] = new userrec();
3383 clientlist[New] = oldnick->second;
3384 /*delete oldnick->second; */
3385 clientlist.erase(oldnick);
3387 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3389 return clientlist[New];
3392 /* adds or updates an entry in the whowas list */
3393 void AddWhoWas(userrec* u)
3395 user_hash::iterator iter = whowas.find(u->nick);
3396 userrec *a = new userrec();
3397 strcpy(a->nick,u->nick);
3398 strcpy(a->ident,u->ident);
3399 strcpy(a->dhost,u->dhost);
3400 strcpy(a->host,u->host);
3401 strcpy(a->fullname,u->fullname);
3402 strcpy(a->server,u->server);
3403 a->signon = u->signon;
3405 /* MAX_WHOWAS: max number of /WHOWAS items
3406 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3407 * can be replaced by a newer one
3410 if (iter == whowas.end())
3412 if (whowas.size() == WHOWAS_MAX)
3414 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3416 // 3600 seconds in an hour ;)
3417 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3421 log(DEBUG,"added WHOWAS entry, purged an old record");
3428 log(DEBUG,"added fresh WHOWAS entry");
3429 whowas[a->nick] = a;
3434 log(DEBUG,"updated WHOWAS entry");
3435 delete iter->second;
3441 /* add a client connection to the sockets list */
3442 void AddClient(int socket, char* host, int port, bool iscached)
3446 char resolved[MAXBUF];
3449 user_hash::iterator iter;
3451 tempnick = ConvToStr(socket) + "-unknown";
3452 sprintf(tn2,"%d-unknown",socket);
3454 iter = clientlist.find(tempnick);
3456 if (iter != clientlist.end()) return;
3459 * It is OK to access the value here this way since we know
3460 * it exists, we just created it above.
3462 * At NO other time should you access a value in a map or a
3463 * hash_map this way.
3465 clientlist[tempnick] = new userrec();
3467 NonBlocking(socket);
3468 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3471 clientlist[tempnick]->fd = socket;
3472 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3473 strncpy(clientlist[tempnick]->host, host,160);
3474 strncpy(clientlist[tempnick]->dhost, host,160);
3475 strncpy(clientlist[tempnick]->server, ServerName,256);
3476 clientlist[tempnick]->registered = 0;
3477 clientlist[tempnick]->signon = time(NULL);
3478 clientlist[tempnick]->nping = time(NULL)+240;
3479 clientlist[tempnick]->lastping = 1;
3480 clientlist[tempnick]->port = port;
3484 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3488 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3491 if (clientlist.size() == MAXCLIENTS)
3492 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3495 void handle_names(char **parameters, int pcnt, userrec *user)
3499 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3501 c = FindChan(parameters[0]);
3504 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3506 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3510 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3515 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3520 user->idle_lastmsg = time(NULL);
3522 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3524 if (parameters[0][0] == '#')
3526 chan = FindChan(parameters[0]);
3529 if ((chan->noexternal) && (!has_channel(user,chan)))
3531 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3534 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3536 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3539 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3543 /* no such nick/channel */
3544 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3549 dest = Find(parameters[0]);
3552 if (strcmp(dest->awaymsg,""))
3554 /* auto respond with aweh msg */
3555 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3557 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3561 /* no such nick/channel */
3562 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3566 void handle_notice(char **parameters, int pcnt, userrec *user)
3571 user->idle_lastmsg = time(NULL);
3573 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3575 if (parameters[0][0] == '#')
3577 chan = FindChan(parameters[0]);
3580 if ((chan->noexternal) && (!has_channel(user,chan)))
3582 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3585 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3587 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3590 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3594 /* no such nick/channel */
3595 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3600 dest = Find(parameters[0]);
3603 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3607 /* no such nick/channel */
3608 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3614 char* chlist(userrec *user)
3619 log(DEBUG,"chlist: %s",user->nick);
3625 for (i = 0; i != MAXCHANS; i++)
3627 if (user->chans[i].channel != NULL)
3629 if (user->chans[i].channel->name)
3631 strcpy(cmp,user->chans[i].channel->name);
3633 if (!strstr(lst,cmp))
3635 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3637 strcat(lst,cmode(user,user->chans[i].channel));
3638 strcat(lst,user->chans[i].channel->name);
3648 void handle_info(char **parameters, int pcnt, userrec *user)
3650 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3651 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3652 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3653 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3656 void handle_time(char **parameters, int pcnt, userrec *user)
3659 struct tm * timeinfo;
3662 timeinfo = localtime ( &rawtime );
3663 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3667 void handle_whois(char **parameters, int pcnt, userrec *user)
3672 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3674 dest = Find(parameters[0]);
3677 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
3678 if (dest->registered == 7)
3680 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3681 if ((user == dest) || (strchr(user->modes,'o')))
3683 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3685 if (strcmp(chlist(dest),""))
3687 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3689 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3690 if (strcmp(dest->awaymsg,""))
3692 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3694 if (strchr(dest->modes,'o'))
3696 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3698 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3699 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3701 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3705 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3710 /* no such nick/channel */
3711 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3715 void handle_quit(char **parameters, int pcnt, userrec *user)
3717 user_hash::iterator iter = clientlist.find(user->nick);
3720 if (user->registered == 7)
3722 /* theres more to do here, but for now just close the socket */
3725 if (parameters[0][0] == ':')
3729 reason = parameters[0];
3731 if (strlen(reason)>MAXQUIT)
3733 reason[MAXQUIT-1] = '\0';
3736 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3737 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3738 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3742 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3743 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3744 WriteCommonExcept(user,"QUIT :Client exited");
3746 FOREACH_MOD OnUserQuit(user);
3750 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3751 fd_reap.push_back(user->fd);
3753 if (iter != clientlist.end())
3755 log(DEBUG,"deleting user hash value %d",iter->second);
3756 if ((iter->second) && (user->registered == 7)) {
3757 delete iter->second;
3759 clientlist.erase(iter);
3762 if (user->registered == 7) {
3763 purge_empty_chans();
3767 void handle_who(char **parameters, int pcnt, userrec *user)
3769 chanrec* Ptr = NULL;
3771 /* theres more to do here, but for now just close the socket */
3774 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3776 if (user->chans[0].channel)
3778 Ptr = user->chans[0].channel;
3779 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3781 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3783 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3789 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3793 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3797 if (parameters[0][0] = '#')
3799 Ptr = FindChan(parameters[0]);
3802 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3804 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3806 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3809 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3813 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3819 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3821 Ptr = user->chans[0].channel;
3822 printf(user->chans[0].channel->name);
3823 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3825 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3827 if (strchr(i->second->modes,'o'))
3829 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3833 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3839 void handle_wallops(char **parameters, int pcnt, userrec *user)
3841 WriteWallOps(user,"%s",parameters[0]);
3844 void handle_list(char **parameters, int pcnt, userrec *user)
3848 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3849 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3851 if ((!i->second->c_private) && (!i->second->secret))
3853 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3856 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3860 void handle_rehash(char **parameters, int pcnt, userrec *user)
3862 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3864 FOREACH_MOD OnRehash();
3865 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3871 return clientlist.size();
3874 int usercount_invisible(void)
3878 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3880 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3885 int usercount_opers(void)
3889 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3891 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3896 int usercount_unknown(void)
3900 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3902 if ((i->second->fd) && (i->second->registered != 7))
3910 return chanlist.size();
3913 int servercount(void)
3918 void handle_lusers(char **parameters, int pcnt, userrec *user)
3920 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3921 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3922 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3923 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3924 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3927 void handle_admin(char **parameters, int pcnt, userrec *user)
3929 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3930 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
3931 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3932 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
3935 void ShowMOTD(userrec *user)
3939 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3942 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3943 for (int i = 0; i != MOTD.size(); i++)
3945 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3947 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3950 void ShowRULES(userrec *user)
3954 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3957 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3958 for (int i = 0; i != RULES.size(); i++)
3960 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3962 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3965 /* shows the message of the day, and any other on-logon stuff */
3966 void ConnectUser(userrec *user)
3968 user->registered = 7;
3969 user->idle_lastmsg = time(NULL);
3970 log(DEBUG,"ConnectUser: %s",user->nick);
3972 if (strcmp(Passwd(user),"") && (!user->haspassed))
3974 kill_link(user,"Invalid password");
3979 kill_link(user,"Unauthorised connection");
3983 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3984 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3985 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3986 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3987 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3988 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);
3989 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);
3991 FOREACH_MOD OnUserConnect(user);
3992 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3995 void handle_version(char **parameters, int pcnt, userrec *user)
3997 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
4000 void handle_ping(char **parameters, int pcnt, userrec *user)
4002 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
4005 void handle_pong(char **parameters, int pcnt, userrec *user)
4007 // set the user as alive so they survive to next ping
4011 void handle_motd(char **parameters, int pcnt, userrec *user)
4016 void handle_rules(char **parameters, int pcnt, userrec *user)
4021 void handle_user(char **parameters, int pcnt, userrec *user)
4023 if (user->registered < 3)
4025 if (isident(parameters[0]) == 0) {
4026 // This kinda Sucks, According to the RFC thou, its either this,
4027 // or "You have already registered" :p -- Craig
4028 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
4031 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
4032 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
4033 strncat(user->ident,parameters[0],IDENTMAX);
4034 strncpy(user->fullname,parameters[3],128);
4035 user->registered = (user->registered | 1);
4040 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4043 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
4044 if (user->registered == 3)
4046 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4051 void handle_userhost(char **parameters, int pcnt, userrec *user)
4053 char Return[MAXBUF],junk[MAXBUF];
4054 sprintf(Return,"302 %s :",user->nick);
4055 for (int i = 0; i < pcnt; i++)
4057 userrec *u = Find(parameters[i]);
4060 if (strchr(u->modes,'o'))
4062 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
4063 strcat(Return,junk);
4067 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
4068 strcat(Return,junk);
4072 WriteServ(user->fd,Return);
4076 void handle_ison(char **parameters, int pcnt, userrec *user)
4078 char Return[MAXBUF];
4079 sprintf(Return,"303 %s :",user->nick);
4080 for (int i = 0; i < pcnt; i++)
4082 userrec *u = Find(parameters[i]);
4085 strcat(Return,u->nick);
4089 WriteServ(user->fd,Return);
4093 void handle_away(char **parameters, int pcnt, userrec *user)
4097 strcpy(user->awaymsg,parameters[0]);
4098 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
4102 strcpy(user->awaymsg,"");
4103 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
4107 void handle_whowas(char **parameters, int pcnt, userrec* user)
4109 user_hash::iterator i = whowas.find(parameters[0]);
4111 if (i == whowas.end())
4113 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
4114 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4118 time_t rawtime = i->second->signon;
4122 timeinfo = localtime(&rawtime);
4123 strcpy(b,asctime(timeinfo));
4124 b[strlen(b)-1] = '\0';
4126 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
4127 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
4128 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
4133 void handle_trace(char **parameters, int pcnt, userrec *user)
4135 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4139 if (isnick(i->second->nick))
4141 if (strchr(i->second->modes,'o'))
4143 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
4147 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
4152 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4158 void handle_modules(char **parameters, int pcnt, userrec *user)
4160 for (int i = 0; i < module_names.size(); i++)
4162 Version V = modules[i]->GetVersion();
4163 WriteServ(user->fd,"900 0x%08lx %d.%d.%d.%d :%s",modules[i],V.Major,V.Minor,V.Revision,V.Build,module_names[i].c_str());
4167 void handle_stats(char **parameters, int pcnt, userrec *user)
4173 if (strlen(parameters[0])>1)
4175 /* make the stats query 1 character long */
4176 parameters[0][1] = '\0';
4179 /* stats m (list number of times each command has been used, plus bytecount) */
4180 if (!strcasecmp(parameters[0],"m"))
4182 for (int i = 0; i < cmdlist.size(); i++)
4184 if (cmdlist[i].handler_function)
4186 if (cmdlist[i].use_count)
4188 /* RPL_STATSCOMMANDS */
4189 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4196 /* stats z (debug and memory info) */
4197 if (!strcasecmp(parameters[0],"z"))
4199 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4200 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4201 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4202 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4203 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4204 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4205 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4206 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4210 if (!strcasecmp(parameters[0],"o"))
4212 for (int i = 0; i < ConfValueEnum("oper"); i++)
4214 char LoginName[MAXBUF];
4215 char HostName[MAXBUF];
4216 char OperType[MAXBUF];
4217 ConfValue("oper","name",i,LoginName);
4218 ConfValue("oper","host",i,HostName);
4219 ConfValue("oper","type",i,OperType);
4220 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4224 /* stats l (show user I/O stats) */
4225 if (!strcasecmp(parameters[0],"l"))
4227 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4228 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4230 if (isnick(i->second->nick))
4232 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);
4236 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);
4242 /* stats u (show server uptime) */
4243 if (!strcasecmp(parameters[0],"u"))
4245 time_t current_time = 0;
4246 current_time = time(NULL);
4247 time_t server_uptime = current_time - startup_time;
4249 stime = gmtime(&server_uptime);
4250 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4251 * Craig suggested this, and it seemed a good idea so in it went */
4252 if (stime->tm_year > 70)
4254 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);
4258 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);
4262 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4263 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4267 void handle_connect(char **parameters, int pcnt, userrec *user)
4269 char Link_ServerName[1024];
4270 char Link_IPAddr[1024];
4271 char Link_Port[1024];
4272 char Link_Pass[1024];
4276 for (int i = 0; i < ConfValueEnum("link"); i++)
4278 ConfValue("link","name",i,Link_ServerName);
4279 ConfValue("link","ipaddr",i,Link_IPAddr);
4280 ConfValue("link","port",i,Link_Port);
4281 ConfValue("link","sendpass",i,Link_Pass);
4282 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4283 LinkPort = atoi(Link_Port);
4284 if (match(Link_ServerName,parameters[0])) {
4290 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4294 // TODO: Perform a check here to stop a server being linked twice!
4296 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4298 if (me[defaultRoute])
4301 // at this point parameters[0] is an ip in a string.
4302 // TODO: Look this up from the <link> blocks instead!
4303 for (int j = 0; j < 255; j++) {
4304 if (servers[j] == NULL) {
4305 servers[j] = new serverrec;
4306 strcpy(servers[j]->internal_addr,Link_IPAddr);
4307 strcpy(servers[j]->name,Link_ServerName);
4308 log(DEBUG,"Allocated new serverrec");
4309 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4311 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4316 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4320 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);
4324 void handle_squit(char **parameters, int pcnt, userrec *user)
4326 // send out an squit across the mesh and then clear the server list (for local squit)
4329 void handle_oper(char **parameters, int pcnt, userrec *user)
4331 char LoginName[MAXBUF];
4332 char Password[MAXBUF];
4333 char OperType[MAXBUF];
4334 char TypeName[MAXBUF];
4335 char Hostname[MAXBUF];
4338 for (i = 0; i < ConfValueEnum("oper"); i++)
4340 ConfValue("oper","name",i,LoginName);
4341 ConfValue("oper","password",i,Password);
4342 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4344 /* correct oper credentials */
4345 ConfValue("oper","type",i,OperType);
4346 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4347 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4348 WriteServ(user->fd,"MODE %s :+o",user->nick);
4349 for (j =0; j < ConfValueEnum("type"); j++)
4351 ConfValue("type","name",j,TypeName);
4352 if (!strcmp(TypeName,OperType))
4354 /* found this oper's opertype */
4355 ConfValue("type","host",j,Hostname);
4356 strncpy(user->dhost,Hostname,256);
4359 if (!strchr(user->modes,'o'))
4361 strcat(user->modes,"o");
4367 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4368 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4371 void handle_nick(char **parameters, int pcnt, userrec *user)
4375 log(DEBUG,"not enough params for handle_nick");
4380 log(DEBUG,"invalid parameter passed to handle_nick");
4383 if (!strlen(parameters[0]))
4385 log(DEBUG,"zero length new nick passed to handle_nick");
4390 log(DEBUG,"invalid user passed to handle_nick");
4395 log(DEBUG,"invalid old nick passed to handle_nick");
4398 if (!strcasecmp(user->nick,parameters[0]))
4400 log(DEBUG,"old nick is new nick, skipping");
4405 if (strlen(parameters[0]) > 1)
4407 if (parameters[0][0] == ':')
4412 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4414 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4418 if (isnick(parameters[0]) == 0)
4420 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4424 if (user->registered == 7)
4426 WriteCommon(user,"NICK %s",parameters[0]);
4429 /* change the nick of the user in the users_hash */
4430 user = ReHashNick(user->nick, parameters[0]);
4431 /* actually change the nick within the record */
4433 if (!user->nick) return;
4435 strncpy(user->nick, parameters[0],NICKMAX);
4437 log(DEBUG,"new nick set: %s",user->nick);
4439 if (user->registered < 3)
4440 user->registered = (user->registered | 2);
4441 if (user->registered == 3)
4443 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4446 log(DEBUG,"exit nickchange: %s",user->nick);
4449 int process_parameters(char **command_p,char *parameters)
4454 q = strlen(parameters);
4457 /* no parameters, command_p invalid! */
4460 if (parameters[0] == ':')
4462 command_p[0] = parameters+1;
4467 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4469 /* only one parameter */
4470 command_p[0] = parameters;
4471 if (parameters[0] == ':')
4473 if (strchr(parameters,' ') != NULL)
4481 command_p[j++] = parameters;
4482 for (i = 0; i <= q; i++)
4484 if (parameters[i] == ' ')
4486 command_p[j++] = parameters+i+1;
4487 parameters[i] = '\0';
4488 if (command_p[j-1][0] == ':')
4490 *command_p[j-1]++; /* remove dodgy ":" */
4492 /* parameter like this marks end of the sequence */
4496 return j; /* returns total number of items in the list */
4499 void process_command(userrec *user, char* cmd)
4503 char *command_p[127];
4504 char p[MAXBUF], temp[MAXBUF];
4505 int i, j, items, cmd_found;
4507 for (int i = 0; i < 127; i++)
4508 command_p[i] = NULL;
4518 if (!strcmp(cmd,""))
4525 FOREACH_MOD OnServerRaw(tmp,true);
4526 const char* cmd2 = tmp.c_str();
4527 snprintf(cmd,512,"%s",cmd2);
4529 if (!strchr(cmd,' '))
4531 /* no parameters, lets skip the formalities and not chop up
4534 command_p[0] = NULL;
4536 for (int i = 0; i <= strlen(cmd); i++)
4538 cmd[i] = toupper(cmd[i]);
4545 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4546 for (i = 0; i < strlen(temp); i++)
4548 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4554 /* split the full string into a command plus parameters */
4558 if (strchr(cmd,' '))
4560 for (i = 0; i <= strlen(cmd); i++)
4562 /* capitalise the command ONLY, leave params intact */
4563 cmd[i] = toupper(cmd[i]);
4564 /* are we nearly there yet?! :P */
4568 parameters = cmd+i+1;
4576 for (i = 0; i <= strlen(cmd); i++)
4578 cmd[i] = toupper(cmd[i]);
4586 if (strlen(command)>MAXCOMMAND)
4588 command[MAXCOMMAND-1] = '\0';
4589 WriteOpers("Possible command-flood from %s, sending excessively long commands.",user->nick);
4592 for (i = 0; i != cmdlist.size(); i++)
4594 if (strcmp(cmdlist[i].command,""))
4596 if (!strcmp(command, cmdlist[i].command))
4600 if (strcmp(parameters,""))
4602 items = process_parameters(command_p,parameters);
4607 command_p[0] = NULL;
4613 command_p[0] = NULL;
4618 /* activity resets the ping pending timer */
4619 user->nping = time(NULL) + 120;
4620 if ((items) < cmdlist[i].min_params)
4622 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4623 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4626 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4628 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4629 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4633 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4635 if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4637 if ((!isnick(user->nick)) || (user->registered != 7))
4639 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4640 WriteServ(user->fd,"451 %s :You have not registered",command);
4644 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4646 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4647 if (cmdlist[i].handler_function)
4649 /* ikky /stats counters */
4654 user->bytes_in += strlen(temp);
4657 cmdlist[i].use_count++;
4658 cmdlist[i].total_bytes+=strlen(temp);
4661 /* WARNING: nothing may come after the
4662 * command handler call, as the handler
4663 * may free the user structure! */
4665 cmdlist[i].handler_function(command_p,items,user);
4671 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4672 WriteServ(user->fd,"451 %s :You have not registered",command);
4680 if ((!cmd_found) && (user))
4682 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4683 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4688 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4691 /* create the command and push it onto the table */
4692 strcpy(comm.command,cmd);
4693 comm.handler_function = f;
4694 comm.flags_needed = flags;
4695 comm.min_params = minparams;
4697 comm.total_bytes = 0;
4698 cmdlist.push_back(comm);
4699 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4702 void SetupCommandTable(void)
4704 createcommand("USER",handle_user,0,4);
4705 createcommand("NICK",handle_nick,0,1);
4706 createcommand("QUIT",handle_quit,0,0);
4707 createcommand("VERSION",handle_version,0,0);
4708 createcommand("PING",handle_ping,0,1);
4709 createcommand("PONG",handle_pong,0,1);
4710 createcommand("ADMIN",handle_admin,0,0);
4711 createcommand("PRIVMSG",handle_privmsg,0,2);
4712 createcommand("INFO",handle_info,0,0);
4713 createcommand("TIME",handle_time,0,0);
4714 createcommand("WHOIS",handle_whois,0,1);
4715 createcommand("WALLOPS",handle_wallops,'o',1);
4716 createcommand("NOTICE",handle_notice,0,2);
4717 createcommand("JOIN",handle_join,0,1);
4718 createcommand("NAMES",handle_names,0,1);
4719 createcommand("PART",handle_part,0,1);
4720 createcommand("KICK",handle_kick,0,2);
4721 createcommand("MODE",handle_mode,0,1);
4722 createcommand("TOPIC",handle_topic,0,1);
4723 createcommand("WHO",handle_who,0,1);
4724 createcommand("MOTD",handle_motd,0,0);
4725 createcommand("RULES",handle_join,0,0);
4726 createcommand("OPER",handle_oper,0,2);
4727 createcommand("LIST",handle_list,0,0);
4728 createcommand("DIE",handle_die,'o',1);
4729 createcommand("RESTART",handle_restart,'o',1);
4730 createcommand("KILL",handle_kill,'o',2);
4731 createcommand("REHASH",handle_rehash,'o',0);
4732 createcommand("LUSERS",handle_lusers,0,0);
4733 createcommand("STATS",handle_stats,0,1);
4734 createcommand("USERHOST",handle_userhost,0,1);
4735 createcommand("AWAY",handle_away,0,0);
4736 createcommand("ISON",handle_ison,0,0);
4737 createcommand("SUMMON",handle_summon,0,0);
4738 createcommand("USERS",handle_users,0,0);
4739 createcommand("INVITE",handle_invite,0,2);
4740 createcommand("PASS",handle_pass,0,1);
4741 createcommand("TRACE",handle_trace,'o',0);
4742 createcommand("WHOWAS",handle_whowas,0,1);
4743 createcommand("CONNECT",handle_connect,'o',1);
4744 createcommand("SQUIT",handle_squit,'o',1);
4745 createcommand("MODULES",handle_modules,'o',0);
4748 void process_buffer(userrec *user)
4752 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4759 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4762 if (!strcmp(user->inbuf,""))
4766 strncpy(cmd,user->inbuf,MAXBUF);
4767 if (!strcmp(cmd,""))
4771 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4773 cmd[strlen(cmd)-1] = '\0';
4775 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4777 cmd[strlen(cmd)-1] = '\0';
4779 strcpy(user->inbuf,"");
4780 if (!strcmp(cmd,""))
4784 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4788 process_command(user,cmd);
4792 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4794 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4798 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4800 char response[10240];
4801 char token = udp_msg[0];
4802 char* params = udp_msg + 2;
4803 char finalparam[1024];
4804 strcpy(finalparam," :xxxx");
4805 if (strstr(params," :")) {
4806 strncpy(finalparam,strstr(params," :"),1024);
4809 // S test.chatspike.net password :ChatSpike InspIRCd test server
4810 char* servername = strtok(params," ");
4811 char* password = strtok(NULL," ");
4812 char* serverdesc = finalparam+2;
4813 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4816 char Link_ServerName[1024];
4817 char Link_IPAddr[1024];
4818 char Link_Port[1024];
4819 char Link_Pass[1024];
4820 char Link_SendPass[1024];
4823 // search for a corresponding <link> block in the config files
4824 for (int i = 0; i < ConfValueEnum("link"); i++)
4826 ConfValue("link","name",i,Link_ServerName);
4827 ConfValue("link","ipaddr",i,Link_IPAddr);
4828 ConfValue("link","port",i,Link_Port);
4829 ConfValue("link","recvpass",i,Link_Pass);
4830 ConfValue("link","sendpass",i,Link_SendPass);
4831 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4832 LinkPort = atoi(Link_Port);
4833 if (!strcasecmp(Link_ServerName,servername)) {
4834 if (!strcasecmp(Link_IPAddr,udp_host)) {
4835 if (LinkPort == udp_port) {
4836 // we have a matching link line -
4837 // send a 'diminutive' server message back...
4838 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4839 serv->SendPacket(response,udp_host,udp_port,0);
4840 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4841 for (int j = 0; j < 255; j++) {
4842 if (servers[j] == NULL) {
4843 servers[j] = new serverrec;
4844 strcpy(servers[j]->internal_addr,udp_host);
4845 strcpy(servers[j]->name,servername);
4846 // create a server record for this server
4847 snprintf(response,10240,"O %d",MyKey);
4848 serv->SendPacket(response,udp_host,udp_port,0);
4852 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4856 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4860 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4864 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4867 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4868 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4873 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4874 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4875 // array, which is only added by an 'S' packet or BeginLink().
4876 for (int i = 0; i < 255; i++) {
4877 if (servers[i] != NULL) {
4878 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4879 servers[i]->key = atoi(params);
4880 log(DEBUG,"Key for this server is now %d",servers[i]->key);
4881 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4886 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4890 // S test.chatspike.net password :ChatSpike InspIRCd test server
4891 char* servername = strtok(params," ");
4892 char* password = strtok(NULL," ");
4893 char* serverdesc = finalparam+2;
4895 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4896 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4897 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4898 // a connect, so put out an oper alert!
4903 // for now, just accept all, we'll fix that later.
4904 WriteOpers("%s accepted our link credentials ",servername);
4906 char Link_ServerName[1024];
4907 char Link_IPAddr[1024];
4908 char Link_Port[1024];
4909 char Link_Pass[1024];
4910 char Link_SendPass[1024];
4913 // search for a corresponding <link> block in the config files
4914 for (int i = 0; i < ConfValueEnum("link"); i++)
4916 ConfValue("link","name",i,Link_ServerName);
4917 ConfValue("link","ipaddr",i,Link_IPAddr);
4918 ConfValue("link","port",i,Link_Port);
4919 ConfValue("link","recvpass",i,Link_Pass);
4920 ConfValue("link","sendpass",i,Link_SendPass);
4921 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4922 LinkPort = atoi(Link_Port);
4923 if (!strcasecmp(Link_ServerName,servername)) {
4924 if (!strcasecmp(Link_IPAddr,udp_host)) {
4925 if (LinkPort == udp_port) {
4926 // matching link at this end too, we're all done!
4927 // at this point we must begin key exchange and insert this
4928 // server into our 'active' table.
4929 for (int j = 0; j < 255; j++) {
4930 if (servers[j] != NULL) {
4931 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4932 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4933 snprintf(response,10240,"O %d",MyKey);
4934 serv->SendPacket(response,udp_host,udp_port,0);
4939 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4944 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4948 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4952 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4955 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4956 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4961 char* error_message = finalparam+2;
4962 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4963 // remove this server from any lists
4964 for (int j = 0; j < 255; j++) {
4965 if (servers[j] != NULL) {
4966 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4976 serverrec* source_server = NULL;
4978 for (int j = 0; j < 255; j++) {
4979 if (servers[j] != NULL) {
4980 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4981 if (servers[j]->key == theirkey) {
4982 // found a valid key for this server, can process restricted stuff here
4983 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4991 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4995 int reap_counter = 0;
4999 struct sockaddr_in client, server;
5000 char addrs[MAXBUF][255];
5001 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5003 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5004 int selectResult = 0;
5005 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5006 char resolvedHost[MAXBUF];
5010 log_file = fopen("ircd.log","a+");
5013 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5017 log(DEBUG,"InspIRCd: startup: begin");
5021 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5023 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5025 SetupCommandTable();
5026 log(DEBUG,"InspIRCd: startup: default command table set up");
5029 if (strcmp(DieValue,""))
5031 printf("WARNING: %s\n\n",DieValue);
5034 log(DEBUG,"InspIRCd: startup: read config");
5036 int count2 = 0, count3 = 0;
5037 for (count = 0; count < ConfValueEnum("bind"); count++)
5039 ConfValue("bind","port",count,configToken);
5040 ConfValue("bind","address",count,Addr);
5041 ConfValue("bind","type",count,Type);
5042 if (!strcmp(Type,"servers"))
5044 char Default[MAXBUF];
5045 strcpy(Default,"no");
5046 ConfValue("bind","default",count,Default);
5047 if (strchr(Default,'y'))
5049 defaultRoute = count3;
5050 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5052 me[count3] = new serverrec(ServerName,100L,false);
5053 me[count3]->CreateListener(Addr,atoi(configToken));
5058 ports[count2] = atoi(configToken);
5059 strcpy(addrs[count2],Addr);
5062 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5065 UDPportCount = count3;
5067 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5069 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5073 /* BugFix By Craig! :p */
5075 for (count = 0; count2 < ConfValueEnum("module"); count2++)
5077 char modfile[MAXBUF];
5078 ConfValue("module","name",count,configToken);
5079 sprintf(modfile,"%s/%s",MOD_PATH,configToken);
5080 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5081 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5082 /* If The File Doesnt exist, Trying to load it
5083 * Will Segfault the IRCd.. So, check to see if
5084 * it Exists, Before Proceeding. */
5085 if (FileExists(modfile))
5087 factory[count] = new ircd_module(modfile);
5088 if (factory[count]->LastError())
5090 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5091 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5094 if (factory[count]->factory)
5096 modules[count] = factory[count]->factory->CreateModule();
5097 /* save the module and the module's classfactory, if
5098 * this isnt done, random crashes can occur :/ */
5099 module_names.push_back(modfile);
5103 log(DEBUG,"Unable to load %s",modfile);
5104 sprintf("Unable to load %s\nExiting...\n",modfile);
5107 /* Increase the Count */
5112 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5113 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5116 MODCOUNT = count - 1;
5117 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5119 printf("\nInspIRCd is now running!\n");
5121 startup_time = time(NULL);
5125 log(VERBOSE,"Not forking as -nofork was specified");
5129 if (DaemonSeed() == ERROR)
5131 log(DEBUG,"InspIRCd: startup: can't daemonise");
5132 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5138 /* setup select call */
5139 FD_ZERO(&selectFds);
5140 log(DEBUG,"InspIRCd: startup: zero selects");
5141 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5143 for (count = 0; count < portCount; count++)
5145 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5147 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5150 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5152 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5154 else /* well we at least bound to one socket so we'll continue */
5160 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5162 /* if we didn't bind to anything then abort */
5163 if (boundPortCount == 0)
5165 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5169 length = sizeof (client);
5170 int flip_flop = 0, udp_port = 0;
5171 char udp_msg[MAXBUF], udp_host[MAXBUF];
5173 /* main loop for multiplexing/resetting */
5176 /* set up select call */
5177 for (count = 0; count < boundPortCount; count++)
5179 FD_SET (openSockfd[count], &selectFds);
5182 /* added timeout! select was waiting forever... wank... :/ */
5193 vector<int>::iterator niterator;
5196 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5197 // them in a list, then reap the list every second or so.
5198 if (reap_counter>5000) {
5199 if (fd_reap.size() > 0) {
5200 for( int n = 0; n < fd_reap.size(); n++)
5202 Blocking(fd_reap[n]);
5204 NonBlocking(fd_reap[n]);
5213 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5215 for (int x = 0; x != UDPportCount; x++)
5218 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5220 if (strlen(udp_msg)<1) {
5221 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5224 FOREACH_MOD OnPacketReceive(udp_msg);
5225 // Packets must go back via the route they arrived on :)
5226 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5231 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5235 if (!count2->second) break;
5238 if (count2->second->fd)
5240 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5242 if (!count2->second->lastping)
5244 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5245 kill_link(count2->second,"Ping timeout");
5248 Write(count2->second->fd,"PING :%s",ServerName);
5249 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5250 count2->second->lastping = 0;
5251 count2->second->nping = time(NULL)+120;
5254 result = read(count2->second->fd, data, 1);
5255 // result EAGAIN means nothing read
5256 if (result == EAGAIN)
5264 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5265 kill_link(count2->second,"Client exited");
5266 // must bail here? kill_link removes the hash, corrupting the iterator
5267 log(DEBUG,"Bailing from client exit");
5271 else if (result > 0)
5276 // until the buffer is at 509 chars anything can be inserted into it.
5277 if (strlen(count2->second->inbuf) < 509) {
5278 strncat(count2->second->inbuf, data, result);
5281 // once you reach 509 chars, only a \r or \n can be inserted,
5282 // completing the line.
5283 if ((strlen(count2->second->inbuf) >= 509) && ((data[0] == '\r') || (data[0] == '\n'))) {
5284 count2->second->inbuf[509] = '\r';
5285 count2->second->inbuf[510] = '\n';
5286 count2->second->inbuf[511] = '\0';
5289 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5291 /* at least one complete line is waiting to be processed */
5292 if (!count2->second->fd)
5296 if (strlen(count2->second->inbuf)<513)
5298 // double check the length before processing!
5299 process_buffer(count2->second);
5309 /* select is reporting a waiting socket. Poll them all to find out which */
5310 if (selectResult > 0)
5312 char target[MAXBUF], resolved[MAXBUF];
5313 for (count = 0; count < boundPortCount; count++)
5315 if (FD_ISSET (openSockfd[count], &selectFds))
5317 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5319 address_cache::iterator iter = IP.find(client.sin_addr);
5320 bool iscached = false;
5321 if (iter == IP.end())
5323 /* ip isn't in cache, add it */
5324 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5325 if(CleanAndResolve(resolved, target) != TRUE)
5327 strncpy(resolved,target,MAXBUF);
5329 /* hostname now in 'target' */
5330 IP[client.sin_addr] = new string(resolved);
5331 /* hostname in cache */
5335 /* found ip (cached) */
5336 strncpy(resolved, iter->second->c_str(), MAXBUF);
5340 if (incomingSockfd < 0)
5342 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5343 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5347 AddClient(incomingSockfd, resolved, ports[count], iscached);
5348 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5357 close (incomingSockfd);