1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2003 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
32 #include <ext/hash_map>
41 #include "connection.h"
53 #define nspace __gnu_cxx
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
66 char restartpass[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 time_t startup_time = time(NULL);
78 extern vector<Module*> modules;
79 extern vector<ircd_module*> factory;
86 template<> struct nspace::hash<in_addr>
88 size_t operator()(const struct in_addr &a) const
91 memcpy(&q,&a,sizeof(size_t));
96 template<> struct nspace::hash<string>
98 size_t operator()(const string &s) const
101 static struct hash<const char *> strhash;
113 bool operator()(const string& s1, const string& s2) const
115 char a[MAXBUF],b[MAXBUF];
116 strcpy(a,s1.c_str());
117 strcpy(b,s2.c_str());
118 return (strcasecmp(a,b) == 0);
123 struct InAddr_HashComp
126 bool operator()(const in_addr &s1, const in_addr &s2) const
131 memcpy(&q,&s1,sizeof(size_t));
132 memcpy(&p,&s2,sizeof(size_t));
140 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
141 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
142 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
143 typedef std::deque<command_t> command_table;
146 serverrec* servers[255];
148 user_hash clientlist;
151 command_table cmdlist;
158 struct linger linger = { 0 };
159 char bannerBuffer[MAXBUF];
160 int boundPortCount = 0;
161 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
162 int defaultRoute = 0;
166 long MyKey = C.GenKey();
170 int has_channel(userrec *u, chanrec *c);
171 int usercount(chanrec *c);
172 int usercount_i(chanrec *c);
173 void update_stats_l(int fd,int data_out);
174 char* Passwd(userrec *user);
175 bool IsDenied(userrec *user);
176 void AddWhoWas(userrec* u);
179 void safedelete(userrec *p)
183 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
184 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
189 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
193 void safedelete(chanrec *p)
198 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
202 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
207 /* chop a string down to 512 characters and preserve linefeed (irc max
214 FOREACH_MOD OnServerRaw(temp,false);
215 const char* str2 = temp.c_str();
216 sprintf(str,"%s",str2);
219 if (strlen(str) > 512)
228 std::string getservername()
233 std::string getserverdesc()
238 std::string getnetworkname()
243 std::string getadminname()
248 std::string getadminemail()
253 std::string getadminnick()
258 void log(int level,char *text, ...)
260 char textbuffer[MAXBUF];
264 struct tm * timeinfo;
265 if (level < LogLevel)
269 timeinfo = localtime (&rawtime);
271 f = fopen("ircd.log","a+");
275 va_start (argsPtr, text);
276 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
278 strcpy(b,asctime(timeinfo));
279 b[strlen(b)-1] = ':';
280 fprintf(f,"%s %s\n",b,textbuffer);
285 printf("Can't write log file, bailing!!!");
290 void readfile(file_cache &F, const char* fname)
293 char linebuf[MAXBUF];
295 log(DEBUG,"readfile: loading %s",fname);
297 file = fopen(fname,"r");
302 fgets(linebuf,sizeof(linebuf),file);
303 linebuf[strlen(linebuf)-1]='\0';
304 if (!strcmp(linebuf,""))
310 F.push_back(linebuf);
317 log(DEBUG,"readfile: failed to load file: %s",fname);
319 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
322 void ReadConfig(void)
324 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
327 ConfValue("server","name",0,ServerName);
328 ConfValue("server","description",0,ServerDesc);
329 ConfValue("server","network",0,Network);
330 ConfValue("admin","name",0,AdminName);
331 ConfValue("admin","email",0,AdminEmail);
332 ConfValue("admin","nick",0,AdminNick);
333 ConfValue("files","motd",0,motd);
334 ConfValue("files","rules",0,rules);
335 ConfValue("power","diepass",0,diepass);
336 ConfValue("power","pause",0,pauseval);
337 ConfValue("power","restartpass",0,restartpass);
338 ConfValue("options","prefixquit",0,PrefixQuit);
339 ConfValue("die","value",0,DieValue);
340 ConfValue("options","loglevel",0,dbg);
341 if (!strcmp(dbg,"debug"))
343 if (!strcmp(dbg,"verbose"))
345 if (!strcmp(dbg,"default"))
347 if (!strcmp(dbg,"sparse"))
349 if (!strcmp(dbg,"none"))
351 readfile(RULES,rules);
352 log(DEBUG,"Reading connect classes");
354 for (int i = 0; i < ConfValueEnum("connect"); i++)
357 ConfValue("connect","allow",i,Value);
358 if (strcmp(Value,""))
360 strcpy(c.host,Value);
363 ConfValue("connect","password",i,Value);
364 strcpy(c.pass,Value);
365 Classes.push_back(c);
366 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
370 ConfValue("connect","deny",i,Value);
371 strcpy(c.host,Value);
373 Classes.push_back(c);
374 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
383 log(DEBUG,"Blocking: %d",s);
384 flags = fcntl(s, F_GETFL, 0);
385 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
388 void NonBlocking(int s)
391 log(DEBUG,"NonBlocking: %d",s);
392 flags = fcntl(s, F_GETFL, 0);
393 fcntl(s, F_SETFL, flags | O_NONBLOCK);
397 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
399 struct hostent *hostPtr = NULL;
402 memset (resolvedHost, '\0',MAXBUF);
403 if(unresolvedHost == NULL)
405 if ((inet_aton(unresolvedHost,&addr)) == 0)
407 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
409 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
411 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
415 /* write formatted text to a socket, in same format as printf */
417 void Write(int sock,char *text, ...)
419 char textbuffer[MAXBUF];
423 va_start (argsPtr, text);
424 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
426 sprintf(tb,"%s\r\n",textbuffer);
428 write(sock,tb,strlen(tb));
429 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
432 /* write a server formatted numeric response to a single socket */
434 void WriteServ(int sock, char* text, ...)
436 char textbuffer[MAXBUF],tb[MAXBUF];
438 va_start (argsPtr, text);
440 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
442 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
444 write(sock,tb,strlen(tb));
445 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
448 /* write text from an originating user to originating user */
450 void WriteFrom(int sock, userrec *user,char* text, ...)
452 char textbuffer[MAXBUF],tb[MAXBUF];
454 va_start (argsPtr, text);
456 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
458 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
460 write(sock,tb,strlen(tb));
461 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
464 /* write text to an destination user from a source user (e.g. user privmsg) */
466 void WriteTo(userrec *source, userrec *dest,char *data, ...)
468 char textbuffer[MAXBUF],tb[MAXBUF];
470 va_start (argsPtr, data);
471 if ((!dest) || (!source))
475 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
478 WriteFrom(dest->fd,source,"%s",textbuffer);
481 /* write formatted text from a source user to all users on a channel
482 * including the sender (NOT for privmsg, notice etc!) */
484 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
486 char textbuffer[MAXBUF];
488 va_start (argsPtr, text);
489 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
491 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
493 if (has_channel(i->second,Ptr))
495 WriteTo(user,i->second,"%s",textbuffer);
500 /* write formatted text from a source user to all users on a channel except
501 * for the sender (for privmsg etc) */
503 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
505 char textbuffer[MAXBUF];
507 va_start (argsPtr, text);
508 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
511 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
513 if (has_channel(i->second,Ptr) && (user != i->second))
515 WriteTo(user,i->second,"%s",textbuffer);
520 int c_count(userrec* u)
523 for (int i =0; i != MAXCHANS; i++)
524 if (u->chans[i].channel)
530 /* return 0 or 1 depending if users u and u2 share one or more common channels
531 * (used by QUIT, NICK etc which arent channel specific notices) */
533 int common_channels(userrec *u, userrec *u2)
542 for (i = 0; i != MAXCHANS; i++)
544 for (z = 0; z != MAXCHANS; z++)
546 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
548 if ((c_count(u)) && (c_count(u2)))
558 /* write a formatted string to all users who share at least one common
559 * channel, including the source user e.g. for use in NICK */
561 void WriteCommon(userrec *u, char* text, ...)
563 char textbuffer[MAXBUF];
565 va_start (argsPtr, text);
566 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
569 WriteFrom(u->fd,u,"%s",textbuffer);
571 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
573 if (common_channels(u,i->second) && (i->second != u))
575 WriteFrom(i->second->fd,u,"%s",textbuffer);
580 /* write a formatted string to all users who share at least one common
581 * channel, NOT including the source user e.g. for use in QUIT */
583 void WriteCommonExcept(userrec *u, char* text, ...)
585 char textbuffer[MAXBUF];
587 va_start (argsPtr, text);
588 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
591 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
593 if ((common_channels(u,i->second)) && (u != i->second))
595 WriteFrom(i->second->fd,u,"%s",textbuffer);
600 void WriteOpers(char* text, ...)
602 char textbuffer[MAXBUF];
604 va_start (argsPtr, text);
605 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
608 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
610 if (strchr(i->second->modes,'o'))
612 if (strchr(i->second->modes,'s'))
614 // send server notices to all with +s
615 // (TODO: needs SNOMASKs)
616 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
622 void WriteWallOps(userrec *source, char* text, ...)
625 char textbuffer[MAXBUF];
627 va_start (argsPtr, text);
628 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
631 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
633 if (strchr(i->second->modes,'w'))
635 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
640 /* convert a string to lowercase. Note following special circumstances
641 * taken from RFC 1459. Many "official" server branches still hold to this
642 * rule so i will too;
644 * Because of IRC's scandanavian origin, the characters {}| are
645 * considered to be the lower case equivalents of the characters []\,
646 * respectively. This is a critical issue when determining the
647 * equivalence of two nicknames.
650 void strlower(char *n)
656 for (int i = 0; i != strlen(n); i++)
658 n[i] = tolower(n[i]);
668 /* verify that a user's ident and nickname is valid */
670 int isident(const char* n)
683 for (i = 0; i != strlen(n); i++)
685 if ((n[i] < 33) || (n[i] > 125))
689 /* can't occur ANYWHERE in an Ident! */
690 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
699 int isnick(const char* n)
711 if (strlen(n) > NICKMAX-1)
715 for (i = 0; i != strlen(n); i++)
717 if ((n[i] < 33) || (n[i] > 125))
721 /* can't occur ANYWHERE in a nickname! */
722 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
726 /* can't occur as the first char of a nickname... */
727 if ((strchr("0123456789",n[i])) && (!i))
735 /* Find a user record by nickname and return a pointer to it */
737 userrec* Find(string nick)
739 user_hash::iterator iter = clientlist.find(nick);
741 if (iter == clientlist.end())
742 /* Couldn't find it */
748 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
750 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
752 if (i->second->fd == fd)
754 i->second->bytes_out+=data_out;
755 i->second->cmds_out++;
761 /* find a channel record by channel name and return a pointer to it */
763 chanrec* FindChan(const char* chan)
765 chan_hash::iterator iter = chanlist.find(chan);
767 if (iter == chanlist.end())
768 /* Couldn't find it */
775 void purge_empty_chans(void)
777 int go_again = 1, purge = 0;
782 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
785 if (!usercount(i->second))
787 /* kill the record */
788 if (i != chanlist.end())
790 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
801 log(DEBUG,"completed channel purge, killed %d",purge);
804 /* returns the status character for a given user on a channel, e.g. @ for op,
805 * % for halfop etc. If the user has several modes set, the highest mode
806 * the user has must be returned. */
808 char* cmode(userrec *user, chanrec *chan)
811 for (i = 0; i != MAXCHANS; i++)
813 if ((user->chans[i].channel == chan) && (chan != NULL))
815 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
819 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
823 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
832 char scratch[MAXMODES];
834 char* chanmodes(chanrec *chan)
837 if (chan->noexternal)
845 if (strcmp(chan->key,""))
853 if (chan->inviteonly)
869 if (strcmp(chan->key,""))
872 strcat(scratch,chan->key);
877 sprintf(foo," %d",chan->limit);
880 log(DEBUG,"chanmodes: %s %s",chan->name,scratch);
884 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
885 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
886 * highest mode the user has must be returned. */
888 int cstatus(userrec *user, chanrec *chan)
891 for (i = 0; i != MAXCHANS; i++)
893 if ((user->chans[i].channel == chan) && (chan != NULL))
895 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
899 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
903 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
907 return STATUS_NORMAL;
913 /* compile a userlist of a channel into a string, each nick seperated by
914 * spaces and op, voice etc status shown as @ and + */
916 void userlist(userrec *user,chanrec *c)
918 sprintf(list,"353 %s = %s :", user->nick, c->name);
919 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
921 if (has_channel(i->second,c))
923 if (isnick(i->second->nick))
925 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
927 /* user is +i, and source not on the channel, does not show
928 * nick in NAMES list */
931 strcat(list,cmode(i->second,c));
932 strcat(list,i->second->nick);
934 if (strlen(list)>(480-NICKMAX))
936 /* list overflowed into
937 * multiple numerics */
938 WriteServ(user->fd,list);
939 sprintf(list,"353 %s = %s :", user->nick, c->name);
944 /* if whats left in the list isnt empty, send it */
945 if (list[strlen(list)-1] != ':')
947 WriteServ(user->fd,list);
951 /* return a count of the users on a specific channel accounting for
952 * invisible users who won't increase the count. e.g. for /LIST */
954 int usercount_i(chanrec *c)
960 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
964 if (has_channel(i->second,c))
966 if (isnick(i->second->nick))
968 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
970 /* user is +i, and source not on the channel, does not show
971 * nick in NAMES list */
979 log(DEBUG,"usercount_i: %s %d",c->name,count);
984 int usercount(chanrec *c)
990 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
994 if (has_channel(i->second,c))
996 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1003 log(DEBUG,"usercount: %s %d",c->name,count);
1008 /* add a channel to a user, creating the record for it if needed and linking
1009 * it to the user record */
1011 chanrec* add_channel(userrec *user, char* cname, char* key)
1017 if ((!cname) || (!user))
1021 if (strlen(cname) > CHANMAX-1)
1023 cname[CHANMAX-1] = '\0';
1026 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1028 if ((has_channel(user,FindChan(cname))) && (FindChan(cname)))
1030 return NULL; // already on the channel!
1033 if (!FindChan(cname))
1035 /* create a new one */
1036 log(DEBUG,"add_channel: creating: %s",cname);
1038 chanlist[cname] = new chanrec();
1040 strcpy(chanlist[cname]->name, cname);
1041 chanlist[cname]->topiclock = 1;
1042 chanlist[cname]->noexternal = 1;
1043 chanlist[cname]->created = time(NULL);
1044 strcpy(chanlist[cname]->topic, "");
1045 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1046 chanlist[cname]->topicset = 0;
1047 Ptr = chanlist[cname];
1048 log(DEBUG,"add_channel: created: %s",cname);
1049 /* set created to 2 to indicate user
1050 * is the first in the channel
1051 * and should be given ops */
1057 /* channel exists, just fish out a pointer to its struct */
1058 Ptr = FindChan(cname);
1061 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1062 if (strcmp(Ptr->key,""))
1064 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1067 log(DEBUG,"add_channel: no key given in JOIN");
1068 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1073 log(DEBUG,"key at %p is %s",key,key);
1074 if (strcasecmp(key,Ptr->key))
1076 log(DEBUG,"add_channel: bad key given in JOIN");
1077 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1082 log(DEBUG,"add_channel: no key");
1084 if (Ptr->inviteonly)
1086 log(DEBUG,"add_channel: channel is +i");
1087 if (user->IsInvited(Ptr->name))
1089 /* user was invited to channel */
1090 /* there may be an optional channel NOTICE here */
1094 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1098 log(DEBUG,"add_channel: channel is not +i");
1102 if (usercount(Ptr) == Ptr->limit)
1104 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1109 log(DEBUG,"add_channel: about to walk banlist");
1111 /* check user against the channel banlist */
1112 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1114 if (match(user->GetFullHost(),i->data))
1116 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1121 log(DEBUG,"add_channel: bans checked");
1123 user->RemoveInvite(Ptr->name);
1125 log(DEBUG,"add_channel: invites removed");
1131 log(DEBUG,"Passed channel checks");
1133 for (i =0; i != MAXCHANS; i++)
1135 if (user->chans[i].channel == NULL)
1137 log(DEBUG,"Adding into their channel list");
1141 /* first user in is given ops */
1142 user->chans[i].uc_modes = UCMODE_OP;
1146 user->chans[i].uc_modes = 0;
1148 user->chans[i].channel = Ptr;
1149 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1151 log(DEBUG,"Sent JOIN to client");
1155 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1156 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1159 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1160 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1161 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1162 FOREACH_MOD OnUserJoin(user,Ptr);
1166 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1167 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1171 /* remove a channel from a users record, and remove the record from memory
1172 * if the channel has become empty */
1174 chanrec* del_channel(userrec *user, char* cname, char* reason)
1180 if ((!cname) || (!user))
1185 Ptr = FindChan(cname);
1192 FOREACH_MOD OnUserPart(user,Ptr);
1193 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1195 for (i =0; i != MAXCHANS; i++)
1197 /* zap it from the channel list of the user */
1198 if (user->chans[i].channel == Ptr)
1202 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1206 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1208 user->chans[i].uc_modes = 0;
1209 user->chans[i].channel = NULL;
1210 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1215 /* if there are no users left on the channel */
1216 if (!usercount(Ptr))
1218 chan_hash::iterator iter = chanlist.find(Ptr->name);
1220 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1222 /* kill the record */
1223 if (iter != chanlist.end())
1225 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1226 delete iter->second;
1227 chanlist.erase(iter);
1233 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1238 if ((!Ptr) || (!user) || (!src))
1243 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1245 if (!has_channel(user,Ptr))
1247 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1250 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1252 if (cstatus(src,Ptr) == STATUS_HOP)
1254 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1258 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1264 for (i =0; i != MAXCHANS; i++)
1266 /* zap it from the channel list of the user */
1267 if (user->chans[i].channel == Ptr)
1269 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1270 user->chans[i].uc_modes = 0;
1271 user->chans[i].channel = NULL;
1272 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1277 /* if there are no users left on the channel */
1278 if (!usercount(Ptr))
1280 chan_hash::iterator iter = chanlist.find(Ptr->name);
1282 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1284 /* kill the record */
1285 if (iter != chanlist.end())
1287 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1288 delete iter->second;
1289 chanlist.erase(iter);
1295 /* returns 1 if user u has channel c in their record, 0 if not */
1297 int has_channel(userrec *u, chanrec *c)
1305 for (i =0; i != MAXCHANS; i++)
1307 if (u->chans[i].channel == c)
1315 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1320 if ((!user) || (!dest) || (!chan))
1324 if (status != STATUS_OP)
1326 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1333 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1339 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1344 for (i = 0; i != MAXCHANS; i++)
1346 if ((d->chans[i].channel == chan) && (chan != NULL))
1348 if (d->chans[i].uc_modes & UCMODE_OP)
1350 /* mode already set on user, dont allow multiple */
1353 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1354 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1362 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1367 if ((!user) || (!dest) || (!chan))
1371 if (status != STATUS_OP)
1373 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1381 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1386 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1391 for (i = 0; i != MAXCHANS; i++)
1393 if ((d->chans[i].channel == chan) && (chan != NULL))
1395 if (d->chans[i].uc_modes & UCMODE_HOP)
1397 /* mode already set on user, dont allow multiple */
1400 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1401 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1409 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1414 if ((!user) || (!dest) || (!chan))
1418 if (status < STATUS_HOP)
1420 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1428 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1433 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1438 for (i = 0; i != MAXCHANS; i++)
1440 if ((d->chans[i].channel == chan) && (chan != NULL))
1442 if (d->chans[i].uc_modes & UCMODE_VOICE)
1444 /* mode already set on user, dont allow multiple */
1447 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1448 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1456 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1461 if ((!user) || (!dest) || (!chan))
1465 if (status != STATUS_OP)
1467 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1475 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1480 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1485 for (i = 0; i != MAXCHANS; i++)
1487 if ((d->chans[i].channel == chan) && (chan != NULL))
1489 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1491 /* mode already set on user, dont allow multiple */
1494 d->chans[i].uc_modes ^= UCMODE_OP;
1495 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1503 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1508 if ((!user) || (!dest) || (!chan))
1512 if (status != STATUS_OP)
1514 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1522 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1527 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1532 for (i = 0; i != MAXCHANS; i++)
1534 if ((d->chans[i].channel == chan) && (chan != NULL))
1536 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1538 /* mode already set on user, dont allow multiple */
1541 d->chans[i].uc_modes ^= UCMODE_HOP;
1542 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1550 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1555 if ((!user) || (!dest) || (!chan))
1559 if (status < STATUS_HOP)
1561 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1569 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1574 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1579 for (i = 0; i != MAXCHANS; i++)
1581 if ((d->chans[i].channel == chan) && (chan != NULL))
1583 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1585 /* mode already set on user, dont allow multiple */
1588 d->chans[i].uc_modes ^= UCMODE_VOICE;
1589 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1597 void TidyBan(char *ban)
1599 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1603 char* pos_of_pling = strchr(temp,'!');
1604 char* pos_of_at = strchr(temp,'@');
1606 pos_of_pling[0] = '\0';
1607 pos_of_at[0] = '\0';
1611 strncpy(NICK,temp,NICKMAX);
1612 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1613 strncpy(HOST,pos_of_at,160);
1615 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1618 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1621 if ((!user) || (!dest) || (!chan))
1623 if (strchr(dest,'!')==0)
1625 if (strchr(dest,'@')==0)
1627 for (int i = 0; i < strlen(dest); i++)
1630 for (int i = 0; i < strlen(dest); i++)
1634 for (int i = 0; i < strlen(dest); i++)
1640 for (int i = 0; i < strlen(dest); i++)
1645 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1648 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1650 if (!strcasecmp(i->data,dest))
1652 // dont allow a user to set the same ban twice
1657 b.set_time = time(NULL);
1658 strncpy(b.data,dest,MAXBUF);
1659 strncpy(b.set_by,user->nick,NICKMAX);
1660 chan->bans.push_back(b);
1664 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1666 if ((!user) || (!dest) || (!chan))
1671 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1672 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1674 if (!strcasecmp(i->data,dest))
1676 chan->bans.erase(i);
1683 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt)
1685 char modelist[MAXBUF];
1686 char outlist[MAXBUF];
1687 char outstr[MAXBUF];
1688 char outpars[32][MAXBUF];
1694 bool k_set = false, l_set = false;
1701 log(DEBUG,"process_modes: start");
1703 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1704 /* parameters[2] onwards are parameters for
1705 * modes that require them :) */
1706 strcpy(outlist,"+");
1709 log(DEBUG,"process_modes: modelist: %s",modelist);
1711 for (ptr = 0; ptr < strlen(modelist); ptr++)
1716 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1717 char modechar = modelist[ptr];
1718 switch (modelist[ptr])
1723 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1725 outlist[strlen(outlist)-1] = '-';
1729 strcat(outlist,"-");
1739 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1741 outlist[strlen(outlist)-1] = '+';
1745 strcat(outlist,"+");
1752 if ((param >= pcnt)) break;
1755 r = give_ops(user,parameters[param++],chan,status);
1759 r = take_ops(user,parameters[param++],chan,status);
1763 strcat(outlist,"o");
1764 strcpy(outpars[pc++],parameters[param-1]);
1769 if ((param >= pcnt)) break;
1772 r = give_hops(user,parameters[param++],chan,status);
1776 r = take_hops(user,parameters[param++],chan,status);
1780 strcat(outlist,"h");
1781 strcpy(outpars[pc++],parameters[param-1]);
1787 if ((param >= pcnt)) break;
1790 r = give_voice(user,parameters[param++],chan,status);
1794 r = take_voice(user,parameters[param++],chan,status);
1798 strcat(outlist,"v");
1799 strcpy(outpars[pc++],parameters[param-1]);
1804 if ((param >= pcnt)) break;
1807 r = add_ban(user,parameters[param++],chan,status);
1811 r = take_ban(user,parameters[param++],chan,status);
1815 strcat(outlist,"b");
1816 strcpy(outpars[pc++],parameters[param-1]);
1821 if ((param >= pcnt))
1829 if (!strcmp(chan->key,""))
1831 strcat(outlist,"k");
1832 strcpy(outpars[pc++],parameters[param++]);
1833 strcpy(chan->key,parameters[param-1]);
1839 /* only allow -k if correct key given */
1840 if (strcmp(chan->key,""))
1842 strcat(outlist,"k");
1843 strcpy(chan->key,"");
1853 strcat(outlist,"l");
1858 if ((param >= pcnt)) break;
1864 bool invalid = false;
1865 for (int i = 0; i < strlen(parameters[param]); i++)
1867 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
1872 if (atoi(parameters[param]) < 1)
1880 chan->limit = atoi(parameters[param]);
1883 strcat(outlist,"l");
1884 strcpy(outpars[pc++],parameters[param++]);
1891 if (chan->inviteonly != mdir)
1893 strcat(outlist,"i");
1895 chan->inviteonly = mdir;
1899 if (chan->topiclock != mdir)
1901 strcat(outlist,"t");
1903 chan->topiclock = mdir;
1907 if (chan->noexternal != mdir)
1909 strcat(outlist,"n");
1911 chan->noexternal = mdir;
1915 if (chan->moderated != mdir)
1917 strcat(outlist,"m");
1919 chan->moderated = mdir;
1923 if (chan->secret != mdir)
1925 strcat(outlist,"s");
1926 if (chan->c_private)
1928 chan->c_private = 0;
1931 strcat(outlist,"-p+");
1935 strcat(outlist,"+p-");
1939 chan->secret = mdir;
1943 if (chan->c_private != mdir)
1945 strcat(outlist,"p");
1951 strcat(outlist,"-s+");
1955 strcat(outlist,"+s-");
1959 chan->c_private = mdir;
1965 if (ModeDefined(modelist[ptr],MT_CHANNEL))
1967 if ((ModeDefinedOn(modelist[ptr],MT_CHANNEL)>0) && (mdir))
1969 p.push_back(parameters[param]);
1971 if ((ModeDefinedOff(modelist[ptr],MT_CHANNEL)>0) && (!mdir))
1973 p.push_back(parameters[param]);
1975 for (int i = 0; i <= MODCOUNT; i++)
1977 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
1979 char app[] = {modechar, 0};
1980 strcat(outlist, app);
1981 chan->SetCustomMode(modelist[ptr],mdir);
1982 // include parameters in output if mode has them
1983 if ((ModeDefinedOn(modelist[ptr],MT_CHANNEL)>0) || (ModeDefinedOff(modelist[ptr],MT_CHANNEL)>0))
1985 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
1986 strcpy(outpars[pc++],parameters[param++]);
1997 /* this ensures only the *valid* modes are sent out onto the network */
1998 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2000 outlist[strlen(outlist)-1] = '\0';
2002 if (strcmp(outlist,""))
2004 strcpy(outstr,outlist);
2005 for (ptr = 0; ptr < pc; ptr++)
2008 strcat(outstr,outpars[ptr]);
2010 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2014 void handle_mode(char **parameters, int pcnt, userrec *user)
2020 char outpars[MAXBUF];
2022 dest = Find(parameters[0]);
2024 if ((dest) && (pcnt == 1))
2026 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2029 if ((dest) && (pcnt > 1))
2034 if (strchr(user->modes,'o'))
2045 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2049 strcpy(outpars,"+");
2052 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2055 for (i = 0; i < strlen(parameters[1]); i++)
2057 if (parameters[1][i] == '+')
2061 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2063 outpars[strlen(outpars)-1] = '+';
2067 strcat(outpars,"+");
2073 if (parameters[1][i] == '-')
2077 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2079 outpars[strlen(outpars)-1] = '-';
2083 strcat(outpars,"-");
2091 if (strchr(user->modes,'o'))
2097 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2106 if (!strchr(dest->modes,parameters[1][i]))
2108 dest->modes[strlen(dest->modes)+1]='\0';
2109 dest->modes[strlen(dest->modes)] = parameters[1][i];
2110 outpars[strlen(outpars)+1]='\0';
2111 outpars[strlen(outpars)] = parameters[1][i];
2120 outpars[strlen(outpars)+1]='\0';
2121 outpars[strlen(outpars)] = parameters[1][i];
2124 for (q = 0; q < strlen(user->modes); q++)
2126 if (user->modes[q] != parameters[1][i])
2128 moo[0] = user->modes[q];
2133 strcpy(user->modes,temp);
2138 if (strlen(outpars))
2144 while (i < strlen (outpars))
2146 b[z++] = outpars[i++];
2148 if (i<strlen(outpars)-1)
2150 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2152 // someones playing silly buggers and trying
2153 // to put a +- or -+ into the line...
2157 if (i == strlen(outpars)-1)
2159 if ((outpars[i] == '-') || (outpars[i] == '+'))
2167 if ((b[z] == '-') || (b[z] == '+'))
2170 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2173 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2178 Ptr = FindChan(parameters[0]);
2183 /* just /modes #channel */
2184 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2185 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2191 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2194 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2196 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2198 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2202 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2204 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2208 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt);
2212 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2216 /* This function pokes and hacks at a parameter list like the following:
2218 * PART #winbot, #darkgalaxy :m00!
2220 * to turn it into a series of individual calls like this:
2222 * PART #winbot :m00!
2223 * PART #darkgalaxy :m00!
2225 * The seperate calls are sent to a callback function provided by the caller
2226 * (the caller will usually call itself recursively). The callback function
2227 * must be a command handler. Calling this function on a line with no list causes
2228 * no action to be taken. You must provide a starting and ending parameter number
2229 * where the range of the list can be found, useful if you have a terminating
2230 * parameter as above which is actually not part of the list, or parameters
2231 * before the actual list as well. This code is used by many functions which
2232 * can function as "one to list" (see the RFC) */
2234 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2239 char blog[32][MAXBUF];
2240 char blog2[32][MAXBUF];
2241 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2242 char keystr[MAXBUF];
2245 for (i = 0; i <32; i++)
2248 for (i = 0; i <32; i++)
2249 strcpy(blog2[i],"");
2252 for (i = 0; i <10; i++)
2256 parameters[i] = moo;
2261 if (pcnt > 1) /* we have a key to copy */
2263 strcpy(keystr,parameters[1]);
2267 if (!parameters[start])
2271 if (!strchr(parameters[start],','))
2276 for (i = start; i <= end; i++)
2280 strcat(plist,parameters[i]);
2288 for (i = 0; i < t; i++)
2290 if (plist[i] == ',')
2293 strcpy(blog[j++],param);
2297 strcpy(blog[j++],param);
2300 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2305 if ((joins) && (keystr))
2307 if (strchr(keystr,','))
2311 t2 = strlen(keystr);
2312 for (i = 0; i < t2; i++)
2314 if (keystr[i] == ',')
2317 strcpy(blog2[j++],param);
2321 strcpy(blog2[j++],param);
2326 for (j = 0; j < total; j++)
2332 for (q = end; q < pcnt-1; q++)
2334 if (parameters[q+1])
2336 pars[q-end+1] = parameters[q+1];
2339 if ((joins) && (parameters[1]))
2350 /* repeatedly call the function with the hacked parameter list */
2351 if ((joins) && (pcnt > 1))
2355 // pars[1] already set up and containing key from blog2[j]
2360 pars[1] = parameters[1];
2366 fn(pars,pcnt-(end-start),u);
2373 void handle_join(char **parameters, int pcnt, userrec *user)
2378 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2380 if (parameters[0][0] == '#')
2382 Ptr = add_channel(user,parameters[0],parameters[1]);
2387 void handle_part(char **parameters, int pcnt, userrec *user)
2393 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2395 del_channel(user,parameters[0],parameters[1]);
2399 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2401 del_channel(user,parameters[0],NULL);
2405 void handle_kick(char **parameters, int pcnt, userrec *user)
2407 chanrec* Ptr = FindChan(parameters[0]);
2408 userrec* u = Find(parameters[1]);
2412 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2416 if (!has_channel(u,Ptr))
2418 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2424 kick_channel(user,u,Ptr,parameters[2]);
2428 kick_channel(user,u,Ptr,user->nick);
2433 void handle_die(char **parameters, int pcnt, userrec *user)
2435 log(DEBUG,"die: %s",user->nick);
2436 if (!strcmp(parameters[0],diepass))
2438 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2444 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2448 void handle_restart(char **parameters, int pcnt, userrec *user)
2450 log(DEBUG,"restart: %s",user->nick);
2451 if (!strcmp(parameters[0],restartpass))
2453 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2456 /* Will finish this later when i can be arsed :) */
2460 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2465 void kill_link(userrec *user,char* reason)
2467 user_hash::iterator iter = clientlist.find(user->nick);
2469 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2470 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2471 fdatasync(user->fd);
2472 log(DEBUG,"closing fd %d",user->fd);
2474 /* bugfix, cant close() a nonblocking socket (sux!) */
2475 if (user->registered == 7) {
2476 FOREACH_MOD OnUserQuit(user);
2477 WriteCommonExcept(user,"QUIT :%s",reason);
2480 /* push the socket on a stack of sockets due to be closed at the next opportunity */
2481 fd_reap.push_back(user->fd);
2483 bool do_purge = false;
2485 if (user->registered == 7) {
2486 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2490 if (iter != clientlist.end())
2492 log(DEBUG,"deleting user hash value %d",iter->second);
2493 if ((iter->second) && (user->registered == 7)) {
2494 delete iter->second;
2496 clientlist.erase(iter);
2499 purge_empty_chans();
2503 void handle_kill(char **parameters, int pcnt, userrec *user)
2505 userrec *u = Find(parameters[0]);
2506 char killreason[MAXBUF];
2508 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
2511 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
2512 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
2513 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
2514 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
2515 kill_link(u,killreason);
2519 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2523 void handle_summon(char **parameters, int pcnt, userrec *user)
2525 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
2528 void handle_users(char **parameters, int pcnt, userrec *user)
2530 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
2534 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2536 char* Passwd(userrec *user)
2538 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2540 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2548 bool IsDenied(userrec *user)
2550 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2552 if (match(user->host,i->host) && (i->type == CC_DENY))
2561 void handle_pass(char **parameters, int pcnt, userrec *user)
2563 if (!strcasecmp(parameters[0],Passwd(user)))
2565 user->haspassed = true;
2569 void handle_invite(char **parameters, int pcnt, userrec *user)
2571 userrec* u = Find(parameters[0]);
2572 chanrec* c = FindChan(parameters[1]);
2578 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
2584 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2593 if (cstatus(user,c) < STATUS_HOP)
2595 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
2599 u->InviteTo(c->name);
2600 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2601 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2605 void handle_topic(char **parameters, int pcnt, userrec *user)
2611 if (strlen(parameters[0]) <= CHANMAX)
2613 Ptr = FindChan(parameters[0]);
2618 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2619 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2623 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2628 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2634 if (loop_call(handle_topic,parameters,pcnt,user,0,pcnt-2,0))
2636 if (strlen(parameters[0]) <= CHANMAX)
2638 Ptr = FindChan(parameters[0]);
2641 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2643 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
2646 strcpy(Ptr->topic,parameters[1]);
2647 strcpy(Ptr->setby,user->nick);
2648 Ptr->topicset = time(NULL);
2649 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2653 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2659 /* sends out an error notice to all connected clients (not to be used
2662 void send_error(char *s)
2664 log(DEBUG,"send_error: %s",s);
2665 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2667 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2671 void Error(int status)
2673 signal (SIGALRM, SIG_IGN);
2674 signal (SIGPIPE, SIG_IGN);
2675 signal (SIGTERM, SIG_IGN);
2676 signal (SIGABRT, SIG_IGN);
2677 signal (SIGSEGV, SIG_IGN);
2678 signal (SIGURG, SIG_IGN);
2679 signal (SIGKILL, SIG_IGN);
2680 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2681 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2685 int main (int argc, char *argv[])
2688 log(DEBUG,"*** InspIRCd starting up!");
2689 if (!FileExists(CONFIG_FILE))
2691 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2692 log(DEBUG,"main: no config");
2693 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2696 if (InspIRCd() == ERROR)
2698 log(DEBUG,"main: daemon function bailed");
2699 printf("ERROR: could not initialise. Shutting down.\n");
2706 template<typename T> inline string ConvToStr(const T &in)
2709 if (!(tmp << in)) return string();
2713 /* re-allocates a nick in the user_hash after they change nicknames,
2714 * returns a pointer to the new user as it may have moved */
2716 userrec* ReHashNick(char* Old, char* New)
2718 user_hash::iterator newnick;
2719 user_hash::iterator oldnick = clientlist.find(Old);
2721 log(DEBUG,"ReHashNick: %s %s",Old,New);
2723 if (!strcasecmp(Old,New))
2725 log(DEBUG,"old nick is new nick, skipping");
2726 return oldnick->second;
2729 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2731 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2733 clientlist[New] = new userrec();
2734 clientlist[New] = oldnick->second;
2735 /*delete oldnick->second; */
2736 clientlist.erase(oldnick);
2738 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2740 return clientlist[New];
2743 /* adds or updates an entry in the whowas list */
2744 void AddWhoWas(userrec* u)
2746 user_hash::iterator iter = whowas.find(u->nick);
2747 userrec *a = new userrec();
2748 strcpy(a->nick,u->nick);
2749 strcpy(a->ident,u->ident);
2750 strcpy(a->dhost,u->dhost);
2751 strcpy(a->host,u->host);
2752 strcpy(a->fullname,u->fullname);
2753 strcpy(a->server,u->server);
2754 a->signon = u->signon;
2756 /* MAX_WHOWAS: max number of /WHOWAS items
2757 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2758 * can be replaced by a newer one
2761 if (iter == whowas.end())
2763 if (whowas.size() == WHOWAS_MAX)
2765 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2767 // 3600 seconds in an hour ;)
2768 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2772 log(DEBUG,"added WHOWAS entry, purged an old record");
2779 log(DEBUG,"added fresh WHOWAS entry");
2780 whowas[a->nick] = a;
2785 log(DEBUG,"updated WHOWAS entry");
2786 delete iter->second;
2792 /* add a client connection to the sockets list */
2793 void AddClient(int socket, char* host, int port, bool iscached)
2797 char resolved[MAXBUF];
2800 user_hash::iterator iter;
2802 tempnick = ConvToStr(socket) + "-unknown";
2803 sprintf(tn2,"%d-unknown",socket);
2805 iter = clientlist.find(tempnick);
2807 if (iter != clientlist.end()) return;
2810 * It is OK to access the value here this way since we know
2811 * it exists, we just created it above.
2813 * At NO other time should you access a value in a map or a
2814 * hash_map this way.
2816 clientlist[tempnick] = new userrec();
2818 NonBlocking(socket);
2819 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
2822 clientlist[tempnick]->fd = socket;
2823 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2824 strncpy(clientlist[tempnick]->host, host,160);
2825 strncpy(clientlist[tempnick]->dhost, host,160);
2826 strncpy(clientlist[tempnick]->server, ServerName,256);
2827 clientlist[tempnick]->registered = 0;
2828 clientlist[tempnick]->signon = time(NULL);
2829 clientlist[tempnick]->nping = time(NULL)+240;
2830 clientlist[tempnick]->lastping = 1;
2831 clientlist[tempnick]->port = port;
2835 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2839 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2842 if (clientlist.size() == MAXCLIENTS)
2843 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2846 void handle_names(char **parameters, int pcnt, userrec *user)
2850 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
2852 c = FindChan(parameters[0]);
2855 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
2857 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
2861 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2866 void handle_privmsg(char **parameters, int pcnt, userrec *user)
2871 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
2873 if (parameters[0][0] == '#')
2875 chan = FindChan(parameters[0]);
2878 if ((chan->noexternal) && (!has_channel(user,chan)))
2880 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
2883 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
2885 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
2888 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
2892 /* no such nick/channel */
2893 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2898 dest = Find(parameters[0]);
2901 if (strcmp(dest->awaymsg,""))
2903 /* auto respond with aweh msg */
2904 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
2906 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
2910 /* no such nick/channel */
2911 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2915 void handle_notice(char **parameters, int pcnt, userrec *user)
2920 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
2922 if (parameters[0][0] == '#')
2924 chan = FindChan(parameters[0]);
2927 if ((chan->noexternal) && (!has_channel(user,chan)))
2929 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
2932 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
2934 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
2937 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
2941 /* no such nick/channel */
2942 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2947 dest = Find(parameters[0]);
2950 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
2954 /* no such nick/channel */
2955 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2961 char* chlist(userrec *user)
2966 log(DEBUG,"chlist: %s",user->nick);
2972 for (i = 0; i != MAXCHANS; i++)
2974 if (user->chans[i].channel != NULL)
2976 if (user->chans[i].channel->name)
2978 strcpy(cmp,user->chans[i].channel->name);
2980 if (!strstr(lst,cmp))
2982 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
2984 strcat(lst,cmode(user,user->chans[i].channel));
2985 strcat(lst,user->chans[i].channel->name);
2995 void handle_info(char **parameters, int pcnt, userrec *user)
2997 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
2998 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
2999 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3000 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3003 void handle_time(char **parameters, int pcnt, userrec *user)
3006 struct tm * timeinfo;
3009 timeinfo = localtime ( &rawtime );
3010 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3014 void handle_whois(char **parameters, int pcnt, userrec *user)
3019 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3021 dest = Find(parameters[0]);
3024 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3025 if ((user == dest) || (strchr(user->modes,'o')))
3027 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3029 if (strcmp(chlist(dest),""))
3031 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3033 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3034 if (strcmp(dest->awaymsg,""))
3036 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3038 if (strchr(dest->modes,'o'))
3040 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3042 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3043 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3045 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3049 /* no such nick/channel */
3050 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3054 void handle_quit(char **parameters, int pcnt, userrec *user)
3056 user_hash::iterator iter = clientlist.find(user->nick);
3058 /* theres more to do here, but for now just close the socket */
3061 if (parameters[0][0] == ':')
3065 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3066 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3067 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3071 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3072 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3073 WriteCommonExcept(user,"QUIT :Client exited");
3076 FOREACH_MOD OnUserQuit(user);
3078 /* confucious say, he who close nonblocking socket, get nothing! */
3081 NonBlocking(user->fd);
3084 if (iter != clientlist.end())
3086 log(DEBUG,"deleting user hash value");
3087 delete iter->second;
3088 clientlist.erase(iter);
3091 purge_empty_chans();
3094 void handle_who(char **parameters, int pcnt, userrec *user)
3096 chanrec* Ptr = NULL;
3098 /* theres more to do here, but for now just close the socket */
3101 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3103 if (user->chans[0].channel)
3105 Ptr = user->chans[0].channel;
3106 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3108 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3110 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);
3116 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3120 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3124 if (parameters[0][0] = '#')
3126 Ptr = FindChan(parameters[0]);
3129 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3131 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3133 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);
3136 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3140 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3146 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3148 Ptr = user->chans[0].channel;
3149 printf(user->chans[0].channel->name);
3150 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3152 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3154 if (strchr(i->second->modes,'o'))
3156 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);
3160 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3166 void handle_wallops(char **parameters, int pcnt, userrec *user)
3168 WriteWallOps(user,"%s",parameters[0]);
3171 void handle_list(char **parameters, int pcnt, userrec *user)
3175 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3176 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3178 if ((!i->second->c_private) && (!i->second->secret))
3180 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3183 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3187 void handle_rehash(char **parameters, int pcnt, userrec *user)
3189 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3191 FOREACH_MOD OnRehash();
3192 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3198 return clientlist.size();
3201 int usercount_invisible(void)
3205 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3207 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3212 int usercount_opers(void)
3216 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3218 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3223 int usercount_unknown(void)
3227 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3229 if ((i->second->fd) && (i->second->registered != 7))
3237 return chanlist.size();
3240 int servercount(void)
3245 void handle_lusers(char **parameters, int pcnt, userrec *user)
3247 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3248 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3249 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3250 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3251 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3254 void handle_admin(char **parameters, int pcnt, userrec *user)
3256 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3257 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
3258 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3259 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
3262 void ShowMOTD(userrec *user)
3266 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3269 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3270 for (int i = 0; i != MOTD.size(); i++)
3272 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3274 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3277 void ShowRULES(userrec *user)
3281 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3284 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3285 for (int i = 0; i != RULES.size(); i++)
3287 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3289 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3292 /* shows the message of the day, and any other on-logon stuff */
3293 void ConnectUser(userrec *user)
3295 user->registered = 7;
3296 user->idle_lastmsg = time(NULL);
3297 log(DEBUG,"ConnectUser: %s",user->nick);
3299 if (strcmp(Passwd(user),"") && (!user->haspassed))
3301 Write(user->fd,"ERROR :Closing link: Invalid password");
3302 fdatasync(user->fd);
3303 kill_link(user,"Invalid password");
3308 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3309 fdatasync(user->fd);
3310 kill_link(user,"Unauthorised connection");
3313 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3314 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3315 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3316 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3317 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3318 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);
3319 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);
3321 FOREACH_MOD OnUserConnect(user);
3322 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3325 void handle_version(char **parameters, int pcnt, userrec *user)
3327 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3330 void handle_ping(char **parameters, int pcnt, userrec *user)
3332 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3335 void handle_pong(char **parameters, int pcnt, userrec *user)
3337 // set the user as alive so they survive to next ping
3341 void handle_motd(char **parameters, int pcnt, userrec *user)
3346 void handle_rules(char **parameters, int pcnt, userrec *user)
3351 void handle_user(char **parameters, int pcnt, userrec *user)
3353 if (user->registered < 3)
3355 if (isident(parameters[0]) == 0) {
3356 // This kinda Sucks, According to the RFC thou, its either this,
3357 // or "You have already registered" :p -- Craig
3358 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3361 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3362 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3363 strncat(user->ident,parameters[0],IDENTMAX);
3364 strncpy(user->fullname,parameters[3],128);
3365 user->registered = (user->registered | 1);
3370 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3373 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3374 if (user->registered == 3)
3376 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3381 void handle_userhost(char **parameters, int pcnt, userrec *user)
3383 char Return[MAXBUF],junk[MAXBUF];
3384 sprintf(Return,"302 %s :",user->nick);
3385 for (int i = 0; i < pcnt; i++)
3387 userrec *u = Find(parameters[i]);
3390 if (strchr(u->modes,'o'))
3392 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3393 strcat(Return,junk);
3397 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3398 strcat(Return,junk);
3402 WriteServ(user->fd,Return);
3406 void handle_ison(char **parameters, int pcnt, userrec *user)
3408 char Return[MAXBUF];
3409 sprintf(Return,"303 %s :",user->nick);
3410 for (int i = 0; i < pcnt; i++)
3412 userrec *u = Find(parameters[i]);
3415 strcat(Return,u->nick);
3419 WriteServ(user->fd,Return);
3423 void handle_away(char **parameters, int pcnt, userrec *user)
3427 strcpy(user->awaymsg,parameters[0]);
3428 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3432 strcpy(user->awaymsg,"");
3433 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3437 void handle_whowas(char **parameters, int pcnt, userrec* user)
3439 user_hash::iterator i = whowas.find(parameters[0]);
3441 if (i == whowas.end())
3443 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3444 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3448 time_t rawtime = i->second->signon;
3452 timeinfo = localtime(&rawtime);
3453 strcpy(b,asctime(timeinfo));
3454 b[strlen(b)-1] = '\0';
3456 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3457 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3458 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3463 void handle_trace(char **parameters, int pcnt, userrec *user)
3465 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3469 if (isnick(i->second->nick))
3471 if (strchr(i->second->modes,'o'))
3473 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3477 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3482 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3488 void handle_stats(char **parameters, int pcnt, userrec *user)
3494 if (strlen(parameters[0])>1)
3496 /* make the stats query 1 character long */
3497 parameters[0][1] = '\0';
3500 /* stats m (list number of times each command has been used, plus bytecount) */
3501 if (!strcasecmp(parameters[0],"m"))
3503 for (int i = 0; i < cmdlist.size(); i++)
3505 if (cmdlist[i].handler_function)
3507 if (cmdlist[i].use_count)
3509 /* RPL_STATSCOMMANDS */
3510 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3517 /* stats z (debug and memory info) */
3518 if (!strcasecmp(parameters[0],"z"))
3520 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3521 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3522 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3523 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3524 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3525 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3526 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3527 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3531 if (!strcasecmp(parameters[0],"o"))
3533 for (int i = 0; i < ConfValueEnum("oper"); i++)
3535 char LoginName[MAXBUF];
3536 char HostName[MAXBUF];
3537 char OperType[MAXBUF];
3538 ConfValue("oper","name",i,LoginName);
3539 ConfValue("oper","host",i,HostName);
3540 ConfValue("oper","type",i,OperType);
3541 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3545 /* stats l (show user I/O stats) */
3546 if (!strcasecmp(parameters[0],"l"))
3548 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3549 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3551 if (isnick(i->second->nick))
3553 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);
3557 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);
3563 /* stats u (show server uptime) */
3564 if (!strcasecmp(parameters[0],"u"))
3566 time_t current_time = 0;
3567 current_time = time(NULL);
3568 time_t server_uptime = current_time - startup_time;
3570 stime = gmtime(&server_uptime);
3571 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3572 * Craig suggested this, and it seemed a good idea so in it went */
3573 if (stime->tm_year > 70)
3575 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);
3579 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);
3583 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3584 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3588 void handle_connect(char **parameters, int pcnt, userrec *user)
3590 char Link_ServerName[1024];
3591 char Link_IPAddr[1024];
3592 char Link_Port[1024];
3593 char Link_Pass[1024];
3597 for (int i = 0; i < ConfValueEnum("link"); i++)
3599 ConfValue("link","name",i,Link_ServerName);
3600 ConfValue("link","ipaddr",i,Link_IPAddr);
3601 ConfValue("link","port",i,Link_Port);
3602 ConfValue("link","sendpass",i,Link_Pass);
3603 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3604 LinkPort = atoi(Link_Port);
3605 if (match(Link_ServerName,parameters[0])) {
3611 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3615 // TODO: Perform a check here to stop a server being linked twice!
3617 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3619 if (me[defaultRoute])
3622 // at this point parameters[0] is an ip in a string.
3623 // TODO: Look this up from the <link> blocks instead!
3624 for (int j = 0; j < 255; j++) {
3625 if (servers[j] == NULL) {
3626 servers[j] = new serverrec;
3627 strcpy(servers[j]->internal_addr,Link_IPAddr);
3628 strcpy(servers[j]->name,Link_ServerName);
3629 log(DEBUG,"Allocated new serverrec");
3630 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
3632 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
3637 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
3641 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);
3645 void handle_squit(char **parameters, int pcnt, userrec *user)
3647 // send out an squit across the mesh and then clear the server list (for local squit)
3650 void handle_oper(char **parameters, int pcnt, userrec *user)
3652 char LoginName[MAXBUF];
3653 char Password[MAXBUF];
3654 char OperType[MAXBUF];
3655 char TypeName[MAXBUF];
3656 char Hostname[MAXBUF];
3659 for (i = 0; i < ConfValueEnum("oper"); i++)
3661 ConfValue("oper","name",i,LoginName);
3662 ConfValue("oper","password",i,Password);
3663 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3665 /* correct oper credentials */
3666 ConfValue("oper","type",i,OperType);
3667 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3668 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3669 WriteServ(user->fd,"MODE %s :+o",user->nick);
3670 for (j =0; j < ConfValueEnum("type"); j++)
3672 ConfValue("type","name",j,TypeName);
3673 if (!strcmp(TypeName,OperType))
3675 /* found this oper's opertype */
3676 ConfValue("type","host",j,Hostname);
3677 strncpy(user->dhost,Hostname,256);
3680 if (!strchr(user->modes,'o'))
3682 strcat(user->modes,"o");
3688 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3689 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3692 void handle_nick(char **parameters, int pcnt, userrec *user)
3696 log(DEBUG,"not enough params for handle_nick");
3701 log(DEBUG,"invalid parameter passed to handle_nick");
3704 if (!strlen(parameters[0]))
3706 log(DEBUG,"zero length new nick passed to handle_nick");
3711 log(DEBUG,"invalid user passed to handle_nick");
3716 log(DEBUG,"invalid old nick passed to handle_nick");
3719 if (!strcasecmp(user->nick,parameters[0]))
3721 log(DEBUG,"old nick is new nick, skipping");
3726 if (strlen(parameters[0]) > 1)
3728 if (parameters[0][0] == ':')
3733 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
3735 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
3739 if (isnick(parameters[0]) == 0)
3741 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
3745 if (user->registered == 7)
3747 WriteCommon(user,"NICK %s",parameters[0]);
3750 /* change the nick of the user in the users_hash */
3751 user = ReHashNick(user->nick, parameters[0]);
3752 /* actually change the nick within the record */
3754 if (!user->nick) return;
3756 strncpy(user->nick, parameters[0],NICKMAX);
3758 log(DEBUG,"new nick set: %s",user->nick);
3760 if (user->registered < 3)
3761 user->registered = (user->registered | 2);
3762 if (user->registered == 3)
3764 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3767 log(DEBUG,"exit nickchange: %s",user->nick);
3770 int process_parameters(char **command_p,char *parameters)
3775 q = strlen(parameters);
3778 /* no parameters, command_p invalid! */
3781 if (parameters[0] == ':')
3783 command_p[0] = parameters+1;
3788 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
3790 /* only one parameter */
3791 command_p[0] = parameters;
3792 if (parameters[0] == ':')
3794 if (strchr(parameters,' ') != NULL)
3802 command_p[j++] = parameters;
3803 for (i = 0; i <= q; i++)
3805 if (parameters[i] == ' ')
3807 command_p[j++] = parameters+i+1;
3808 parameters[i] = '\0';
3809 if (command_p[j-1][0] == ':')
3811 *command_p[j-1]++; /* remove dodgy ":" */
3813 /* parameter like this marks end of the sequence */
3817 return j; /* returns total number of items in the list */
3820 void process_command(userrec *user, char* cmd)
3824 char *command_p[127];
3825 char p[MAXBUF], temp[MAXBUF];
3826 int i, j, items, cmd_found;
3828 for (int i = 0; i < 127; i++)
3829 command_p[i] = NULL;
3839 if (!strcmp(cmd,""))
3846 FOREACH_MOD OnServerRaw(tmp,true);
3847 const char* cmd2 = tmp.c_str();
3848 snprintf(cmd,512,"%s",cmd2);
3850 if (!strchr(cmd,' '))
3852 /* no parameters, lets skip the formalities and not chop up
3855 command_p[0] = NULL;
3857 for (int i = 0; i <= strlen(cmd); i++)
3859 cmd[i] = toupper(cmd[i]);
3866 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
3867 for (i = 0; i < strlen(temp); i++)
3869 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
3875 /* split the full string into a command plus parameters */
3879 if (strchr(cmd,' '))
3881 for (i = 0; i <= strlen(cmd); i++)
3883 /* capitalise the command ONLY, leave params intact */
3884 cmd[i] = toupper(cmd[i]);
3885 /* are we nearly there yet?! :P */
3889 parameters = cmd+i+1;
3897 for (i = 0; i <= strlen(cmd); i++)
3899 cmd[i] = toupper(cmd[i]);
3907 for (i = 0; i != cmdlist.size(); i++)
3909 if (strcmp(cmdlist[i].command,""))
3911 if (!strcmp(command, cmdlist[i].command))
3915 if (strcmp(parameters,""))
3917 items = process_parameters(command_p,parameters);
3922 command_p[0] = NULL;
3928 command_p[0] = NULL;
3933 user->idle_lastmsg = time(NULL);
3934 /* activity resets the ping pending timer */
3935 user->nping = time(NULL) + 120;
3936 if ((items) < cmdlist[i].min_params)
3938 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
3939 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
3942 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
3944 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3945 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
3949 /* if the command isnt USER, PASS, or NICK, and nick is empty,
3951 if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
3953 if ((!isnick(user->nick)) || (user->registered != 7))
3955 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3956 WriteServ(user->fd,"451 %s :You have not registered",command);
3960 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
3962 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
3963 if (cmdlist[i].handler_function)
3965 /* ikky /stats counters */
3970 user->bytes_in += strlen(temp);
3973 cmdlist[i].use_count++;
3974 cmdlist[i].total_bytes+=strlen(temp);
3977 /* WARNING: nothing may come after the
3978 * command handler call, as the handler
3979 * may free the user structure! */
3981 cmdlist[i].handler_function(command_p,items,user);
3987 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3988 WriteServ(user->fd,"451 %s :You have not registered",command);
3996 if ((!cmd_found) && (user))
3998 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
3999 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4004 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4007 /* create the command and push it onto the table */
4008 strcpy(comm.command,cmd);
4009 comm.handler_function = f;
4010 comm.flags_needed = flags;
4011 comm.min_params = minparams;
4013 comm.total_bytes = 0;
4014 cmdlist.push_back(comm);
4017 void SetupCommandTable(void)
4019 createcommand("USER",handle_user,0,4);
4020 createcommand("NICK",handle_nick,0,1);
4021 createcommand("QUIT",handle_quit,0,0);
4022 createcommand("VERSION",handle_version,0,0);
4023 createcommand("PING",handle_ping,0,1);
4024 createcommand("PONG",handle_pong,0,1);
4025 createcommand("ADMIN",handle_admin,0,0);
4026 createcommand("PRIVMSG",handle_privmsg,0,2);
4027 createcommand("INFO",handle_info,0,0);
4028 createcommand("TIME",handle_time,0,0);
4029 createcommand("WHOIS",handle_whois,0,1);
4030 createcommand("WALLOPS",handle_wallops,'o',1);
4031 createcommand("NOTICE",handle_notice,0,2);
4032 createcommand("JOIN",handle_join,0,1);
4033 createcommand("NAMES",handle_names,0,1);
4034 createcommand("PART",handle_part,0,1);
4035 createcommand("KICK",handle_kick,0,2);
4036 createcommand("MODE",handle_mode,0,1);
4037 createcommand("TOPIC",handle_topic,0,1);
4038 createcommand("WHO",handle_who,0,1);
4039 createcommand("MOTD",handle_motd,0,0);
4040 createcommand("RULES",handle_join,0,0);
4041 createcommand("OPER",handle_oper,0,2);
4042 createcommand("LIST",handle_list,0,0);
4043 createcommand("DIE",handle_die,'o',1);
4044 createcommand("RESTART",handle_restart,'o',1);
4045 createcommand("KILL",handle_kill,'o',2);
4046 createcommand("REHASH",handle_rehash,'o',0);
4047 createcommand("LUSERS",handle_lusers,0,0);
4048 createcommand("STATS",handle_stats,0,1);
4049 createcommand("USERHOST",handle_userhost,0,1);
4050 createcommand("AWAY",handle_away,0,0);
4051 createcommand("ISON",handle_ison,0,0);
4052 createcommand("SUMMON",handle_summon,0,0);
4053 createcommand("USERS",handle_users,0,0);
4054 createcommand("INVITE",handle_invite,0,2);
4055 createcommand("PASS",handle_pass,0,1);
4056 createcommand("TRACE",handle_trace,'o',0);
4057 createcommand("WHOWAS",handle_whowas,0,1);
4058 createcommand("CONNECT",handle_connect,'o',1);
4059 createcommand("SQUIT",handle_squit,'o',1);
4062 void process_buffer(userrec *user)
4070 if (!strcmp(user->inbuf,""))
4074 strncpy(cmd,user->inbuf,MAXBUF);
4075 if (!strcmp(cmd,""))
4079 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4081 cmd[strlen(cmd)-1] = '\0';
4083 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4085 cmd[strlen(cmd)-1] = '\0';
4087 strcpy(user->inbuf,"");
4088 if (!strcmp(cmd,""))
4092 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4093 process_command(user,cmd);
4096 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4098 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4102 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4104 char response[10240];
4105 char token = udp_msg[0];
4106 char* params = udp_msg + 2;
4107 char finalparam[1024];
4108 strcpy(finalparam," :xxxx");
4109 if (strstr(params," :")) {
4110 strncpy(finalparam,strstr(params," :"),1024);
4113 // S test.chatspike.net password :ChatSpike InspIRCd test server
4114 char* servername = strtok(params," ");
4115 char* password = strtok(NULL," ");
4116 char* serverdesc = finalparam+2;
4117 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4120 char Link_ServerName[1024];
4121 char Link_IPAddr[1024];
4122 char Link_Port[1024];
4123 char Link_Pass[1024];
4124 char Link_SendPass[1024];
4127 // search for a corresponding <link> block in the config files
4128 for (int i = 0; i < ConfValueEnum("link"); i++)
4130 ConfValue("link","name",i,Link_ServerName);
4131 ConfValue("link","ipaddr",i,Link_IPAddr);
4132 ConfValue("link","port",i,Link_Port);
4133 ConfValue("link","recvpass",i,Link_Pass);
4134 ConfValue("link","sendpass",i,Link_SendPass);
4135 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4136 LinkPort = atoi(Link_Port);
4137 if (!strcasecmp(Link_ServerName,servername)) {
4138 if (!strcasecmp(Link_IPAddr,udp_host)) {
4139 if (LinkPort == udp_port) {
4140 // we have a matching link line -
4141 // send a 'diminutive' server message back...
4142 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4143 serv->SendPacket(response,udp_host,udp_port,0);
4144 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4145 for (int j = 0; j < 255; j++) {
4146 if (servers[j] == NULL) {
4147 servers[j] = new serverrec;
4148 strcpy(servers[j]->internal_addr,udp_host);
4149 strcpy(servers[j]->name,servername);
4150 // create a server record for this server
4151 snprintf(response,10240,"O %d",MyKey);
4152 serv->SendPacket(response,udp_host,udp_port,0);
4156 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4160 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4164 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4168 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4171 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4172 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4177 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4178 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4179 // array, which is only added by an 'S' packet or BeginLink().
4180 for (int i = 0; i < 255; i++) {
4181 if (servers[i] != NULL) {
4182 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4183 servers[i]->key = atoi(params);
4184 log(DEBUG,"Key for this server is now %d",servers[i]->key);
4185 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4190 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4194 // S test.chatspike.net password :ChatSpike InspIRCd test server
4195 char* servername = strtok(params," ");
4196 char* password = strtok(NULL," ");
4197 char* serverdesc = finalparam+2;
4199 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4200 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4201 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4202 // a connect, so put out an oper alert!
4207 // for now, just accept all, we'll fix that later.
4208 WriteOpers("%s accepted our link credentials ",servername);
4210 char Link_ServerName[1024];
4211 char Link_IPAddr[1024];
4212 char Link_Port[1024];
4213 char Link_Pass[1024];
4214 char Link_SendPass[1024];
4217 // search for a corresponding <link> block in the config files
4218 for (int i = 0; i < ConfValueEnum("link"); i++)
4220 ConfValue("link","name",i,Link_ServerName);
4221 ConfValue("link","ipaddr",i,Link_IPAddr);
4222 ConfValue("link","port",i,Link_Port);
4223 ConfValue("link","recvpass",i,Link_Pass);
4224 ConfValue("link","sendpass",i,Link_SendPass);
4225 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4226 LinkPort = atoi(Link_Port);
4227 if (!strcasecmp(Link_ServerName,servername)) {
4228 if (!strcasecmp(Link_IPAddr,udp_host)) {
4229 if (LinkPort == udp_port) {
4230 // matching link at this end too, we're all done!
4231 // at this point we must begin key exchange and insert this
4232 // server into our 'active' table.
4233 for (int j = 0; j < 255; j++) {
4234 if (servers[j] != NULL) {
4235 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4236 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4237 snprintf(response,10240,"O %d",MyKey);
4238 serv->SendPacket(response,udp_host,udp_port,0);
4243 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4248 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4252 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4256 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4259 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4260 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4265 char* error_message = finalparam+2;
4266 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4267 // remove this server from any lists
4268 for (int j = 0; j < 255; j++) {
4269 if (servers[j] != NULL) {
4270 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4280 serverrec* source_server = NULL;
4282 for (int j = 0; j < 255; j++) {
4283 if (servers[j] != NULL) {
4284 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4285 if (servers[j]->key == theirkey) {
4286 // found a valid key for this server, can process restricted stuff here
4287 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4295 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4299 int reap_counter = 0;
4303 struct sockaddr_in client, server;
4304 char addrs[MAXBUF][255];
4305 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4307 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4308 int selectResult = 0;
4309 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4310 char resolvedHost[MAXBUF];
4314 log(DEBUG,"InspIRCd: startup: begin");
4318 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4320 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4322 SetupCommandTable();
4323 log(DEBUG,"InspIRCd: startup: default command table set up");
4326 if (strcmp(DieValue,""))
4328 printf("WARNING: %s\n\n",DieValue);
4331 log(DEBUG,"InspIRCd: startup: read config");
4333 int count2 = 0, count3 = 0;
4334 for (count = 0; count < ConfValueEnum("bind"); count++)
4336 ConfValue("bind","port",count,configToken);
4337 ConfValue("bind","address",count,Addr);
4338 ConfValue("bind","type",count,Type);
4339 if (!strcmp(Type,"servers"))
4341 char Default[MAXBUF];
4342 strcpy(Default,"no");
4343 ConfValue("bind","default",count,Default);
4344 if (strchr(Default,'y'))
4346 defaultRoute = count3;
4347 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4349 me[count3] = new serverrec(ServerName,100L,false);
4350 me[count3]->CreateListener(Addr,atoi(configToken));
4355 ports[count2] = atoi(configToken);
4356 strcpy(addrs[count2],Addr);
4359 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4362 UDPportCount = count3;
4364 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4366 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4370 /* BugFix By Craig! :p */
4372 for (count = 0; count2 < ConfValueEnum("module"); count2++)
4374 char modfile[MAXBUF];
4375 ConfValue("module","name",count,configToken);
4376 sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4377 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4378 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4379 /* If The File Doesnt exist, Trying to load it
4380 * Will Segfault the IRCd.. So, check to see if
4381 * it Exists, Before Proceeding. */
4382 if (FileExists(modfile))
4384 factory[count] = new ircd_module(modfile);
4385 if (factory[count]->LastError())
4387 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4388 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4391 if (factory[count]->factory)
4393 modules[count] = factory[count]->factory->CreateModule();
4394 /* save the module and the module's classfactory, if
4395 * this isnt done, random crashes can occur :/ */
4399 log(DEBUG,"Unable to load %s",modfile);
4400 sprintf("Unable to load %s\nExiting...\n",modfile);
4403 /* Increase the Count */
4408 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4409 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4412 MODCOUNT = count - 1;
4413 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4415 printf("\nInspIRCd is now running!\n");
4417 startup_time = time(NULL);
4419 if (DaemonSeed() == ERROR)
4421 log(DEBUG,"InspIRCd: startup: can't daemonise");
4422 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4427 /* setup select call */
4428 FD_ZERO(&selectFds);
4429 log(DEBUG,"InspIRCd: startup: zero selects");
4430 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4432 for (count = 0; count < portCount; count++)
4434 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4436 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4439 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4441 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4443 else /* well we at least bound to one socket so we'll continue */
4449 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4451 /* if we didn't bind to anything then abort */
4452 if (boundPortCount == 0)
4454 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4458 length = sizeof (client);
4459 int flip_flop = 0, udp_port = 0;
4460 char udp_msg[MAXBUF], udp_host[MAXBUF];
4462 /* main loop for multiplexing/resetting */
4465 /* set up select call */
4466 for (count = 0; count < boundPortCount; count++)
4468 FD_SET (openSockfd[count], &selectFds);
4471 /* added timeout! select was waiting forever... wank... :/ */
4482 vector<int>::iterator niterator;
4485 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4486 // them in a list, then reap the list every second or so.
4487 if (reap_counter>5000) {
4488 if (fd_reap.size() > 0) {
4489 for( int n = 0; n < fd_reap.size(); n++)
4491 Blocking(fd_reap[n]);
4493 NonBlocking(fd_reap[n]);
4502 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4504 for (int x = 0; x != UDPportCount; x++)
4507 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
4509 if (strlen(udp_msg)<1) {
4510 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
4513 FOREACH_MOD OnPacketReceive(udp_msg);
4514 // Packets must go back via the route they arrived on :)
4515 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
4520 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
4524 if (!count2->second) break;
4527 if (count2->second->fd)
4529 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4531 if (!count2->second->lastping)
4533 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4534 kill_link(count2->second,"Ping timeout");
4537 Write(count2->second->fd,"PING :%s",ServerName);
4538 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4539 count2->second->lastping = 0;
4540 count2->second->nping = time(NULL)+120;
4543 result = read(count2->second->fd, data, 1);
4544 // result EAGAIN means nothing read
4545 if (result == EAGAIN)
4551 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
4552 kill_link(count2->second,"Client exited");
4554 else if (result > 0)
4556 strncat(count2->second->inbuf, data, result);
4557 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r'))
4559 /* at least one complete line is waiting to be processed */
4560 if (!count2->second->fd)
4564 process_buffer(count2->second);
4572 /* select is reporting a waiting socket. Poll them all to find out which */
4573 if (selectResult > 0)
4575 char target[MAXBUF], resolved[MAXBUF];
4576 for (count = 0; count < boundPortCount; count++)
4578 if (FD_ISSET (openSockfd[count], &selectFds))
4580 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4582 address_cache::iterator iter = IP.find(client.sin_addr);
4583 bool iscached = false;
4584 if (iter == IP.end())
4586 /* ip isn't in cache, add it */
4587 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4588 if(CleanAndResolve(resolved, target) != TRUE)
4590 strncpy(resolved,target,MAXBUF);
4592 /* hostname now in 'target' */
4593 IP[client.sin_addr] = new string(resolved);
4594 /* hostname in cache */
4598 /* found ip (cached) */
4599 strncpy(resolved, iter->second->c_str(), MAXBUF);
4603 if (incomingSockfd < 0)
4605 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4606 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4610 AddClient(incomingSockfd, resolved, ports[count], iscached);
4611 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4620 close (incomingSockfd);