1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2003 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 extern vector<ircd_module*> factory;
88 template<> struct nspace::hash<in_addr>
90 size_t operator()(const struct in_addr &a) const
93 memcpy(&q,&a,sizeof(size_t));
98 template<> struct nspace::hash<string>
100 size_t operator()(const string &s) const
103 static struct hash<const char *> strhash;
115 bool operator()(const string& s1, const string& s2) const
117 char a[MAXBUF],b[MAXBUF];
118 strcpy(a,s1.c_str());
119 strcpy(b,s2.c_str());
120 return (strcasecmp(a,b) == 0);
125 struct InAddr_HashComp
128 bool operator()(const in_addr &s1, const in_addr &s2) const
133 memcpy(&q,&s1,sizeof(size_t));
134 memcpy(&p,&s2,sizeof(size_t));
142 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
143 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
144 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
145 typedef std::deque<command_t> command_table;
148 serverrec* servers[255];
150 user_hash clientlist;
153 command_table cmdlist;
160 struct linger linger = { 0 };
161 char bannerBuffer[MAXBUF];
162 int boundPortCount = 0;
163 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
164 int defaultRoute = 0;
168 long MyKey = C.GenKey();
172 int has_channel(userrec *u, chanrec *c);
173 int usercount(chanrec *c);
174 int usercount_i(chanrec *c);
175 void update_stats_l(int fd,int data_out);
176 char* Passwd(userrec *user);
177 bool IsDenied(userrec *user);
178 void AddWhoWas(userrec* u);
181 void safedelete(userrec *p)
185 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
186 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
191 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
195 void safedelete(chanrec *p)
200 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
204 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
209 /* chop a string down to 512 characters and preserve linefeed (irc max
216 FOREACH_MOD OnServerRaw(temp,false);
217 const char* str2 = temp.c_str();
218 sprintf(str,"%s",str2);
221 if (strlen(str) > 512)
230 std::string getservername()
235 std::string getserverdesc()
240 std::string getnetworkname()
245 std::string getadminname()
250 std::string getadminemail()
255 std::string getadminnick()
260 void log(int level,char *text, ...)
262 char textbuffer[MAXBUF];
266 struct tm * timeinfo;
267 if (level < LogLevel)
271 timeinfo = localtime (&rawtime);
273 f = fopen("ircd.log","a+");
277 va_start (argsPtr, text);
278 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
280 strcpy(b,asctime(timeinfo));
281 b[strlen(b)-1] = ':';
282 fprintf(f,"%s %s\n",b,textbuffer);
286 // nofork enabled? display it on terminal too
287 printf("%s %s\n",b,textbuffer);
292 printf("Can't write log file, bailing!!!");
297 void readfile(file_cache &F, const char* fname)
300 char linebuf[MAXBUF];
302 log(DEBUG,"readfile: loading %s",fname);
304 file = fopen(fname,"r");
309 fgets(linebuf,sizeof(linebuf),file);
310 linebuf[strlen(linebuf)-1]='\0';
311 if (!strcmp(linebuf,""))
317 F.push_back(linebuf);
324 log(DEBUG,"readfile: failed to load file: %s",fname);
326 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
329 void ReadConfig(void)
331 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
334 ConfValue("server","name",0,ServerName);
335 ConfValue("server","description",0,ServerDesc);
336 ConfValue("server","network",0,Network);
337 ConfValue("admin","name",0,AdminName);
338 ConfValue("admin","email",0,AdminEmail);
339 ConfValue("admin","nick",0,AdminNick);
340 ConfValue("files","motd",0,motd);
341 ConfValue("files","rules",0,rules);
342 ConfValue("power","diepass",0,diepass);
343 ConfValue("power","pause",0,pauseval);
344 ConfValue("power","restartpass",0,restartpass);
345 ConfValue("options","prefixquit",0,PrefixQuit);
346 ConfValue("die","value",0,DieValue);
347 ConfValue("options","loglevel",0,dbg);
348 if (!strcmp(dbg,"debug"))
350 if (!strcmp(dbg,"verbose"))
352 if (!strcmp(dbg,"default"))
354 if (!strcmp(dbg,"sparse"))
356 if (!strcmp(dbg,"none"))
358 readfile(RULES,rules);
359 log(DEBUG,"Reading connect classes");
361 for (int i = 0; i < ConfValueEnum("connect"); i++)
364 ConfValue("connect","allow",i,Value);
365 if (strcmp(Value,""))
367 strcpy(c.host,Value);
370 ConfValue("connect","password",i,Value);
371 strcpy(c.pass,Value);
372 Classes.push_back(c);
373 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
377 ConfValue("connect","deny",i,Value);
378 strcpy(c.host,Value);
380 Classes.push_back(c);
381 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
390 log(DEBUG,"Blocking: %d",s);
391 flags = fcntl(s, F_GETFL, 0);
392 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
395 void NonBlocking(int s)
398 log(DEBUG,"NonBlocking: %d",s);
399 flags = fcntl(s, F_GETFL, 0);
400 fcntl(s, F_SETFL, flags | O_NONBLOCK);
404 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
406 struct hostent *hostPtr = NULL;
409 memset (resolvedHost, '\0',MAXBUF);
410 if(unresolvedHost == NULL)
412 if ((inet_aton(unresolvedHost,&addr)) == 0)
414 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
416 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
418 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
422 /* write formatted text to a socket, in same format as printf */
424 void Write(int sock,char *text, ...)
426 char textbuffer[MAXBUF];
430 va_start (argsPtr, text);
431 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
433 sprintf(tb,"%s\r\n",textbuffer);
435 write(sock,tb,strlen(tb));
436 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
439 /* write a server formatted numeric response to a single socket */
441 void WriteServ(int sock, char* text, ...)
443 char textbuffer[MAXBUF],tb[MAXBUF];
445 va_start (argsPtr, text);
447 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
449 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
451 write(sock,tb,strlen(tb));
452 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
455 /* write text from an originating user to originating user */
457 void WriteFrom(int sock, userrec *user,char* text, ...)
459 char textbuffer[MAXBUF],tb[MAXBUF];
461 va_start (argsPtr, text);
463 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
465 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
467 write(sock,tb,strlen(tb));
468 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
471 /* write text to an destination user from a source user (e.g. user privmsg) */
473 void WriteTo(userrec *source, userrec *dest,char *data, ...)
475 char textbuffer[MAXBUF],tb[MAXBUF];
477 va_start (argsPtr, data);
478 if ((!dest) || (!source))
482 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
485 WriteFrom(dest->fd,source,"%s",textbuffer);
488 /* write formatted text from a source user to all users on a channel
489 * including the sender (NOT for privmsg, notice etc!) */
491 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
493 char textbuffer[MAXBUF];
495 va_start (argsPtr, text);
496 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
498 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
500 if (has_channel(i->second,Ptr))
502 WriteTo(user,i->second,"%s",textbuffer);
507 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
509 char textbuffer[MAXBUF];
511 va_start (argsPtr, text);
512 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
514 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
516 if (has_channel(i->second,Ptr))
518 WriteServ(i->second->fd,"%s",textbuffer);
524 /* write formatted text from a source user to all users on a channel except
525 * for the sender (for privmsg etc) */
527 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
529 char textbuffer[MAXBUF];
531 va_start (argsPtr, text);
532 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
535 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
537 if (has_channel(i->second,Ptr) && (user != i->second))
539 WriteTo(user,i->second,"%s",textbuffer);
544 int c_count(userrec* u)
547 for (int i =0; i != MAXCHANS; i++)
548 if (u->chans[i].channel)
554 /* return 0 or 1 depending if users u and u2 share one or more common channels
555 * (used by QUIT, NICK etc which arent channel specific notices) */
557 int common_channels(userrec *u, userrec *u2)
566 for (i = 0; i != MAXCHANS; i++)
568 for (z = 0; z != MAXCHANS; z++)
570 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
572 if ((c_count(u)) && (c_count(u2)))
582 /* write a formatted string to all users who share at least one common
583 * channel, including the source user e.g. for use in NICK */
585 void WriteCommon(userrec *u, char* text, ...)
587 char textbuffer[MAXBUF];
589 va_start (argsPtr, text);
590 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
593 WriteFrom(u->fd,u,"%s",textbuffer);
595 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
597 if (common_channels(u,i->second) && (i->second != u))
599 WriteFrom(i->second->fd,u,"%s",textbuffer);
604 /* write a formatted string to all users who share at least one common
605 * channel, NOT including the source user e.g. for use in QUIT */
607 void WriteCommonExcept(userrec *u, char* text, ...)
609 char textbuffer[MAXBUF];
611 va_start (argsPtr, text);
612 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
615 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
617 if ((common_channels(u,i->second)) && (u != i->second))
619 WriteFrom(i->second->fd,u,"%s",textbuffer);
624 void WriteOpers(char* text, ...)
626 char textbuffer[MAXBUF];
628 va_start (argsPtr, text);
629 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
632 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
634 if (strchr(i->second->modes,'o'))
636 if (strchr(i->second->modes,'s'))
638 // send server notices to all with +s
639 // (TODO: needs SNOMASKs)
640 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
646 void WriteWallOps(userrec *source, char* text, ...)
649 char textbuffer[MAXBUF];
651 va_start (argsPtr, text);
652 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
655 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
657 if (strchr(i->second->modes,'w'))
659 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
664 /* convert a string to lowercase. Note following special circumstances
665 * taken from RFC 1459. Many "official" server branches still hold to this
666 * rule so i will too;
668 * Because of IRC's scandanavian origin, the characters {}| are
669 * considered to be the lower case equivalents of the characters []\,
670 * respectively. This is a critical issue when determining the
671 * equivalence of two nicknames.
674 void strlower(char *n)
680 for (int i = 0; i != strlen(n); i++)
682 n[i] = tolower(n[i]);
692 /* verify that a user's ident and nickname is valid */
694 int isident(const char* n)
707 for (i = 0; i != strlen(n); i++)
709 if ((n[i] < 33) || (n[i] > 125))
713 /* can't occur ANYWHERE in an Ident! */
714 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
723 int isnick(const char* n)
735 if (strlen(n) > NICKMAX-1)
739 for (i = 0; i != strlen(n); i++)
741 if ((n[i] < 33) || (n[i] > 125))
745 /* can't occur ANYWHERE in a nickname! */
746 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
750 /* can't occur as the first char of a nickname... */
751 if ((strchr("0123456789",n[i])) && (!i))
759 /* Find a user record by nickname and return a pointer to it */
761 userrec* Find(string nick)
763 user_hash::iterator iter = clientlist.find(nick);
765 if (iter == clientlist.end())
766 /* Couldn't find it */
772 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
774 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
776 if (i->second->fd == fd)
778 i->second->bytes_out+=data_out;
779 i->second->cmds_out++;
785 /* find a channel record by channel name and return a pointer to it */
787 chanrec* FindChan(const char* chan)
789 chan_hash::iterator iter = chanlist.find(chan);
791 if (iter == chanlist.end())
792 /* Couldn't find it */
799 void purge_empty_chans(void)
801 int go_again = 1, purge = 0;
806 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
809 if (!usercount(i->second))
811 /* kill the record */
812 if (i != chanlist.end())
814 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
825 log(DEBUG,"completed channel purge, killed %d",purge);
828 /* returns the status character for a given user on a channel, e.g. @ for op,
829 * % for halfop etc. If the user has several modes set, the highest mode
830 * the user has must be returned. */
832 char* cmode(userrec *user, chanrec *chan)
835 for (i = 0; i != MAXCHANS; i++)
837 if ((user->chans[i].channel == chan) && (chan != NULL))
839 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
843 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
847 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
856 char scratch[MAXMODES];
858 char* chanmodes(chanrec *chan)
861 if (chan->noexternal)
869 if (strcmp(chan->key,""))
877 if (chan->inviteonly)
893 if (strcmp(chan->key,""))
896 strcat(scratch,chan->key);
901 sprintf(foo," %d",chan->limit);
904 log(DEBUG,"chanmodes: %s %s",chan->name,scratch);
908 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
909 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
910 * highest mode the user has must be returned. */
912 int cstatus(userrec *user, chanrec *chan)
915 for (i = 0; i != MAXCHANS; i++)
917 if ((user->chans[i].channel == chan) && (chan != NULL))
919 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
923 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
927 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
931 return STATUS_NORMAL;
937 /* compile a userlist of a channel into a string, each nick seperated by
938 * spaces and op, voice etc status shown as @ and + */
940 void userlist(userrec *user,chanrec *c)
942 sprintf(list,"353 %s = %s :", user->nick, c->name);
943 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
945 if (has_channel(i->second,c))
947 if (isnick(i->second->nick))
949 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
951 /* user is +i, and source not on the channel, does not show
952 * nick in NAMES list */
955 strcat(list,cmode(i->second,c));
956 strcat(list,i->second->nick);
958 if (strlen(list)>(480-NICKMAX))
960 /* list overflowed into
961 * multiple numerics */
962 WriteServ(user->fd,list);
963 sprintf(list,"353 %s = %s :", user->nick, c->name);
968 /* if whats left in the list isnt empty, send it */
969 if (list[strlen(list)-1] != ':')
971 WriteServ(user->fd,list);
975 /* return a count of the users on a specific channel accounting for
976 * invisible users who won't increase the count. e.g. for /LIST */
978 int usercount_i(chanrec *c)
984 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
988 if (has_channel(i->second,c))
990 if (isnick(i->second->nick))
992 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
994 /* user is +i, and source not on the channel, does not show
995 * nick in NAMES list */
1003 log(DEBUG,"usercount_i: %s %d",c->name,count);
1008 int usercount(chanrec *c)
1014 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1018 if (has_channel(i->second,c))
1020 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1027 log(DEBUG,"usercount: %s %d",c->name,count);
1032 /* add a channel to a user, creating the record for it if needed and linking
1033 * it to the user record */
1035 chanrec* add_channel(userrec *user, char* cname, char* key)
1041 if ((!cname) || (!user))
1045 if (strlen(cname) > CHANMAX-1)
1047 cname[CHANMAX-1] = '\0';
1050 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1052 if ((has_channel(user,FindChan(cname))) && (FindChan(cname)))
1054 return NULL; // already on the channel!
1057 if (!FindChan(cname))
1059 /* create a new one */
1060 log(DEBUG,"add_channel: creating: %s",cname);
1062 chanlist[cname] = new chanrec();
1064 strcpy(chanlist[cname]->name, cname);
1065 chanlist[cname]->topiclock = 1;
1066 chanlist[cname]->noexternal = 1;
1067 chanlist[cname]->created = time(NULL);
1068 strcpy(chanlist[cname]->topic, "");
1069 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1070 chanlist[cname]->topicset = 0;
1071 Ptr = chanlist[cname];
1072 log(DEBUG,"add_channel: created: %s",cname);
1073 /* set created to 2 to indicate user
1074 * is the first in the channel
1075 * and should be given ops */
1081 /* channel exists, just fish out a pointer to its struct */
1082 Ptr = FindChan(cname);
1085 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1086 if (strcmp(Ptr->key,""))
1088 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1091 log(DEBUG,"add_channel: no key given in JOIN");
1092 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1097 log(DEBUG,"key at %p is %s",key,key);
1098 if (strcasecmp(key,Ptr->key))
1100 log(DEBUG,"add_channel: bad key given in JOIN");
1101 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1106 log(DEBUG,"add_channel: no key");
1108 if (Ptr->inviteonly)
1110 log(DEBUG,"add_channel: channel is +i");
1111 if (user->IsInvited(Ptr->name))
1113 /* user was invited to channel */
1114 /* there may be an optional channel NOTICE here */
1118 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1122 log(DEBUG,"add_channel: channel is not +i");
1126 if (usercount(Ptr) == Ptr->limit)
1128 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1133 log(DEBUG,"add_channel: about to walk banlist");
1135 /* check user against the channel banlist */
1136 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1138 if (match(user->GetFullHost(),i->data))
1140 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1145 log(DEBUG,"add_channel: bans checked");
1147 user->RemoveInvite(Ptr->name);
1149 log(DEBUG,"add_channel: invites removed");
1155 log(DEBUG,"Passed channel checks");
1157 for (i =0; i != MAXCHANS; i++)
1159 if (user->chans[i].channel == NULL)
1161 log(DEBUG,"Adding into their channel list");
1165 /* first user in is given ops */
1166 user->chans[i].uc_modes = UCMODE_OP;
1170 user->chans[i].uc_modes = 0;
1172 user->chans[i].channel = Ptr;
1173 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1175 log(DEBUG,"Sent JOIN to client");
1179 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1180 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1183 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1184 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1185 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1186 FOREACH_MOD OnUserJoin(user,Ptr);
1190 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1191 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1195 /* remove a channel from a users record, and remove the record from memory
1196 * if the channel has become empty */
1198 chanrec* del_channel(userrec *user, char* cname, char* reason)
1204 if ((!cname) || (!user))
1209 Ptr = FindChan(cname);
1216 FOREACH_MOD OnUserPart(user,Ptr);
1217 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1219 for (i =0; i != MAXCHANS; i++)
1221 /* zap it from the channel list of the user */
1222 if (user->chans[i].channel == Ptr)
1226 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1230 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1232 user->chans[i].uc_modes = 0;
1233 user->chans[i].channel = NULL;
1234 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1239 /* if there are no users left on the channel */
1240 if (!usercount(Ptr))
1242 chan_hash::iterator iter = chanlist.find(Ptr->name);
1244 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1246 /* kill the record */
1247 if (iter != chanlist.end())
1249 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1250 delete iter->second;
1251 chanlist.erase(iter);
1257 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1262 if ((!Ptr) || (!user) || (!src))
1267 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1269 if (!has_channel(user,Ptr))
1271 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1274 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1276 if (cstatus(src,Ptr) == STATUS_HOP)
1278 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1282 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1288 for (i =0; i != MAXCHANS; i++)
1290 /* zap it from the channel list of the user */
1291 if (user->chans[i].channel == Ptr)
1293 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1294 user->chans[i].uc_modes = 0;
1295 user->chans[i].channel = NULL;
1296 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1301 /* if there are no users left on the channel */
1302 if (!usercount(Ptr))
1304 chan_hash::iterator iter = chanlist.find(Ptr->name);
1306 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1308 /* kill the record */
1309 if (iter != chanlist.end())
1311 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1312 delete iter->second;
1313 chanlist.erase(iter);
1319 /* returns 1 if user u has channel c in their record, 0 if not */
1321 int has_channel(userrec *u, chanrec *c)
1329 for (i =0; i != MAXCHANS; i++)
1331 if (u->chans[i].channel == c)
1339 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1344 if ((!user) || (!dest) || (!chan))
1348 if (status != STATUS_OP)
1350 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1357 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1363 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1368 for (i = 0; i != MAXCHANS; i++)
1370 if ((d->chans[i].channel == chan) && (chan != NULL))
1372 if (d->chans[i].uc_modes & UCMODE_OP)
1374 /* mode already set on user, dont allow multiple */
1377 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1378 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1386 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1391 if ((!user) || (!dest) || (!chan))
1395 if (status != STATUS_OP)
1397 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1405 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1410 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1415 for (i = 0; i != MAXCHANS; i++)
1417 if ((d->chans[i].channel == chan) && (chan != NULL))
1419 if (d->chans[i].uc_modes & UCMODE_HOP)
1421 /* mode already set on user, dont allow multiple */
1424 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1425 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1433 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1438 if ((!user) || (!dest) || (!chan))
1442 if (status < STATUS_HOP)
1444 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1452 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1457 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1462 for (i = 0; i != MAXCHANS; i++)
1464 if ((d->chans[i].channel == chan) && (chan != NULL))
1466 if (d->chans[i].uc_modes & UCMODE_VOICE)
1468 /* mode already set on user, dont allow multiple */
1471 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1472 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1480 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1485 if ((!user) || (!dest) || (!chan))
1489 if (status != STATUS_OP)
1491 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1499 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1504 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1509 for (i = 0; i != MAXCHANS; i++)
1511 if ((d->chans[i].channel == chan) && (chan != NULL))
1513 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1515 /* mode already set on user, dont allow multiple */
1518 d->chans[i].uc_modes ^= UCMODE_OP;
1519 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1527 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1532 if ((!user) || (!dest) || (!chan))
1536 if (status != STATUS_OP)
1538 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1546 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1551 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1556 for (i = 0; i != MAXCHANS; i++)
1558 if ((d->chans[i].channel == chan) && (chan != NULL))
1560 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1562 /* mode already set on user, dont allow multiple */
1565 d->chans[i].uc_modes ^= UCMODE_HOP;
1566 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1574 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1579 if ((!user) || (!dest) || (!chan))
1583 if (status < STATUS_HOP)
1585 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1593 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1598 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1603 for (i = 0; i != MAXCHANS; i++)
1605 if ((d->chans[i].channel == chan) && (chan != NULL))
1607 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1609 /* mode already set on user, dont allow multiple */
1612 d->chans[i].uc_modes ^= UCMODE_VOICE;
1613 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1621 void TidyBan(char *ban)
1623 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1627 char* pos_of_pling = strchr(temp,'!');
1628 char* pos_of_at = strchr(temp,'@');
1630 pos_of_pling[0] = '\0';
1631 pos_of_at[0] = '\0';
1635 strncpy(NICK,temp,NICKMAX);
1636 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1637 strncpy(HOST,pos_of_at,160);
1639 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1642 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1645 if ((!user) || (!dest) || (!chan))
1647 if (strchr(dest,'!')==0)
1649 if (strchr(dest,'@')==0)
1651 for (int i = 0; i < strlen(dest); i++)
1654 for (int i = 0; i < strlen(dest); i++)
1658 for (int i = 0; i < strlen(dest); i++)
1664 for (int i = 0; i < strlen(dest); i++)
1669 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1672 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1674 if (!strcasecmp(i->data,dest))
1676 // dont allow a user to set the same ban twice
1681 b.set_time = time(NULL);
1682 strncpy(b.data,dest,MAXBUF);
1683 strncpy(b.set_by,user->nick,NICKMAX);
1684 chan->bans.push_back(b);
1688 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1690 if ((!user) || (!dest) || (!chan))
1695 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1696 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1698 if (!strcasecmp(i->data,dest))
1700 chan->bans.erase(i);
1707 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1709 char modelist[MAXBUF];
1710 char outlist[MAXBUF];
1711 char outstr[MAXBUF];
1712 char outpars[32][MAXBUF];
1718 bool k_set = false, l_set = false;
1725 log(DEBUG,"process_modes: start");
1727 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1728 /* parameters[2] onwards are parameters for
1729 * modes that require them :) */
1730 strcpy(outlist,"+");
1733 log(DEBUG,"process_modes: modelist: %s",modelist);
1735 for (ptr = 0; ptr < strlen(modelist); ptr++)
1740 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1741 char modechar = modelist[ptr];
1742 switch (modelist[ptr])
1747 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1749 outlist[strlen(outlist)-1] = '-';
1753 strcat(outlist,"-");
1763 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1765 outlist[strlen(outlist)-1] = '+';
1769 strcat(outlist,"+");
1776 if ((param >= pcnt)) break;
1779 r = give_ops(user,parameters[param++],chan,status);
1783 r = take_ops(user,parameters[param++],chan,status);
1787 strcat(outlist,"o");
1788 strcpy(outpars[pc++],parameters[param-1]);
1793 if ((param >= pcnt)) break;
1796 r = give_hops(user,parameters[param++],chan,status);
1800 r = take_hops(user,parameters[param++],chan,status);
1804 strcat(outlist,"h");
1805 strcpy(outpars[pc++],parameters[param-1]);
1811 if ((param >= pcnt)) break;
1814 r = give_voice(user,parameters[param++],chan,status);
1818 r = take_voice(user,parameters[param++],chan,status);
1822 strcat(outlist,"v");
1823 strcpy(outpars[pc++],parameters[param-1]);
1828 if ((param >= pcnt)) break;
1831 r = add_ban(user,parameters[param++],chan,status);
1835 r = take_ban(user,parameters[param++],chan,status);
1839 strcat(outlist,"b");
1840 strcpy(outpars[pc++],parameters[param-1]);
1845 if ((param >= pcnt))
1853 if (!strcmp(chan->key,""))
1855 strcat(outlist,"k");
1856 strcpy(outpars[pc++],parameters[param++]);
1857 strcpy(chan->key,parameters[param-1]);
1863 /* only allow -k if correct key given */
1864 if (strcmp(chan->key,""))
1866 strcat(outlist,"k");
1867 strcpy(chan->key,"");
1877 strcat(outlist,"l");
1882 if ((param >= pcnt)) break;
1888 bool invalid = false;
1889 for (int i = 0; i < strlen(parameters[param]); i++)
1891 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
1896 if (atoi(parameters[param]) < 1)
1904 chan->limit = atoi(parameters[param]);
1907 strcat(outlist,"l");
1908 strcpy(outpars[pc++],parameters[param++]);
1915 if (chan->inviteonly != mdir)
1917 strcat(outlist,"i");
1919 chan->inviteonly = mdir;
1923 if (chan->topiclock != mdir)
1925 strcat(outlist,"t");
1927 chan->topiclock = mdir;
1931 if (chan->noexternal != mdir)
1933 strcat(outlist,"n");
1935 chan->noexternal = mdir;
1939 if (chan->moderated != mdir)
1941 strcat(outlist,"m");
1943 chan->moderated = mdir;
1947 if (chan->secret != mdir)
1949 strcat(outlist,"s");
1950 if (chan->c_private)
1952 chan->c_private = 0;
1955 strcat(outlist,"-p+");
1959 strcat(outlist,"+p-");
1963 chan->secret = mdir;
1967 if (chan->c_private != mdir)
1969 strcat(outlist,"p");
1975 strcat(outlist,"-s+");
1979 strcat(outlist,"+s-");
1983 chan->c_private = mdir;
1989 if (ModeDefined(modelist[ptr],MT_CHANNEL))
1991 if ((ModeDefinedOn(modelist[ptr],MT_CHANNEL)>0) && (mdir))
1993 p.push_back(parameters[param]);
1995 if ((ModeDefinedOff(modelist[ptr],MT_CHANNEL)>0) && (!mdir))
1997 p.push_back(parameters[param]);
1999 for (int i = 0; i <= MODCOUNT; i++)
2001 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2003 char app[] = {modechar, 0};
2004 strcat(outlist, app);
2005 chan->SetCustomMode(modelist[ptr],mdir);
2006 // include parameters in output if mode has them
2007 if ((ModeDefinedOn(modelist[ptr],MT_CHANNEL)>0) || (ModeDefinedOff(modelist[ptr],MT_CHANNEL)>0))
2009 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2010 strcpy(outpars[pc++],parameters[param++]);
2021 /* this ensures only the *valid* modes are sent out onto the network */
2022 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2024 outlist[strlen(outlist)-1] = '\0';
2026 if (strcmp(outlist,""))
2028 strcpy(outstr,outlist);
2029 for (ptr = 0; ptr < pc; ptr++)
2032 strcat(outstr,outpars[ptr]);
2036 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2040 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2045 void handle_mode(char **parameters, int pcnt, userrec *user)
2051 char outpars[MAXBUF];
2053 dest = Find(parameters[0]);
2055 if ((dest) && (pcnt == 1))
2057 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2060 if ((dest) && (pcnt > 1))
2065 if (strchr(user->modes,'o'))
2076 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2080 strcpy(outpars,"+");
2083 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2086 for (i = 0; i < strlen(parameters[1]); i++)
2088 if (parameters[1][i] == '+')
2092 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2094 outpars[strlen(outpars)-1] = '+';
2098 strcat(outpars,"+");
2104 if (parameters[1][i] == '-')
2108 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2110 outpars[strlen(outpars)-1] = '-';
2114 strcat(outpars,"-");
2122 if (strchr(user->modes,'o'))
2128 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2137 if (!strchr(dest->modes,parameters[1][i]))
2139 dest->modes[strlen(dest->modes)+1]='\0';
2140 dest->modes[strlen(dest->modes)] = parameters[1][i];
2141 outpars[strlen(outpars)+1]='\0';
2142 outpars[strlen(outpars)] = parameters[1][i];
2151 outpars[strlen(outpars)+1]='\0';
2152 outpars[strlen(outpars)] = parameters[1][i];
2155 for (q = 0; q < strlen(user->modes); q++)
2157 if (user->modes[q] != parameters[1][i])
2159 moo[0] = user->modes[q];
2164 strcpy(user->modes,temp);
2169 if (strlen(outpars))
2175 while (i < strlen (outpars))
2177 b[z++] = outpars[i++];
2179 if (i<strlen(outpars)-1)
2181 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2183 // someones playing silly buggers and trying
2184 // to put a +- or -+ into the line...
2188 if (i == strlen(outpars)-1)
2190 if ((outpars[i] == '-') || (outpars[i] == '+'))
2198 if ((b[z] == '-') || (b[z] == '+'))
2201 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2204 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2209 Ptr = FindChan(parameters[0]);
2214 /* just /modes #channel */
2215 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2216 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2222 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2225 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2227 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2229 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2233 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2235 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2239 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2243 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2250 void server_mode(char **parameters, int pcnt, userrec *user)
2256 char outpars[MAXBUF];
2258 dest = Find(parameters[0]);
2260 if ((dest) && (pcnt > 1))
2262 strcpy(outpars,"+");
2265 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2268 for (i = 0; i < strlen(parameters[1]); i++)
2270 if (parameters[1][i] == '+')
2274 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2276 outpars[strlen(outpars)-1] = '+';
2280 strcat(outpars,"+");
2286 if (parameters[1][i] == '-')
2290 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2292 outpars[strlen(outpars)-1] = '-';
2296 strcat(outpars,"-");
2304 if (strchr(user->modes,'o'))
2310 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2319 if (!strchr(dest->modes,parameters[1][i]))
2321 dest->modes[strlen(dest->modes)+1]='\0';
2322 dest->modes[strlen(dest->modes)] = parameters[1][i];
2323 outpars[strlen(outpars)+1]='\0';
2324 outpars[strlen(outpars)] = parameters[1][i];
2333 outpars[strlen(outpars)+1]='\0';
2334 outpars[strlen(outpars)] = parameters[1][i];
2337 for (q = 0; q < strlen(user->modes); q++)
2339 if (user->modes[q] != parameters[1][i])
2341 moo[0] = user->modes[q];
2346 strcpy(user->modes,temp);
2351 if (strlen(outpars))
2357 while (i < strlen (outpars))
2359 b[z++] = outpars[i++];
2361 if (i<strlen(outpars)-1)
2363 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2365 // someones playing silly buggers and trying
2366 // to put a +- or -+ into the line...
2370 if (i == strlen(outpars)-1)
2372 if ((outpars[i] == '-') || (outpars[i] == '+'))
2380 if ((b[z] == '-') || (b[z] == '+'))
2383 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2386 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2391 Ptr = FindChan(parameters[0]);
2394 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2398 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2403 /* This function pokes and hacks at a parameter list like the following:
2405 * PART #winbot, #darkgalaxy :m00!
2407 * to turn it into a series of individual calls like this:
2409 * PART #winbot :m00!
2410 * PART #darkgalaxy :m00!
2412 * The seperate calls are sent to a callback function provided by the caller
2413 * (the caller will usually call itself recursively). The callback function
2414 * must be a command handler. Calling this function on a line with no list causes
2415 * no action to be taken. You must provide a starting and ending parameter number
2416 * where the range of the list can be found, useful if you have a terminating
2417 * parameter as above which is actually not part of the list, or parameters
2418 * before the actual list as well. This code is used by many functions which
2419 * can function as "one to list" (see the RFC) */
2421 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2426 char blog[32][MAXBUF];
2427 char blog2[32][MAXBUF];
2428 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2429 char keystr[MAXBUF];
2432 for (i = 0; i <32; i++)
2435 for (i = 0; i <32; i++)
2436 strcpy(blog2[i],"");
2439 for (i = 0; i <10; i++)
2443 parameters[i] = moo;
2448 if (pcnt > 1) /* we have a key to copy */
2450 strcpy(keystr,parameters[1]);
2454 if (!parameters[start])
2458 if (!strchr(parameters[start],','))
2463 for (i = start; i <= end; i++)
2467 strcat(plist,parameters[i]);
2475 for (i = 0; i < t; i++)
2477 if (plist[i] == ',')
2480 strcpy(blog[j++],param);
2484 strcpy(blog[j++],param);
2487 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2492 if ((joins) && (keystr))
2494 if (strchr(keystr,','))
2498 t2 = strlen(keystr);
2499 for (i = 0; i < t2; i++)
2501 if (keystr[i] == ',')
2504 strcpy(blog2[j++],param);
2508 strcpy(blog2[j++],param);
2513 for (j = 0; j < total; j++)
2519 for (q = end; q < pcnt-1; q++)
2521 if (parameters[q+1])
2523 pars[q-end+1] = parameters[q+1];
2526 if ((joins) && (parameters[1]))
2537 /* repeatedly call the function with the hacked parameter list */
2538 if ((joins) && (pcnt > 1))
2542 // pars[1] already set up and containing key from blog2[j]
2547 pars[1] = parameters[1];
2553 fn(pars,pcnt-(end-start),u);
2560 void handle_join(char **parameters, int pcnt, userrec *user)
2565 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2567 if (parameters[0][0] == '#')
2569 Ptr = add_channel(user,parameters[0],parameters[1]);
2574 void handle_part(char **parameters, int pcnt, userrec *user)
2580 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2582 del_channel(user,parameters[0],parameters[1]);
2586 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2588 del_channel(user,parameters[0],NULL);
2592 void handle_kick(char **parameters, int pcnt, userrec *user)
2594 chanrec* Ptr = FindChan(parameters[0]);
2595 userrec* u = Find(parameters[1]);
2599 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2603 if (!has_channel(u,Ptr))
2605 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2611 kick_channel(user,u,Ptr,parameters[2]);
2615 kick_channel(user,u,Ptr,user->nick);
2620 void handle_die(char **parameters, int pcnt, userrec *user)
2622 log(DEBUG,"die: %s",user->nick);
2623 if (!strcmp(parameters[0],diepass))
2625 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2631 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2635 void handle_restart(char **parameters, int pcnt, userrec *user)
2637 log(DEBUG,"restart: %s",user->nick);
2638 if (!strcmp(parameters[0],restartpass))
2640 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2643 /* Will finish this later when i can be arsed :) */
2647 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2652 void kill_link(userrec *user,char* reason)
2654 user_hash::iterator iter = clientlist.find(user->nick);
2656 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2657 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2658 fdatasync(user->fd);
2659 log(DEBUG,"closing fd %d",user->fd);
2661 /* bugfix, cant close() a nonblocking socket (sux!) */
2662 if (user->registered == 7) {
2663 FOREACH_MOD OnUserQuit(user);
2664 WriteCommonExcept(user,"QUIT :%s",reason);
2667 /* push the socket on a stack of sockets due to be closed at the next opportunity */
2668 fd_reap.push_back(user->fd);
2670 bool do_purge = false;
2672 if (user->registered == 7) {
2673 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2677 if (iter != clientlist.end())
2679 log(DEBUG,"deleting user hash value %d",iter->second);
2680 if ((iter->second) && (user->registered == 7)) {
2681 delete iter->second;
2683 clientlist.erase(iter);
2686 purge_empty_chans();
2690 void handle_kill(char **parameters, int pcnt, userrec *user)
2692 userrec *u = Find(parameters[0]);
2693 char killreason[MAXBUF];
2695 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
2698 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
2699 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
2700 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
2701 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
2702 kill_link(u,killreason);
2706 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2710 void handle_summon(char **parameters, int pcnt, userrec *user)
2712 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
2715 void handle_users(char **parameters, int pcnt, userrec *user)
2717 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
2721 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2723 char* Passwd(userrec *user)
2725 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2727 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2735 bool IsDenied(userrec *user)
2737 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2739 if (match(user->host,i->host) && (i->type == CC_DENY))
2748 void handle_pass(char **parameters, int pcnt, userrec *user)
2750 if (!strcasecmp(parameters[0],Passwd(user)))
2752 user->haspassed = true;
2756 void handle_invite(char **parameters, int pcnt, userrec *user)
2758 userrec* u = Find(parameters[0]);
2759 chanrec* c = FindChan(parameters[1]);
2765 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
2771 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2780 if (cstatus(user,c) < STATUS_HOP)
2782 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
2786 u->InviteTo(c->name);
2787 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2788 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2792 void handle_topic(char **parameters, int pcnt, userrec *user)
2798 if (strlen(parameters[0]) <= CHANMAX)
2800 Ptr = FindChan(parameters[0]);
2805 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2806 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2810 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2815 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2821 if (loop_call(handle_topic,parameters,pcnt,user,0,pcnt-2,0))
2823 if (strlen(parameters[0]) <= CHANMAX)
2825 Ptr = FindChan(parameters[0]);
2828 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2830 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
2833 strcpy(Ptr->topic,parameters[1]);
2834 strcpy(Ptr->setby,user->nick);
2835 Ptr->topicset = time(NULL);
2836 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2840 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2846 /* sends out an error notice to all connected clients (not to be used
2849 void send_error(char *s)
2851 log(DEBUG,"send_error: %s",s);
2852 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2854 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2858 void Error(int status)
2860 signal (SIGALRM, SIG_IGN);
2861 signal (SIGPIPE, SIG_IGN);
2862 signal (SIGTERM, SIG_IGN);
2863 signal (SIGABRT, SIG_IGN);
2864 signal (SIGSEGV, SIG_IGN);
2865 signal (SIGURG, SIG_IGN);
2866 signal (SIGKILL, SIG_IGN);
2867 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2868 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2872 int main (int argc, char *argv[])
2875 log(DEBUG,"*** InspIRCd starting up!");
2876 if (!FileExists(CONFIG_FILE))
2878 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2879 log(DEBUG,"main: no config");
2880 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2884 if (!strcmp(argv[1],"-nofork")) {
2888 if (InspIRCd() == ERROR)
2890 log(DEBUG,"main: daemon function bailed");
2891 printf("ERROR: could not initialise. Shutting down.\n");
2898 template<typename T> inline string ConvToStr(const T &in)
2901 if (!(tmp << in)) return string();
2905 /* re-allocates a nick in the user_hash after they change nicknames,
2906 * returns a pointer to the new user as it may have moved */
2908 userrec* ReHashNick(char* Old, char* New)
2910 user_hash::iterator newnick;
2911 user_hash::iterator oldnick = clientlist.find(Old);
2913 log(DEBUG,"ReHashNick: %s %s",Old,New);
2915 if (!strcasecmp(Old,New))
2917 log(DEBUG,"old nick is new nick, skipping");
2918 return oldnick->second;
2921 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2923 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2925 clientlist[New] = new userrec();
2926 clientlist[New] = oldnick->second;
2927 /*delete oldnick->second; */
2928 clientlist.erase(oldnick);
2930 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2932 return clientlist[New];
2935 /* adds or updates an entry in the whowas list */
2936 void AddWhoWas(userrec* u)
2938 user_hash::iterator iter = whowas.find(u->nick);
2939 userrec *a = new userrec();
2940 strcpy(a->nick,u->nick);
2941 strcpy(a->ident,u->ident);
2942 strcpy(a->dhost,u->dhost);
2943 strcpy(a->host,u->host);
2944 strcpy(a->fullname,u->fullname);
2945 strcpy(a->server,u->server);
2946 a->signon = u->signon;
2948 /* MAX_WHOWAS: max number of /WHOWAS items
2949 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2950 * can be replaced by a newer one
2953 if (iter == whowas.end())
2955 if (whowas.size() == WHOWAS_MAX)
2957 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2959 // 3600 seconds in an hour ;)
2960 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2964 log(DEBUG,"added WHOWAS entry, purged an old record");
2971 log(DEBUG,"added fresh WHOWAS entry");
2972 whowas[a->nick] = a;
2977 log(DEBUG,"updated WHOWAS entry");
2978 delete iter->second;
2984 /* add a client connection to the sockets list */
2985 void AddClient(int socket, char* host, int port, bool iscached)
2989 char resolved[MAXBUF];
2992 user_hash::iterator iter;
2994 tempnick = ConvToStr(socket) + "-unknown";
2995 sprintf(tn2,"%d-unknown",socket);
2997 iter = clientlist.find(tempnick);
2999 if (iter != clientlist.end()) return;
3002 * It is OK to access the value here this way since we know
3003 * it exists, we just created it above.
3005 * At NO other time should you access a value in a map or a
3006 * hash_map this way.
3008 clientlist[tempnick] = new userrec();
3010 NonBlocking(socket);
3011 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3014 clientlist[tempnick]->fd = socket;
3015 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3016 strncpy(clientlist[tempnick]->host, host,160);
3017 strncpy(clientlist[tempnick]->dhost, host,160);
3018 strncpy(clientlist[tempnick]->server, ServerName,256);
3019 clientlist[tempnick]->registered = 0;
3020 clientlist[tempnick]->signon = time(NULL);
3021 clientlist[tempnick]->nping = time(NULL)+240;
3022 clientlist[tempnick]->lastping = 1;
3023 clientlist[tempnick]->port = port;
3027 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3031 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3034 if (clientlist.size() == MAXCLIENTS)
3035 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3038 void handle_names(char **parameters, int pcnt, userrec *user)
3042 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3044 c = FindChan(parameters[0]);
3047 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3049 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3053 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3058 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3063 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3065 if (parameters[0][0] == '#')
3067 chan = FindChan(parameters[0]);
3070 if ((chan->noexternal) && (!has_channel(user,chan)))
3072 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3075 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3077 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3080 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3084 /* no such nick/channel */
3085 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3090 dest = Find(parameters[0]);
3093 if (strcmp(dest->awaymsg,""))
3095 /* auto respond with aweh msg */
3096 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3098 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3102 /* no such nick/channel */
3103 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3107 void handle_notice(char **parameters, int pcnt, userrec *user)
3112 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3114 if (parameters[0][0] == '#')
3116 chan = FindChan(parameters[0]);
3119 if ((chan->noexternal) && (!has_channel(user,chan)))
3121 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3124 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3126 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3129 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3133 /* no such nick/channel */
3134 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3139 dest = Find(parameters[0]);
3142 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3146 /* no such nick/channel */
3147 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3153 char* chlist(userrec *user)
3158 log(DEBUG,"chlist: %s",user->nick);
3164 for (i = 0; i != MAXCHANS; i++)
3166 if (user->chans[i].channel != NULL)
3168 if (user->chans[i].channel->name)
3170 strcpy(cmp,user->chans[i].channel->name);
3172 if (!strstr(lst,cmp))
3174 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3176 strcat(lst,cmode(user,user->chans[i].channel));
3177 strcat(lst,user->chans[i].channel->name);
3187 void handle_info(char **parameters, int pcnt, userrec *user)
3189 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3190 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3191 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3192 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3195 void handle_time(char **parameters, int pcnt, userrec *user)
3198 struct tm * timeinfo;
3201 timeinfo = localtime ( &rawtime );
3202 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3206 void handle_whois(char **parameters, int pcnt, userrec *user)
3211 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3213 dest = Find(parameters[0]);
3216 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3217 if ((user == dest) || (strchr(user->modes,'o')))
3219 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3221 if (strcmp(chlist(dest),""))
3223 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3225 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3226 if (strcmp(dest->awaymsg,""))
3228 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3230 if (strchr(dest->modes,'o'))
3232 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3234 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3235 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3237 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3241 /* no such nick/channel */
3242 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3246 void handle_quit(char **parameters, int pcnt, userrec *user)
3248 user_hash::iterator iter = clientlist.find(user->nick);
3250 if (user->registered == 7)
3252 /* theres more to do here, but for now just close the socket */
3255 if (parameters[0][0] == ':')
3259 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3260 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3261 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3265 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3266 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3267 WriteCommonExcept(user,"QUIT :Client exited");
3269 FOREACH_MOD OnUserQuit(user);
3273 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3274 fd_reap.push_back(user->fd);
3276 if (iter != clientlist.end())
3278 log(DEBUG,"deleting user hash value %d",iter->second);
3279 if ((iter->second) && (user->registered == 7)) {
3280 delete iter->second;
3282 clientlist.erase(iter);
3285 if (user->registered == 7) {
3286 purge_empty_chans();
3290 void handle_who(char **parameters, int pcnt, userrec *user)
3292 chanrec* Ptr = NULL;
3294 /* theres more to do here, but for now just close the socket */
3297 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3299 if (user->chans[0].channel)
3301 Ptr = user->chans[0].channel;
3302 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3304 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3306 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);
3312 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3316 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3320 if (parameters[0][0] = '#')
3322 Ptr = FindChan(parameters[0]);
3325 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3327 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3329 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);
3332 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3336 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3342 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3344 Ptr = user->chans[0].channel;
3345 printf(user->chans[0].channel->name);
3346 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3348 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3350 if (strchr(i->second->modes,'o'))
3352 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);
3356 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3362 void handle_wallops(char **parameters, int pcnt, userrec *user)
3364 WriteWallOps(user,"%s",parameters[0]);
3367 void handle_list(char **parameters, int pcnt, userrec *user)
3371 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3372 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3374 if ((!i->second->c_private) && (!i->second->secret))
3376 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3379 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3383 void handle_rehash(char **parameters, int pcnt, userrec *user)
3385 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3387 FOREACH_MOD OnRehash();
3388 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3394 return clientlist.size();
3397 int usercount_invisible(void)
3401 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3403 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3408 int usercount_opers(void)
3412 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3414 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3419 int usercount_unknown(void)
3423 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3425 if ((i->second->fd) && (i->second->registered != 7))
3433 return chanlist.size();
3436 int servercount(void)
3441 void handle_lusers(char **parameters, int pcnt, userrec *user)
3443 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3444 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3445 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3446 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3447 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3450 void handle_admin(char **parameters, int pcnt, userrec *user)
3452 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3453 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
3454 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3455 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
3458 void ShowMOTD(userrec *user)
3462 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3465 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3466 for (int i = 0; i != MOTD.size(); i++)
3468 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3470 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3473 void ShowRULES(userrec *user)
3477 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3480 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3481 for (int i = 0; i != RULES.size(); i++)
3483 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3485 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3488 /* shows the message of the day, and any other on-logon stuff */
3489 void ConnectUser(userrec *user)
3491 user->registered = 7;
3492 user->idle_lastmsg = time(NULL);
3493 log(DEBUG,"ConnectUser: %s",user->nick);
3495 if (strcmp(Passwd(user),"") && (!user->haspassed))
3497 Write(user->fd,"ERROR :Closing link: Invalid password");
3498 fdatasync(user->fd);
3499 kill_link(user,"Invalid password");
3504 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3505 fdatasync(user->fd);
3506 kill_link(user,"Unauthorised connection");
3509 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3510 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3511 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3512 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3513 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3514 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);
3515 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);
3517 FOREACH_MOD OnUserConnect(user);
3518 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3521 void handle_version(char **parameters, int pcnt, userrec *user)
3523 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3526 void handle_ping(char **parameters, int pcnt, userrec *user)
3528 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3531 void handle_pong(char **parameters, int pcnt, userrec *user)
3533 // set the user as alive so they survive to next ping
3537 void handle_motd(char **parameters, int pcnt, userrec *user)
3542 void handle_rules(char **parameters, int pcnt, userrec *user)
3547 void handle_user(char **parameters, int pcnt, userrec *user)
3549 if (user->registered < 3)
3551 if (isident(parameters[0]) == 0) {
3552 // This kinda Sucks, According to the RFC thou, its either this,
3553 // or "You have already registered" :p -- Craig
3554 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3557 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3558 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3559 strncat(user->ident,parameters[0],IDENTMAX);
3560 strncpy(user->fullname,parameters[3],128);
3561 user->registered = (user->registered | 1);
3566 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3569 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3570 if (user->registered == 3)
3572 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3577 void handle_userhost(char **parameters, int pcnt, userrec *user)
3579 char Return[MAXBUF],junk[MAXBUF];
3580 sprintf(Return,"302 %s :",user->nick);
3581 for (int i = 0; i < pcnt; i++)
3583 userrec *u = Find(parameters[i]);
3586 if (strchr(u->modes,'o'))
3588 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3589 strcat(Return,junk);
3593 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3594 strcat(Return,junk);
3598 WriteServ(user->fd,Return);
3602 void handle_ison(char **parameters, int pcnt, userrec *user)
3604 char Return[MAXBUF];
3605 sprintf(Return,"303 %s :",user->nick);
3606 for (int i = 0; i < pcnt; i++)
3608 userrec *u = Find(parameters[i]);
3611 strcat(Return,u->nick);
3615 WriteServ(user->fd,Return);
3619 void handle_away(char **parameters, int pcnt, userrec *user)
3623 strcpy(user->awaymsg,parameters[0]);
3624 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3628 strcpy(user->awaymsg,"");
3629 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3633 void handle_whowas(char **parameters, int pcnt, userrec* user)
3635 user_hash::iterator i = whowas.find(parameters[0]);
3637 if (i == whowas.end())
3639 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3640 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3644 time_t rawtime = i->second->signon;
3648 timeinfo = localtime(&rawtime);
3649 strcpy(b,asctime(timeinfo));
3650 b[strlen(b)-1] = '\0';
3652 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3653 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3654 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3659 void handle_trace(char **parameters, int pcnt, userrec *user)
3661 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3665 if (isnick(i->second->nick))
3667 if (strchr(i->second->modes,'o'))
3669 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3673 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3678 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3684 void handle_stats(char **parameters, int pcnt, userrec *user)
3690 if (strlen(parameters[0])>1)
3692 /* make the stats query 1 character long */
3693 parameters[0][1] = '\0';
3696 /* stats m (list number of times each command has been used, plus bytecount) */
3697 if (!strcasecmp(parameters[0],"m"))
3699 for (int i = 0; i < cmdlist.size(); i++)
3701 if (cmdlist[i].handler_function)
3703 if (cmdlist[i].use_count)
3705 /* RPL_STATSCOMMANDS */
3706 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3713 /* stats z (debug and memory info) */
3714 if (!strcasecmp(parameters[0],"z"))
3716 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3717 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3718 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3719 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3720 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3721 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3722 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3723 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3727 if (!strcasecmp(parameters[0],"o"))
3729 for (int i = 0; i < ConfValueEnum("oper"); i++)
3731 char LoginName[MAXBUF];
3732 char HostName[MAXBUF];
3733 char OperType[MAXBUF];
3734 ConfValue("oper","name",i,LoginName);
3735 ConfValue("oper","host",i,HostName);
3736 ConfValue("oper","type",i,OperType);
3737 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3741 /* stats l (show user I/O stats) */
3742 if (!strcasecmp(parameters[0],"l"))
3744 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3745 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3747 if (isnick(i->second->nick))
3749 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);
3753 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);
3759 /* stats u (show server uptime) */
3760 if (!strcasecmp(parameters[0],"u"))
3762 time_t current_time = 0;
3763 current_time = time(NULL);
3764 time_t server_uptime = current_time - startup_time;
3766 stime = gmtime(&server_uptime);
3767 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3768 * Craig suggested this, and it seemed a good idea so in it went */
3769 if (stime->tm_year > 70)
3771 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);
3775 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);
3779 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3780 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3784 void handle_connect(char **parameters, int pcnt, userrec *user)
3786 char Link_ServerName[1024];
3787 char Link_IPAddr[1024];
3788 char Link_Port[1024];
3789 char Link_Pass[1024];
3793 for (int i = 0; i < ConfValueEnum("link"); i++)
3795 ConfValue("link","name",i,Link_ServerName);
3796 ConfValue("link","ipaddr",i,Link_IPAddr);
3797 ConfValue("link","port",i,Link_Port);
3798 ConfValue("link","sendpass",i,Link_Pass);
3799 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3800 LinkPort = atoi(Link_Port);
3801 if (match(Link_ServerName,parameters[0])) {
3807 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3811 // TODO: Perform a check here to stop a server being linked twice!
3813 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3815 if (me[defaultRoute])
3818 // at this point parameters[0] is an ip in a string.
3819 // TODO: Look this up from the <link> blocks instead!
3820 for (int j = 0; j < 255; j++) {
3821 if (servers[j] == NULL) {
3822 servers[j] = new serverrec;
3823 strcpy(servers[j]->internal_addr,Link_IPAddr);
3824 strcpy(servers[j]->name,Link_ServerName);
3825 log(DEBUG,"Allocated new serverrec");
3826 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
3828 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
3833 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
3837 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);
3841 void handle_squit(char **parameters, int pcnt, userrec *user)
3843 // send out an squit across the mesh and then clear the server list (for local squit)
3846 void handle_oper(char **parameters, int pcnt, userrec *user)
3848 char LoginName[MAXBUF];
3849 char Password[MAXBUF];
3850 char OperType[MAXBUF];
3851 char TypeName[MAXBUF];
3852 char Hostname[MAXBUF];
3855 for (i = 0; i < ConfValueEnum("oper"); i++)
3857 ConfValue("oper","name",i,LoginName);
3858 ConfValue("oper","password",i,Password);
3859 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3861 /* correct oper credentials */
3862 ConfValue("oper","type",i,OperType);
3863 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3864 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3865 WriteServ(user->fd,"MODE %s :+o",user->nick);
3866 for (j =0; j < ConfValueEnum("type"); j++)
3868 ConfValue("type","name",j,TypeName);
3869 if (!strcmp(TypeName,OperType))
3871 /* found this oper's opertype */
3872 ConfValue("type","host",j,Hostname);
3873 strncpy(user->dhost,Hostname,256);
3876 if (!strchr(user->modes,'o'))
3878 strcat(user->modes,"o");
3884 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3885 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3888 void handle_nick(char **parameters, int pcnt, userrec *user)
3892 log(DEBUG,"not enough params for handle_nick");
3897 log(DEBUG,"invalid parameter passed to handle_nick");
3900 if (!strlen(parameters[0]))
3902 log(DEBUG,"zero length new nick passed to handle_nick");
3907 log(DEBUG,"invalid user passed to handle_nick");
3912 log(DEBUG,"invalid old nick passed to handle_nick");
3915 if (!strcasecmp(user->nick,parameters[0]))
3917 log(DEBUG,"old nick is new nick, skipping");
3922 if (strlen(parameters[0]) > 1)
3924 if (parameters[0][0] == ':')
3929 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
3931 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
3935 if (isnick(parameters[0]) == 0)
3937 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
3941 if (user->registered == 7)
3943 WriteCommon(user,"NICK %s",parameters[0]);
3946 /* change the nick of the user in the users_hash */
3947 user = ReHashNick(user->nick, parameters[0]);
3948 /* actually change the nick within the record */
3950 if (!user->nick) return;
3952 strncpy(user->nick, parameters[0],NICKMAX);
3954 log(DEBUG,"new nick set: %s",user->nick);
3956 if (user->registered < 3)
3957 user->registered = (user->registered | 2);
3958 if (user->registered == 3)
3960 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3963 log(DEBUG,"exit nickchange: %s",user->nick);
3966 int process_parameters(char **command_p,char *parameters)
3971 q = strlen(parameters);
3974 /* no parameters, command_p invalid! */
3977 if (parameters[0] == ':')
3979 command_p[0] = parameters+1;
3984 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
3986 /* only one parameter */
3987 command_p[0] = parameters;
3988 if (parameters[0] == ':')
3990 if (strchr(parameters,' ') != NULL)
3998 command_p[j++] = parameters;
3999 for (i = 0; i <= q; i++)
4001 if (parameters[i] == ' ')
4003 command_p[j++] = parameters+i+1;
4004 parameters[i] = '\0';
4005 if (command_p[j-1][0] == ':')
4007 *command_p[j-1]++; /* remove dodgy ":" */
4009 /* parameter like this marks end of the sequence */
4013 return j; /* returns total number of items in the list */
4016 void process_command(userrec *user, char* cmd)
4020 char *command_p[127];
4021 char p[MAXBUF], temp[MAXBUF];
4022 int i, j, items, cmd_found;
4024 for (int i = 0; i < 127; i++)
4025 command_p[i] = NULL;
4035 if (!strcmp(cmd,""))
4042 FOREACH_MOD OnServerRaw(tmp,true);
4043 const char* cmd2 = tmp.c_str();
4044 snprintf(cmd,512,"%s",cmd2);
4046 if (!strchr(cmd,' '))
4048 /* no parameters, lets skip the formalities and not chop up
4051 command_p[0] = NULL;
4053 for (int i = 0; i <= strlen(cmd); i++)
4055 cmd[i] = toupper(cmd[i]);
4062 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4063 for (i = 0; i < strlen(temp); i++)
4065 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4071 /* split the full string into a command plus parameters */
4075 if (strchr(cmd,' '))
4077 for (i = 0; i <= strlen(cmd); i++)
4079 /* capitalise the command ONLY, leave params intact */
4080 cmd[i] = toupper(cmd[i]);
4081 /* are we nearly there yet?! :P */
4085 parameters = cmd+i+1;
4093 for (i = 0; i <= strlen(cmd); i++)
4095 cmd[i] = toupper(cmd[i]);
4103 for (i = 0; i != cmdlist.size(); i++)
4105 if (strcmp(cmdlist[i].command,""))
4107 if (!strcmp(command, cmdlist[i].command))
4111 if (strcmp(parameters,""))
4113 items = process_parameters(command_p,parameters);
4118 command_p[0] = NULL;
4124 command_p[0] = NULL;
4129 user->idle_lastmsg = time(NULL);
4130 /* activity resets the ping pending timer */
4131 user->nping = time(NULL) + 120;
4132 if ((items) < cmdlist[i].min_params)
4134 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4135 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4138 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4140 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4141 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4145 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4147 if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4149 if ((!isnick(user->nick)) || (user->registered != 7))
4151 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4152 WriteServ(user->fd,"451 %s :You have not registered",command);
4156 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4158 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4159 if (cmdlist[i].handler_function)
4161 /* ikky /stats counters */
4166 user->bytes_in += strlen(temp);
4169 cmdlist[i].use_count++;
4170 cmdlist[i].total_bytes+=strlen(temp);
4173 /* WARNING: nothing may come after the
4174 * command handler call, as the handler
4175 * may free the user structure! */
4177 cmdlist[i].handler_function(command_p,items,user);
4183 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4184 WriteServ(user->fd,"451 %s :You have not registered",command);
4192 if ((!cmd_found) && (user))
4194 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4195 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4200 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4203 /* create the command and push it onto the table */
4204 strcpy(comm.command,cmd);
4205 comm.handler_function = f;
4206 comm.flags_needed = flags;
4207 comm.min_params = minparams;
4209 comm.total_bytes = 0;
4210 cmdlist.push_back(comm);
4211 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4214 void SetupCommandTable(void)
4216 createcommand("USER",handle_user,0,4);
4217 createcommand("NICK",handle_nick,0,1);
4218 createcommand("QUIT",handle_quit,0,0);
4219 createcommand("VERSION",handle_version,0,0);
4220 createcommand("PING",handle_ping,0,1);
4221 createcommand("PONG",handle_pong,0,1);
4222 createcommand("ADMIN",handle_admin,0,0);
4223 createcommand("PRIVMSG",handle_privmsg,0,2);
4224 createcommand("INFO",handle_info,0,0);
4225 createcommand("TIME",handle_time,0,0);
4226 createcommand("WHOIS",handle_whois,0,1);
4227 createcommand("WALLOPS",handle_wallops,'o',1);
4228 createcommand("NOTICE",handle_notice,0,2);
4229 createcommand("JOIN",handle_join,0,1);
4230 createcommand("NAMES",handle_names,0,1);
4231 createcommand("PART",handle_part,0,1);
4232 createcommand("KICK",handle_kick,0,2);
4233 createcommand("MODE",handle_mode,0,1);
4234 createcommand("TOPIC",handle_topic,0,1);
4235 createcommand("WHO",handle_who,0,1);
4236 createcommand("MOTD",handle_motd,0,0);
4237 createcommand("RULES",handle_join,0,0);
4238 createcommand("OPER",handle_oper,0,2);
4239 createcommand("LIST",handle_list,0,0);
4240 createcommand("DIE",handle_die,'o',1);
4241 createcommand("RESTART",handle_restart,'o',1);
4242 createcommand("KILL",handle_kill,'o',2);
4243 createcommand("REHASH",handle_rehash,'o',0);
4244 createcommand("LUSERS",handle_lusers,0,0);
4245 createcommand("STATS",handle_stats,0,1);
4246 createcommand("USERHOST",handle_userhost,0,1);
4247 createcommand("AWAY",handle_away,0,0);
4248 createcommand("ISON",handle_ison,0,0);
4249 createcommand("SUMMON",handle_summon,0,0);
4250 createcommand("USERS",handle_users,0,0);
4251 createcommand("INVITE",handle_invite,0,2);
4252 createcommand("PASS",handle_pass,0,1);
4253 createcommand("TRACE",handle_trace,'o',0);
4254 createcommand("WHOWAS",handle_whowas,0,1);
4255 createcommand("CONNECT",handle_connect,'o',1);
4256 createcommand("SQUIT",handle_squit,'o',1);
4259 void process_buffer(userrec *user)
4267 if (!strcmp(user->inbuf,""))
4271 strncpy(cmd,user->inbuf,MAXBUF);
4272 if (!strcmp(cmd,""))
4276 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4278 cmd[strlen(cmd)-1] = '\0';
4280 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4282 cmd[strlen(cmd)-1] = '\0';
4284 strcpy(user->inbuf,"");
4285 if (!strcmp(cmd,""))
4289 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4290 process_command(user,cmd);
4293 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4295 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4299 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4301 char response[10240];
4302 char token = udp_msg[0];
4303 char* params = udp_msg + 2;
4304 char finalparam[1024];
4305 strcpy(finalparam," :xxxx");
4306 if (strstr(params," :")) {
4307 strncpy(finalparam,strstr(params," :"),1024);
4310 // S test.chatspike.net password :ChatSpike InspIRCd test server
4311 char* servername = strtok(params," ");
4312 char* password = strtok(NULL," ");
4313 char* serverdesc = finalparam+2;
4314 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4317 char Link_ServerName[1024];
4318 char Link_IPAddr[1024];
4319 char Link_Port[1024];
4320 char Link_Pass[1024];
4321 char Link_SendPass[1024];
4324 // search for a corresponding <link> block in the config files
4325 for (int i = 0; i < ConfValueEnum("link"); i++)
4327 ConfValue("link","name",i,Link_ServerName);
4328 ConfValue("link","ipaddr",i,Link_IPAddr);
4329 ConfValue("link","port",i,Link_Port);
4330 ConfValue("link","recvpass",i,Link_Pass);
4331 ConfValue("link","sendpass",i,Link_SendPass);
4332 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4333 LinkPort = atoi(Link_Port);
4334 if (!strcasecmp(Link_ServerName,servername)) {
4335 if (!strcasecmp(Link_IPAddr,udp_host)) {
4336 if (LinkPort == udp_port) {
4337 // we have a matching link line -
4338 // send a 'diminutive' server message back...
4339 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4340 serv->SendPacket(response,udp_host,udp_port,0);
4341 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4342 for (int j = 0; j < 255; j++) {
4343 if (servers[j] == NULL) {
4344 servers[j] = new serverrec;
4345 strcpy(servers[j]->internal_addr,udp_host);
4346 strcpy(servers[j]->name,servername);
4347 // create a server record for this server
4348 snprintf(response,10240,"O %d",MyKey);
4349 serv->SendPacket(response,udp_host,udp_port,0);
4353 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4357 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4361 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4365 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4368 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4369 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4374 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4375 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4376 // array, which is only added by an 'S' packet or BeginLink().
4377 for (int i = 0; i < 255; i++) {
4378 if (servers[i] != NULL) {
4379 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4380 servers[i]->key = atoi(params);
4381 log(DEBUG,"Key for this server is now %d",servers[i]->key);
4382 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4387 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4391 // S test.chatspike.net password :ChatSpike InspIRCd test server
4392 char* servername = strtok(params," ");
4393 char* password = strtok(NULL," ");
4394 char* serverdesc = finalparam+2;
4396 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4397 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4398 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4399 // a connect, so put out an oper alert!
4404 // for now, just accept all, we'll fix that later.
4405 WriteOpers("%s accepted our link credentials ",servername);
4407 char Link_ServerName[1024];
4408 char Link_IPAddr[1024];
4409 char Link_Port[1024];
4410 char Link_Pass[1024];
4411 char Link_SendPass[1024];
4414 // search for a corresponding <link> block in the config files
4415 for (int i = 0; i < ConfValueEnum("link"); i++)
4417 ConfValue("link","name",i,Link_ServerName);
4418 ConfValue("link","ipaddr",i,Link_IPAddr);
4419 ConfValue("link","port",i,Link_Port);
4420 ConfValue("link","recvpass",i,Link_Pass);
4421 ConfValue("link","sendpass",i,Link_SendPass);
4422 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4423 LinkPort = atoi(Link_Port);
4424 if (!strcasecmp(Link_ServerName,servername)) {
4425 if (!strcasecmp(Link_IPAddr,udp_host)) {
4426 if (LinkPort == udp_port) {
4427 // matching link at this end too, we're all done!
4428 // at this point we must begin key exchange and insert this
4429 // server into our 'active' table.
4430 for (int j = 0; j < 255; j++) {
4431 if (servers[j] != NULL) {
4432 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4433 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4434 snprintf(response,10240,"O %d",MyKey);
4435 serv->SendPacket(response,udp_host,udp_port,0);
4440 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4445 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4449 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4453 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4456 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4457 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4462 char* error_message = finalparam+2;
4463 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4464 // remove this server from any lists
4465 for (int j = 0; j < 255; j++) {
4466 if (servers[j] != NULL) {
4467 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4477 serverrec* source_server = NULL;
4479 for (int j = 0; j < 255; j++) {
4480 if (servers[j] != NULL) {
4481 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4482 if (servers[j]->key == theirkey) {
4483 // found a valid key for this server, can process restricted stuff here
4484 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4492 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4496 int reap_counter = 0;
4500 struct sockaddr_in client, server;
4501 char addrs[MAXBUF][255];
4502 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4504 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4505 int selectResult = 0;
4506 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4507 char resolvedHost[MAXBUF];
4511 log(DEBUG,"InspIRCd: startup: begin");
4515 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4517 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4519 SetupCommandTable();
4520 log(DEBUG,"InspIRCd: startup: default command table set up");
4523 if (strcmp(DieValue,""))
4525 printf("WARNING: %s\n\n",DieValue);
4528 log(DEBUG,"InspIRCd: startup: read config");
4530 int count2 = 0, count3 = 0;
4531 for (count = 0; count < ConfValueEnum("bind"); count++)
4533 ConfValue("bind","port",count,configToken);
4534 ConfValue("bind","address",count,Addr);
4535 ConfValue("bind","type",count,Type);
4536 if (!strcmp(Type,"servers"))
4538 char Default[MAXBUF];
4539 strcpy(Default,"no");
4540 ConfValue("bind","default",count,Default);
4541 if (strchr(Default,'y'))
4543 defaultRoute = count3;
4544 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4546 me[count3] = new serverrec(ServerName,100L,false);
4547 me[count3]->CreateListener(Addr,atoi(configToken));
4552 ports[count2] = atoi(configToken);
4553 strcpy(addrs[count2],Addr);
4556 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4559 UDPportCount = count3;
4561 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4563 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4567 /* BugFix By Craig! :p */
4569 for (count = 0; count2 < ConfValueEnum("module"); count2++)
4571 char modfile[MAXBUF];
4572 ConfValue("module","name",count,configToken);
4573 sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4574 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4575 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4576 /* If The File Doesnt exist, Trying to load it
4577 * Will Segfault the IRCd.. So, check to see if
4578 * it Exists, Before Proceeding. */
4579 if (FileExists(modfile))
4581 factory[count] = new ircd_module(modfile);
4582 if (factory[count]->LastError())
4584 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4585 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4588 if (factory[count]->factory)
4590 modules[count] = factory[count]->factory->CreateModule();
4591 /* save the module and the module's classfactory, if
4592 * this isnt done, random crashes can occur :/ */
4596 log(DEBUG,"Unable to load %s",modfile);
4597 sprintf("Unable to load %s\nExiting...\n",modfile);
4600 /* Increase the Count */
4605 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4606 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4609 MODCOUNT = count - 1;
4610 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4612 printf("\nInspIRCd is now running!\n");
4614 startup_time = time(NULL);
4618 log(VERBOSE,"Not forking as -nofork was specified");
4622 if (DaemonSeed() == ERROR)
4624 log(DEBUG,"InspIRCd: startup: can't daemonise");
4625 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4631 /* setup select call */
4632 FD_ZERO(&selectFds);
4633 log(DEBUG,"InspIRCd: startup: zero selects");
4634 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4636 for (count = 0; count < portCount; count++)
4638 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4640 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4643 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4645 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4647 else /* well we at least bound to one socket so we'll continue */
4653 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4655 /* if we didn't bind to anything then abort */
4656 if (boundPortCount == 0)
4658 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4662 length = sizeof (client);
4663 int flip_flop = 0, udp_port = 0;
4664 char udp_msg[MAXBUF], udp_host[MAXBUF];
4666 /* main loop for multiplexing/resetting */
4669 /* set up select call */
4670 for (count = 0; count < boundPortCount; count++)
4672 FD_SET (openSockfd[count], &selectFds);
4675 /* added timeout! select was waiting forever... wank... :/ */
4686 vector<int>::iterator niterator;
4689 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4690 // them in a list, then reap the list every second or so.
4691 if (reap_counter>5000) {
4692 if (fd_reap.size() > 0) {
4693 for( int n = 0; n < fd_reap.size(); n++)
4695 Blocking(fd_reap[n]);
4697 NonBlocking(fd_reap[n]);
4706 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4708 for (int x = 0; x != UDPportCount; x++)
4711 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
4713 if (strlen(udp_msg)<1) {
4714 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
4717 FOREACH_MOD OnPacketReceive(udp_msg);
4718 // Packets must go back via the route they arrived on :)
4719 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
4724 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
4728 if (!count2->second) break;
4731 if (count2->second->fd)
4733 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4735 if (!count2->second->lastping)
4737 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4738 kill_link(count2->second,"Ping timeout");
4741 Write(count2->second->fd,"PING :%s",ServerName);
4742 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4743 count2->second->lastping = 0;
4744 count2->second->nping = time(NULL)+120;
4747 result = read(count2->second->fd, data, 1);
4748 // result EAGAIN means nothing read
4749 if (result == EAGAIN)
4755 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
4756 kill_link(count2->second,"Client exited");
4758 else if (result > 0)
4760 strncat(count2->second->inbuf, data, result);
4761 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r'))
4763 /* at least one complete line is waiting to be processed */
4764 if (!count2->second->fd)
4768 process_buffer(count2->second);
4776 /* select is reporting a waiting socket. Poll them all to find out which */
4777 if (selectResult > 0)
4779 char target[MAXBUF], resolved[MAXBUF];
4780 for (count = 0; count < boundPortCount; count++)
4782 if (FD_ISSET (openSockfd[count], &selectFds))
4784 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4786 address_cache::iterator iter = IP.find(client.sin_addr);
4787 bool iscached = false;
4788 if (iter == IP.end())
4790 /* ip isn't in cache, add it */
4791 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4792 if(CleanAndResolve(resolved, target) != TRUE)
4794 strncpy(resolved,target,MAXBUF);
4796 /* hostname now in 'target' */
4797 IP[client.sin_addr] = new string(resolved);
4798 /* hostname in cache */
4802 /* found ip (cached) */
4803 strncpy(resolved, iter->second->c_str(), MAXBUF);
4807 if (incomingSockfd < 0)
4809 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4810 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4814 AddClient(incomingSockfd, resolved, ports[count], iscached);
4815 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4824 close (incomingSockfd);