1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2003 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
32 #include <ext/hash_map>
41 #include "connection.h"
53 #define nspace __gnu_cxx
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
66 char restartpass[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 time_t startup_time = time(NULL);
78 extern vector<Module*> modules;
79 extern vector<ircd_module*> factory;
88 template<> struct nspace::hash<in_addr>
90 size_t operator()(const struct in_addr &a) const
93 memcpy(&q,&a,sizeof(size_t));
98 template<> struct nspace::hash<string>
100 size_t operator()(const string &s) const
103 static struct hash<const char *> strhash;
115 bool operator()(const string& s1, const string& s2) const
117 char a[MAXBUF],b[MAXBUF];
118 strcpy(a,s1.c_str());
119 strcpy(b,s2.c_str());
120 return (strcasecmp(a,b) == 0);
125 struct InAddr_HashComp
128 bool operator()(const in_addr &s1, const in_addr &s2) const
133 memcpy(&q,&s1,sizeof(size_t));
134 memcpy(&p,&s2,sizeof(size_t));
142 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
143 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
144 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
145 typedef std::deque<command_t> command_table;
148 serverrec* servers[255];
150 user_hash clientlist;
153 command_table cmdlist;
160 struct linger linger = { 0 };
161 char bannerBuffer[MAXBUF];
162 int boundPortCount = 0;
163 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
164 int defaultRoute = 0;
168 long MyKey = C.GenKey();
172 int has_channel(userrec *u, chanrec *c);
173 int usercount(chanrec *c);
174 int usercount_i(chanrec *c);
175 void update_stats_l(int fd,int data_out);
176 char* Passwd(userrec *user);
177 bool IsDenied(userrec *user);
178 void AddWhoWas(userrec* u);
181 void safedelete(userrec *p)
185 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
186 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
191 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
195 void safedelete(chanrec *p)
200 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
204 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
209 /* chop a string down to 512 characters and preserve linefeed (irc max
216 FOREACH_MOD OnServerRaw(temp,false);
217 const char* str2 = temp.c_str();
218 sprintf(str,"%s",str2);
221 if (strlen(str) > 512)
230 std::string getservername()
235 std::string getserverdesc()
240 std::string getnetworkname()
245 std::string getadminname()
250 std::string getadminemail()
255 std::string getadminnick()
260 void log(int level,char *text, ...)
262 char textbuffer[MAXBUF];
266 struct tm * timeinfo;
267 if (level < LogLevel)
271 timeinfo = localtime (&rawtime);
273 f = fopen("ircd.log","a+");
277 va_start (argsPtr, text);
278 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
280 strcpy(b,asctime(timeinfo));
281 b[strlen(b)-1] = ':';
282 fprintf(f,"%s %s\n",b,textbuffer);
286 // nofork enabled? display it on terminal too
287 printf("%s %s\n",b,textbuffer);
292 printf("Can't write log file, bailing!!!");
297 void readfile(file_cache &F, const char* fname)
300 char linebuf[MAXBUF];
302 log(DEBUG,"readfile: loading %s",fname);
304 file = fopen(fname,"r");
309 fgets(linebuf,sizeof(linebuf),file);
310 linebuf[strlen(linebuf)-1]='\0';
311 if (!strcmp(linebuf,""))
317 F.push_back(linebuf);
324 log(DEBUG,"readfile: failed to load file: %s",fname);
326 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
329 void ReadConfig(void)
331 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
334 ConfValue("server","name",0,ServerName);
335 ConfValue("server","description",0,ServerDesc);
336 ConfValue("server","network",0,Network);
337 ConfValue("admin","name",0,AdminName);
338 ConfValue("admin","email",0,AdminEmail);
339 ConfValue("admin","nick",0,AdminNick);
340 ConfValue("files","motd",0,motd);
341 ConfValue("files","rules",0,rules);
342 ConfValue("power","diepass",0,diepass);
343 ConfValue("power","pause",0,pauseval);
344 ConfValue("power","restartpass",0,restartpass);
345 ConfValue("options","prefixquit",0,PrefixQuit);
346 ConfValue("die","value",0,DieValue);
347 ConfValue("options","loglevel",0,dbg);
348 if (!strcmp(dbg,"debug"))
350 if (!strcmp(dbg,"verbose"))
352 if (!strcmp(dbg,"default"))
354 if (!strcmp(dbg,"sparse"))
356 if (!strcmp(dbg,"none"))
358 readfile(RULES,rules);
359 log(DEBUG,"Reading connect classes");
361 for (int i = 0; i < ConfValueEnum("connect"); i++)
364 ConfValue("connect","allow",i,Value);
365 if (strcmp(Value,""))
367 strcpy(c.host,Value);
370 ConfValue("connect","password",i,Value);
371 strcpy(c.pass,Value);
372 Classes.push_back(c);
373 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
377 ConfValue("connect","deny",i,Value);
378 strcpy(c.host,Value);
380 Classes.push_back(c);
381 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
390 log(DEBUG,"Blocking: %d",s);
391 flags = fcntl(s, F_GETFL, 0);
392 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
395 void NonBlocking(int s)
398 log(DEBUG,"NonBlocking: %d",s);
399 flags = fcntl(s, F_GETFL, 0);
400 fcntl(s, F_SETFL, flags | O_NONBLOCK);
404 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
406 struct hostent *hostPtr = NULL;
409 memset (resolvedHost, '\0',MAXBUF);
410 if(unresolvedHost == NULL)
412 if ((inet_aton(unresolvedHost,&addr)) == 0)
414 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
416 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
418 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
422 /* write formatted text to a socket, in same format as printf */
424 void Write(int sock,char *text, ...)
426 char textbuffer[MAXBUF];
430 va_start (argsPtr, text);
431 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
433 sprintf(tb,"%s\r\n",textbuffer);
435 write(sock,tb,strlen(tb));
436 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
439 /* write a server formatted numeric response to a single socket */
441 void WriteServ(int sock, char* text, ...)
443 char textbuffer[MAXBUF],tb[MAXBUF];
445 va_start (argsPtr, text);
447 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
449 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
451 write(sock,tb,strlen(tb));
452 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
455 /* write text from an originating user to originating user */
457 void WriteFrom(int sock, userrec *user,char* text, ...)
459 char textbuffer[MAXBUF],tb[MAXBUF];
461 va_start (argsPtr, text);
463 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
465 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
467 write(sock,tb,strlen(tb));
468 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
471 /* write text to an destination user from a source user (e.g. user privmsg) */
473 void WriteTo(userrec *source, userrec *dest,char *data, ...)
475 char textbuffer[MAXBUF],tb[MAXBUF];
477 va_start (argsPtr, data);
478 if ((!dest) || (!source))
482 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
485 WriteFrom(dest->fd,source,"%s",textbuffer);
488 /* write formatted text from a source user to all users on a channel
489 * including the sender (NOT for privmsg, notice etc!) */
491 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
493 char textbuffer[MAXBUF];
495 va_start (argsPtr, text);
496 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
498 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
500 if (has_channel(i->second,Ptr))
502 WriteTo(user,i->second,"%s",textbuffer);
507 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
509 char textbuffer[MAXBUF];
511 va_start (argsPtr, text);
512 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
514 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
516 if (has_channel(i->second,Ptr))
518 WriteServ(i->second->fd,"%s",textbuffer);
524 /* write formatted text from a source user to all users on a channel except
525 * for the sender (for privmsg etc) */
527 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
529 char textbuffer[MAXBUF];
531 va_start (argsPtr, text);
532 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
535 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
537 if (has_channel(i->second,Ptr) && (user != i->second))
539 WriteTo(user,i->second,"%s",textbuffer);
544 int c_count(userrec* u)
547 for (int i =0; i != MAXCHANS; i++)
548 if (u->chans[i].channel)
554 /* return 0 or 1 depending if users u and u2 share one or more common channels
555 * (used by QUIT, NICK etc which arent channel specific notices) */
557 int common_channels(userrec *u, userrec *u2)
566 for (i = 0; i != MAXCHANS; i++)
568 for (z = 0; z != MAXCHANS; z++)
570 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
572 if ((c_count(u)) && (c_count(u2)))
582 /* write a formatted string to all users who share at least one common
583 * channel, including the source user e.g. for use in NICK */
585 void WriteCommon(userrec *u, char* text, ...)
587 char textbuffer[MAXBUF];
589 va_start (argsPtr, text);
590 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
593 WriteFrom(u->fd,u,"%s",textbuffer);
595 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
597 if (common_channels(u,i->second) && (i->second != u))
599 WriteFrom(i->second->fd,u,"%s",textbuffer);
604 /* write a formatted string to all users who share at least one common
605 * channel, NOT including the source user e.g. for use in QUIT */
607 void WriteCommonExcept(userrec *u, char* text, ...)
609 char textbuffer[MAXBUF];
611 va_start (argsPtr, text);
612 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
615 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
617 if ((common_channels(u,i->second)) && (u != i->second))
619 WriteFrom(i->second->fd,u,"%s",textbuffer);
624 void WriteOpers(char* text, ...)
626 char textbuffer[MAXBUF];
628 va_start (argsPtr, text);
629 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
632 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
634 if (strchr(i->second->modes,'o'))
636 if (strchr(i->second->modes,'s'))
638 // send server notices to all with +s
639 // (TODO: needs SNOMASKs)
640 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
646 void WriteWallOps(userrec *source, char* text, ...)
649 char textbuffer[MAXBUF];
651 va_start (argsPtr, text);
652 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
655 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
657 if (strchr(i->second->modes,'w'))
659 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
664 /* convert a string to lowercase. Note following special circumstances
665 * taken from RFC 1459. Many "official" server branches still hold to this
666 * rule so i will too;
668 * Because of IRC's scandanavian origin, the characters {}| are
669 * considered to be the lower case equivalents of the characters []\,
670 * respectively. This is a critical issue when determining the
671 * equivalence of two nicknames.
674 void strlower(char *n)
680 for (int i = 0; i != strlen(n); i++)
682 n[i] = tolower(n[i]);
692 /* verify that a user's ident and nickname is valid */
694 int isident(const char* n)
707 for (i = 0; i != strlen(n); i++)
709 if ((n[i] < 33) || (n[i] > 125))
713 /* can't occur ANYWHERE in an Ident! */
714 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
723 int isnick(const char* n)
735 if (strlen(n) > NICKMAX-1)
739 for (i = 0; i != strlen(n); i++)
741 if ((n[i] < 33) || (n[i] > 125))
745 /* can't occur ANYWHERE in a nickname! */
746 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
750 /* can't occur as the first char of a nickname... */
751 if ((strchr("0123456789",n[i])) && (!i))
759 /* Find a user record by nickname and return a pointer to it */
761 userrec* Find(string nick)
763 user_hash::iterator iter = clientlist.find(nick);
765 if (iter == clientlist.end())
766 /* Couldn't find it */
772 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
774 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
776 if (i->second->fd == fd)
778 i->second->bytes_out+=data_out;
779 i->second->cmds_out++;
785 /* find a channel record by channel name and return a pointer to it */
787 chanrec* FindChan(const char* chan)
789 chan_hash::iterator iter = chanlist.find(chan);
791 if (iter == chanlist.end())
792 /* Couldn't find it */
799 void purge_empty_chans(void)
801 int go_again = 1, purge = 0;
806 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
809 if (!usercount(i->second))
811 /* kill the record */
812 if (i != chanlist.end())
814 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
825 log(DEBUG,"completed channel purge, killed %d",purge);
828 /* returns the status character for a given user on a channel, e.g. @ for op,
829 * % for halfop etc. If the user has several modes set, the highest mode
830 * the user has must be returned. */
832 char* cmode(userrec *user, chanrec *chan)
835 for (i = 0; i != MAXCHANS; i++)
837 if ((user->chans[i].channel == chan) && (chan != NULL))
839 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
843 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
847 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
856 char scratch[MAXMODES];
857 char sparam[MAXMODES];
859 char* chanmodes(chanrec *chan)
863 if (chan->noexternal)
871 if (strcmp(chan->key,""))
879 if (chan->inviteonly)
895 if (strcmp(chan->key,""))
897 strcat(sparam,chan->key);
902 sprintf(foo," %d",chan->limit);
905 if (strlen(chan->custom_modes))
907 // TODO: Tack on mode parameters here -
908 // IN ORDER OF CUSTOM_MODES!
909 strncat(scratch,chan->custom_modes,MAXMODES);
911 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
912 strncat(scratch,sparam,MAXMODES);
916 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
917 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
918 * highest mode the user has must be returned. */
920 int cstatus(userrec *user, chanrec *chan)
923 for (i = 0; i != MAXCHANS; i++)
925 if ((user->chans[i].channel == chan) && (chan != NULL))
927 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
931 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
935 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
939 return STATUS_NORMAL;
945 /* compile a userlist of a channel into a string, each nick seperated by
946 * spaces and op, voice etc status shown as @ and + */
948 void userlist(userrec *user,chanrec *c)
950 sprintf(list,"353 %s = %s :", user->nick, c->name);
951 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
953 if (has_channel(i->second,c))
955 if (isnick(i->second->nick))
957 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
959 /* user is +i, and source not on the channel, does not show
960 * nick in NAMES list */
963 strcat(list,cmode(i->second,c));
964 strcat(list,i->second->nick);
966 if (strlen(list)>(480-NICKMAX))
968 /* list overflowed into
969 * multiple numerics */
970 WriteServ(user->fd,list);
971 sprintf(list,"353 %s = %s :", user->nick, c->name);
976 /* if whats left in the list isnt empty, send it */
977 if (list[strlen(list)-1] != ':')
979 WriteServ(user->fd,list);
983 /* return a count of the users on a specific channel accounting for
984 * invisible users who won't increase the count. e.g. for /LIST */
986 int usercount_i(chanrec *c)
992 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
996 if (has_channel(i->second,c))
998 if (isnick(i->second->nick))
1000 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1002 /* user is +i, and source not on the channel, does not show
1003 * nick in NAMES list */
1011 log(DEBUG,"usercount_i: %s %d",c->name,count);
1016 int usercount(chanrec *c)
1022 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1026 if (has_channel(i->second,c))
1028 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1035 log(DEBUG,"usercount: %s %d",c->name,count);
1040 /* add a channel to a user, creating the record for it if needed and linking
1041 * it to the user record */
1043 chanrec* add_channel(userrec *user, char* cname, char* key)
1049 // we MUST declare this wherever we use FOREACH_RESULT
1052 if ((!cname) || (!user))
1056 if (strlen(cname) > CHANMAX-1)
1058 cname[CHANMAX-1] = '\0';
1061 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1063 if ((has_channel(user,FindChan(cname))) && (FindChan(cname)))
1065 return NULL; // already on the channel!
1069 if (!FindChan(cname))
1071 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1076 /* create a new one */
1077 log(DEBUG,"add_channel: creating: %s",cname);
1079 chanlist[cname] = new chanrec();
1081 strcpy(chanlist[cname]->name, cname);
1082 chanlist[cname]->topiclock = 1;
1083 chanlist[cname]->noexternal = 1;
1084 chanlist[cname]->created = time(NULL);
1085 strcpy(chanlist[cname]->topic, "");
1086 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1087 chanlist[cname]->topicset = 0;
1088 Ptr = chanlist[cname];
1089 log(DEBUG,"add_channel: created: %s",cname);
1090 /* set created to 2 to indicate user
1091 * is the first in the channel
1092 * and should be given ops */
1098 /* channel exists, just fish out a pointer to its struct */
1099 Ptr = FindChan(cname);
1102 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1107 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1108 if (strcmp(Ptr->key,""))
1110 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1113 log(DEBUG,"add_channel: no key given in JOIN");
1114 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1119 log(DEBUG,"key at %p is %s",key,key);
1120 if (strcasecmp(key,Ptr->key))
1122 log(DEBUG,"add_channel: bad key given in JOIN");
1123 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1128 log(DEBUG,"add_channel: no key");
1130 if (Ptr->inviteonly)
1132 log(DEBUG,"add_channel: channel is +i");
1133 if (user->IsInvited(Ptr->name))
1135 /* user was invited to channel */
1136 /* there may be an optional channel NOTICE here */
1140 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1144 log(DEBUG,"add_channel: channel is not +i");
1148 if (usercount(Ptr) == Ptr->limit)
1150 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1155 log(DEBUG,"add_channel: about to walk banlist");
1157 /* check user against the channel banlist */
1158 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1160 if (match(user->GetFullHost(),i->data))
1162 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1167 log(DEBUG,"add_channel: bans checked");
1169 user->RemoveInvite(Ptr->name);
1171 log(DEBUG,"add_channel: invites removed");
1177 log(DEBUG,"Passed channel checks");
1179 for (i =0; i != MAXCHANS; i++)
1181 if (user->chans[i].channel == NULL)
1183 log(DEBUG,"Adding into their channel list");
1187 /* first user in is given ops */
1188 user->chans[i].uc_modes = UCMODE_OP;
1192 user->chans[i].uc_modes = 0;
1194 user->chans[i].channel = Ptr;
1195 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1197 log(DEBUG,"Sent JOIN to client");
1201 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1202 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1205 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1206 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1207 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1208 FOREACH_MOD OnUserJoin(user,Ptr);
1212 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1213 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1217 /* remove a channel from a users record, and remove the record from memory
1218 * if the channel has become empty */
1220 chanrec* del_channel(userrec *user, char* cname, char* reason)
1226 if ((!cname) || (!user))
1231 Ptr = FindChan(cname);
1238 FOREACH_MOD OnUserPart(user,Ptr);
1239 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1241 for (i =0; i != MAXCHANS; i++)
1243 /* zap it from the channel list of the user */
1244 if (user->chans[i].channel == Ptr)
1248 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1252 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1254 user->chans[i].uc_modes = 0;
1255 user->chans[i].channel = NULL;
1256 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1261 /* if there are no users left on the channel */
1262 if (!usercount(Ptr))
1264 chan_hash::iterator iter = chanlist.find(Ptr->name);
1266 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1268 /* kill the record */
1269 if (iter != chanlist.end())
1271 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1272 delete iter->second;
1273 chanlist.erase(iter);
1279 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1284 if ((!Ptr) || (!user) || (!src))
1289 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1291 if (!has_channel(user,Ptr))
1293 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1296 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1298 if (cstatus(src,Ptr) == STATUS_HOP)
1300 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1304 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1310 for (i =0; i != MAXCHANS; i++)
1312 /* zap it from the channel list of the user */
1313 if (user->chans[i].channel == Ptr)
1315 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1316 user->chans[i].uc_modes = 0;
1317 user->chans[i].channel = NULL;
1318 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1323 /* if there are no users left on the channel */
1324 if (!usercount(Ptr))
1326 chan_hash::iterator iter = chanlist.find(Ptr->name);
1328 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1330 /* kill the record */
1331 if (iter != chanlist.end())
1333 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1334 delete iter->second;
1335 chanlist.erase(iter);
1341 /* returns 1 if user u has channel c in their record, 0 if not */
1343 int has_channel(userrec *u, chanrec *c)
1351 for (i =0; i != MAXCHANS; i++)
1353 if (u->chans[i].channel == c)
1361 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1366 if ((!user) || (!dest) || (!chan))
1370 if (status != STATUS_OP)
1372 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1379 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1385 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1390 for (i = 0; i != MAXCHANS; i++)
1392 if ((d->chans[i].channel == chan) && (chan != NULL))
1394 if (d->chans[i].uc_modes & UCMODE_OP)
1396 /* mode already set on user, dont allow multiple */
1399 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1400 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1408 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1413 if ((!user) || (!dest) || (!chan))
1417 if (status != STATUS_OP)
1419 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1427 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1432 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1437 for (i = 0; i != MAXCHANS; i++)
1439 if ((d->chans[i].channel == chan) && (chan != NULL))
1441 if (d->chans[i].uc_modes & UCMODE_HOP)
1443 /* mode already set on user, dont allow multiple */
1446 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1447 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1455 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1460 if ((!user) || (!dest) || (!chan))
1464 if (status < STATUS_HOP)
1466 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1474 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1479 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1484 for (i = 0; i != MAXCHANS; i++)
1486 if ((d->chans[i].channel == chan) && (chan != NULL))
1488 if (d->chans[i].uc_modes & UCMODE_VOICE)
1490 /* mode already set on user, dont allow multiple */
1493 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1494 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1502 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1507 if ((!user) || (!dest) || (!chan))
1511 if (status != STATUS_OP)
1513 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1521 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1526 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1531 for (i = 0; i != MAXCHANS; i++)
1533 if ((d->chans[i].channel == chan) && (chan != NULL))
1535 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1537 /* mode already set on user, dont allow multiple */
1540 d->chans[i].uc_modes ^= UCMODE_OP;
1541 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1549 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1554 if ((!user) || (!dest) || (!chan))
1558 if (status != STATUS_OP)
1560 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1568 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1573 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1578 for (i = 0; i != MAXCHANS; i++)
1580 if ((d->chans[i].channel == chan) && (chan != NULL))
1582 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1584 /* mode already set on user, dont allow multiple */
1587 d->chans[i].uc_modes ^= UCMODE_HOP;
1588 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1596 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1601 if ((!user) || (!dest) || (!chan))
1605 if (status < STATUS_HOP)
1607 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1615 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1620 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1625 for (i = 0; i != MAXCHANS; i++)
1627 if ((d->chans[i].channel == chan) && (chan != NULL))
1629 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1631 /* mode already set on user, dont allow multiple */
1634 d->chans[i].uc_modes ^= UCMODE_VOICE;
1635 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1643 void TidyBan(char *ban)
1645 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1649 char* pos_of_pling = strchr(temp,'!');
1650 char* pos_of_at = strchr(temp,'@');
1652 pos_of_pling[0] = '\0';
1653 pos_of_at[0] = '\0';
1657 strncpy(NICK,temp,NICKMAX);
1658 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1659 strncpy(HOST,pos_of_at,160);
1661 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1664 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1667 if ((!user) || (!dest) || (!chan))
1669 if (strchr(dest,'!')==0)
1671 if (strchr(dest,'@')==0)
1673 for (int i = 0; i < strlen(dest); i++)
1676 for (int i = 0; i < strlen(dest); i++)
1680 for (int i = 0; i < strlen(dest); i++)
1686 for (int i = 0; i < strlen(dest); i++)
1691 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1694 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1696 if (!strcasecmp(i->data,dest))
1698 // dont allow a user to set the same ban twice
1703 b.set_time = time(NULL);
1704 strncpy(b.data,dest,MAXBUF);
1705 strncpy(b.set_by,user->nick,NICKMAX);
1706 chan->bans.push_back(b);
1710 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1712 if ((!user) || (!dest) || (!chan))
1717 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1718 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1720 if (!strcasecmp(i->data,dest))
1722 chan->bans.erase(i);
1729 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1731 char modelist[MAXBUF];
1732 char outlist[MAXBUF];
1733 char outstr[MAXBUF];
1734 char outpars[32][MAXBUF];
1740 bool k_set = false, l_set = false;
1747 log(DEBUG,"process_modes: start");
1749 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1750 /* parameters[2] onwards are parameters for
1751 * modes that require them :) */
1752 strcpy(outlist,"+");
1755 log(DEBUG,"process_modes: modelist: %s",modelist);
1757 for (ptr = 0; ptr < strlen(modelist); ptr++)
1762 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1763 char modechar = modelist[ptr];
1764 switch (modelist[ptr])
1769 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1771 outlist[strlen(outlist)-1] = '-';
1775 strcat(outlist,"-");
1785 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1787 outlist[strlen(outlist)-1] = '+';
1791 strcat(outlist,"+");
1798 if ((param >= pcnt)) break;
1801 r = give_ops(user,parameters[param++],chan,status);
1805 r = take_ops(user,parameters[param++],chan,status);
1809 strcat(outlist,"o");
1810 strcpy(outpars[pc++],parameters[param-1]);
1815 if ((param >= pcnt)) break;
1818 r = give_hops(user,parameters[param++],chan,status);
1822 r = take_hops(user,parameters[param++],chan,status);
1826 strcat(outlist,"h");
1827 strcpy(outpars[pc++],parameters[param-1]);
1833 if ((param >= pcnt)) break;
1836 r = give_voice(user,parameters[param++],chan,status);
1840 r = take_voice(user,parameters[param++],chan,status);
1844 strcat(outlist,"v");
1845 strcpy(outpars[pc++],parameters[param-1]);
1850 if ((param >= pcnt)) break;
1853 r = add_ban(user,parameters[param++],chan,status);
1857 r = take_ban(user,parameters[param++],chan,status);
1861 strcat(outlist,"b");
1862 strcpy(outpars[pc++],parameters[param-1]);
1867 if ((param >= pcnt))
1875 if (!strcmp(chan->key,""))
1877 strcat(outlist,"k");
1878 strcpy(outpars[pc++],parameters[param++]);
1879 strcpy(chan->key,parameters[param-1]);
1885 /* only allow -k if correct key given */
1886 if (strcmp(chan->key,""))
1888 strcat(outlist,"k");
1889 strcpy(chan->key,"");
1899 strcat(outlist,"l");
1904 if ((param >= pcnt)) break;
1910 bool invalid = false;
1911 for (int i = 0; i < strlen(parameters[param]); i++)
1913 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
1918 if (atoi(parameters[param]) < 1)
1926 chan->limit = atoi(parameters[param]);
1929 strcat(outlist,"l");
1930 strcpy(outpars[pc++],parameters[param++]);
1937 if (chan->inviteonly != mdir)
1939 strcat(outlist,"i");
1941 chan->inviteonly = mdir;
1945 if (chan->topiclock != mdir)
1947 strcat(outlist,"t");
1949 chan->topiclock = mdir;
1953 if (chan->noexternal != mdir)
1955 strcat(outlist,"n");
1957 chan->noexternal = mdir;
1961 if (chan->moderated != mdir)
1963 strcat(outlist,"m");
1965 chan->moderated = mdir;
1969 if (chan->secret != mdir)
1971 strcat(outlist,"s");
1972 if (chan->c_private)
1974 chan->c_private = 0;
1977 strcat(outlist,"-p+");
1981 strcat(outlist,"+p-");
1985 chan->secret = mdir;
1989 if (chan->c_private != mdir)
1991 strcat(outlist,"p");
1997 strcat(outlist,"-s+");
2001 strcat(outlist,"+s-");
2005 chan->c_private = mdir;
2009 log(DEBUG,"Preprocessing custom mode %c",modechar);
2012 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2014 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2017 if (ModeDefined(modechar,MT_CHANNEL))
2019 log(DEBUG,"A module has claimed this mode");
2020 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2022 p.push_back(parameters[param]);
2024 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2026 p.push_back(parameters[param]);
2028 bool handled = false;
2029 for (int i = 0; i <= MODCOUNT; i++)
2033 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2035 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2036 char app[] = {modechar, 0};
2039 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2041 strcat(outlist, app);
2043 else if (!strchr(outlist,modechar))
2045 strcat(outlist, app);
2048 chan->SetCustomMode(modechar,mdir);
2049 // include parameters in output if mode has them
2050 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) || (ModeDefinedOff(modechar,MT_CHANNEL)>0))
2052 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2053 strcpy(outpars[pc++],parameters[param++]);
2055 // break, because only one module can handle the mode.
2067 /* this ensures only the *valid* modes are sent out onto the network */
2068 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2070 outlist[strlen(outlist)-1] = '\0';
2072 if (strcmp(outlist,""))
2074 strcpy(outstr,outlist);
2075 for (ptr = 0; ptr < pc; ptr++)
2078 strcat(outstr,outpars[ptr]);
2082 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2086 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2091 void handle_mode(char **parameters, int pcnt, userrec *user)
2097 char outpars[MAXBUF];
2099 dest = Find(parameters[0]);
2101 if ((dest) && (pcnt == 1))
2103 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2106 if ((dest) && (pcnt > 1))
2111 if (strchr(user->modes,'o'))
2122 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2126 strcpy(outpars,"+");
2129 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2132 for (i = 0; i < strlen(parameters[1]); i++)
2134 if (parameters[1][i] == '+')
2138 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2140 outpars[strlen(outpars)-1] = '+';
2144 strcat(outpars,"+");
2150 if (parameters[1][i] == '-')
2154 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2156 outpars[strlen(outpars)-1] = '-';
2160 strcat(outpars,"-");
2168 if (strchr(user->modes,'o'))
2174 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2183 if (!strchr(dest->modes,parameters[1][i]))
2185 dest->modes[strlen(dest->modes)+1]='\0';
2186 dest->modes[strlen(dest->modes)] = parameters[1][i];
2187 outpars[strlen(outpars)+1]='\0';
2188 outpars[strlen(outpars)] = parameters[1][i];
2197 outpars[strlen(outpars)+1]='\0';
2198 outpars[strlen(outpars)] = parameters[1][i];
2201 for (q = 0; q < strlen(user->modes); q++)
2203 if (user->modes[q] != parameters[1][i])
2205 moo[0] = user->modes[q];
2210 strcpy(user->modes,temp);
2215 if (strlen(outpars))
2221 while (i < strlen (outpars))
2223 b[z++] = outpars[i++];
2225 if (i<strlen(outpars)-1)
2227 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2229 // someones playing silly buggers and trying
2230 // to put a +- or -+ into the line...
2234 if (i == strlen(outpars)-1)
2236 if ((outpars[i] == '-') || (outpars[i] == '+'))
2244 if ((b[z] == '-') || (b[z] == '+'))
2247 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2250 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2255 Ptr = FindChan(parameters[0]);
2260 /* just /modes #channel */
2261 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2262 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2268 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2271 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2273 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2275 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2279 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2281 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2285 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2289 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2296 void server_mode(char **parameters, int pcnt, userrec *user)
2302 char outpars[MAXBUF];
2304 dest = Find(parameters[0]);
2306 if ((dest) && (pcnt > 1))
2308 strcpy(outpars,"+");
2311 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2314 for (i = 0; i < strlen(parameters[1]); i++)
2316 if (parameters[1][i] == '+')
2320 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2322 outpars[strlen(outpars)-1] = '+';
2326 strcat(outpars,"+");
2332 if (parameters[1][i] == '-')
2336 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2338 outpars[strlen(outpars)-1] = '-';
2342 strcat(outpars,"-");
2350 if (strchr(user->modes,'o'))
2356 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2365 if (!strchr(dest->modes,parameters[1][i]))
2367 dest->modes[strlen(dest->modes)+1]='\0';
2368 dest->modes[strlen(dest->modes)] = parameters[1][i];
2369 outpars[strlen(outpars)+1]='\0';
2370 outpars[strlen(outpars)] = parameters[1][i];
2379 outpars[strlen(outpars)+1]='\0';
2380 outpars[strlen(outpars)] = parameters[1][i];
2383 for (q = 0; q < strlen(user->modes); q++)
2385 if (user->modes[q] != parameters[1][i])
2387 moo[0] = user->modes[q];
2392 strcpy(user->modes,temp);
2397 if (strlen(outpars))
2403 while (i < strlen (outpars))
2405 b[z++] = outpars[i++];
2407 if (i<strlen(outpars)-1)
2409 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2411 // someones playing silly buggers and trying
2412 // to put a +- or -+ into the line...
2416 if (i == strlen(outpars)-1)
2418 if ((outpars[i] == '-') || (outpars[i] == '+'))
2426 if ((b[z] == '-') || (b[z] == '+'))
2429 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2432 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2437 Ptr = FindChan(parameters[0]);
2440 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2444 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2449 /* This function pokes and hacks at a parameter list like the following:
2451 * PART #winbot, #darkgalaxy :m00!
2453 * to turn it into a series of individual calls like this:
2455 * PART #winbot :m00!
2456 * PART #darkgalaxy :m00!
2458 * The seperate calls are sent to a callback function provided by the caller
2459 * (the caller will usually call itself recursively). The callback function
2460 * must be a command handler. Calling this function on a line with no list causes
2461 * no action to be taken. You must provide a starting and ending parameter number
2462 * where the range of the list can be found, useful if you have a terminating
2463 * parameter as above which is actually not part of the list, or parameters
2464 * before the actual list as well. This code is used by many functions which
2465 * can function as "one to list" (see the RFC) */
2467 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2472 char blog[32][MAXBUF];
2473 char blog2[32][MAXBUF];
2474 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2475 char keystr[MAXBUF];
2478 for (i = 0; i <32; i++)
2481 for (i = 0; i <32; i++)
2482 strcpy(blog2[i],"");
2485 for (i = 0; i <10; i++)
2489 parameters[i] = moo;
2494 if (pcnt > 1) /* we have a key to copy */
2496 strcpy(keystr,parameters[1]);
2500 if (!parameters[start])
2504 if (!strchr(parameters[start],','))
2509 for (i = start; i <= end; i++)
2513 strcat(plist,parameters[i]);
2521 for (i = 0; i < t; i++)
2523 if (plist[i] == ',')
2526 strcpy(blog[j++],param);
2530 strcpy(blog[j++],param);
2533 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2538 if ((joins) && (keystr))
2540 if (strchr(keystr,','))
2544 t2 = strlen(keystr);
2545 for (i = 0; i < t2; i++)
2547 if (keystr[i] == ',')
2550 strcpy(blog2[j++],param);
2554 strcpy(blog2[j++],param);
2559 for (j = 0; j < total; j++)
2565 for (q = end; q < pcnt-1; q++)
2567 if (parameters[q+1])
2569 pars[q-end+1] = parameters[q+1];
2572 if ((joins) && (parameters[1]))
2583 /* repeatedly call the function with the hacked parameter list */
2584 if ((joins) && (pcnt > 1))
2588 // pars[1] already set up and containing key from blog2[j]
2593 pars[1] = parameters[1];
2599 fn(pars,pcnt-(end-start),u);
2606 void handle_join(char **parameters, int pcnt, userrec *user)
2611 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2613 if (parameters[0][0] == '#')
2615 Ptr = add_channel(user,parameters[0],parameters[1]);
2620 void handle_part(char **parameters, int pcnt, userrec *user)
2626 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2628 del_channel(user,parameters[0],parameters[1]);
2632 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2634 del_channel(user,parameters[0],NULL);
2638 void handle_kick(char **parameters, int pcnt, userrec *user)
2640 chanrec* Ptr = FindChan(parameters[0]);
2641 userrec* u = Find(parameters[1]);
2645 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2649 if (!has_channel(u,Ptr))
2651 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2657 kick_channel(user,u,Ptr,parameters[2]);
2661 kick_channel(user,u,Ptr,user->nick);
2666 void handle_die(char **parameters, int pcnt, userrec *user)
2668 log(DEBUG,"die: %s",user->nick);
2669 if (!strcmp(parameters[0],diepass))
2671 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2677 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2681 void handle_restart(char **parameters, int pcnt, userrec *user)
2683 log(DEBUG,"restart: %s",user->nick);
2684 if (!strcmp(parameters[0],restartpass))
2686 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2689 /* Will finish this later when i can be arsed :) */
2693 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2698 void kill_link(userrec *user,char* reason)
2700 user_hash::iterator iter = clientlist.find(user->nick);
2702 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2703 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2704 fdatasync(user->fd);
2705 log(DEBUG,"closing fd %d",user->fd);
2707 /* bugfix, cant close() a nonblocking socket (sux!) */
2708 if (user->registered == 7) {
2709 FOREACH_MOD OnUserQuit(user);
2710 WriteCommonExcept(user,"QUIT :%s",reason);
2713 /* push the socket on a stack of sockets due to be closed at the next opportunity */
2714 fd_reap.push_back(user->fd);
2716 bool do_purge = false;
2718 if (user->registered == 7) {
2719 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2723 if (iter != clientlist.end())
2725 log(DEBUG,"deleting user hash value %d",iter->second);
2726 if ((iter->second) && (user->registered == 7)) {
2727 delete iter->second;
2729 clientlist.erase(iter);
2732 purge_empty_chans();
2736 void handle_kill(char **parameters, int pcnt, userrec *user)
2738 userrec *u = Find(parameters[0]);
2739 char killreason[MAXBUF];
2741 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
2744 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
2745 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
2746 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
2747 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
2748 kill_link(u,killreason);
2752 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2756 void handle_summon(char **parameters, int pcnt, userrec *user)
2758 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
2761 void handle_users(char **parameters, int pcnt, userrec *user)
2763 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
2767 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2769 char* Passwd(userrec *user)
2771 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2773 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2781 bool IsDenied(userrec *user)
2783 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2785 if (match(user->host,i->host) && (i->type == CC_DENY))
2794 void handle_pass(char **parameters, int pcnt, userrec *user)
2796 if (!strcasecmp(parameters[0],Passwd(user)))
2798 user->haspassed = true;
2802 void handle_invite(char **parameters, int pcnt, userrec *user)
2804 userrec* u = Find(parameters[0]);
2805 chanrec* c = FindChan(parameters[1]);
2811 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
2817 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2826 if (cstatus(user,c) < STATUS_HOP)
2828 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
2832 u->InviteTo(c->name);
2833 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2834 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2838 void handle_topic(char **parameters, int pcnt, userrec *user)
2844 if (strlen(parameters[0]) <= CHANMAX)
2846 Ptr = FindChan(parameters[0]);
2851 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2852 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2856 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2861 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2867 if (loop_call(handle_topic,parameters,pcnt,user,0,pcnt-2,0))
2869 if (strlen(parameters[0]) <= CHANMAX)
2871 Ptr = FindChan(parameters[0]);
2874 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2876 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
2879 strcpy(Ptr->topic,parameters[1]);
2880 strcpy(Ptr->setby,user->nick);
2881 Ptr->topicset = time(NULL);
2882 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2886 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2892 /* sends out an error notice to all connected clients (not to be used
2895 void send_error(char *s)
2897 log(DEBUG,"send_error: %s",s);
2898 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2900 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2904 void Error(int status)
2906 signal (SIGALRM, SIG_IGN);
2907 signal (SIGPIPE, SIG_IGN);
2908 signal (SIGTERM, SIG_IGN);
2909 signal (SIGABRT, SIG_IGN);
2910 signal (SIGSEGV, SIG_IGN);
2911 signal (SIGURG, SIG_IGN);
2912 signal (SIGKILL, SIG_IGN);
2913 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2914 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2918 int main (int argc, char *argv[])
2921 log(DEBUG,"*** InspIRCd starting up!");
2922 if (!FileExists(CONFIG_FILE))
2924 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2925 log(DEBUG,"main: no config");
2926 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2930 if (!strcmp(argv[1],"-nofork")) {
2934 if (InspIRCd() == ERROR)
2936 log(DEBUG,"main: daemon function bailed");
2937 printf("ERROR: could not initialise. Shutting down.\n");
2944 template<typename T> inline string ConvToStr(const T &in)
2947 if (!(tmp << in)) return string();
2951 /* re-allocates a nick in the user_hash after they change nicknames,
2952 * returns a pointer to the new user as it may have moved */
2954 userrec* ReHashNick(char* Old, char* New)
2956 user_hash::iterator newnick;
2957 user_hash::iterator oldnick = clientlist.find(Old);
2959 log(DEBUG,"ReHashNick: %s %s",Old,New);
2961 if (!strcasecmp(Old,New))
2963 log(DEBUG,"old nick is new nick, skipping");
2964 return oldnick->second;
2967 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2969 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2971 clientlist[New] = new userrec();
2972 clientlist[New] = oldnick->second;
2973 /*delete oldnick->second; */
2974 clientlist.erase(oldnick);
2976 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2978 return clientlist[New];
2981 /* adds or updates an entry in the whowas list */
2982 void AddWhoWas(userrec* u)
2984 user_hash::iterator iter = whowas.find(u->nick);
2985 userrec *a = new userrec();
2986 strcpy(a->nick,u->nick);
2987 strcpy(a->ident,u->ident);
2988 strcpy(a->dhost,u->dhost);
2989 strcpy(a->host,u->host);
2990 strcpy(a->fullname,u->fullname);
2991 strcpy(a->server,u->server);
2992 a->signon = u->signon;
2994 /* MAX_WHOWAS: max number of /WHOWAS items
2995 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2996 * can be replaced by a newer one
2999 if (iter == whowas.end())
3001 if (whowas.size() == WHOWAS_MAX)
3003 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3005 // 3600 seconds in an hour ;)
3006 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3010 log(DEBUG,"added WHOWAS entry, purged an old record");
3017 log(DEBUG,"added fresh WHOWAS entry");
3018 whowas[a->nick] = a;
3023 log(DEBUG,"updated WHOWAS entry");
3024 delete iter->second;
3030 /* add a client connection to the sockets list */
3031 void AddClient(int socket, char* host, int port, bool iscached)
3035 char resolved[MAXBUF];
3038 user_hash::iterator iter;
3040 tempnick = ConvToStr(socket) + "-unknown";
3041 sprintf(tn2,"%d-unknown",socket);
3043 iter = clientlist.find(tempnick);
3045 if (iter != clientlist.end()) return;
3048 * It is OK to access the value here this way since we know
3049 * it exists, we just created it above.
3051 * At NO other time should you access a value in a map or a
3052 * hash_map this way.
3054 clientlist[tempnick] = new userrec();
3056 NonBlocking(socket);
3057 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3060 clientlist[tempnick]->fd = socket;
3061 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3062 strncpy(clientlist[tempnick]->host, host,160);
3063 strncpy(clientlist[tempnick]->dhost, host,160);
3064 strncpy(clientlist[tempnick]->server, ServerName,256);
3065 clientlist[tempnick]->registered = 0;
3066 clientlist[tempnick]->signon = time(NULL);
3067 clientlist[tempnick]->nping = time(NULL)+240;
3068 clientlist[tempnick]->lastping = 1;
3069 clientlist[tempnick]->port = port;
3073 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3077 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3080 if (clientlist.size() == MAXCLIENTS)
3081 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3084 void handle_names(char **parameters, int pcnt, userrec *user)
3088 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3090 c = FindChan(parameters[0]);
3093 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3095 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3099 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3104 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3109 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3111 if (parameters[0][0] == '#')
3113 chan = FindChan(parameters[0]);
3116 if ((chan->noexternal) && (!has_channel(user,chan)))
3118 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3121 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3123 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3126 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3130 /* no such nick/channel */
3131 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3136 dest = Find(parameters[0]);
3139 if (strcmp(dest->awaymsg,""))
3141 /* auto respond with aweh msg */
3142 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3144 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3148 /* no such nick/channel */
3149 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3153 void handle_notice(char **parameters, int pcnt, userrec *user)
3158 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3160 if (parameters[0][0] == '#')
3162 chan = FindChan(parameters[0]);
3165 if ((chan->noexternal) && (!has_channel(user,chan)))
3167 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3170 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3172 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3175 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3179 /* no such nick/channel */
3180 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3185 dest = Find(parameters[0]);
3188 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3192 /* no such nick/channel */
3193 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3199 char* chlist(userrec *user)
3204 log(DEBUG,"chlist: %s",user->nick);
3210 for (i = 0; i != MAXCHANS; i++)
3212 if (user->chans[i].channel != NULL)
3214 if (user->chans[i].channel->name)
3216 strcpy(cmp,user->chans[i].channel->name);
3218 if (!strstr(lst,cmp))
3220 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3222 strcat(lst,cmode(user,user->chans[i].channel));
3223 strcat(lst,user->chans[i].channel->name);
3233 void handle_info(char **parameters, int pcnt, userrec *user)
3235 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3236 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3237 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3238 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3241 void handle_time(char **parameters, int pcnt, userrec *user)
3244 struct tm * timeinfo;
3247 timeinfo = localtime ( &rawtime );
3248 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3252 void handle_whois(char **parameters, int pcnt, userrec *user)
3257 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3259 dest = Find(parameters[0]);
3262 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3263 if ((user == dest) || (strchr(user->modes,'o')))
3265 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3267 if (strcmp(chlist(dest),""))
3269 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3271 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3272 if (strcmp(dest->awaymsg,""))
3274 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3276 if (strchr(dest->modes,'o'))
3278 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3280 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3281 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3283 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3287 /* no such nick/channel */
3288 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3292 void handle_quit(char **parameters, int pcnt, userrec *user)
3294 user_hash::iterator iter = clientlist.find(user->nick);
3296 if (user->registered == 7)
3298 /* theres more to do here, but for now just close the socket */
3301 if (parameters[0][0] == ':')
3305 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3306 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3307 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3311 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3312 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3313 WriteCommonExcept(user,"QUIT :Client exited");
3315 FOREACH_MOD OnUserQuit(user);
3319 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3320 fd_reap.push_back(user->fd);
3322 if (iter != clientlist.end())
3324 log(DEBUG,"deleting user hash value %d",iter->second);
3325 if ((iter->second) && (user->registered == 7)) {
3326 delete iter->second;
3328 clientlist.erase(iter);
3331 if (user->registered == 7) {
3332 purge_empty_chans();
3336 void handle_who(char **parameters, int pcnt, userrec *user)
3338 chanrec* Ptr = NULL;
3340 /* theres more to do here, but for now just close the socket */
3343 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3345 if (user->chans[0].channel)
3347 Ptr = user->chans[0].channel;
3348 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3350 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3352 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3358 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3362 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3366 if (parameters[0][0] = '#')
3368 Ptr = FindChan(parameters[0]);
3371 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3373 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3375 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);
3378 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3382 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3388 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3390 Ptr = user->chans[0].channel;
3391 printf(user->chans[0].channel->name);
3392 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3394 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3396 if (strchr(i->second->modes,'o'))
3398 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);
3402 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3408 void handle_wallops(char **parameters, int pcnt, userrec *user)
3410 WriteWallOps(user,"%s",parameters[0]);
3413 void handle_list(char **parameters, int pcnt, userrec *user)
3417 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3418 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3420 if ((!i->second->c_private) && (!i->second->secret))
3422 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3425 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3429 void handle_rehash(char **parameters, int pcnt, userrec *user)
3431 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3433 FOREACH_MOD OnRehash();
3434 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3440 return clientlist.size();
3443 int usercount_invisible(void)
3447 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3449 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3454 int usercount_opers(void)
3458 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3460 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3465 int usercount_unknown(void)
3469 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3471 if ((i->second->fd) && (i->second->registered != 7))
3479 return chanlist.size();
3482 int servercount(void)
3487 void handle_lusers(char **parameters, int pcnt, userrec *user)
3489 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3490 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3491 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3492 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3493 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3496 void handle_admin(char **parameters, int pcnt, userrec *user)
3498 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3499 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
3500 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3501 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
3504 void ShowMOTD(userrec *user)
3508 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3511 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3512 for (int i = 0; i != MOTD.size(); i++)
3514 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3516 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3519 void ShowRULES(userrec *user)
3523 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3526 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3527 for (int i = 0; i != RULES.size(); i++)
3529 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3531 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3534 /* shows the message of the day, and any other on-logon stuff */
3535 void ConnectUser(userrec *user)
3537 user->registered = 7;
3538 user->idle_lastmsg = time(NULL);
3539 log(DEBUG,"ConnectUser: %s",user->nick);
3541 if (strcmp(Passwd(user),"") && (!user->haspassed))
3543 Write(user->fd,"ERROR :Closing link: Invalid password");
3544 fdatasync(user->fd);
3545 kill_link(user,"Invalid password");
3550 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3551 fdatasync(user->fd);
3552 kill_link(user,"Unauthorised connection");
3555 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3556 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3557 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3558 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3559 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3560 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);
3561 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);
3563 FOREACH_MOD OnUserConnect(user);
3564 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3567 void handle_version(char **parameters, int pcnt, userrec *user)
3569 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3572 void handle_ping(char **parameters, int pcnt, userrec *user)
3574 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3577 void handle_pong(char **parameters, int pcnt, userrec *user)
3579 // set the user as alive so they survive to next ping
3583 void handle_motd(char **parameters, int pcnt, userrec *user)
3588 void handle_rules(char **parameters, int pcnt, userrec *user)
3593 void handle_user(char **parameters, int pcnt, userrec *user)
3595 if (user->registered < 3)
3597 if (isident(parameters[0]) == 0) {
3598 // This kinda Sucks, According to the RFC thou, its either this,
3599 // or "You have already registered" :p -- Craig
3600 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3603 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3604 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3605 strncat(user->ident,parameters[0],IDENTMAX);
3606 strncpy(user->fullname,parameters[3],128);
3607 user->registered = (user->registered | 1);
3612 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3615 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3616 if (user->registered == 3)
3618 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3623 void handle_userhost(char **parameters, int pcnt, userrec *user)
3625 char Return[MAXBUF],junk[MAXBUF];
3626 sprintf(Return,"302 %s :",user->nick);
3627 for (int i = 0; i < pcnt; i++)
3629 userrec *u = Find(parameters[i]);
3632 if (strchr(u->modes,'o'))
3634 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3635 strcat(Return,junk);
3639 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3640 strcat(Return,junk);
3644 WriteServ(user->fd,Return);
3648 void handle_ison(char **parameters, int pcnt, userrec *user)
3650 char Return[MAXBUF];
3651 sprintf(Return,"303 %s :",user->nick);
3652 for (int i = 0; i < pcnt; i++)
3654 userrec *u = Find(parameters[i]);
3657 strcat(Return,u->nick);
3661 WriteServ(user->fd,Return);
3665 void handle_away(char **parameters, int pcnt, userrec *user)
3669 strcpy(user->awaymsg,parameters[0]);
3670 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3674 strcpy(user->awaymsg,"");
3675 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3679 void handle_whowas(char **parameters, int pcnt, userrec* user)
3681 user_hash::iterator i = whowas.find(parameters[0]);
3683 if (i == whowas.end())
3685 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3686 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3690 time_t rawtime = i->second->signon;
3694 timeinfo = localtime(&rawtime);
3695 strcpy(b,asctime(timeinfo));
3696 b[strlen(b)-1] = '\0';
3698 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3699 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3700 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3705 void handle_trace(char **parameters, int pcnt, userrec *user)
3707 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3711 if (isnick(i->second->nick))
3713 if (strchr(i->second->modes,'o'))
3715 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3719 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3724 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3730 void handle_stats(char **parameters, int pcnt, userrec *user)
3736 if (strlen(parameters[0])>1)
3738 /* make the stats query 1 character long */
3739 parameters[0][1] = '\0';
3742 /* stats m (list number of times each command has been used, plus bytecount) */
3743 if (!strcasecmp(parameters[0],"m"))
3745 for (int i = 0; i < cmdlist.size(); i++)
3747 if (cmdlist[i].handler_function)
3749 if (cmdlist[i].use_count)
3751 /* RPL_STATSCOMMANDS */
3752 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3759 /* stats z (debug and memory info) */
3760 if (!strcasecmp(parameters[0],"z"))
3762 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3763 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3764 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3765 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3766 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3767 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3768 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3769 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3773 if (!strcasecmp(parameters[0],"o"))
3775 for (int i = 0; i < ConfValueEnum("oper"); i++)
3777 char LoginName[MAXBUF];
3778 char HostName[MAXBUF];
3779 char OperType[MAXBUF];
3780 ConfValue("oper","name",i,LoginName);
3781 ConfValue("oper","host",i,HostName);
3782 ConfValue("oper","type",i,OperType);
3783 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3787 /* stats l (show user I/O stats) */
3788 if (!strcasecmp(parameters[0],"l"))
3790 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3791 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3793 if (isnick(i->second->nick))
3795 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);
3799 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);
3805 /* stats u (show server uptime) */
3806 if (!strcasecmp(parameters[0],"u"))
3808 time_t current_time = 0;
3809 current_time = time(NULL);
3810 time_t server_uptime = current_time - startup_time;
3812 stime = gmtime(&server_uptime);
3813 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3814 * Craig suggested this, and it seemed a good idea so in it went */
3815 if (stime->tm_year > 70)
3817 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);
3821 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);
3825 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3826 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3830 void handle_connect(char **parameters, int pcnt, userrec *user)
3832 char Link_ServerName[1024];
3833 char Link_IPAddr[1024];
3834 char Link_Port[1024];
3835 char Link_Pass[1024];
3839 for (int i = 0; i < ConfValueEnum("link"); i++)
3841 ConfValue("link","name",i,Link_ServerName);
3842 ConfValue("link","ipaddr",i,Link_IPAddr);
3843 ConfValue("link","port",i,Link_Port);
3844 ConfValue("link","sendpass",i,Link_Pass);
3845 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3846 LinkPort = atoi(Link_Port);
3847 if (match(Link_ServerName,parameters[0])) {
3853 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3857 // TODO: Perform a check here to stop a server being linked twice!
3859 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3861 if (me[defaultRoute])
3864 // at this point parameters[0] is an ip in a string.
3865 // TODO: Look this up from the <link> blocks instead!
3866 for (int j = 0; j < 255; j++) {
3867 if (servers[j] == NULL) {
3868 servers[j] = new serverrec;
3869 strcpy(servers[j]->internal_addr,Link_IPAddr);
3870 strcpy(servers[j]->name,Link_ServerName);
3871 log(DEBUG,"Allocated new serverrec");
3872 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
3874 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
3879 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
3883 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);
3887 void handle_squit(char **parameters, int pcnt, userrec *user)
3889 // send out an squit across the mesh and then clear the server list (for local squit)
3892 void handle_oper(char **parameters, int pcnt, userrec *user)
3894 char LoginName[MAXBUF];
3895 char Password[MAXBUF];
3896 char OperType[MAXBUF];
3897 char TypeName[MAXBUF];
3898 char Hostname[MAXBUF];
3901 for (i = 0; i < ConfValueEnum("oper"); i++)
3903 ConfValue("oper","name",i,LoginName);
3904 ConfValue("oper","password",i,Password);
3905 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3907 /* correct oper credentials */
3908 ConfValue("oper","type",i,OperType);
3909 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3910 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3911 WriteServ(user->fd,"MODE %s :+o",user->nick);
3912 for (j =0; j < ConfValueEnum("type"); j++)
3914 ConfValue("type","name",j,TypeName);
3915 if (!strcmp(TypeName,OperType))
3917 /* found this oper's opertype */
3918 ConfValue("type","host",j,Hostname);
3919 strncpy(user->dhost,Hostname,256);
3922 if (!strchr(user->modes,'o'))
3924 strcat(user->modes,"o");
3930 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3931 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3934 void handle_nick(char **parameters, int pcnt, userrec *user)
3938 log(DEBUG,"not enough params for handle_nick");
3943 log(DEBUG,"invalid parameter passed to handle_nick");
3946 if (!strlen(parameters[0]))
3948 log(DEBUG,"zero length new nick passed to handle_nick");
3953 log(DEBUG,"invalid user passed to handle_nick");
3958 log(DEBUG,"invalid old nick passed to handle_nick");
3961 if (!strcasecmp(user->nick,parameters[0]))
3963 log(DEBUG,"old nick is new nick, skipping");
3968 if (strlen(parameters[0]) > 1)
3970 if (parameters[0][0] == ':')
3975 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
3977 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
3981 if (isnick(parameters[0]) == 0)
3983 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
3987 if (user->registered == 7)
3989 WriteCommon(user,"NICK %s",parameters[0]);
3992 /* change the nick of the user in the users_hash */
3993 user = ReHashNick(user->nick, parameters[0]);
3994 /* actually change the nick within the record */
3996 if (!user->nick) return;
3998 strncpy(user->nick, parameters[0],NICKMAX);
4000 log(DEBUG,"new nick set: %s",user->nick);
4002 if (user->registered < 3)
4003 user->registered = (user->registered | 2);
4004 if (user->registered == 3)
4006 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4009 log(DEBUG,"exit nickchange: %s",user->nick);
4012 int process_parameters(char **command_p,char *parameters)
4017 q = strlen(parameters);
4020 /* no parameters, command_p invalid! */
4023 if (parameters[0] == ':')
4025 command_p[0] = parameters+1;
4030 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4032 /* only one parameter */
4033 command_p[0] = parameters;
4034 if (parameters[0] == ':')
4036 if (strchr(parameters,' ') != NULL)
4044 command_p[j++] = parameters;
4045 for (i = 0; i <= q; i++)
4047 if (parameters[i] == ' ')
4049 command_p[j++] = parameters+i+1;
4050 parameters[i] = '\0';
4051 if (command_p[j-1][0] == ':')
4053 *command_p[j-1]++; /* remove dodgy ":" */
4055 /* parameter like this marks end of the sequence */
4059 return j; /* returns total number of items in the list */
4062 void process_command(userrec *user, char* cmd)
4066 char *command_p[127];
4067 char p[MAXBUF], temp[MAXBUF];
4068 int i, j, items, cmd_found;
4070 for (int i = 0; i < 127; i++)
4071 command_p[i] = NULL;
4081 if (!strcmp(cmd,""))
4088 FOREACH_MOD OnServerRaw(tmp,true);
4089 const char* cmd2 = tmp.c_str();
4090 snprintf(cmd,512,"%s",cmd2);
4092 if (!strchr(cmd,' '))
4094 /* no parameters, lets skip the formalities and not chop up
4097 command_p[0] = NULL;
4099 for (int i = 0; i <= strlen(cmd); i++)
4101 cmd[i] = toupper(cmd[i]);
4108 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4109 for (i = 0; i < strlen(temp); i++)
4111 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4117 /* split the full string into a command plus parameters */
4121 if (strchr(cmd,' '))
4123 for (i = 0; i <= strlen(cmd); i++)
4125 /* capitalise the command ONLY, leave params intact */
4126 cmd[i] = toupper(cmd[i]);
4127 /* are we nearly there yet?! :P */
4131 parameters = cmd+i+1;
4139 for (i = 0; i <= strlen(cmd); i++)
4141 cmd[i] = toupper(cmd[i]);
4149 for (i = 0; i != cmdlist.size(); i++)
4151 if (strcmp(cmdlist[i].command,""))
4153 if (!strcmp(command, cmdlist[i].command))
4157 if (strcmp(parameters,""))
4159 items = process_parameters(command_p,parameters);
4164 command_p[0] = NULL;
4170 command_p[0] = NULL;
4175 user->idle_lastmsg = time(NULL);
4176 /* activity resets the ping pending timer */
4177 user->nping = time(NULL) + 120;
4178 if ((items) < cmdlist[i].min_params)
4180 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4181 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4184 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4186 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4187 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4191 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4193 if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4195 if ((!isnick(user->nick)) || (user->registered != 7))
4197 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4198 WriteServ(user->fd,"451 %s :You have not registered",command);
4202 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4204 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4205 if (cmdlist[i].handler_function)
4207 /* ikky /stats counters */
4212 user->bytes_in += strlen(temp);
4215 cmdlist[i].use_count++;
4216 cmdlist[i].total_bytes+=strlen(temp);
4219 /* WARNING: nothing may come after the
4220 * command handler call, as the handler
4221 * may free the user structure! */
4223 cmdlist[i].handler_function(command_p,items,user);
4229 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4230 WriteServ(user->fd,"451 %s :You have not registered",command);
4238 if ((!cmd_found) && (user))
4240 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4241 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4246 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4249 /* create the command and push it onto the table */
4250 strcpy(comm.command,cmd);
4251 comm.handler_function = f;
4252 comm.flags_needed = flags;
4253 comm.min_params = minparams;
4255 comm.total_bytes = 0;
4256 cmdlist.push_back(comm);
4257 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4260 void SetupCommandTable(void)
4262 createcommand("USER",handle_user,0,4);
4263 createcommand("NICK",handle_nick,0,1);
4264 createcommand("QUIT",handle_quit,0,0);
4265 createcommand("VERSION",handle_version,0,0);
4266 createcommand("PING",handle_ping,0,1);
4267 createcommand("PONG",handle_pong,0,1);
4268 createcommand("ADMIN",handle_admin,0,0);
4269 createcommand("PRIVMSG",handle_privmsg,0,2);
4270 createcommand("INFO",handle_info,0,0);
4271 createcommand("TIME",handle_time,0,0);
4272 createcommand("WHOIS",handle_whois,0,1);
4273 createcommand("WALLOPS",handle_wallops,'o',1);
4274 createcommand("NOTICE",handle_notice,0,2);
4275 createcommand("JOIN",handle_join,0,1);
4276 createcommand("NAMES",handle_names,0,1);
4277 createcommand("PART",handle_part,0,1);
4278 createcommand("KICK",handle_kick,0,2);
4279 createcommand("MODE",handle_mode,0,1);
4280 createcommand("TOPIC",handle_topic,0,1);
4281 createcommand("WHO",handle_who,0,1);
4282 createcommand("MOTD",handle_motd,0,0);
4283 createcommand("RULES",handle_join,0,0);
4284 createcommand("OPER",handle_oper,0,2);
4285 createcommand("LIST",handle_list,0,0);
4286 createcommand("DIE",handle_die,'o',1);
4287 createcommand("RESTART",handle_restart,'o',1);
4288 createcommand("KILL",handle_kill,'o',2);
4289 createcommand("REHASH",handle_rehash,'o',0);
4290 createcommand("LUSERS",handle_lusers,0,0);
4291 createcommand("STATS",handle_stats,0,1);
4292 createcommand("USERHOST",handle_userhost,0,1);
4293 createcommand("AWAY",handle_away,0,0);
4294 createcommand("ISON",handle_ison,0,0);
4295 createcommand("SUMMON",handle_summon,0,0);
4296 createcommand("USERS",handle_users,0,0);
4297 createcommand("INVITE",handle_invite,0,2);
4298 createcommand("PASS",handle_pass,0,1);
4299 createcommand("TRACE",handle_trace,'o',0);
4300 createcommand("WHOWAS",handle_whowas,0,1);
4301 createcommand("CONNECT",handle_connect,'o',1);
4302 createcommand("SQUIT",handle_squit,'o',1);
4305 void process_buffer(userrec *user)
4313 if (!strcmp(user->inbuf,""))
4317 strncpy(cmd,user->inbuf,MAXBUF);
4318 if (!strcmp(cmd,""))
4322 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4324 cmd[strlen(cmd)-1] = '\0';
4326 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4328 cmd[strlen(cmd)-1] = '\0';
4330 strcpy(user->inbuf,"");
4331 if (!strcmp(cmd,""))
4335 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4336 process_command(user,cmd);
4339 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4341 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4345 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4347 char response[10240];
4348 char token = udp_msg[0];
4349 char* params = udp_msg + 2;
4350 char finalparam[1024];
4351 strcpy(finalparam," :xxxx");
4352 if (strstr(params," :")) {
4353 strncpy(finalparam,strstr(params," :"),1024);
4356 // S test.chatspike.net password :ChatSpike InspIRCd test server
4357 char* servername = strtok(params," ");
4358 char* password = strtok(NULL," ");
4359 char* serverdesc = finalparam+2;
4360 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4363 char Link_ServerName[1024];
4364 char Link_IPAddr[1024];
4365 char Link_Port[1024];
4366 char Link_Pass[1024];
4367 char Link_SendPass[1024];
4370 // search for a corresponding <link> block in the config files
4371 for (int i = 0; i < ConfValueEnum("link"); i++)
4373 ConfValue("link","name",i,Link_ServerName);
4374 ConfValue("link","ipaddr",i,Link_IPAddr);
4375 ConfValue("link","port",i,Link_Port);
4376 ConfValue("link","recvpass",i,Link_Pass);
4377 ConfValue("link","sendpass",i,Link_SendPass);
4378 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4379 LinkPort = atoi(Link_Port);
4380 if (!strcasecmp(Link_ServerName,servername)) {
4381 if (!strcasecmp(Link_IPAddr,udp_host)) {
4382 if (LinkPort == udp_port) {
4383 // we have a matching link line -
4384 // send a 'diminutive' server message back...
4385 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4386 serv->SendPacket(response,udp_host,udp_port,0);
4387 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4388 for (int j = 0; j < 255; j++) {
4389 if (servers[j] == NULL) {
4390 servers[j] = new serverrec;
4391 strcpy(servers[j]->internal_addr,udp_host);
4392 strcpy(servers[j]->name,servername);
4393 // create a server record for this server
4394 snprintf(response,10240,"O %d",MyKey);
4395 serv->SendPacket(response,udp_host,udp_port,0);
4399 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4403 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4407 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4411 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4414 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4415 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4420 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4421 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4422 // array, which is only added by an 'S' packet or BeginLink().
4423 for (int i = 0; i < 255; i++) {
4424 if (servers[i] != NULL) {
4425 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4426 servers[i]->key = atoi(params);
4427 log(DEBUG,"Key for this server is now %d",servers[i]->key);
4428 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4433 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4437 // S test.chatspike.net password :ChatSpike InspIRCd test server
4438 char* servername = strtok(params," ");
4439 char* password = strtok(NULL," ");
4440 char* serverdesc = finalparam+2;
4442 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4443 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4444 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4445 // a connect, so put out an oper alert!
4450 // for now, just accept all, we'll fix that later.
4451 WriteOpers("%s accepted our link credentials ",servername);
4453 char Link_ServerName[1024];
4454 char Link_IPAddr[1024];
4455 char Link_Port[1024];
4456 char Link_Pass[1024];
4457 char Link_SendPass[1024];
4460 // search for a corresponding <link> block in the config files
4461 for (int i = 0; i < ConfValueEnum("link"); i++)
4463 ConfValue("link","name",i,Link_ServerName);
4464 ConfValue("link","ipaddr",i,Link_IPAddr);
4465 ConfValue("link","port",i,Link_Port);
4466 ConfValue("link","recvpass",i,Link_Pass);
4467 ConfValue("link","sendpass",i,Link_SendPass);
4468 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4469 LinkPort = atoi(Link_Port);
4470 if (!strcasecmp(Link_ServerName,servername)) {
4471 if (!strcasecmp(Link_IPAddr,udp_host)) {
4472 if (LinkPort == udp_port) {
4473 // matching link at this end too, we're all done!
4474 // at this point we must begin key exchange and insert this
4475 // server into our 'active' table.
4476 for (int j = 0; j < 255; j++) {
4477 if (servers[j] != NULL) {
4478 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4479 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4480 snprintf(response,10240,"O %d",MyKey);
4481 serv->SendPacket(response,udp_host,udp_port,0);
4486 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4491 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4495 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4499 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4502 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4503 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4508 char* error_message = finalparam+2;
4509 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4510 // remove this server from any lists
4511 for (int j = 0; j < 255; j++) {
4512 if (servers[j] != NULL) {
4513 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4523 serverrec* source_server = NULL;
4525 for (int j = 0; j < 255; j++) {
4526 if (servers[j] != NULL) {
4527 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4528 if (servers[j]->key == theirkey) {
4529 // found a valid key for this server, can process restricted stuff here
4530 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4538 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4542 int reap_counter = 0;
4546 struct sockaddr_in client, server;
4547 char addrs[MAXBUF][255];
4548 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4550 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4551 int selectResult = 0;
4552 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4553 char resolvedHost[MAXBUF];
4557 log(DEBUG,"InspIRCd: startup: begin");
4561 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4563 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4565 SetupCommandTable();
4566 log(DEBUG,"InspIRCd: startup: default command table set up");
4569 if (strcmp(DieValue,""))
4571 printf("WARNING: %s\n\n",DieValue);
4574 log(DEBUG,"InspIRCd: startup: read config");
4576 int count2 = 0, count3 = 0;
4577 for (count = 0; count < ConfValueEnum("bind"); count++)
4579 ConfValue("bind","port",count,configToken);
4580 ConfValue("bind","address",count,Addr);
4581 ConfValue("bind","type",count,Type);
4582 if (!strcmp(Type,"servers"))
4584 char Default[MAXBUF];
4585 strcpy(Default,"no");
4586 ConfValue("bind","default",count,Default);
4587 if (strchr(Default,'y'))
4589 defaultRoute = count3;
4590 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4592 me[count3] = new serverrec(ServerName,100L,false);
4593 me[count3]->CreateListener(Addr,atoi(configToken));
4598 ports[count2] = atoi(configToken);
4599 strcpy(addrs[count2],Addr);
4602 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4605 UDPportCount = count3;
4607 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4609 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4613 /* BugFix By Craig! :p */
4615 for (count = 0; count2 < ConfValueEnum("module"); count2++)
4617 char modfile[MAXBUF];
4618 ConfValue("module","name",count,configToken);
4619 sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4620 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4621 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4622 /* If The File Doesnt exist, Trying to load it
4623 * Will Segfault the IRCd.. So, check to see if
4624 * it Exists, Before Proceeding. */
4625 if (FileExists(modfile))
4627 factory[count] = new ircd_module(modfile);
4628 if (factory[count]->LastError())
4630 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4631 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4634 if (factory[count]->factory)
4636 modules[count] = factory[count]->factory->CreateModule();
4637 /* save the module and the module's classfactory, if
4638 * this isnt done, random crashes can occur :/ */
4642 log(DEBUG,"Unable to load %s",modfile);
4643 sprintf("Unable to load %s\nExiting...\n",modfile);
4646 /* Increase the Count */
4651 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4652 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4655 MODCOUNT = count - 1;
4656 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4658 printf("\nInspIRCd is now running!\n");
4660 startup_time = time(NULL);
4664 log(VERBOSE,"Not forking as -nofork was specified");
4668 if (DaemonSeed() == ERROR)
4670 log(DEBUG,"InspIRCd: startup: can't daemonise");
4671 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4677 /* setup select call */
4678 FD_ZERO(&selectFds);
4679 log(DEBUG,"InspIRCd: startup: zero selects");
4680 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4682 for (count = 0; count < portCount; count++)
4684 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4686 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4689 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4691 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4693 else /* well we at least bound to one socket so we'll continue */
4699 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4701 /* if we didn't bind to anything then abort */
4702 if (boundPortCount == 0)
4704 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4708 length = sizeof (client);
4709 int flip_flop = 0, udp_port = 0;
4710 char udp_msg[MAXBUF], udp_host[MAXBUF];
4712 /* main loop for multiplexing/resetting */
4715 /* set up select call */
4716 for (count = 0; count < boundPortCount; count++)
4718 FD_SET (openSockfd[count], &selectFds);
4721 /* added timeout! select was waiting forever... wank... :/ */
4732 vector<int>::iterator niterator;
4735 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4736 // them in a list, then reap the list every second or so.
4737 if (reap_counter>5000) {
4738 if (fd_reap.size() > 0) {
4739 for( int n = 0; n < fd_reap.size(); n++)
4741 Blocking(fd_reap[n]);
4743 NonBlocking(fd_reap[n]);
4752 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4754 for (int x = 0; x != UDPportCount; x++)
4757 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
4759 if (strlen(udp_msg)<1) {
4760 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
4763 FOREACH_MOD OnPacketReceive(udp_msg);
4764 // Packets must go back via the route they arrived on :)
4765 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
4770 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
4774 if (!count2->second) break;
4777 if (count2->second->fd)
4779 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4781 if (!count2->second->lastping)
4783 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4784 kill_link(count2->second,"Ping timeout");
4787 Write(count2->second->fd,"PING :%s",ServerName);
4788 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4789 count2->second->lastping = 0;
4790 count2->second->nping = time(NULL)+120;
4793 result = read(count2->second->fd, data, 1);
4794 // result EAGAIN means nothing read
4795 if (result == EAGAIN)
4801 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
4802 kill_link(count2->second,"Client exited");
4804 else if (result > 0)
4806 strncat(count2->second->inbuf, data, result);
4807 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r'))
4809 /* at least one complete line is waiting to be processed */
4810 if (!count2->second->fd)
4814 process_buffer(count2->second);
4822 /* select is reporting a waiting socket. Poll them all to find out which */
4823 if (selectResult > 0)
4825 char target[MAXBUF], resolved[MAXBUF];
4826 for (count = 0; count < boundPortCount; count++)
4828 if (FD_ISSET (openSockfd[count], &selectFds))
4830 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4832 address_cache::iterator iter = IP.find(client.sin_addr);
4833 bool iscached = false;
4834 if (iter == IP.end())
4836 /* ip isn't in cache, add it */
4837 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4838 if(CleanAndResolve(resolved, target) != TRUE)
4840 strncpy(resolved,target,MAXBUF);
4842 /* hostname now in 'target' */
4843 IP[client.sin_addr] = new string(resolved);
4844 /* hostname in cache */
4848 /* found ip (cached) */
4849 strncpy(resolved, iter->second->c_str(), MAXBUF);
4853 if (incomingSockfd < 0)
4855 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4856 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4860 AddClient(incomingSockfd, resolved, ports[count], iscached);
4861 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4870 close (incomingSockfd);