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;
86 template<> struct nspace::hash<in_addr>
88 size_t operator()(const struct in_addr &a) const
91 memcpy(&q,&a,sizeof(size_t));
96 template<> struct nspace::hash<string>
98 size_t operator()(const string &s) const
101 static struct hash<const char *> strhash;
113 bool operator()(const string& s1, const string& s2) const
115 char a[MAXBUF],b[MAXBUF];
116 strcpy(a,s1.c_str());
117 strcpy(b,s2.c_str());
118 return (strcasecmp(a,b) == 0);
123 struct InAddr_HashComp
126 bool operator()(const in_addr &s1, const in_addr &s2) const
131 memcpy(&q,&s1,sizeof(size_t));
132 memcpy(&p,&s2,sizeof(size_t));
140 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
141 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
142 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
143 typedef std::deque<command_t> command_table;
146 serverrec* servers[255];
148 user_hash clientlist;
151 command_table cmdlist;
158 struct linger linger = { 0 };
159 char bannerBuffer[MAXBUF];
160 int boundPortCount = 0;
161 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
162 int defaultRoute = 0;
166 long MyKey = C.GenKey();
170 int has_channel(userrec *u, chanrec *c);
171 int usercount(chanrec *c);
172 int usercount_i(chanrec *c);
173 void update_stats_l(int fd,int data_out);
174 char* Passwd(userrec *user);
175 bool IsDenied(userrec *user);
176 void AddWhoWas(userrec* u);
179 void safedelete(userrec *p)
183 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
184 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
189 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
193 void safedelete(chanrec *p)
198 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
202 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
207 /* chop a string down to 512 characters and preserve linefeed (irc max
214 FOREACH_MOD OnServerRaw(temp,false);
215 const char* str2 = temp.c_str();
216 sprintf(str,"%s",str2);
219 if (strlen(str) > 512)
228 std::string getservername()
233 std::string getserverdesc()
238 std::string getnetworkname()
243 std::string getadminname()
248 std::string getadminemail()
253 std::string getadminnick()
258 void log(int level,char *text, ...)
260 char textbuffer[MAXBUF];
264 struct tm * timeinfo;
265 if (level < LogLevel)
269 timeinfo = localtime (&rawtime);
271 f = fopen("ircd.log","a+");
275 va_start (argsPtr, text);
276 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
278 strcpy(b,asctime(timeinfo));
279 b[strlen(b)-1] = ':';
280 fprintf(f,"%s %s\n",b,textbuffer);
285 printf("Can't write log file, bailing!!!");
290 void readfile(file_cache &F, const char* fname)
293 char linebuf[MAXBUF];
295 log(DEBUG,"readfile: loading %s",fname);
297 file = fopen(fname,"r");
302 fgets(linebuf,sizeof(linebuf),file);
303 linebuf[strlen(linebuf)-1]='\0';
304 if (!strcmp(linebuf,""))
310 F.push_back(linebuf);
317 log(DEBUG,"readfile: failed to load file: %s",fname);
319 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
322 void ReadConfig(void)
324 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
327 ConfValue("server","name",0,ServerName);
328 ConfValue("server","description",0,ServerDesc);
329 ConfValue("server","network",0,Network);
330 ConfValue("admin","name",0,AdminName);
331 ConfValue("admin","email",0,AdminEmail);
332 ConfValue("admin","nick",0,AdminNick);
333 ConfValue("files","motd",0,motd);
334 ConfValue("files","rules",0,rules);
335 ConfValue("power","diepass",0,diepass);
336 ConfValue("power","pause",0,pauseval);
337 ConfValue("power","restartpass",0,restartpass);
338 ConfValue("options","prefixquit",0,PrefixQuit);
339 ConfValue("die","value",0,DieValue);
340 ConfValue("options","loglevel",0,dbg);
341 if (!strcmp(dbg,"debug"))
343 if (!strcmp(dbg,"verbose"))
345 if (!strcmp(dbg,"default"))
347 if (!strcmp(dbg,"sparse"))
349 if (!strcmp(dbg,"none"))
351 readfile(RULES,rules);
352 log(DEBUG,"Reading connect classes");
354 for (int i = 0; i < ConfValueEnum("connect"); i++)
357 ConfValue("connect","allow",i,Value);
358 if (strcmp(Value,""))
360 strcpy(c.host,Value);
363 ConfValue("connect","password",i,Value);
364 strcpy(c.pass,Value);
365 Classes.push_back(c);
366 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
370 ConfValue("connect","deny",i,Value);
371 strcpy(c.host,Value);
373 Classes.push_back(c);
374 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
383 log(DEBUG,"Blocking: %d",s);
384 flags = fcntl(s, F_GETFL, 0);
385 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
388 void NonBlocking(int s)
391 log(DEBUG,"NonBlocking: %d",s);
392 flags = fcntl(s, F_GETFL, 0);
393 fcntl(s, F_SETFL, flags | O_NONBLOCK);
397 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
399 struct hostent *hostPtr = NULL;
402 memset (resolvedHost, '\0',MAXBUF);
403 if(unresolvedHost == NULL)
405 if ((inet_aton(unresolvedHost,&addr)) == 0)
407 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
409 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
411 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
415 /* write formatted text to a socket, in same format as printf */
417 void Write(int sock,char *text, ...)
419 char textbuffer[MAXBUF];
423 va_start (argsPtr, text);
424 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
426 sprintf(tb,"%s\r\n",textbuffer);
428 write(sock,tb,strlen(tb));
429 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
432 /* write a server formatted numeric response to a single socket */
434 void WriteServ(int sock, char* text, ...)
436 char textbuffer[MAXBUF],tb[MAXBUF];
438 va_start (argsPtr, text);
440 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
442 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
444 write(sock,tb,strlen(tb));
445 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
448 /* write text from an originating user to originating user */
450 void WriteFrom(int sock, userrec *user,char* text, ...)
452 char textbuffer[MAXBUF],tb[MAXBUF];
454 va_start (argsPtr, text);
456 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
458 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
460 write(sock,tb,strlen(tb));
461 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
464 /* write text to an destination user from a source user (e.g. user privmsg) */
466 void WriteTo(userrec *source, userrec *dest,char *data, ...)
468 char textbuffer[MAXBUF],tb[MAXBUF];
470 va_start (argsPtr, data);
471 if ((!dest) || (!source))
475 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
478 WriteFrom(dest->fd,source,"%s",textbuffer);
481 /* write formatted text from a source user to all users on a channel
482 * including the sender (NOT for privmsg, notice etc!) */
484 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
486 char textbuffer[MAXBUF];
488 va_start (argsPtr, text);
489 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
491 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
493 if (has_channel(i->second,Ptr))
495 WriteTo(user,i->second,"%s",textbuffer);
500 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
502 char textbuffer[MAXBUF];
504 va_start (argsPtr, text);
505 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
507 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
509 if (has_channel(i->second,Ptr))
511 WriteServ(i->second->fd,"%s",textbuffer);
517 /* write formatted text from a source user to all users on a channel except
518 * for the sender (for privmsg etc) */
520 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
522 char textbuffer[MAXBUF];
524 va_start (argsPtr, text);
525 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
528 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
530 if (has_channel(i->second,Ptr) && (user != i->second))
532 WriteTo(user,i->second,"%s",textbuffer);
537 int c_count(userrec* u)
540 for (int i =0; i != MAXCHANS; i++)
541 if (u->chans[i].channel)
547 /* return 0 or 1 depending if users u and u2 share one or more common channels
548 * (used by QUIT, NICK etc which arent channel specific notices) */
550 int common_channels(userrec *u, userrec *u2)
559 for (i = 0; i != MAXCHANS; i++)
561 for (z = 0; z != MAXCHANS; z++)
563 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
565 if ((c_count(u)) && (c_count(u2)))
575 /* write a formatted string to all users who share at least one common
576 * channel, including the source user e.g. for use in NICK */
578 void WriteCommon(userrec *u, char* text, ...)
580 char textbuffer[MAXBUF];
582 va_start (argsPtr, text);
583 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
586 WriteFrom(u->fd,u,"%s",textbuffer);
588 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
590 if (common_channels(u,i->second) && (i->second != u))
592 WriteFrom(i->second->fd,u,"%s",textbuffer);
597 /* write a formatted string to all users who share at least one common
598 * channel, NOT including the source user e.g. for use in QUIT */
600 void WriteCommonExcept(userrec *u, char* text, ...)
602 char textbuffer[MAXBUF];
604 va_start (argsPtr, text);
605 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
608 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
610 if ((common_channels(u,i->second)) && (u != i->second))
612 WriteFrom(i->second->fd,u,"%s",textbuffer);
617 void WriteOpers(char* text, ...)
619 char textbuffer[MAXBUF];
621 va_start (argsPtr, text);
622 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
625 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
627 if (strchr(i->second->modes,'o'))
629 if (strchr(i->second->modes,'s'))
631 // send server notices to all with +s
632 // (TODO: needs SNOMASKs)
633 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
639 void WriteWallOps(userrec *source, char* text, ...)
642 char textbuffer[MAXBUF];
644 va_start (argsPtr, text);
645 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
648 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
650 if (strchr(i->second->modes,'w'))
652 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
657 /* convert a string to lowercase. Note following special circumstances
658 * taken from RFC 1459. Many "official" server branches still hold to this
659 * rule so i will too;
661 * Because of IRC's scandanavian origin, the characters {}| are
662 * considered to be the lower case equivalents of the characters []\,
663 * respectively. This is a critical issue when determining the
664 * equivalence of two nicknames.
667 void strlower(char *n)
673 for (int i = 0; i != strlen(n); i++)
675 n[i] = tolower(n[i]);
685 /* verify that a user's ident and nickname is valid */
687 int isident(const char* n)
700 for (i = 0; i != strlen(n); i++)
702 if ((n[i] < 33) || (n[i] > 125))
706 /* can't occur ANYWHERE in an Ident! */
707 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
716 int isnick(const char* n)
728 if (strlen(n) > NICKMAX-1)
732 for (i = 0; i != strlen(n); i++)
734 if ((n[i] < 33) || (n[i] > 125))
738 /* can't occur ANYWHERE in a nickname! */
739 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
743 /* can't occur as the first char of a nickname... */
744 if ((strchr("0123456789",n[i])) && (!i))
752 /* Find a user record by nickname and return a pointer to it */
754 userrec* Find(string nick)
756 user_hash::iterator iter = clientlist.find(nick);
758 if (iter == clientlist.end())
759 /* Couldn't find it */
765 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
767 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
769 if (i->second->fd == fd)
771 i->second->bytes_out+=data_out;
772 i->second->cmds_out++;
778 /* find a channel record by channel name and return a pointer to it */
780 chanrec* FindChan(const char* chan)
782 chan_hash::iterator iter = chanlist.find(chan);
784 if (iter == chanlist.end())
785 /* Couldn't find it */
792 void purge_empty_chans(void)
794 int go_again = 1, purge = 0;
799 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
802 if (!usercount(i->second))
804 /* kill the record */
805 if (i != chanlist.end())
807 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
818 log(DEBUG,"completed channel purge, killed %d",purge);
821 /* returns the status character for a given user on a channel, e.g. @ for op,
822 * % for halfop etc. If the user has several modes set, the highest mode
823 * the user has must be returned. */
825 char* cmode(userrec *user, chanrec *chan)
828 for (i = 0; i != MAXCHANS; i++)
830 if ((user->chans[i].channel == chan) && (chan != NULL))
832 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
836 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
840 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
849 char scratch[MAXMODES];
851 char* chanmodes(chanrec *chan)
854 if (chan->noexternal)
862 if (strcmp(chan->key,""))
870 if (chan->inviteonly)
886 if (strcmp(chan->key,""))
889 strcat(scratch,chan->key);
894 sprintf(foo," %d",chan->limit);
897 log(DEBUG,"chanmodes: %s %s",chan->name,scratch);
901 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
902 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
903 * highest mode the user has must be returned. */
905 int cstatus(userrec *user, chanrec *chan)
908 for (i = 0; i != MAXCHANS; i++)
910 if ((user->chans[i].channel == chan) && (chan != NULL))
912 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
916 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
920 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
924 return STATUS_NORMAL;
930 /* compile a userlist of a channel into a string, each nick seperated by
931 * spaces and op, voice etc status shown as @ and + */
933 void userlist(userrec *user,chanrec *c)
935 sprintf(list,"353 %s = %s :", user->nick, c->name);
936 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
938 if (has_channel(i->second,c))
940 if (isnick(i->second->nick))
942 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
944 /* user is +i, and source not on the channel, does not show
945 * nick in NAMES list */
948 strcat(list,cmode(i->second,c));
949 strcat(list,i->second->nick);
951 if (strlen(list)>(480-NICKMAX))
953 /* list overflowed into
954 * multiple numerics */
955 WriteServ(user->fd,list);
956 sprintf(list,"353 %s = %s :", user->nick, c->name);
961 /* if whats left in the list isnt empty, send it */
962 if (list[strlen(list)-1] != ':')
964 WriteServ(user->fd,list);
968 /* return a count of the users on a specific channel accounting for
969 * invisible users who won't increase the count. e.g. for /LIST */
971 int usercount_i(chanrec *c)
977 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
981 if (has_channel(i->second,c))
983 if (isnick(i->second->nick))
985 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
987 /* user is +i, and source not on the channel, does not show
988 * nick in NAMES list */
996 log(DEBUG,"usercount_i: %s %d",c->name,count);
1001 int usercount(chanrec *c)
1007 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1011 if (has_channel(i->second,c))
1013 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1020 log(DEBUG,"usercount: %s %d",c->name,count);
1025 /* add a channel to a user, creating the record for it if needed and linking
1026 * it to the user record */
1028 chanrec* add_channel(userrec *user, char* cname, char* key)
1034 if ((!cname) || (!user))
1038 if (strlen(cname) > CHANMAX-1)
1040 cname[CHANMAX-1] = '\0';
1043 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1045 if ((has_channel(user,FindChan(cname))) && (FindChan(cname)))
1047 return NULL; // already on the channel!
1050 if (!FindChan(cname))
1052 /* create a new one */
1053 log(DEBUG,"add_channel: creating: %s",cname);
1055 chanlist[cname] = new chanrec();
1057 strcpy(chanlist[cname]->name, cname);
1058 chanlist[cname]->topiclock = 1;
1059 chanlist[cname]->noexternal = 1;
1060 chanlist[cname]->created = time(NULL);
1061 strcpy(chanlist[cname]->topic, "");
1062 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1063 chanlist[cname]->topicset = 0;
1064 Ptr = chanlist[cname];
1065 log(DEBUG,"add_channel: created: %s",cname);
1066 /* set created to 2 to indicate user
1067 * is the first in the channel
1068 * and should be given ops */
1074 /* channel exists, just fish out a pointer to its struct */
1075 Ptr = FindChan(cname);
1078 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1079 if (strcmp(Ptr->key,""))
1081 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1084 log(DEBUG,"add_channel: no key given in JOIN");
1085 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1090 log(DEBUG,"key at %p is %s",key,key);
1091 if (strcasecmp(key,Ptr->key))
1093 log(DEBUG,"add_channel: bad key given in JOIN");
1094 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1099 log(DEBUG,"add_channel: no key");
1101 if (Ptr->inviteonly)
1103 log(DEBUG,"add_channel: channel is +i");
1104 if (user->IsInvited(Ptr->name))
1106 /* user was invited to channel */
1107 /* there may be an optional channel NOTICE here */
1111 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1115 log(DEBUG,"add_channel: channel is not +i");
1119 if (usercount(Ptr) == Ptr->limit)
1121 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1126 log(DEBUG,"add_channel: about to walk banlist");
1128 /* check user against the channel banlist */
1129 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1131 if (match(user->GetFullHost(),i->data))
1133 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1138 log(DEBUG,"add_channel: bans checked");
1140 user->RemoveInvite(Ptr->name);
1142 log(DEBUG,"add_channel: invites removed");
1148 log(DEBUG,"Passed channel checks");
1150 for (i =0; i != MAXCHANS; i++)
1152 if (user->chans[i].channel == NULL)
1154 log(DEBUG,"Adding into their channel list");
1158 /* first user in is given ops */
1159 user->chans[i].uc_modes = UCMODE_OP;
1163 user->chans[i].uc_modes = 0;
1165 user->chans[i].channel = Ptr;
1166 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1168 log(DEBUG,"Sent JOIN to client");
1172 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1173 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1176 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1177 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1178 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1179 FOREACH_MOD OnUserJoin(user,Ptr);
1183 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1184 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1188 /* remove a channel from a users record, and remove the record from memory
1189 * if the channel has become empty */
1191 chanrec* del_channel(userrec *user, char* cname, char* reason)
1197 if ((!cname) || (!user))
1202 Ptr = FindChan(cname);
1209 FOREACH_MOD OnUserPart(user,Ptr);
1210 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1212 for (i =0; i != MAXCHANS; i++)
1214 /* zap it from the channel list of the user */
1215 if (user->chans[i].channel == Ptr)
1219 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1223 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1225 user->chans[i].uc_modes = 0;
1226 user->chans[i].channel = NULL;
1227 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1232 /* if there are no users left on the channel */
1233 if (!usercount(Ptr))
1235 chan_hash::iterator iter = chanlist.find(Ptr->name);
1237 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1239 /* kill the record */
1240 if (iter != chanlist.end())
1242 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1243 delete iter->second;
1244 chanlist.erase(iter);
1250 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1255 if ((!Ptr) || (!user) || (!src))
1260 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1262 if (!has_channel(user,Ptr))
1264 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1267 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1269 if (cstatus(src,Ptr) == STATUS_HOP)
1271 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1275 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1281 for (i =0; i != MAXCHANS; i++)
1283 /* zap it from the channel list of the user */
1284 if (user->chans[i].channel == Ptr)
1286 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1287 user->chans[i].uc_modes = 0;
1288 user->chans[i].channel = NULL;
1289 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1294 /* if there are no users left on the channel */
1295 if (!usercount(Ptr))
1297 chan_hash::iterator iter = chanlist.find(Ptr->name);
1299 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1301 /* kill the record */
1302 if (iter != chanlist.end())
1304 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1305 delete iter->second;
1306 chanlist.erase(iter);
1312 /* returns 1 if user u has channel c in their record, 0 if not */
1314 int has_channel(userrec *u, chanrec *c)
1322 for (i =0; i != MAXCHANS; i++)
1324 if (u->chans[i].channel == c)
1332 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1337 if ((!user) || (!dest) || (!chan))
1341 if (status != STATUS_OP)
1343 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1350 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1356 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1361 for (i = 0; i != MAXCHANS; i++)
1363 if ((d->chans[i].channel == chan) && (chan != NULL))
1365 if (d->chans[i].uc_modes & UCMODE_OP)
1367 /* mode already set on user, dont allow multiple */
1370 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1371 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1379 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1384 if ((!user) || (!dest) || (!chan))
1388 if (status != STATUS_OP)
1390 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1398 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1403 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1408 for (i = 0; i != MAXCHANS; i++)
1410 if ((d->chans[i].channel == chan) && (chan != NULL))
1412 if (d->chans[i].uc_modes & UCMODE_HOP)
1414 /* mode already set on user, dont allow multiple */
1417 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1418 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1426 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1431 if ((!user) || (!dest) || (!chan))
1435 if (status < STATUS_HOP)
1437 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1445 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1450 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1455 for (i = 0; i != MAXCHANS; i++)
1457 if ((d->chans[i].channel == chan) && (chan != NULL))
1459 if (d->chans[i].uc_modes & UCMODE_VOICE)
1461 /* mode already set on user, dont allow multiple */
1464 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1465 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1473 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1478 if ((!user) || (!dest) || (!chan))
1482 if (status != STATUS_OP)
1484 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1492 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1497 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1502 for (i = 0; i != MAXCHANS; i++)
1504 if ((d->chans[i].channel == chan) && (chan != NULL))
1506 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1508 /* mode already set on user, dont allow multiple */
1511 d->chans[i].uc_modes ^= UCMODE_OP;
1512 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1520 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1525 if ((!user) || (!dest) || (!chan))
1529 if (status != STATUS_OP)
1531 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1539 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1544 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1549 for (i = 0; i != MAXCHANS; i++)
1551 if ((d->chans[i].channel == chan) && (chan != NULL))
1553 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1555 /* mode already set on user, dont allow multiple */
1558 d->chans[i].uc_modes ^= UCMODE_HOP;
1559 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1567 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1572 if ((!user) || (!dest) || (!chan))
1576 if (status < STATUS_HOP)
1578 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1586 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1591 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1596 for (i = 0; i != MAXCHANS; i++)
1598 if ((d->chans[i].channel == chan) && (chan != NULL))
1600 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1602 /* mode already set on user, dont allow multiple */
1605 d->chans[i].uc_modes ^= UCMODE_VOICE;
1606 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1614 void TidyBan(char *ban)
1616 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1620 char* pos_of_pling = strchr(temp,'!');
1621 char* pos_of_at = strchr(temp,'@');
1623 pos_of_pling[0] = '\0';
1624 pos_of_at[0] = '\0';
1628 strncpy(NICK,temp,NICKMAX);
1629 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1630 strncpy(HOST,pos_of_at,160);
1632 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1635 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1638 if ((!user) || (!dest) || (!chan))
1640 if (strchr(dest,'!')==0)
1642 if (strchr(dest,'@')==0)
1644 for (int i = 0; i < strlen(dest); i++)
1647 for (int i = 0; i < strlen(dest); i++)
1651 for (int i = 0; i < strlen(dest); i++)
1657 for (int i = 0; i < strlen(dest); i++)
1662 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1665 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1667 if (!strcasecmp(i->data,dest))
1669 // dont allow a user to set the same ban twice
1674 b.set_time = time(NULL);
1675 strncpy(b.data,dest,MAXBUF);
1676 strncpy(b.set_by,user->nick,NICKMAX);
1677 chan->bans.push_back(b);
1681 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1683 if ((!user) || (!dest) || (!chan))
1688 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1689 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1691 if (!strcasecmp(i->data,dest))
1693 chan->bans.erase(i);
1700 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1702 char modelist[MAXBUF];
1703 char outlist[MAXBUF];
1704 char outstr[MAXBUF];
1705 char outpars[32][MAXBUF];
1711 bool k_set = false, l_set = false;
1718 log(DEBUG,"process_modes: start");
1720 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1721 /* parameters[2] onwards are parameters for
1722 * modes that require them :) */
1723 strcpy(outlist,"+");
1726 log(DEBUG,"process_modes: modelist: %s",modelist);
1728 for (ptr = 0; ptr < strlen(modelist); ptr++)
1733 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1734 char modechar = modelist[ptr];
1735 switch (modelist[ptr])
1740 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1742 outlist[strlen(outlist)-1] = '-';
1746 strcat(outlist,"-");
1756 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1758 outlist[strlen(outlist)-1] = '+';
1762 strcat(outlist,"+");
1769 if ((param >= pcnt)) break;
1772 r = give_ops(user,parameters[param++],chan,status);
1776 r = take_ops(user,parameters[param++],chan,status);
1780 strcat(outlist,"o");
1781 strcpy(outpars[pc++],parameters[param-1]);
1786 if ((param >= pcnt)) break;
1789 r = give_hops(user,parameters[param++],chan,status);
1793 r = take_hops(user,parameters[param++],chan,status);
1797 strcat(outlist,"h");
1798 strcpy(outpars[pc++],parameters[param-1]);
1804 if ((param >= pcnt)) break;
1807 r = give_voice(user,parameters[param++],chan,status);
1811 r = take_voice(user,parameters[param++],chan,status);
1815 strcat(outlist,"v");
1816 strcpy(outpars[pc++],parameters[param-1]);
1821 if ((param >= pcnt)) break;
1824 r = add_ban(user,parameters[param++],chan,status);
1828 r = take_ban(user,parameters[param++],chan,status);
1832 strcat(outlist,"b");
1833 strcpy(outpars[pc++],parameters[param-1]);
1838 if ((param >= pcnt))
1846 if (!strcmp(chan->key,""))
1848 strcat(outlist,"k");
1849 strcpy(outpars[pc++],parameters[param++]);
1850 strcpy(chan->key,parameters[param-1]);
1856 /* only allow -k if correct key given */
1857 if (strcmp(chan->key,""))
1859 strcat(outlist,"k");
1860 strcpy(chan->key,"");
1870 strcat(outlist,"l");
1875 if ((param >= pcnt)) break;
1881 bool invalid = false;
1882 for (int i = 0; i < strlen(parameters[param]); i++)
1884 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
1889 if (atoi(parameters[param]) < 1)
1897 chan->limit = atoi(parameters[param]);
1900 strcat(outlist,"l");
1901 strcpy(outpars[pc++],parameters[param++]);
1908 if (chan->inviteonly != mdir)
1910 strcat(outlist,"i");
1912 chan->inviteonly = mdir;
1916 if (chan->topiclock != mdir)
1918 strcat(outlist,"t");
1920 chan->topiclock = mdir;
1924 if (chan->noexternal != mdir)
1926 strcat(outlist,"n");
1928 chan->noexternal = mdir;
1932 if (chan->moderated != mdir)
1934 strcat(outlist,"m");
1936 chan->moderated = mdir;
1940 if (chan->secret != mdir)
1942 strcat(outlist,"s");
1943 if (chan->c_private)
1945 chan->c_private = 0;
1948 strcat(outlist,"-p+");
1952 strcat(outlist,"+p-");
1956 chan->secret = mdir;
1960 if (chan->c_private != mdir)
1962 strcat(outlist,"p");
1968 strcat(outlist,"-s+");
1972 strcat(outlist,"+s-");
1976 chan->c_private = mdir;
1982 if (ModeDefined(modelist[ptr],MT_CHANNEL))
1984 if ((ModeDefinedOn(modelist[ptr],MT_CHANNEL)>0) && (mdir))
1986 p.push_back(parameters[param]);
1988 if ((ModeDefinedOff(modelist[ptr],MT_CHANNEL)>0) && (!mdir))
1990 p.push_back(parameters[param]);
1992 for (int i = 0; i <= MODCOUNT; i++)
1994 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
1996 char app[] = {modechar, 0};
1997 strcat(outlist, app);
1998 chan->SetCustomMode(modelist[ptr],mdir);
1999 // include parameters in output if mode has them
2000 if ((ModeDefinedOn(modelist[ptr],MT_CHANNEL)>0) || (ModeDefinedOff(modelist[ptr],MT_CHANNEL)>0))
2002 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2003 strcpy(outpars[pc++],parameters[param++]);
2014 /* this ensures only the *valid* modes are sent out onto the network */
2015 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2017 outlist[strlen(outlist)-1] = '\0';
2019 if (strcmp(outlist,""))
2021 strcpy(outstr,outlist);
2022 for (ptr = 0; ptr < pc; ptr++)
2025 strcat(outstr,outpars[ptr]);
2029 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2033 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2038 void handle_mode(char **parameters, int pcnt, userrec *user)
2044 char outpars[MAXBUF];
2046 dest = Find(parameters[0]);
2048 if ((dest) && (pcnt == 1))
2050 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2053 if ((dest) && (pcnt > 1))
2058 if (strchr(user->modes,'o'))
2069 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2073 strcpy(outpars,"+");
2076 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2079 for (i = 0; i < strlen(parameters[1]); i++)
2081 if (parameters[1][i] == '+')
2085 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2087 outpars[strlen(outpars)-1] = '+';
2091 strcat(outpars,"+");
2097 if (parameters[1][i] == '-')
2101 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2103 outpars[strlen(outpars)-1] = '-';
2107 strcat(outpars,"-");
2115 if (strchr(user->modes,'o'))
2121 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2130 if (!strchr(dest->modes,parameters[1][i]))
2132 dest->modes[strlen(dest->modes)+1]='\0';
2133 dest->modes[strlen(dest->modes)] = parameters[1][i];
2134 outpars[strlen(outpars)+1]='\0';
2135 outpars[strlen(outpars)] = parameters[1][i];
2144 outpars[strlen(outpars)+1]='\0';
2145 outpars[strlen(outpars)] = parameters[1][i];
2148 for (q = 0; q < strlen(user->modes); q++)
2150 if (user->modes[q] != parameters[1][i])
2152 moo[0] = user->modes[q];
2157 strcpy(user->modes,temp);
2162 if (strlen(outpars))
2168 while (i < strlen (outpars))
2170 b[z++] = outpars[i++];
2172 if (i<strlen(outpars)-1)
2174 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2176 // someones playing silly buggers and trying
2177 // to put a +- or -+ into the line...
2181 if (i == strlen(outpars)-1)
2183 if ((outpars[i] == '-') || (outpars[i] == '+'))
2191 if ((b[z] == '-') || (b[z] == '+'))
2194 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2197 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2202 Ptr = FindChan(parameters[0]);
2207 /* just /modes #channel */
2208 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2209 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2215 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2218 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2220 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2222 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2226 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2228 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2232 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2236 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2243 void server_mode(char **parameters, int pcnt, userrec *user)
2249 char outpars[MAXBUF];
2251 dest = Find(parameters[0]);
2253 if ((dest) && (pcnt > 1))
2255 strcpy(outpars,"+");
2258 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2261 for (i = 0; i < strlen(parameters[1]); i++)
2263 if (parameters[1][i] == '+')
2267 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2269 outpars[strlen(outpars)-1] = '+';
2273 strcat(outpars,"+");
2279 if (parameters[1][i] == '-')
2283 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2285 outpars[strlen(outpars)-1] = '-';
2289 strcat(outpars,"-");
2297 if (strchr(user->modes,'o'))
2303 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2312 if (!strchr(dest->modes,parameters[1][i]))
2314 dest->modes[strlen(dest->modes)+1]='\0';
2315 dest->modes[strlen(dest->modes)] = parameters[1][i];
2316 outpars[strlen(outpars)+1]='\0';
2317 outpars[strlen(outpars)] = parameters[1][i];
2326 outpars[strlen(outpars)+1]='\0';
2327 outpars[strlen(outpars)] = parameters[1][i];
2330 for (q = 0; q < strlen(user->modes); q++)
2332 if (user->modes[q] != parameters[1][i])
2334 moo[0] = user->modes[q];
2339 strcpy(user->modes,temp);
2344 if (strlen(outpars))
2350 while (i < strlen (outpars))
2352 b[z++] = outpars[i++];
2354 if (i<strlen(outpars)-1)
2356 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2358 // someones playing silly buggers and trying
2359 // to put a +- or -+ into the line...
2363 if (i == strlen(outpars)-1)
2365 if ((outpars[i] == '-') || (outpars[i] == '+'))
2373 if ((b[z] == '-') || (b[z] == '+'))
2376 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2379 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2384 Ptr = FindChan(parameters[0]);
2387 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2391 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2396 /* This function pokes and hacks at a parameter list like the following:
2398 * PART #winbot, #darkgalaxy :m00!
2400 * to turn it into a series of individual calls like this:
2402 * PART #winbot :m00!
2403 * PART #darkgalaxy :m00!
2405 * The seperate calls are sent to a callback function provided by the caller
2406 * (the caller will usually call itself recursively). The callback function
2407 * must be a command handler. Calling this function on a line with no list causes
2408 * no action to be taken. You must provide a starting and ending parameter number
2409 * where the range of the list can be found, useful if you have a terminating
2410 * parameter as above which is actually not part of the list, or parameters
2411 * before the actual list as well. This code is used by many functions which
2412 * can function as "one to list" (see the RFC) */
2414 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2419 char blog[32][MAXBUF];
2420 char blog2[32][MAXBUF];
2421 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2422 char keystr[MAXBUF];
2425 for (i = 0; i <32; i++)
2428 for (i = 0; i <32; i++)
2429 strcpy(blog2[i],"");
2432 for (i = 0; i <10; i++)
2436 parameters[i] = moo;
2441 if (pcnt > 1) /* we have a key to copy */
2443 strcpy(keystr,parameters[1]);
2447 if (!parameters[start])
2451 if (!strchr(parameters[start],','))
2456 for (i = start; i <= end; i++)
2460 strcat(plist,parameters[i]);
2468 for (i = 0; i < t; i++)
2470 if (plist[i] == ',')
2473 strcpy(blog[j++],param);
2477 strcpy(blog[j++],param);
2480 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2485 if ((joins) && (keystr))
2487 if (strchr(keystr,','))
2491 t2 = strlen(keystr);
2492 for (i = 0; i < t2; i++)
2494 if (keystr[i] == ',')
2497 strcpy(blog2[j++],param);
2501 strcpy(blog2[j++],param);
2506 for (j = 0; j < total; j++)
2512 for (q = end; q < pcnt-1; q++)
2514 if (parameters[q+1])
2516 pars[q-end+1] = parameters[q+1];
2519 if ((joins) && (parameters[1]))
2530 /* repeatedly call the function with the hacked parameter list */
2531 if ((joins) && (pcnt > 1))
2535 // pars[1] already set up and containing key from blog2[j]
2540 pars[1] = parameters[1];
2546 fn(pars,pcnt-(end-start),u);
2553 void handle_join(char **parameters, int pcnt, userrec *user)
2558 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2560 if (parameters[0][0] == '#')
2562 Ptr = add_channel(user,parameters[0],parameters[1]);
2567 void handle_part(char **parameters, int pcnt, userrec *user)
2573 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2575 del_channel(user,parameters[0],parameters[1]);
2579 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2581 del_channel(user,parameters[0],NULL);
2585 void handle_kick(char **parameters, int pcnt, userrec *user)
2587 chanrec* Ptr = FindChan(parameters[0]);
2588 userrec* u = Find(parameters[1]);
2592 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2596 if (!has_channel(u,Ptr))
2598 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2604 kick_channel(user,u,Ptr,parameters[2]);
2608 kick_channel(user,u,Ptr,user->nick);
2613 void handle_die(char **parameters, int pcnt, userrec *user)
2615 log(DEBUG,"die: %s",user->nick);
2616 if (!strcmp(parameters[0],diepass))
2618 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2624 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2628 void handle_restart(char **parameters, int pcnt, userrec *user)
2630 log(DEBUG,"restart: %s",user->nick);
2631 if (!strcmp(parameters[0],restartpass))
2633 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2636 /* Will finish this later when i can be arsed :) */
2640 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2645 void kill_link(userrec *user,char* reason)
2647 user_hash::iterator iter = clientlist.find(user->nick);
2649 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2650 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2651 fdatasync(user->fd);
2652 log(DEBUG,"closing fd %d",user->fd);
2654 /* bugfix, cant close() a nonblocking socket (sux!) */
2655 if (user->registered == 7) {
2656 FOREACH_MOD OnUserQuit(user);
2657 WriteCommonExcept(user,"QUIT :%s",reason);
2660 /* push the socket on a stack of sockets due to be closed at the next opportunity */
2661 fd_reap.push_back(user->fd);
2663 bool do_purge = false;
2665 if (user->registered == 7) {
2666 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2670 if (iter != clientlist.end())
2672 log(DEBUG,"deleting user hash value %d",iter->second);
2673 if ((iter->second) && (user->registered == 7)) {
2674 delete iter->second;
2676 clientlist.erase(iter);
2679 purge_empty_chans();
2683 void handle_kill(char **parameters, int pcnt, userrec *user)
2685 userrec *u = Find(parameters[0]);
2686 char killreason[MAXBUF];
2688 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
2691 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
2692 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
2693 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
2694 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
2695 kill_link(u,killreason);
2699 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2703 void handle_summon(char **parameters, int pcnt, userrec *user)
2705 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
2708 void handle_users(char **parameters, int pcnt, userrec *user)
2710 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
2714 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2716 char* Passwd(userrec *user)
2718 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2720 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2728 bool IsDenied(userrec *user)
2730 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2732 if (match(user->host,i->host) && (i->type == CC_DENY))
2741 void handle_pass(char **parameters, int pcnt, userrec *user)
2743 if (!strcasecmp(parameters[0],Passwd(user)))
2745 user->haspassed = true;
2749 void handle_invite(char **parameters, int pcnt, userrec *user)
2751 userrec* u = Find(parameters[0]);
2752 chanrec* c = FindChan(parameters[1]);
2758 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
2764 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2773 if (cstatus(user,c) < STATUS_HOP)
2775 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
2779 u->InviteTo(c->name);
2780 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2781 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2785 void handle_topic(char **parameters, int pcnt, userrec *user)
2791 if (strlen(parameters[0]) <= CHANMAX)
2793 Ptr = FindChan(parameters[0]);
2798 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2799 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2803 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2808 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2814 if (loop_call(handle_topic,parameters,pcnt,user,0,pcnt-2,0))
2816 if (strlen(parameters[0]) <= CHANMAX)
2818 Ptr = FindChan(parameters[0]);
2821 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2823 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
2826 strcpy(Ptr->topic,parameters[1]);
2827 strcpy(Ptr->setby,user->nick);
2828 Ptr->topicset = time(NULL);
2829 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2833 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2839 /* sends out an error notice to all connected clients (not to be used
2842 void send_error(char *s)
2844 log(DEBUG,"send_error: %s",s);
2845 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2847 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2851 void Error(int status)
2853 signal (SIGALRM, SIG_IGN);
2854 signal (SIGPIPE, SIG_IGN);
2855 signal (SIGTERM, SIG_IGN);
2856 signal (SIGABRT, SIG_IGN);
2857 signal (SIGSEGV, SIG_IGN);
2858 signal (SIGURG, SIG_IGN);
2859 signal (SIGKILL, SIG_IGN);
2860 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2861 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2865 int main (int argc, char *argv[])
2868 log(DEBUG,"*** InspIRCd starting up!");
2869 if (!FileExists(CONFIG_FILE))
2871 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2872 log(DEBUG,"main: no config");
2873 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2876 if (InspIRCd() == ERROR)
2878 log(DEBUG,"main: daemon function bailed");
2879 printf("ERROR: could not initialise. Shutting down.\n");
2886 template<typename T> inline string ConvToStr(const T &in)
2889 if (!(tmp << in)) return string();
2893 /* re-allocates a nick in the user_hash after they change nicknames,
2894 * returns a pointer to the new user as it may have moved */
2896 userrec* ReHashNick(char* Old, char* New)
2898 user_hash::iterator newnick;
2899 user_hash::iterator oldnick = clientlist.find(Old);
2901 log(DEBUG,"ReHashNick: %s %s",Old,New);
2903 if (!strcasecmp(Old,New))
2905 log(DEBUG,"old nick is new nick, skipping");
2906 return oldnick->second;
2909 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2911 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2913 clientlist[New] = new userrec();
2914 clientlist[New] = oldnick->second;
2915 /*delete oldnick->second; */
2916 clientlist.erase(oldnick);
2918 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2920 return clientlist[New];
2923 /* adds or updates an entry in the whowas list */
2924 void AddWhoWas(userrec* u)
2926 user_hash::iterator iter = whowas.find(u->nick);
2927 userrec *a = new userrec();
2928 strcpy(a->nick,u->nick);
2929 strcpy(a->ident,u->ident);
2930 strcpy(a->dhost,u->dhost);
2931 strcpy(a->host,u->host);
2932 strcpy(a->fullname,u->fullname);
2933 strcpy(a->server,u->server);
2934 a->signon = u->signon;
2936 /* MAX_WHOWAS: max number of /WHOWAS items
2937 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2938 * can be replaced by a newer one
2941 if (iter == whowas.end())
2943 if (whowas.size() == WHOWAS_MAX)
2945 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2947 // 3600 seconds in an hour ;)
2948 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2952 log(DEBUG,"added WHOWAS entry, purged an old record");
2959 log(DEBUG,"added fresh WHOWAS entry");
2960 whowas[a->nick] = a;
2965 log(DEBUG,"updated WHOWAS entry");
2966 delete iter->second;
2972 /* add a client connection to the sockets list */
2973 void AddClient(int socket, char* host, int port, bool iscached)
2977 char resolved[MAXBUF];
2980 user_hash::iterator iter;
2982 tempnick = ConvToStr(socket) + "-unknown";
2983 sprintf(tn2,"%d-unknown",socket);
2985 iter = clientlist.find(tempnick);
2987 if (iter != clientlist.end()) return;
2990 * It is OK to access the value here this way since we know
2991 * it exists, we just created it above.
2993 * At NO other time should you access a value in a map or a
2994 * hash_map this way.
2996 clientlist[tempnick] = new userrec();
2998 NonBlocking(socket);
2999 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3002 clientlist[tempnick]->fd = socket;
3003 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3004 strncpy(clientlist[tempnick]->host, host,160);
3005 strncpy(clientlist[tempnick]->dhost, host,160);
3006 strncpy(clientlist[tempnick]->server, ServerName,256);
3007 clientlist[tempnick]->registered = 0;
3008 clientlist[tempnick]->signon = time(NULL);
3009 clientlist[tempnick]->nping = time(NULL)+240;
3010 clientlist[tempnick]->lastping = 1;
3011 clientlist[tempnick]->port = port;
3015 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3019 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3022 if (clientlist.size() == MAXCLIENTS)
3023 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3026 void handle_names(char **parameters, int pcnt, userrec *user)
3030 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3032 c = FindChan(parameters[0]);
3035 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3037 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3041 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3046 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3051 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3053 if (parameters[0][0] == '#')
3055 chan = FindChan(parameters[0]);
3058 if ((chan->noexternal) && (!has_channel(user,chan)))
3060 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3063 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3065 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3068 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3072 /* no such nick/channel */
3073 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3078 dest = Find(parameters[0]);
3081 if (strcmp(dest->awaymsg,""))
3083 /* auto respond with aweh msg */
3084 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3086 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3090 /* no such nick/channel */
3091 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3095 void handle_notice(char **parameters, int pcnt, userrec *user)
3100 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3102 if (parameters[0][0] == '#')
3104 chan = FindChan(parameters[0]);
3107 if ((chan->noexternal) && (!has_channel(user,chan)))
3109 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3112 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3114 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3117 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3121 /* no such nick/channel */
3122 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3127 dest = Find(parameters[0]);
3130 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3134 /* no such nick/channel */
3135 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3141 char* chlist(userrec *user)
3146 log(DEBUG,"chlist: %s",user->nick);
3152 for (i = 0; i != MAXCHANS; i++)
3154 if (user->chans[i].channel != NULL)
3156 if (user->chans[i].channel->name)
3158 strcpy(cmp,user->chans[i].channel->name);
3160 if (!strstr(lst,cmp))
3162 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3164 strcat(lst,cmode(user,user->chans[i].channel));
3165 strcat(lst,user->chans[i].channel->name);
3175 void handle_info(char **parameters, int pcnt, userrec *user)
3177 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3178 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3179 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3180 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3183 void handle_time(char **parameters, int pcnt, userrec *user)
3186 struct tm * timeinfo;
3189 timeinfo = localtime ( &rawtime );
3190 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3194 void handle_whois(char **parameters, int pcnt, userrec *user)
3199 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3201 dest = Find(parameters[0]);
3204 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3205 if ((user == dest) || (strchr(user->modes,'o')))
3207 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3209 if (strcmp(chlist(dest),""))
3211 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3213 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3214 if (strcmp(dest->awaymsg,""))
3216 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3218 if (strchr(dest->modes,'o'))
3220 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3222 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3223 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3225 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3229 /* no such nick/channel */
3230 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3234 void handle_quit(char **parameters, int pcnt, userrec *user)
3236 user_hash::iterator iter = clientlist.find(user->nick);
3238 /* theres more to do here, but for now just close the socket */
3241 if (parameters[0][0] == ':')
3245 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3246 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3247 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3251 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3252 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3253 WriteCommonExcept(user,"QUIT :Client exited");
3256 FOREACH_MOD OnUserQuit(user);
3258 /* confucious say, he who close nonblocking socket, get nothing! */
3261 NonBlocking(user->fd);
3264 if (iter != clientlist.end())
3266 log(DEBUG,"deleting user hash value");
3267 delete iter->second;
3268 clientlist.erase(iter);
3271 purge_empty_chans();
3274 void handle_who(char **parameters, int pcnt, userrec *user)
3276 chanrec* Ptr = NULL;
3278 /* theres more to do here, but for now just close the socket */
3281 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3283 if (user->chans[0].channel)
3285 Ptr = user->chans[0].channel;
3286 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3288 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3290 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);
3296 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3300 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3304 if (parameters[0][0] = '#')
3306 Ptr = FindChan(parameters[0]);
3309 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3311 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3313 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);
3316 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3320 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3326 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3328 Ptr = user->chans[0].channel;
3329 printf(user->chans[0].channel->name);
3330 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3332 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3334 if (strchr(i->second->modes,'o'))
3336 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);
3340 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3346 void handle_wallops(char **parameters, int pcnt, userrec *user)
3348 WriteWallOps(user,"%s",parameters[0]);
3351 void handle_list(char **parameters, int pcnt, userrec *user)
3355 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3356 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3358 if ((!i->second->c_private) && (!i->second->secret))
3360 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3363 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3367 void handle_rehash(char **parameters, int pcnt, userrec *user)
3369 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3371 FOREACH_MOD OnRehash();
3372 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3378 return clientlist.size();
3381 int usercount_invisible(void)
3385 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3387 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3392 int usercount_opers(void)
3396 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3398 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3403 int usercount_unknown(void)
3407 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3409 if ((i->second->fd) && (i->second->registered != 7))
3417 return chanlist.size();
3420 int servercount(void)
3425 void handle_lusers(char **parameters, int pcnt, userrec *user)
3427 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3428 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3429 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3430 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3431 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3434 void handle_admin(char **parameters, int pcnt, userrec *user)
3436 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3437 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
3438 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3439 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
3442 void ShowMOTD(userrec *user)
3446 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3449 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3450 for (int i = 0; i != MOTD.size(); i++)
3452 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3454 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3457 void ShowRULES(userrec *user)
3461 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3464 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3465 for (int i = 0; i != RULES.size(); i++)
3467 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3469 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3472 /* shows the message of the day, and any other on-logon stuff */
3473 void ConnectUser(userrec *user)
3475 user->registered = 7;
3476 user->idle_lastmsg = time(NULL);
3477 log(DEBUG,"ConnectUser: %s",user->nick);
3479 if (strcmp(Passwd(user),"") && (!user->haspassed))
3481 Write(user->fd,"ERROR :Closing link: Invalid password");
3482 fdatasync(user->fd);
3483 kill_link(user,"Invalid password");
3488 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3489 fdatasync(user->fd);
3490 kill_link(user,"Unauthorised connection");
3493 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3494 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3495 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3496 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3497 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3498 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);
3499 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);
3501 FOREACH_MOD OnUserConnect(user);
3502 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3505 void handle_version(char **parameters, int pcnt, userrec *user)
3507 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3510 void handle_ping(char **parameters, int pcnt, userrec *user)
3512 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3515 void handle_pong(char **parameters, int pcnt, userrec *user)
3517 // set the user as alive so they survive to next ping
3521 void handle_motd(char **parameters, int pcnt, userrec *user)
3526 void handle_rules(char **parameters, int pcnt, userrec *user)
3531 void handle_user(char **parameters, int pcnt, userrec *user)
3533 if (user->registered < 3)
3535 if (isident(parameters[0]) == 0) {
3536 // This kinda Sucks, According to the RFC thou, its either this,
3537 // or "You have already registered" :p -- Craig
3538 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3541 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3542 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3543 strncat(user->ident,parameters[0],IDENTMAX);
3544 strncpy(user->fullname,parameters[3],128);
3545 user->registered = (user->registered | 1);
3550 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3553 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3554 if (user->registered == 3)
3556 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3561 void handle_userhost(char **parameters, int pcnt, userrec *user)
3563 char Return[MAXBUF],junk[MAXBUF];
3564 sprintf(Return,"302 %s :",user->nick);
3565 for (int i = 0; i < pcnt; i++)
3567 userrec *u = Find(parameters[i]);
3570 if (strchr(u->modes,'o'))
3572 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3573 strcat(Return,junk);
3577 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3578 strcat(Return,junk);
3582 WriteServ(user->fd,Return);
3586 void handle_ison(char **parameters, int pcnt, userrec *user)
3588 char Return[MAXBUF];
3589 sprintf(Return,"303 %s :",user->nick);
3590 for (int i = 0; i < pcnt; i++)
3592 userrec *u = Find(parameters[i]);
3595 strcat(Return,u->nick);
3599 WriteServ(user->fd,Return);
3603 void handle_away(char **parameters, int pcnt, userrec *user)
3607 strcpy(user->awaymsg,parameters[0]);
3608 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3612 strcpy(user->awaymsg,"");
3613 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3617 void handle_whowas(char **parameters, int pcnt, userrec* user)
3619 user_hash::iterator i = whowas.find(parameters[0]);
3621 if (i == whowas.end())
3623 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3624 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3628 time_t rawtime = i->second->signon;
3632 timeinfo = localtime(&rawtime);
3633 strcpy(b,asctime(timeinfo));
3634 b[strlen(b)-1] = '\0';
3636 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3637 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3638 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3643 void handle_trace(char **parameters, int pcnt, userrec *user)
3645 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3649 if (isnick(i->second->nick))
3651 if (strchr(i->second->modes,'o'))
3653 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3657 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3662 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3668 void handle_stats(char **parameters, int pcnt, userrec *user)
3674 if (strlen(parameters[0])>1)
3676 /* make the stats query 1 character long */
3677 parameters[0][1] = '\0';
3680 /* stats m (list number of times each command has been used, plus bytecount) */
3681 if (!strcasecmp(parameters[0],"m"))
3683 for (int i = 0; i < cmdlist.size(); i++)
3685 if (cmdlist[i].handler_function)
3687 if (cmdlist[i].use_count)
3689 /* RPL_STATSCOMMANDS */
3690 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3697 /* stats z (debug and memory info) */
3698 if (!strcasecmp(parameters[0],"z"))
3700 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3701 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3702 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3703 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3704 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3705 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3706 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3707 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3711 if (!strcasecmp(parameters[0],"o"))
3713 for (int i = 0; i < ConfValueEnum("oper"); i++)
3715 char LoginName[MAXBUF];
3716 char HostName[MAXBUF];
3717 char OperType[MAXBUF];
3718 ConfValue("oper","name",i,LoginName);
3719 ConfValue("oper","host",i,HostName);
3720 ConfValue("oper","type",i,OperType);
3721 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3725 /* stats l (show user I/O stats) */
3726 if (!strcasecmp(parameters[0],"l"))
3728 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3729 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3731 if (isnick(i->second->nick))
3733 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);
3737 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);
3743 /* stats u (show server uptime) */
3744 if (!strcasecmp(parameters[0],"u"))
3746 time_t current_time = 0;
3747 current_time = time(NULL);
3748 time_t server_uptime = current_time - startup_time;
3750 stime = gmtime(&server_uptime);
3751 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3752 * Craig suggested this, and it seemed a good idea so in it went */
3753 if (stime->tm_year > 70)
3755 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);
3759 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);
3763 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3764 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3768 void handle_connect(char **parameters, int pcnt, userrec *user)
3770 char Link_ServerName[1024];
3771 char Link_IPAddr[1024];
3772 char Link_Port[1024];
3773 char Link_Pass[1024];
3777 for (int i = 0; i < ConfValueEnum("link"); i++)
3779 ConfValue("link","name",i,Link_ServerName);
3780 ConfValue("link","ipaddr",i,Link_IPAddr);
3781 ConfValue("link","port",i,Link_Port);
3782 ConfValue("link","sendpass",i,Link_Pass);
3783 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3784 LinkPort = atoi(Link_Port);
3785 if (match(Link_ServerName,parameters[0])) {
3791 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3795 // TODO: Perform a check here to stop a server being linked twice!
3797 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3799 if (me[defaultRoute])
3802 // at this point parameters[0] is an ip in a string.
3803 // TODO: Look this up from the <link> blocks instead!
3804 for (int j = 0; j < 255; j++) {
3805 if (servers[j] == NULL) {
3806 servers[j] = new serverrec;
3807 strcpy(servers[j]->internal_addr,Link_IPAddr);
3808 strcpy(servers[j]->name,Link_ServerName);
3809 log(DEBUG,"Allocated new serverrec");
3810 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
3812 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
3817 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
3821 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);
3825 void handle_squit(char **parameters, int pcnt, userrec *user)
3827 // send out an squit across the mesh and then clear the server list (for local squit)
3830 void handle_oper(char **parameters, int pcnt, userrec *user)
3832 char LoginName[MAXBUF];
3833 char Password[MAXBUF];
3834 char OperType[MAXBUF];
3835 char TypeName[MAXBUF];
3836 char Hostname[MAXBUF];
3839 for (i = 0; i < ConfValueEnum("oper"); i++)
3841 ConfValue("oper","name",i,LoginName);
3842 ConfValue("oper","password",i,Password);
3843 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3845 /* correct oper credentials */
3846 ConfValue("oper","type",i,OperType);
3847 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3848 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3849 WriteServ(user->fd,"MODE %s :+o",user->nick);
3850 for (j =0; j < ConfValueEnum("type"); j++)
3852 ConfValue("type","name",j,TypeName);
3853 if (!strcmp(TypeName,OperType))
3855 /* found this oper's opertype */
3856 ConfValue("type","host",j,Hostname);
3857 strncpy(user->dhost,Hostname,256);
3860 if (!strchr(user->modes,'o'))
3862 strcat(user->modes,"o");
3868 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3869 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3872 void handle_nick(char **parameters, int pcnt, userrec *user)
3876 log(DEBUG,"not enough params for handle_nick");
3881 log(DEBUG,"invalid parameter passed to handle_nick");
3884 if (!strlen(parameters[0]))
3886 log(DEBUG,"zero length new nick passed to handle_nick");
3891 log(DEBUG,"invalid user passed to handle_nick");
3896 log(DEBUG,"invalid old nick passed to handle_nick");
3899 if (!strcasecmp(user->nick,parameters[0]))
3901 log(DEBUG,"old nick is new nick, skipping");
3906 if (strlen(parameters[0]) > 1)
3908 if (parameters[0][0] == ':')
3913 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
3915 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
3919 if (isnick(parameters[0]) == 0)
3921 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
3925 if (user->registered == 7)
3927 WriteCommon(user,"NICK %s",parameters[0]);
3930 /* change the nick of the user in the users_hash */
3931 user = ReHashNick(user->nick, parameters[0]);
3932 /* actually change the nick within the record */
3934 if (!user->nick) return;
3936 strncpy(user->nick, parameters[0],NICKMAX);
3938 log(DEBUG,"new nick set: %s",user->nick);
3940 if (user->registered < 3)
3941 user->registered = (user->registered | 2);
3942 if (user->registered == 3)
3944 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3947 log(DEBUG,"exit nickchange: %s",user->nick);
3950 int process_parameters(char **command_p,char *parameters)
3955 q = strlen(parameters);
3958 /* no parameters, command_p invalid! */
3961 if (parameters[0] == ':')
3963 command_p[0] = parameters+1;
3968 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
3970 /* only one parameter */
3971 command_p[0] = parameters;
3972 if (parameters[0] == ':')
3974 if (strchr(parameters,' ') != NULL)
3982 command_p[j++] = parameters;
3983 for (i = 0; i <= q; i++)
3985 if (parameters[i] == ' ')
3987 command_p[j++] = parameters+i+1;
3988 parameters[i] = '\0';
3989 if (command_p[j-1][0] == ':')
3991 *command_p[j-1]++; /* remove dodgy ":" */
3993 /* parameter like this marks end of the sequence */
3997 return j; /* returns total number of items in the list */
4000 void process_command(userrec *user, char* cmd)
4004 char *command_p[127];
4005 char p[MAXBUF], temp[MAXBUF];
4006 int i, j, items, cmd_found;
4008 for (int i = 0; i < 127; i++)
4009 command_p[i] = NULL;
4019 if (!strcmp(cmd,""))
4026 FOREACH_MOD OnServerRaw(tmp,true);
4027 const char* cmd2 = tmp.c_str();
4028 snprintf(cmd,512,"%s",cmd2);
4030 if (!strchr(cmd,' '))
4032 /* no parameters, lets skip the formalities and not chop up
4035 command_p[0] = NULL;
4037 for (int i = 0; i <= strlen(cmd); i++)
4039 cmd[i] = toupper(cmd[i]);
4046 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4047 for (i = 0; i < strlen(temp); i++)
4049 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4055 /* split the full string into a command plus parameters */
4059 if (strchr(cmd,' '))
4061 for (i = 0; i <= strlen(cmd); i++)
4063 /* capitalise the command ONLY, leave params intact */
4064 cmd[i] = toupper(cmd[i]);
4065 /* are we nearly there yet?! :P */
4069 parameters = cmd+i+1;
4077 for (i = 0; i <= strlen(cmd); i++)
4079 cmd[i] = toupper(cmd[i]);
4087 for (i = 0; i != cmdlist.size(); i++)
4089 if (strcmp(cmdlist[i].command,""))
4091 if (!strcmp(command, cmdlist[i].command))
4095 if (strcmp(parameters,""))
4097 items = process_parameters(command_p,parameters);
4102 command_p[0] = NULL;
4108 command_p[0] = NULL;
4113 user->idle_lastmsg = time(NULL);
4114 /* activity resets the ping pending timer */
4115 user->nping = time(NULL) + 120;
4116 if ((items) < cmdlist[i].min_params)
4118 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4119 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4122 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4124 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4125 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4129 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4131 if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4133 if ((!isnick(user->nick)) || (user->registered != 7))
4135 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4136 WriteServ(user->fd,"451 %s :You have not registered",command);
4140 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4142 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4143 if (cmdlist[i].handler_function)
4145 /* ikky /stats counters */
4150 user->bytes_in += strlen(temp);
4153 cmdlist[i].use_count++;
4154 cmdlist[i].total_bytes+=strlen(temp);
4157 /* WARNING: nothing may come after the
4158 * command handler call, as the handler
4159 * may free the user structure! */
4161 cmdlist[i].handler_function(command_p,items,user);
4167 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4168 WriteServ(user->fd,"451 %s :You have not registered",command);
4176 if ((!cmd_found) && (user))
4178 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4179 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4184 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4187 /* create the command and push it onto the table */
4188 strcpy(comm.command,cmd);
4189 comm.handler_function = f;
4190 comm.flags_needed = flags;
4191 comm.min_params = minparams;
4193 comm.total_bytes = 0;
4194 cmdlist.push_back(comm);
4195 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4198 void SetupCommandTable(void)
4200 createcommand("USER",handle_user,0,4);
4201 createcommand("NICK",handle_nick,0,1);
4202 createcommand("QUIT",handle_quit,0,0);
4203 createcommand("VERSION",handle_version,0,0);
4204 createcommand("PING",handle_ping,0,1);
4205 createcommand("PONG",handle_pong,0,1);
4206 createcommand("ADMIN",handle_admin,0,0);
4207 createcommand("PRIVMSG",handle_privmsg,0,2);
4208 createcommand("INFO",handle_info,0,0);
4209 createcommand("TIME",handle_time,0,0);
4210 createcommand("WHOIS",handle_whois,0,1);
4211 createcommand("WALLOPS",handle_wallops,'o',1);
4212 createcommand("NOTICE",handle_notice,0,2);
4213 createcommand("JOIN",handle_join,0,1);
4214 createcommand("NAMES",handle_names,0,1);
4215 createcommand("PART",handle_part,0,1);
4216 createcommand("KICK",handle_kick,0,2);
4217 createcommand("MODE",handle_mode,0,1);
4218 createcommand("TOPIC",handle_topic,0,1);
4219 createcommand("WHO",handle_who,0,1);
4220 createcommand("MOTD",handle_motd,0,0);
4221 createcommand("RULES",handle_join,0,0);
4222 createcommand("OPER",handle_oper,0,2);
4223 createcommand("LIST",handle_list,0,0);
4224 createcommand("DIE",handle_die,'o',1);
4225 createcommand("RESTART",handle_restart,'o',1);
4226 createcommand("KILL",handle_kill,'o',2);
4227 createcommand("REHASH",handle_rehash,'o',0);
4228 createcommand("LUSERS",handle_lusers,0,0);
4229 createcommand("STATS",handle_stats,0,1);
4230 createcommand("USERHOST",handle_userhost,0,1);
4231 createcommand("AWAY",handle_away,0,0);
4232 createcommand("ISON",handle_ison,0,0);
4233 createcommand("SUMMON",handle_summon,0,0);
4234 createcommand("USERS",handle_users,0,0);
4235 createcommand("INVITE",handle_invite,0,2);
4236 createcommand("PASS",handle_pass,0,1);
4237 createcommand("TRACE",handle_trace,'o',0);
4238 createcommand("WHOWAS",handle_whowas,0,1);
4239 createcommand("CONNECT",handle_connect,'o',1);
4240 createcommand("SQUIT",handle_squit,'o',1);
4243 void process_buffer(userrec *user)
4251 if (!strcmp(user->inbuf,""))
4255 strncpy(cmd,user->inbuf,MAXBUF);
4256 if (!strcmp(cmd,""))
4260 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4262 cmd[strlen(cmd)-1] = '\0';
4264 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4266 cmd[strlen(cmd)-1] = '\0';
4268 strcpy(user->inbuf,"");
4269 if (!strcmp(cmd,""))
4273 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4274 process_command(user,cmd);
4277 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4279 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4283 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4285 char response[10240];
4286 char token = udp_msg[0];
4287 char* params = udp_msg + 2;
4288 char finalparam[1024];
4289 strcpy(finalparam," :xxxx");
4290 if (strstr(params," :")) {
4291 strncpy(finalparam,strstr(params," :"),1024);
4294 // S test.chatspike.net password :ChatSpike InspIRCd test server
4295 char* servername = strtok(params," ");
4296 char* password = strtok(NULL," ");
4297 char* serverdesc = finalparam+2;
4298 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4301 char Link_ServerName[1024];
4302 char Link_IPAddr[1024];
4303 char Link_Port[1024];
4304 char Link_Pass[1024];
4305 char Link_SendPass[1024];
4308 // search for a corresponding <link> block in the config files
4309 for (int i = 0; i < ConfValueEnum("link"); i++)
4311 ConfValue("link","name",i,Link_ServerName);
4312 ConfValue("link","ipaddr",i,Link_IPAddr);
4313 ConfValue("link","port",i,Link_Port);
4314 ConfValue("link","recvpass",i,Link_Pass);
4315 ConfValue("link","sendpass",i,Link_SendPass);
4316 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4317 LinkPort = atoi(Link_Port);
4318 if (!strcasecmp(Link_ServerName,servername)) {
4319 if (!strcasecmp(Link_IPAddr,udp_host)) {
4320 if (LinkPort == udp_port) {
4321 // we have a matching link line -
4322 // send a 'diminutive' server message back...
4323 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4324 serv->SendPacket(response,udp_host,udp_port,0);
4325 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4326 for (int j = 0; j < 255; j++) {
4327 if (servers[j] == NULL) {
4328 servers[j] = new serverrec;
4329 strcpy(servers[j]->internal_addr,udp_host);
4330 strcpy(servers[j]->name,servername);
4331 // create a server record for this server
4332 snprintf(response,10240,"O %d",MyKey);
4333 serv->SendPacket(response,udp_host,udp_port,0);
4337 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4341 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4345 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4349 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4352 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4353 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4358 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4359 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4360 // array, which is only added by an 'S' packet or BeginLink().
4361 for (int i = 0; i < 255; i++) {
4362 if (servers[i] != NULL) {
4363 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4364 servers[i]->key = atoi(params);
4365 log(DEBUG,"Key for this server is now %d",servers[i]->key);
4366 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4371 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4375 // S test.chatspike.net password :ChatSpike InspIRCd test server
4376 char* servername = strtok(params," ");
4377 char* password = strtok(NULL," ");
4378 char* serverdesc = finalparam+2;
4380 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4381 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4382 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4383 // a connect, so put out an oper alert!
4388 // for now, just accept all, we'll fix that later.
4389 WriteOpers("%s accepted our link credentials ",servername);
4391 char Link_ServerName[1024];
4392 char Link_IPAddr[1024];
4393 char Link_Port[1024];
4394 char Link_Pass[1024];
4395 char Link_SendPass[1024];
4398 // search for a corresponding <link> block in the config files
4399 for (int i = 0; i < ConfValueEnum("link"); i++)
4401 ConfValue("link","name",i,Link_ServerName);
4402 ConfValue("link","ipaddr",i,Link_IPAddr);
4403 ConfValue("link","port",i,Link_Port);
4404 ConfValue("link","recvpass",i,Link_Pass);
4405 ConfValue("link","sendpass",i,Link_SendPass);
4406 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4407 LinkPort = atoi(Link_Port);
4408 if (!strcasecmp(Link_ServerName,servername)) {
4409 if (!strcasecmp(Link_IPAddr,udp_host)) {
4410 if (LinkPort == udp_port) {
4411 // matching link at this end too, we're all done!
4412 // at this point we must begin key exchange and insert this
4413 // server into our 'active' table.
4414 for (int j = 0; j < 255; j++) {
4415 if (servers[j] != NULL) {
4416 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4417 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4418 snprintf(response,10240,"O %d",MyKey);
4419 serv->SendPacket(response,udp_host,udp_port,0);
4424 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4429 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4433 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4437 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4440 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4441 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4446 char* error_message = finalparam+2;
4447 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4448 // remove this server from any lists
4449 for (int j = 0; j < 255; j++) {
4450 if (servers[j] != NULL) {
4451 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4461 serverrec* source_server = NULL;
4463 for (int j = 0; j < 255; j++) {
4464 if (servers[j] != NULL) {
4465 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4466 if (servers[j]->key == theirkey) {
4467 // found a valid key for this server, can process restricted stuff here
4468 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4476 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4480 int reap_counter = 0;
4484 struct sockaddr_in client, server;
4485 char addrs[MAXBUF][255];
4486 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4488 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4489 int selectResult = 0;
4490 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4491 char resolvedHost[MAXBUF];
4495 log(DEBUG,"InspIRCd: startup: begin");
4499 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4501 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4503 SetupCommandTable();
4504 log(DEBUG,"InspIRCd: startup: default command table set up");
4507 if (strcmp(DieValue,""))
4509 printf("WARNING: %s\n\n",DieValue);
4512 log(DEBUG,"InspIRCd: startup: read config");
4514 int count2 = 0, count3 = 0;
4515 for (count = 0; count < ConfValueEnum("bind"); count++)
4517 ConfValue("bind","port",count,configToken);
4518 ConfValue("bind","address",count,Addr);
4519 ConfValue("bind","type",count,Type);
4520 if (!strcmp(Type,"servers"))
4522 char Default[MAXBUF];
4523 strcpy(Default,"no");
4524 ConfValue("bind","default",count,Default);
4525 if (strchr(Default,'y'))
4527 defaultRoute = count3;
4528 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4530 me[count3] = new serverrec(ServerName,100L,false);
4531 me[count3]->CreateListener(Addr,atoi(configToken));
4536 ports[count2] = atoi(configToken);
4537 strcpy(addrs[count2],Addr);
4540 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4543 UDPportCount = count3;
4545 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4547 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4551 /* BugFix By Craig! :p */
4553 for (count = 0; count2 < ConfValueEnum("module"); count2++)
4555 char modfile[MAXBUF];
4556 ConfValue("module","name",count,configToken);
4557 sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4558 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4559 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4560 /* If The File Doesnt exist, Trying to load it
4561 * Will Segfault the IRCd.. So, check to see if
4562 * it Exists, Before Proceeding. */
4563 if (FileExists(modfile))
4565 factory[count] = new ircd_module(modfile);
4566 if (factory[count]->LastError())
4568 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4569 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4572 if (factory[count]->factory)
4574 modules[count] = factory[count]->factory->CreateModule();
4575 /* save the module and the module's classfactory, if
4576 * this isnt done, random crashes can occur :/ */
4580 log(DEBUG,"Unable to load %s",modfile);
4581 sprintf("Unable to load %s\nExiting...\n",modfile);
4584 /* Increase the Count */
4589 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4590 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4593 MODCOUNT = count - 1;
4594 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4596 printf("\nInspIRCd is now running!\n");
4598 startup_time = time(NULL);
4600 if (DaemonSeed() == ERROR)
4602 log(DEBUG,"InspIRCd: startup: can't daemonise");
4603 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4608 /* setup select call */
4609 FD_ZERO(&selectFds);
4610 log(DEBUG,"InspIRCd: startup: zero selects");
4611 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4613 for (count = 0; count < portCount; count++)
4615 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4617 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4620 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4622 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4624 else /* well we at least bound to one socket so we'll continue */
4630 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4632 /* if we didn't bind to anything then abort */
4633 if (boundPortCount == 0)
4635 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4639 length = sizeof (client);
4640 int flip_flop = 0, udp_port = 0;
4641 char udp_msg[MAXBUF], udp_host[MAXBUF];
4643 /* main loop for multiplexing/resetting */
4646 /* set up select call */
4647 for (count = 0; count < boundPortCount; count++)
4649 FD_SET (openSockfd[count], &selectFds);
4652 /* added timeout! select was waiting forever... wank... :/ */
4663 vector<int>::iterator niterator;
4666 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4667 // them in a list, then reap the list every second or so.
4668 if (reap_counter>5000) {
4669 if (fd_reap.size() > 0) {
4670 for( int n = 0; n < fd_reap.size(); n++)
4672 Blocking(fd_reap[n]);
4674 NonBlocking(fd_reap[n]);
4683 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4685 for (int x = 0; x != UDPportCount; x++)
4688 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
4690 if (strlen(udp_msg)<1) {
4691 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
4694 FOREACH_MOD OnPacketReceive(udp_msg);
4695 // Packets must go back via the route they arrived on :)
4696 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
4701 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
4705 if (!count2->second) break;
4708 if (count2->second->fd)
4710 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4712 if (!count2->second->lastping)
4714 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4715 kill_link(count2->second,"Ping timeout");
4718 Write(count2->second->fd,"PING :%s",ServerName);
4719 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4720 count2->second->lastping = 0;
4721 count2->second->nping = time(NULL)+120;
4724 result = read(count2->second->fd, data, 1);
4725 // result EAGAIN means nothing read
4726 if (result == EAGAIN)
4732 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
4733 kill_link(count2->second,"Client exited");
4735 else if (result > 0)
4737 strncat(count2->second->inbuf, data, result);
4738 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r'))
4740 /* at least one complete line is waiting to be processed */
4741 if (!count2->second->fd)
4745 process_buffer(count2->second);
4753 /* select is reporting a waiting socket. Poll them all to find out which */
4754 if (selectResult > 0)
4756 char target[MAXBUF], resolved[MAXBUF];
4757 for (count = 0; count < boundPortCount; count++)
4759 if (FD_ISSET (openSockfd[count], &selectFds))
4761 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4763 address_cache::iterator iter = IP.find(client.sin_addr);
4764 bool iscached = false;
4765 if (iter == IP.end())
4767 /* ip isn't in cache, add it */
4768 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4769 if(CleanAndResolve(resolved, target) != TRUE)
4771 strncpy(resolved,target,MAXBUF);
4773 /* hostname now in 'target' */
4774 IP[client.sin_addr] = new string(resolved);
4775 /* hostname in cache */
4779 /* found ip (cached) */
4780 strncpy(resolved, iter->second->c_str(), MAXBUF);
4784 if (incomingSockfd < 0)
4786 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4787 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4791 AddClient(incomingSockfd, resolved, ports[count], iscached);
4792 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4801 close (incomingSockfd);