1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2003 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
32 #include <ext/hash_map>
41 #include "connection.h"
53 #define nspace __gnu_cxx
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
66 char restartpass[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 time_t startup_time = time(NULL);
78 extern vector<Module*> modules;
79 extern vector<ircd_module*> factory;
88 template<> struct nspace::hash<in_addr>
90 size_t operator()(const struct in_addr &a) const
93 memcpy(&q,&a,sizeof(size_t));
98 template<> struct nspace::hash<string>
100 size_t operator()(const string &s) const
103 static struct hash<const char *> strhash;
115 bool operator()(const string& s1, const string& s2) const
117 char a[MAXBUF],b[MAXBUF];
118 strcpy(a,s1.c_str());
119 strcpy(b,s2.c_str());
120 return (strcasecmp(a,b) == 0);
125 struct InAddr_HashComp
128 bool operator()(const in_addr &s1, const in_addr &s2) const
133 memcpy(&q,&s1,sizeof(size_t));
134 memcpy(&p,&s2,sizeof(size_t));
142 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
143 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
144 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
145 typedef std::deque<command_t> command_table;
148 serverrec* servers[255];
150 user_hash clientlist;
153 command_table cmdlist;
160 struct linger linger = { 0 };
161 char bannerBuffer[MAXBUF];
162 int boundPortCount = 0;
163 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
164 int defaultRoute = 0;
168 long MyKey = C.GenKey();
172 int has_channel(userrec *u, chanrec *c);
173 int usercount(chanrec *c);
174 int usercount_i(chanrec *c);
175 void update_stats_l(int fd,int data_out);
176 char* Passwd(userrec *user);
177 bool IsDenied(userrec *user);
178 void AddWhoWas(userrec* u);
181 void safedelete(userrec *p)
185 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
186 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
191 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
195 void safedelete(chanrec *p)
200 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
204 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
209 void tidystring(char* str)
211 // strips out double spaces before a : parameter
213 bool go_again = true;
217 bool noparse = false;
220 while (a < strlen(str))
222 if ((a<strlen(str)-1) && (noparse==false))
224 if ((str[a] == ' ') && (str[a+1] == ' '))
226 log(DEBUG,"Tidied extra space out of string: %s",str);
234 if ((str[a] == ' ') && (str[a+1] == ':'))
240 temp[t++] = str[a++];
243 strncpy(str,temp,MAXBUF);
247 /* chop a string down to 512 characters and preserve linefeed (irc max
254 FOREACH_MOD OnServerRaw(temp,false);
255 const char* str2 = temp.c_str();
256 sprintf(str,"%s",str2);
259 if (strlen(str) > 512)
268 std::string getservername()
273 std::string getserverdesc()
278 std::string getnetworkname()
283 std::string getadminname()
288 std::string getadminemail()
293 std::string getadminnick()
298 void log(int level,char *text, ...)
300 char textbuffer[MAXBUF];
304 struct tm * timeinfo;
305 if (level < LogLevel)
309 timeinfo = localtime (&rawtime);
311 f = fopen("ircd.log","a+");
315 va_start (argsPtr, text);
316 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
318 strcpy(b,asctime(timeinfo));
319 b[strlen(b)-1] = ':';
320 fprintf(f,"%s %s\n",b,textbuffer);
324 // nofork enabled? display it on terminal too
325 printf("%s %s\n",b,textbuffer);
330 printf("Can't write log file, bailing!!!");
335 void readfile(file_cache &F, const char* fname)
338 char linebuf[MAXBUF];
340 log(DEBUG,"readfile: loading %s",fname);
342 file = fopen(fname,"r");
347 fgets(linebuf,sizeof(linebuf),file);
348 linebuf[strlen(linebuf)-1]='\0';
349 if (!strcmp(linebuf,""))
355 F.push_back(linebuf);
362 log(DEBUG,"readfile: failed to load file: %s",fname);
364 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
367 void ReadConfig(void)
369 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
372 ConfValue("server","name",0,ServerName);
373 ConfValue("server","description",0,ServerDesc);
374 ConfValue("server","network",0,Network);
375 ConfValue("admin","name",0,AdminName);
376 ConfValue("admin","email",0,AdminEmail);
377 ConfValue("admin","nick",0,AdminNick);
378 ConfValue("files","motd",0,motd);
379 ConfValue("files","rules",0,rules);
380 ConfValue("power","diepass",0,diepass);
381 ConfValue("power","pause",0,pauseval);
382 ConfValue("power","restartpass",0,restartpass);
383 ConfValue("options","prefixquit",0,PrefixQuit);
384 ConfValue("die","value",0,DieValue);
385 ConfValue("options","loglevel",0,dbg);
386 if (!strcmp(dbg,"debug"))
388 if (!strcmp(dbg,"verbose"))
390 if (!strcmp(dbg,"default"))
392 if (!strcmp(dbg,"sparse"))
394 if (!strcmp(dbg,"none"))
396 readfile(RULES,rules);
397 log(DEBUG,"Reading connect classes");
399 for (int i = 0; i < ConfValueEnum("connect"); i++)
402 ConfValue("connect","allow",i,Value);
403 if (strcmp(Value,""))
405 strcpy(c.host,Value);
408 ConfValue("connect","password",i,Value);
409 strcpy(c.pass,Value);
410 Classes.push_back(c);
411 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
415 ConfValue("connect","deny",i,Value);
416 strcpy(c.host,Value);
418 Classes.push_back(c);
419 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
428 log(DEBUG,"Blocking: %d",s);
429 flags = fcntl(s, F_GETFL, 0);
430 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
433 void NonBlocking(int s)
436 log(DEBUG,"NonBlocking: %d",s);
437 flags = fcntl(s, F_GETFL, 0);
438 fcntl(s, F_SETFL, flags | O_NONBLOCK);
442 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
444 struct hostent *hostPtr = NULL;
447 memset (resolvedHost, '\0',MAXBUF);
448 if(unresolvedHost == NULL)
450 if ((inet_aton(unresolvedHost,&addr)) == 0)
452 hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
454 snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
456 snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
460 /* write formatted text to a socket, in same format as printf */
462 void Write(int sock,char *text, ...)
464 char textbuffer[MAXBUF];
468 va_start (argsPtr, text);
469 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
471 sprintf(tb,"%s\r\n",textbuffer);
473 write(sock,tb,strlen(tb));
474 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
477 /* write a server formatted numeric response to a single socket */
479 void WriteServ(int sock, char* text, ...)
481 char textbuffer[MAXBUF],tb[MAXBUF];
483 va_start (argsPtr, text);
485 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
487 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
489 write(sock,tb,strlen(tb));
490 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
493 /* write text from an originating user to originating user */
495 void WriteFrom(int sock, userrec *user,char* text, ...)
497 char textbuffer[MAXBUF],tb[MAXBUF];
499 va_start (argsPtr, text);
501 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
503 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
505 write(sock,tb,strlen(tb));
506 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
509 /* write text to an destination user from a source user (e.g. user privmsg) */
511 void WriteTo(userrec *source, userrec *dest,char *data, ...)
513 char textbuffer[MAXBUF],tb[MAXBUF];
515 va_start (argsPtr, data);
516 if ((!dest) || (!source))
520 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
523 WriteFrom(dest->fd,source,"%s",textbuffer);
526 /* write formatted text from a source user to all users on a channel
527 * including the sender (NOT for privmsg, notice etc!) */
529 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
531 char textbuffer[MAXBUF];
533 va_start (argsPtr, text);
534 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
536 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
538 if (has_channel(i->second,Ptr))
540 WriteTo(user,i->second,"%s",textbuffer);
545 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
547 char textbuffer[MAXBUF];
549 va_start (argsPtr, text);
550 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
552 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
554 if (has_channel(i->second,Ptr))
556 WriteServ(i->second->fd,"%s",textbuffer);
562 /* write formatted text from a source user to all users on a channel except
563 * for the sender (for privmsg etc) */
565 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
567 char textbuffer[MAXBUF];
569 va_start (argsPtr, text);
570 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
573 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
575 if (has_channel(i->second,Ptr) && (user != i->second))
577 WriteTo(user,i->second,"%s",textbuffer);
582 int c_count(userrec* u)
585 for (int i =0; i != MAXCHANS; i++)
586 if (u->chans[i].channel)
592 /* return 0 or 1 depending if users u and u2 share one or more common channels
593 * (used by QUIT, NICK etc which arent channel specific notices) */
595 int common_channels(userrec *u, userrec *u2)
604 for (i = 0; i != MAXCHANS; i++)
606 for (z = 0; z != MAXCHANS; z++)
608 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
610 if ((c_count(u)) && (c_count(u2)))
620 /* write a formatted string to all users who share at least one common
621 * channel, including the source user e.g. for use in NICK */
623 void WriteCommon(userrec *u, char* text, ...)
625 char textbuffer[MAXBUF];
627 va_start (argsPtr, text);
628 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
631 WriteFrom(u->fd,u,"%s",textbuffer);
633 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
635 if (common_channels(u,i->second) && (i->second != u))
637 WriteFrom(i->second->fd,u,"%s",textbuffer);
642 /* write a formatted string to all users who share at least one common
643 * channel, NOT including the source user e.g. for use in QUIT */
645 void WriteCommonExcept(userrec *u, char* text, ...)
647 char textbuffer[MAXBUF];
649 va_start (argsPtr, text);
650 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
653 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
655 if ((common_channels(u,i->second)) && (u != i->second))
657 WriteFrom(i->second->fd,u,"%s",textbuffer);
662 void WriteOpers(char* text, ...)
664 char textbuffer[MAXBUF];
666 va_start (argsPtr, text);
667 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
670 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
672 if (strchr(i->second->modes,'o'))
674 if (strchr(i->second->modes,'s'))
676 // send server notices to all with +s
677 // (TODO: needs SNOMASKs)
678 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
684 void WriteWallOps(userrec *source, char* text, ...)
687 char textbuffer[MAXBUF];
689 va_start (argsPtr, text);
690 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
693 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
695 if (strchr(i->second->modes,'w'))
697 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
702 /* convert a string to lowercase. Note following special circumstances
703 * taken from RFC 1459. Many "official" server branches still hold to this
704 * rule so i will too;
706 * Because of IRC's scandanavian origin, the characters {}| are
707 * considered to be the lower case equivalents of the characters []\,
708 * respectively. This is a critical issue when determining the
709 * equivalence of two nicknames.
712 void strlower(char *n)
718 for (int i = 0; i != strlen(n); i++)
720 n[i] = tolower(n[i]);
730 /* verify that a user's ident and nickname is valid */
732 int isident(const char* n)
745 for (i = 0; i != strlen(n); i++)
747 if ((n[i] < 33) || (n[i] > 125))
751 /* can't occur ANYWHERE in an Ident! */
752 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
761 int isnick(const char* n)
773 if (strlen(n) > NICKMAX-1)
777 for (i = 0; i != strlen(n); i++)
779 if ((n[i] < 33) || (n[i] > 125))
783 /* can't occur ANYWHERE in a nickname! */
784 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
788 /* can't occur as the first char of a nickname... */
789 if ((strchr("0123456789",n[i])) && (!i))
797 /* Find a user record by nickname and return a pointer to it */
799 userrec* Find(string nick)
801 user_hash::iterator iter = clientlist.find(nick);
803 if (iter == clientlist.end())
804 /* Couldn't find it */
810 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
812 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
814 if (i->second->fd == fd)
816 i->second->bytes_out+=data_out;
817 i->second->cmds_out++;
823 /* find a channel record by channel name and return a pointer to it */
825 chanrec* FindChan(const char* chan)
827 chan_hash::iterator iter = chanlist.find(chan);
829 if (iter == chanlist.end())
830 /* Couldn't find it */
837 void purge_empty_chans(void)
839 int go_again = 1, purge = 0;
844 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
847 if (!usercount(i->second))
849 /* kill the record */
850 if (i != chanlist.end())
852 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
863 log(DEBUG,"completed channel purge, killed %d",purge);
866 /* returns the status character for a given user on a channel, e.g. @ for op,
867 * % for halfop etc. If the user has several modes set, the highest mode
868 * the user has must be returned. */
870 char* cmode(userrec *user, chanrec *chan)
873 for (i = 0; i != MAXCHANS; i++)
875 if ((user->chans[i].channel == chan) && (chan != NULL))
877 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
881 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
885 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
894 char scratch[MAXMODES];
895 char sparam[MAXMODES];
897 char* chanmodes(chanrec *chan)
901 if (chan->noexternal)
909 if (strcmp(chan->key,""))
917 if (chan->inviteonly)
933 if (strcmp(chan->key,""))
935 strcat(sparam,chan->key);
940 sprintf(foo," %d",chan->limit);
943 if (strlen(chan->custom_modes))
945 // TODO: Tack on mode parameters here -
946 // IN ORDER OF CUSTOM_MODES!
947 strncat(scratch,chan->custom_modes,MAXMODES);
949 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
950 strncat(scratch,sparam,MAXMODES);
954 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
955 * op, STATUS_VOICE for voice etc. If the user has several modes set, the
956 * highest mode the user has must be returned. */
958 int cstatus(userrec *user, chanrec *chan)
961 for (i = 0; i != MAXCHANS; i++)
963 if ((user->chans[i].channel == chan) && (chan != NULL))
965 if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
969 if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
973 if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
977 return STATUS_NORMAL;
983 /* compile a userlist of a channel into a string, each nick seperated by
984 * spaces and op, voice etc status shown as @ and + */
986 void userlist(userrec *user,chanrec *c)
988 sprintf(list,"353 %s = %s :", user->nick, c->name);
989 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
991 if (has_channel(i->second,c))
993 if (isnick(i->second->nick))
995 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
997 /* user is +i, and source not on the channel, does not show
998 * nick in NAMES list */
1001 strcat(list,cmode(i->second,c));
1002 strcat(list,i->second->nick);
1004 if (strlen(list)>(480-NICKMAX))
1006 /* list overflowed into
1007 * multiple numerics */
1008 WriteServ(user->fd,list);
1009 sprintf(list,"353 %s = %s :", user->nick, c->name);
1014 /* if whats left in the list isnt empty, send it */
1015 if (list[strlen(list)-1] != ':')
1017 WriteServ(user->fd,list);
1021 /* return a count of the users on a specific channel accounting for
1022 * invisible users who won't increase the count. e.g. for /LIST */
1024 int usercount_i(chanrec *c)
1030 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1034 if (has_channel(i->second,c))
1036 if (isnick(i->second->nick))
1038 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1040 /* user is +i, and source not on the channel, does not show
1041 * nick in NAMES list */
1049 log(DEBUG,"usercount_i: %s %d",c->name,count);
1054 int usercount(chanrec *c)
1060 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1064 if (has_channel(i->second,c))
1066 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1073 log(DEBUG,"usercount: %s %d",c->name,count);
1078 /* add a channel to a user, creating the record for it if needed and linking
1079 * it to the user record */
1081 chanrec* add_channel(userrec *user, char* cname, char* key)
1087 // we MUST declare this wherever we use FOREACH_RESULT
1090 if ((!cname) || (!user))
1094 if (strlen(cname) > CHANMAX-1)
1096 cname[CHANMAX-1] = '\0';
1099 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1101 if ((has_channel(user,FindChan(cname))) && (FindChan(cname)))
1103 return NULL; // already on the channel!
1107 if (!FindChan(cname))
1109 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1114 /* create a new one */
1115 log(DEBUG,"add_channel: creating: %s",cname);
1117 chanlist[cname] = new chanrec();
1119 strcpy(chanlist[cname]->name, cname);
1120 chanlist[cname]->topiclock = 1;
1121 chanlist[cname]->noexternal = 1;
1122 chanlist[cname]->created = time(NULL);
1123 strcpy(chanlist[cname]->topic, "");
1124 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1125 chanlist[cname]->topicset = 0;
1126 Ptr = chanlist[cname];
1127 log(DEBUG,"add_channel: created: %s",cname);
1128 /* set created to 2 to indicate user
1129 * is the first in the channel
1130 * and should be given ops */
1136 /* channel exists, just fish out a pointer to its struct */
1137 Ptr = FindChan(cname);
1140 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1145 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1146 if (strcmp(Ptr->key,""))
1148 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1151 log(DEBUG,"add_channel: no key given in JOIN");
1152 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1157 log(DEBUG,"key at %p is %s",key,key);
1158 if (strcasecmp(key,Ptr->key))
1160 log(DEBUG,"add_channel: bad key given in JOIN");
1161 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1166 log(DEBUG,"add_channel: no key");
1168 if (Ptr->inviteonly)
1170 log(DEBUG,"add_channel: channel is +i");
1171 if (user->IsInvited(Ptr->name))
1173 /* user was invited to channel */
1174 /* there may be an optional channel NOTICE here */
1178 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1182 log(DEBUG,"add_channel: channel is not +i");
1186 if (usercount(Ptr) == Ptr->limit)
1188 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1193 log(DEBUG,"add_channel: about to walk banlist");
1195 /* check user against the channel banlist */
1196 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1198 if (match(user->GetFullHost(),i->data))
1200 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1205 log(DEBUG,"add_channel: bans checked");
1207 user->RemoveInvite(Ptr->name);
1209 log(DEBUG,"add_channel: invites removed");
1215 log(DEBUG,"Passed channel checks");
1217 for (i =0; i != MAXCHANS; i++)
1219 if (user->chans[i].channel == NULL)
1221 log(DEBUG,"Adding into their channel list");
1225 /* first user in is given ops */
1226 user->chans[i].uc_modes = UCMODE_OP;
1230 user->chans[i].uc_modes = 0;
1232 user->chans[i].channel = Ptr;
1233 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1235 log(DEBUG,"Sent JOIN to client");
1239 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1240 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1243 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1244 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1245 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1246 FOREACH_MOD OnUserJoin(user,Ptr);
1250 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1251 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1255 /* remove a channel from a users record, and remove the record from memory
1256 * if the channel has become empty */
1258 chanrec* del_channel(userrec *user, char* cname, char* reason)
1264 if ((!cname) || (!user))
1269 Ptr = FindChan(cname);
1276 FOREACH_MOD OnUserPart(user,Ptr);
1277 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1279 for (i =0; i != MAXCHANS; i++)
1281 /* zap it from the channel list of the user */
1282 if (user->chans[i].channel == Ptr)
1286 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1290 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1292 user->chans[i].uc_modes = 0;
1293 user->chans[i].channel = NULL;
1294 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1299 /* if there are no users left on the channel */
1300 if (!usercount(Ptr))
1302 chan_hash::iterator iter = chanlist.find(Ptr->name);
1304 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1306 /* kill the record */
1307 if (iter != chanlist.end())
1309 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1310 delete iter->second;
1311 chanlist.erase(iter);
1317 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1322 if ((!Ptr) || (!user) || (!src))
1327 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1329 if (!has_channel(user,Ptr))
1331 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1334 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1336 if (cstatus(src,Ptr) == STATUS_HOP)
1338 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1342 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1348 for (i =0; i != MAXCHANS; i++)
1350 /* zap it from the channel list of the user */
1351 if (user->chans[i].channel == Ptr)
1353 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1354 user->chans[i].uc_modes = 0;
1355 user->chans[i].channel = NULL;
1356 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1361 /* if there are no users left on the channel */
1362 if (!usercount(Ptr))
1364 chan_hash::iterator iter = chanlist.find(Ptr->name);
1366 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1368 /* kill the record */
1369 if (iter != chanlist.end())
1371 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1372 delete iter->second;
1373 chanlist.erase(iter);
1379 /* returns 1 if user u has channel c in their record, 0 if not */
1381 int has_channel(userrec *u, chanrec *c)
1389 for (i =0; i != MAXCHANS; i++)
1391 if (u->chans[i].channel == c)
1399 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1404 if ((!user) || (!dest) || (!chan))
1408 if (status != STATUS_OP)
1410 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1417 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1423 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1428 for (i = 0; i != MAXCHANS; i++)
1430 if ((d->chans[i].channel == chan) && (chan != NULL))
1432 if (d->chans[i].uc_modes & UCMODE_OP)
1434 /* mode already set on user, dont allow multiple */
1437 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1438 log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1446 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1451 if ((!user) || (!dest) || (!chan))
1455 if (status != STATUS_OP)
1457 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1465 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1470 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1475 for (i = 0; i != MAXCHANS; i++)
1477 if ((d->chans[i].channel == chan) && (chan != NULL))
1479 if (d->chans[i].uc_modes & UCMODE_HOP)
1481 /* mode already set on user, dont allow multiple */
1484 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1485 log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1493 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1498 if ((!user) || (!dest) || (!chan))
1502 if (status < STATUS_HOP)
1504 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1512 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1517 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1522 for (i = 0; i != MAXCHANS; i++)
1524 if ((d->chans[i].channel == chan) && (chan != NULL))
1526 if (d->chans[i].uc_modes & UCMODE_VOICE)
1528 /* mode already set on user, dont allow multiple */
1531 d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1532 log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1540 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1545 if ((!user) || (!dest) || (!chan))
1549 if (status != STATUS_OP)
1551 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1559 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1564 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1569 for (i = 0; i != MAXCHANS; i++)
1571 if ((d->chans[i].channel == chan) && (chan != NULL))
1573 if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1575 /* mode already set on user, dont allow multiple */
1578 d->chans[i].uc_modes ^= UCMODE_OP;
1579 log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1587 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1592 if ((!user) || (!dest) || (!chan))
1596 if (status != STATUS_OP)
1598 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1606 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1611 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1616 for (i = 0; i != MAXCHANS; i++)
1618 if ((d->chans[i].channel == chan) && (chan != NULL))
1620 if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1622 /* mode already set on user, dont allow multiple */
1625 d->chans[i].uc_modes ^= UCMODE_HOP;
1626 log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1634 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1639 if ((!user) || (!dest) || (!chan))
1643 if (status < STATUS_HOP)
1645 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1653 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1658 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1663 for (i = 0; i != MAXCHANS; i++)
1665 if ((d->chans[i].channel == chan) && (chan != NULL))
1667 if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1669 /* mode already set on user, dont allow multiple */
1672 d->chans[i].uc_modes ^= UCMODE_VOICE;
1673 log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1681 void TidyBan(char *ban)
1683 char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1687 char* pos_of_pling = strchr(temp,'!');
1688 char* pos_of_at = strchr(temp,'@');
1690 pos_of_pling[0] = '\0';
1691 pos_of_at[0] = '\0';
1695 strncpy(NICK,temp,NICKMAX);
1696 strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1697 strncpy(HOST,pos_of_at,160);
1699 sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1702 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1705 if ((!user) || (!dest) || (!chan))
1707 if (strchr(dest,'!')==0)
1709 if (strchr(dest,'@')==0)
1711 for (int i = 0; i < strlen(dest); i++)
1714 for (int i = 0; i < strlen(dest); i++)
1718 for (int i = 0; i < strlen(dest); i++)
1724 for (int i = 0; i < strlen(dest); i++)
1729 log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1732 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1734 if (!strcasecmp(i->data,dest))
1736 // dont allow a user to set the same ban twice
1741 b.set_time = time(NULL);
1742 strncpy(b.data,dest,MAXBUF);
1743 strncpy(b.set_by,user->nick,NICKMAX);
1744 chan->bans.push_back(b);
1748 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1750 if ((!user) || (!dest) || (!chan))
1755 log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1756 for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1758 if (!strcasecmp(i->data,dest))
1760 chan->bans.erase(i);
1767 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1769 char modelist[MAXBUF];
1770 char outlist[MAXBUF];
1771 char outstr[MAXBUF];
1772 char outpars[32][MAXBUF];
1778 bool k_set = false, l_set = false;
1785 log(DEBUG,"process_modes: start");
1787 strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1788 /* parameters[2] onwards are parameters for
1789 * modes that require them :) */
1790 strcpy(outlist,"+");
1793 log(DEBUG,"process_modes: modelist: %s",modelist);
1795 for (ptr = 0; ptr < strlen(modelist); ptr++)
1800 log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1801 char modechar = modelist[ptr];
1802 switch (modelist[ptr])
1807 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1809 outlist[strlen(outlist)-1] = '-';
1813 strcat(outlist,"-");
1823 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1825 outlist[strlen(outlist)-1] = '+';
1829 strcat(outlist,"+");
1836 if ((param >= pcnt)) break;
1839 r = give_ops(user,parameters[param++],chan,status);
1843 r = take_ops(user,parameters[param++],chan,status);
1847 strcat(outlist,"o");
1848 strcpy(outpars[pc++],parameters[param-1]);
1853 if ((param >= pcnt)) break;
1856 r = give_hops(user,parameters[param++],chan,status);
1860 r = take_hops(user,parameters[param++],chan,status);
1864 strcat(outlist,"h");
1865 strcpy(outpars[pc++],parameters[param-1]);
1871 if ((param >= pcnt)) break;
1874 r = give_voice(user,parameters[param++],chan,status);
1878 r = take_voice(user,parameters[param++],chan,status);
1882 strcat(outlist,"v");
1883 strcpy(outpars[pc++],parameters[param-1]);
1888 if ((param >= pcnt)) break;
1891 r = add_ban(user,parameters[param++],chan,status);
1895 r = take_ban(user,parameters[param++],chan,status);
1899 strcat(outlist,"b");
1900 strcpy(outpars[pc++],parameters[param-1]);
1905 if ((param >= pcnt))
1913 if (!strcmp(chan->key,""))
1915 strcat(outlist,"k");
1916 strcpy(outpars[pc++],parameters[param++]);
1917 strcpy(chan->key,parameters[param-1]);
1923 /* only allow -k if correct key given */
1924 if (strcmp(chan->key,""))
1926 strcat(outlist,"k");
1927 strcpy(chan->key,"");
1937 strcat(outlist,"l");
1942 if ((param >= pcnt)) break;
1948 bool invalid = false;
1949 for (int i = 0; i < strlen(parameters[param]); i++)
1951 if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
1956 if (atoi(parameters[param]) < 1)
1964 chan->limit = atoi(parameters[param]);
1967 strcat(outlist,"l");
1968 strcpy(outpars[pc++],parameters[param++]);
1975 if (chan->inviteonly != mdir)
1977 strcat(outlist,"i");
1979 chan->inviteonly = mdir;
1983 if (chan->topiclock != mdir)
1985 strcat(outlist,"t");
1987 chan->topiclock = mdir;
1991 if (chan->noexternal != mdir)
1993 strcat(outlist,"n");
1995 chan->noexternal = mdir;
1999 if (chan->moderated != mdir)
2001 strcat(outlist,"m");
2003 chan->moderated = mdir;
2007 if (chan->secret != mdir)
2009 strcat(outlist,"s");
2010 if (chan->c_private)
2012 chan->c_private = 0;
2015 strcat(outlist,"-p+");
2019 strcat(outlist,"+p-");
2023 chan->secret = mdir;
2027 if (chan->c_private != mdir)
2029 strcat(outlist,"p");
2035 strcat(outlist,"-s+");
2039 strcat(outlist,"+s-");
2043 chan->c_private = mdir;
2047 log(DEBUG,"Preprocessing custom mode %c",modechar);
2050 if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2052 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2055 if (ModeDefined(modechar,MT_CHANNEL))
2057 log(DEBUG,"A module has claimed this mode");
2058 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2060 p.push_back(parameters[param]);
2062 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2064 p.push_back(parameters[param]);
2066 bool handled = false;
2067 for (int i = 0; i <= MODCOUNT; i++)
2071 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2073 log(DEBUG,"OnExtendedMode returned nonzero for a module");
2074 char app[] = {modechar, 0};
2077 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2079 strcat(outlist, app);
2081 else if (!strchr(outlist,modechar))
2083 strcat(outlist, app);
2086 chan->SetCustomMode(modechar,mdir);
2087 // include parameters in output if mode has them
2088 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) || (ModeDefinedOff(modechar,MT_CHANNEL)>0))
2090 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2091 strcpy(outpars[pc++],parameters[param++]);
2093 // break, because only one module can handle the mode.
2105 /* this ensures only the *valid* modes are sent out onto the network */
2106 while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2108 outlist[strlen(outlist)-1] = '\0';
2110 if (strcmp(outlist,""))
2112 strcpy(outstr,outlist);
2113 for (ptr = 0; ptr < pc; ptr++)
2116 strcat(outstr,outpars[ptr]);
2120 WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2124 WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2129 void handle_mode(char **parameters, int pcnt, userrec *user)
2135 char outpars[MAXBUF];
2137 dest = Find(parameters[0]);
2139 if ((dest) && (pcnt == 1))
2141 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2144 if ((dest) && (pcnt > 1))
2149 if (strchr(user->modes,'o'))
2160 WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2164 strcpy(outpars,"+");
2167 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2170 for (i = 0; i < strlen(parameters[1]); i++)
2172 if (parameters[1][i] == '+')
2176 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2178 outpars[strlen(outpars)-1] = '+';
2182 strcat(outpars,"+");
2188 if (parameters[1][i] == '-')
2192 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2194 outpars[strlen(outpars)-1] = '-';
2198 strcat(outpars,"-");
2206 if (strchr(user->modes,'o'))
2212 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2221 if (!strchr(dest->modes,parameters[1][i]))
2223 dest->modes[strlen(dest->modes)+1]='\0';
2224 dest->modes[strlen(dest->modes)] = parameters[1][i];
2225 outpars[strlen(outpars)+1]='\0';
2226 outpars[strlen(outpars)] = parameters[1][i];
2235 outpars[strlen(outpars)+1]='\0';
2236 outpars[strlen(outpars)] = parameters[1][i];
2239 for (q = 0; q < strlen(user->modes); q++)
2241 if (user->modes[q] != parameters[1][i])
2243 moo[0] = user->modes[q];
2248 strcpy(user->modes,temp);
2253 if (strlen(outpars))
2259 while (i < strlen (outpars))
2261 b[z++] = outpars[i++];
2263 if (i<strlen(outpars)-1)
2265 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2267 // someones playing silly buggers and trying
2268 // to put a +- or -+ into the line...
2272 if (i == strlen(outpars)-1)
2274 if ((outpars[i] == '-') || (outpars[i] == '+'))
2282 if ((b[z] == '-') || (b[z] == '+'))
2285 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2288 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2293 Ptr = FindChan(parameters[0]);
2298 /* just /modes #channel */
2299 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2300 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2306 if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2309 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2311 WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2313 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2317 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2319 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2323 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2327 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2334 void server_mode(char **parameters, int pcnt, userrec *user)
2340 char outpars[MAXBUF];
2342 dest = Find(parameters[0]);
2344 if ((dest) && (pcnt > 1))
2346 strcpy(outpars,"+");
2349 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2352 for (i = 0; i < strlen(parameters[1]); i++)
2354 if (parameters[1][i] == '+')
2358 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2360 outpars[strlen(outpars)-1] = '+';
2364 strcat(outpars,"+");
2370 if (parameters[1][i] == '-')
2374 if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2376 outpars[strlen(outpars)-1] = '-';
2380 strcat(outpars,"-");
2388 if (strchr(user->modes,'o'))
2394 if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2403 if (!strchr(dest->modes,parameters[1][i]))
2405 dest->modes[strlen(dest->modes)+1]='\0';
2406 dest->modes[strlen(dest->modes)] = parameters[1][i];
2407 outpars[strlen(outpars)+1]='\0';
2408 outpars[strlen(outpars)] = parameters[1][i];
2417 outpars[strlen(outpars)+1]='\0';
2418 outpars[strlen(outpars)] = parameters[1][i];
2421 for (q = 0; q < strlen(user->modes); q++)
2423 if (user->modes[q] != parameters[1][i])
2425 moo[0] = user->modes[q];
2430 strcpy(user->modes,temp);
2435 if (strlen(outpars))
2441 while (i < strlen (outpars))
2443 b[z++] = outpars[i++];
2445 if (i<strlen(outpars)-1)
2447 if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2449 // someones playing silly buggers and trying
2450 // to put a +- or -+ into the line...
2454 if (i == strlen(outpars)-1)
2456 if ((outpars[i] == '-') || (outpars[i] == '+'))
2464 if ((b[z] == '-') || (b[z] == '+'))
2467 if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2470 WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2475 Ptr = FindChan(parameters[0]);
2478 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2482 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2487 /* This function pokes and hacks at a parameter list like the following:
2489 * PART #winbot, #darkgalaxy :m00!
2491 * to turn it into a series of individual calls like this:
2493 * PART #winbot :m00!
2494 * PART #darkgalaxy :m00!
2496 * The seperate calls are sent to a callback function provided by the caller
2497 * (the caller will usually call itself recursively). The callback function
2498 * must be a command handler. Calling this function on a line with no list causes
2499 * no action to be taken. You must provide a starting and ending parameter number
2500 * where the range of the list can be found, useful if you have a terminating
2501 * parameter as above which is actually not part of the list, or parameters
2502 * before the actual list as well. This code is used by many functions which
2503 * can function as "one to list" (see the RFC) */
2505 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2510 char blog[32][MAXBUF];
2511 char blog2[32][MAXBUF];
2512 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2513 char keystr[MAXBUF];
2516 for (i = 0; i <32; i++)
2519 for (i = 0; i <32; i++)
2520 strcpy(blog2[i],"");
2523 for (i = 0; i <10; i++)
2527 parameters[i] = moo;
2532 if (pcnt > 1) /* we have a key to copy */
2534 strcpy(keystr,parameters[1]);
2538 if (!parameters[start])
2542 if (!strchr(parameters[start],','))
2547 for (i = start; i <= end; i++)
2551 strcat(plist,parameters[i]);
2559 for (i = 0; i < t; i++)
2561 if (plist[i] == ',')
2564 strcpy(blog[j++],param);
2568 strcpy(blog[j++],param);
2571 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2576 if ((joins) && (keystr))
2578 if (strchr(keystr,','))
2582 t2 = strlen(keystr);
2583 for (i = 0; i < t2; i++)
2585 if (keystr[i] == ',')
2588 strcpy(blog2[j++],param);
2592 strcpy(blog2[j++],param);
2597 for (j = 0; j < total; j++)
2603 for (q = end; q < pcnt-1; q++)
2605 if (parameters[q+1])
2607 pars[q-end+1] = parameters[q+1];
2610 if ((joins) && (parameters[1]))
2621 /* repeatedly call the function with the hacked parameter list */
2622 if ((joins) && (pcnt > 1))
2626 // pars[1] already set up and containing key from blog2[j]
2631 pars[1] = parameters[1];
2637 fn(pars,pcnt-(end-start),u);
2644 void handle_join(char **parameters, int pcnt, userrec *user)
2649 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2651 if (parameters[0][0] == '#')
2653 Ptr = add_channel(user,parameters[0],parameters[1]);
2658 void handle_part(char **parameters, int pcnt, userrec *user)
2664 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2666 del_channel(user,parameters[0],parameters[1]);
2670 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2672 del_channel(user,parameters[0],NULL);
2676 void handle_kick(char **parameters, int pcnt, userrec *user)
2678 chanrec* Ptr = FindChan(parameters[0]);
2679 userrec* u = Find(parameters[1]);
2683 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2687 if (!has_channel(u,Ptr))
2689 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2695 kick_channel(user,u,Ptr,parameters[2]);
2699 kick_channel(user,u,Ptr,user->nick);
2704 void handle_die(char **parameters, int pcnt, userrec *user)
2706 log(DEBUG,"die: %s",user->nick);
2707 if (!strcmp(parameters[0],diepass))
2709 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2715 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2719 void handle_restart(char **parameters, int pcnt, userrec *user)
2721 log(DEBUG,"restart: %s",user->nick);
2722 if (!strcmp(parameters[0],restartpass))
2724 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2727 /* Will finish this later when i can be arsed :) */
2731 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2736 void kill_link(userrec *user,char* reason)
2738 user_hash::iterator iter = clientlist.find(user->nick);
2740 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2741 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2742 fdatasync(user->fd);
2743 log(DEBUG,"closing fd %d",user->fd);
2745 /* bugfix, cant close() a nonblocking socket (sux!) */
2746 if (user->registered == 7) {
2747 FOREACH_MOD OnUserQuit(user);
2748 WriteCommonExcept(user,"QUIT :%s",reason);
2751 /* push the socket on a stack of sockets due to be closed at the next opportunity */
2752 fd_reap.push_back(user->fd);
2754 bool do_purge = false;
2756 if (user->registered == 7) {
2757 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2761 if (iter != clientlist.end())
2763 log(DEBUG,"deleting user hash value %d",iter->second);
2764 if ((iter->second) && (user->registered == 7)) {
2765 delete iter->second;
2767 clientlist.erase(iter);
2770 purge_empty_chans();
2774 void handle_kill(char **parameters, int pcnt, userrec *user)
2776 userrec *u = Find(parameters[0]);
2777 char killreason[MAXBUF];
2779 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
2782 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
2783 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
2784 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
2785 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
2786 kill_link(u,killreason);
2790 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2794 void handle_summon(char **parameters, int pcnt, userrec *user)
2796 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
2799 void handle_users(char **parameters, int pcnt, userrec *user)
2801 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
2805 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2807 char* Passwd(userrec *user)
2809 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2811 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2819 bool IsDenied(userrec *user)
2821 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2823 if (match(user->host,i->host) && (i->type == CC_DENY))
2832 void handle_pass(char **parameters, int pcnt, userrec *user)
2834 if (!strcasecmp(parameters[0],Passwd(user)))
2836 user->haspassed = true;
2840 void handle_invite(char **parameters, int pcnt, userrec *user)
2842 userrec* u = Find(parameters[0]);
2843 chanrec* c = FindChan(parameters[1]);
2849 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
2855 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2864 if (cstatus(user,c) < STATUS_HOP)
2866 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
2870 u->InviteTo(c->name);
2871 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2872 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2876 void handle_topic(char **parameters, int pcnt, userrec *user)
2882 if (strlen(parameters[0]) <= CHANMAX)
2884 Ptr = FindChan(parameters[0]);
2889 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2890 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2894 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2899 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2905 if (loop_call(handle_topic,parameters,pcnt,user,0,pcnt-2,0))
2907 if (strlen(parameters[0]) <= CHANMAX)
2909 Ptr = FindChan(parameters[0]);
2912 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2914 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
2917 strcpy(Ptr->topic,parameters[1]);
2918 strcpy(Ptr->setby,user->nick);
2919 Ptr->topicset = time(NULL);
2920 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2924 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2930 /* sends out an error notice to all connected clients (not to be used
2933 void send_error(char *s)
2935 log(DEBUG,"send_error: %s",s);
2936 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2938 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2942 void Error(int status)
2944 signal (SIGALRM, SIG_IGN);
2945 signal (SIGPIPE, SIG_IGN);
2946 signal (SIGTERM, SIG_IGN);
2947 signal (SIGABRT, SIG_IGN);
2948 signal (SIGSEGV, SIG_IGN);
2949 signal (SIGURG, SIG_IGN);
2950 signal (SIGKILL, SIG_IGN);
2951 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2952 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2956 int main (int argc, char *argv[])
2959 log(DEBUG,"*** InspIRCd starting up!");
2960 if (!FileExists(CONFIG_FILE))
2962 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2963 log(DEBUG,"main: no config");
2964 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2968 if (!strcmp(argv[1],"-nofork")) {
2972 if (InspIRCd() == ERROR)
2974 log(DEBUG,"main: daemon function bailed");
2975 printf("ERROR: could not initialise. Shutting down.\n");
2982 template<typename T> inline string ConvToStr(const T &in)
2985 if (!(tmp << in)) return string();
2989 /* re-allocates a nick in the user_hash after they change nicknames,
2990 * returns a pointer to the new user as it may have moved */
2992 userrec* ReHashNick(char* Old, char* New)
2994 user_hash::iterator newnick;
2995 user_hash::iterator oldnick = clientlist.find(Old);
2997 log(DEBUG,"ReHashNick: %s %s",Old,New);
2999 if (!strcasecmp(Old,New))
3001 log(DEBUG,"old nick is new nick, skipping");
3002 return oldnick->second;
3005 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3007 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3009 clientlist[New] = new userrec();
3010 clientlist[New] = oldnick->second;
3011 /*delete oldnick->second; */
3012 clientlist.erase(oldnick);
3014 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3016 return clientlist[New];
3019 /* adds or updates an entry in the whowas list */
3020 void AddWhoWas(userrec* u)
3022 user_hash::iterator iter = whowas.find(u->nick);
3023 userrec *a = new userrec();
3024 strcpy(a->nick,u->nick);
3025 strcpy(a->ident,u->ident);
3026 strcpy(a->dhost,u->dhost);
3027 strcpy(a->host,u->host);
3028 strcpy(a->fullname,u->fullname);
3029 strcpy(a->server,u->server);
3030 a->signon = u->signon;
3032 /* MAX_WHOWAS: max number of /WHOWAS items
3033 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3034 * can be replaced by a newer one
3037 if (iter == whowas.end())
3039 if (whowas.size() == WHOWAS_MAX)
3041 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3043 // 3600 seconds in an hour ;)
3044 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3048 log(DEBUG,"added WHOWAS entry, purged an old record");
3055 log(DEBUG,"added fresh WHOWAS entry");
3056 whowas[a->nick] = a;
3061 log(DEBUG,"updated WHOWAS entry");
3062 delete iter->second;
3068 /* add a client connection to the sockets list */
3069 void AddClient(int socket, char* host, int port, bool iscached)
3073 char resolved[MAXBUF];
3076 user_hash::iterator iter;
3078 tempnick = ConvToStr(socket) + "-unknown";
3079 sprintf(tn2,"%d-unknown",socket);
3081 iter = clientlist.find(tempnick);
3083 if (iter != clientlist.end()) return;
3086 * It is OK to access the value here this way since we know
3087 * it exists, we just created it above.
3089 * At NO other time should you access a value in a map or a
3090 * hash_map this way.
3092 clientlist[tempnick] = new userrec();
3094 NonBlocking(socket);
3095 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3098 clientlist[tempnick]->fd = socket;
3099 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3100 strncpy(clientlist[tempnick]->host, host,160);
3101 strncpy(clientlist[tempnick]->dhost, host,160);
3102 strncpy(clientlist[tempnick]->server, ServerName,256);
3103 clientlist[tempnick]->registered = 0;
3104 clientlist[tempnick]->signon = time(NULL);
3105 clientlist[tempnick]->nping = time(NULL)+240;
3106 clientlist[tempnick]->lastping = 1;
3107 clientlist[tempnick]->port = port;
3111 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3115 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3118 if (clientlist.size() == MAXCLIENTS)
3119 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3122 void handle_names(char **parameters, int pcnt, userrec *user)
3126 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3128 c = FindChan(parameters[0]);
3131 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3133 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3137 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3142 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3147 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3149 if (parameters[0][0] == '#')
3151 chan = FindChan(parameters[0]);
3154 if ((chan->noexternal) && (!has_channel(user,chan)))
3156 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3159 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3161 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3164 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3168 /* no such nick/channel */
3169 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3174 dest = Find(parameters[0]);
3177 if (strcmp(dest->awaymsg,""))
3179 /* auto respond with aweh msg */
3180 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3182 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3186 /* no such nick/channel */
3187 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3191 void handle_notice(char **parameters, int pcnt, userrec *user)
3196 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3198 if (parameters[0][0] == '#')
3200 chan = FindChan(parameters[0]);
3203 if ((chan->noexternal) && (!has_channel(user,chan)))
3205 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3208 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3210 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3213 WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3217 /* no such nick/channel */
3218 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3223 dest = Find(parameters[0]);
3226 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3230 /* no such nick/channel */
3231 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3237 char* chlist(userrec *user)
3242 log(DEBUG,"chlist: %s",user->nick);
3248 for (i = 0; i != MAXCHANS; i++)
3250 if (user->chans[i].channel != NULL)
3252 if (user->chans[i].channel->name)
3254 strcpy(cmp,user->chans[i].channel->name);
3256 if (!strstr(lst,cmp))
3258 if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3260 strcat(lst,cmode(user,user->chans[i].channel));
3261 strcat(lst,user->chans[i].channel->name);
3271 void handle_info(char **parameters, int pcnt, userrec *user)
3273 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3274 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3275 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3276 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3279 void handle_time(char **parameters, int pcnt, userrec *user)
3282 struct tm * timeinfo;
3285 timeinfo = localtime ( &rawtime );
3286 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3290 void handle_whois(char **parameters, int pcnt, userrec *user)
3295 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3297 dest = Find(parameters[0]);
3300 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3301 if ((user == dest) || (strchr(user->modes,'o')))
3303 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3305 if (strcmp(chlist(dest),""))
3307 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3309 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3310 if (strcmp(dest->awaymsg,""))
3312 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3314 if (strchr(dest->modes,'o'))
3316 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3318 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3319 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3321 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3325 /* no such nick/channel */
3326 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3330 void handle_quit(char **parameters, int pcnt, userrec *user)
3332 user_hash::iterator iter = clientlist.find(user->nick);
3334 if (user->registered == 7)
3336 /* theres more to do here, but for now just close the socket */
3339 if (parameters[0][0] == ':')
3343 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3344 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3345 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3349 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3350 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3351 WriteCommonExcept(user,"QUIT :Client exited");
3353 FOREACH_MOD OnUserQuit(user);
3357 /* push the socket on a stack of sockets due to be closed at the next opportunity */
3358 fd_reap.push_back(user->fd);
3360 if (iter != clientlist.end())
3362 log(DEBUG,"deleting user hash value %d",iter->second);
3363 if ((iter->second) && (user->registered == 7)) {
3364 delete iter->second;
3366 clientlist.erase(iter);
3369 if (user->registered == 7) {
3370 purge_empty_chans();
3374 void handle_who(char **parameters, int pcnt, userrec *user)
3376 chanrec* Ptr = NULL;
3378 /* theres more to do here, but for now just close the socket */
3381 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3383 if (user->chans[0].channel)
3385 Ptr = user->chans[0].channel;
3386 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3388 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3390 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);
3396 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3400 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3404 if (parameters[0][0] = '#')
3406 Ptr = FindChan(parameters[0]);
3409 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3411 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3413 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);
3416 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3420 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3426 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3428 Ptr = user->chans[0].channel;
3429 printf(user->chans[0].channel->name);
3430 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3432 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3434 if (strchr(i->second->modes,'o'))
3436 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);
3440 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3446 void handle_wallops(char **parameters, int pcnt, userrec *user)
3448 WriteWallOps(user,"%s",parameters[0]);
3451 void handle_list(char **parameters, int pcnt, userrec *user)
3455 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3456 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3458 if ((!i->second->c_private) && (!i->second->secret))
3460 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3463 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3467 void handle_rehash(char **parameters, int pcnt, userrec *user)
3469 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3471 FOREACH_MOD OnRehash();
3472 WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3478 return clientlist.size();
3481 int usercount_invisible(void)
3485 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3487 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3492 int usercount_opers(void)
3496 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3498 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3503 int usercount_unknown(void)
3507 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3509 if ((i->second->fd) && (i->second->registered != 7))
3517 return chanlist.size();
3520 int servercount(void)
3525 void handle_lusers(char **parameters, int pcnt, userrec *user)
3527 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3528 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3529 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3530 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3531 WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3534 void handle_admin(char **parameters, int pcnt, userrec *user)
3536 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3537 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
3538 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3539 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
3542 void ShowMOTD(userrec *user)
3546 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3549 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3550 for (int i = 0; i != MOTD.size(); i++)
3552 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3554 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3557 void ShowRULES(userrec *user)
3561 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3564 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3565 for (int i = 0; i != RULES.size(); i++)
3567 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3569 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3572 /* shows the message of the day, and any other on-logon stuff */
3573 void ConnectUser(userrec *user)
3575 user->registered = 7;
3576 user->idle_lastmsg = time(NULL);
3577 log(DEBUG,"ConnectUser: %s",user->nick);
3579 if (strcmp(Passwd(user),"") && (!user->haspassed))
3581 Write(user->fd,"ERROR :Closing link: Invalid password");
3582 fdatasync(user->fd);
3583 kill_link(user,"Invalid password");
3588 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3589 fdatasync(user->fd);
3590 kill_link(user,"Unauthorised connection");
3593 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3594 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3595 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3596 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3597 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3598 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);
3599 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);
3601 FOREACH_MOD OnUserConnect(user);
3602 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3605 void handle_version(char **parameters, int pcnt, userrec *user)
3607 WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3610 void handle_ping(char **parameters, int pcnt, userrec *user)
3612 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3615 void handle_pong(char **parameters, int pcnt, userrec *user)
3617 // set the user as alive so they survive to next ping
3621 void handle_motd(char **parameters, int pcnt, userrec *user)
3626 void handle_rules(char **parameters, int pcnt, userrec *user)
3631 void handle_user(char **parameters, int pcnt, userrec *user)
3633 if (user->registered < 3)
3635 if (isident(parameters[0]) == 0) {
3636 // This kinda Sucks, According to the RFC thou, its either this,
3637 // or "You have already registered" :p -- Craig
3638 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3641 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3642 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3643 strncat(user->ident,parameters[0],IDENTMAX);
3644 strncpy(user->fullname,parameters[3],128);
3645 user->registered = (user->registered | 1);
3650 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3653 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3654 if (user->registered == 3)
3656 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3661 void handle_userhost(char **parameters, int pcnt, userrec *user)
3663 char Return[MAXBUF],junk[MAXBUF];
3664 sprintf(Return,"302 %s :",user->nick);
3665 for (int i = 0; i < pcnt; i++)
3667 userrec *u = Find(parameters[i]);
3670 if (strchr(u->modes,'o'))
3672 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3673 strcat(Return,junk);
3677 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3678 strcat(Return,junk);
3682 WriteServ(user->fd,Return);
3686 void handle_ison(char **parameters, int pcnt, userrec *user)
3688 char Return[MAXBUF];
3689 sprintf(Return,"303 %s :",user->nick);
3690 for (int i = 0; i < pcnt; i++)
3692 userrec *u = Find(parameters[i]);
3695 strcat(Return,u->nick);
3699 WriteServ(user->fd,Return);
3703 void handle_away(char **parameters, int pcnt, userrec *user)
3707 strcpy(user->awaymsg,parameters[0]);
3708 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3712 strcpy(user->awaymsg,"");
3713 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3717 void handle_whowas(char **parameters, int pcnt, userrec* user)
3719 user_hash::iterator i = whowas.find(parameters[0]);
3721 if (i == whowas.end())
3723 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3724 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3728 time_t rawtime = i->second->signon;
3732 timeinfo = localtime(&rawtime);
3733 strcpy(b,asctime(timeinfo));
3734 b[strlen(b)-1] = '\0';
3736 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3737 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3738 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3743 void handle_trace(char **parameters, int pcnt, userrec *user)
3745 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3749 if (isnick(i->second->nick))
3751 if (strchr(i->second->modes,'o'))
3753 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3757 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3762 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3768 void handle_stats(char **parameters, int pcnt, userrec *user)
3774 if (strlen(parameters[0])>1)
3776 /* make the stats query 1 character long */
3777 parameters[0][1] = '\0';
3780 /* stats m (list number of times each command has been used, plus bytecount) */
3781 if (!strcasecmp(parameters[0],"m"))
3783 for (int i = 0; i < cmdlist.size(); i++)
3785 if (cmdlist[i].handler_function)
3787 if (cmdlist[i].use_count)
3789 /* RPL_STATSCOMMANDS */
3790 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3797 /* stats z (debug and memory info) */
3798 if (!strcasecmp(parameters[0],"z"))
3800 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3801 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3802 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3803 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3804 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3805 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3806 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3807 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3811 if (!strcasecmp(parameters[0],"o"))
3813 for (int i = 0; i < ConfValueEnum("oper"); i++)
3815 char LoginName[MAXBUF];
3816 char HostName[MAXBUF];
3817 char OperType[MAXBUF];
3818 ConfValue("oper","name",i,LoginName);
3819 ConfValue("oper","host",i,HostName);
3820 ConfValue("oper","type",i,OperType);
3821 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3825 /* stats l (show user I/O stats) */
3826 if (!strcasecmp(parameters[0],"l"))
3828 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3829 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3831 if (isnick(i->second->nick))
3833 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);
3837 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);
3843 /* stats u (show server uptime) */
3844 if (!strcasecmp(parameters[0],"u"))
3846 time_t current_time = 0;
3847 current_time = time(NULL);
3848 time_t server_uptime = current_time - startup_time;
3850 stime = gmtime(&server_uptime);
3851 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3852 * Craig suggested this, and it seemed a good idea so in it went */
3853 if (stime->tm_year > 70)
3855 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);
3859 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);
3863 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3864 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3868 void handle_connect(char **parameters, int pcnt, userrec *user)
3870 char Link_ServerName[1024];
3871 char Link_IPAddr[1024];
3872 char Link_Port[1024];
3873 char Link_Pass[1024];
3877 for (int i = 0; i < ConfValueEnum("link"); i++)
3879 ConfValue("link","name",i,Link_ServerName);
3880 ConfValue("link","ipaddr",i,Link_IPAddr);
3881 ConfValue("link","port",i,Link_Port);
3882 ConfValue("link","sendpass",i,Link_Pass);
3883 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3884 LinkPort = atoi(Link_Port);
3885 if (match(Link_ServerName,parameters[0])) {
3891 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3895 // TODO: Perform a check here to stop a server being linked twice!
3897 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3899 if (me[defaultRoute])
3902 // at this point parameters[0] is an ip in a string.
3903 // TODO: Look this up from the <link> blocks instead!
3904 for (int j = 0; j < 255; j++) {
3905 if (servers[j] == NULL) {
3906 servers[j] = new serverrec;
3907 strcpy(servers[j]->internal_addr,Link_IPAddr);
3908 strcpy(servers[j]->name,Link_ServerName);
3909 log(DEBUG,"Allocated new serverrec");
3910 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
3912 WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
3917 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
3921 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);
3925 void handle_squit(char **parameters, int pcnt, userrec *user)
3927 // send out an squit across the mesh and then clear the server list (for local squit)
3930 void handle_oper(char **parameters, int pcnt, userrec *user)
3932 char LoginName[MAXBUF];
3933 char Password[MAXBUF];
3934 char OperType[MAXBUF];
3935 char TypeName[MAXBUF];
3936 char Hostname[MAXBUF];
3939 for (i = 0; i < ConfValueEnum("oper"); i++)
3941 ConfValue("oper","name",i,LoginName);
3942 ConfValue("oper","password",i,Password);
3943 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3945 /* correct oper credentials */
3946 ConfValue("oper","type",i,OperType);
3947 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3948 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3949 WriteServ(user->fd,"MODE %s :+o",user->nick);
3950 for (j =0; j < ConfValueEnum("type"); j++)
3952 ConfValue("type","name",j,TypeName);
3953 if (!strcmp(TypeName,OperType))
3955 /* found this oper's opertype */
3956 ConfValue("type","host",j,Hostname);
3957 strncpy(user->dhost,Hostname,256);
3960 if (!strchr(user->modes,'o'))
3962 strcat(user->modes,"o");
3968 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3969 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3972 void handle_nick(char **parameters, int pcnt, userrec *user)
3976 log(DEBUG,"not enough params for handle_nick");
3981 log(DEBUG,"invalid parameter passed to handle_nick");
3984 if (!strlen(parameters[0]))
3986 log(DEBUG,"zero length new nick passed to handle_nick");
3991 log(DEBUG,"invalid user passed to handle_nick");
3996 log(DEBUG,"invalid old nick passed to handle_nick");
3999 if (!strcasecmp(user->nick,parameters[0]))
4001 log(DEBUG,"old nick is new nick, skipping");
4006 if (strlen(parameters[0]) > 1)
4008 if (parameters[0][0] == ':')
4013 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4015 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4019 if (isnick(parameters[0]) == 0)
4021 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4025 if (user->registered == 7)
4027 WriteCommon(user,"NICK %s",parameters[0]);
4030 /* change the nick of the user in the users_hash */
4031 user = ReHashNick(user->nick, parameters[0]);
4032 /* actually change the nick within the record */
4034 if (!user->nick) return;
4036 strncpy(user->nick, parameters[0],NICKMAX);
4038 log(DEBUG,"new nick set: %s",user->nick);
4040 if (user->registered < 3)
4041 user->registered = (user->registered | 2);
4042 if (user->registered == 3)
4044 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4047 log(DEBUG,"exit nickchange: %s",user->nick);
4050 int process_parameters(char **command_p,char *parameters)
4055 q = strlen(parameters);
4058 /* no parameters, command_p invalid! */
4061 if (parameters[0] == ':')
4063 command_p[0] = parameters+1;
4068 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4070 /* only one parameter */
4071 command_p[0] = parameters;
4072 if (parameters[0] == ':')
4074 if (strchr(parameters,' ') != NULL)
4082 command_p[j++] = parameters;
4083 for (i = 0; i <= q; i++)
4085 if (parameters[i] == ' ')
4087 command_p[j++] = parameters+i+1;
4088 parameters[i] = '\0';
4089 if (command_p[j-1][0] == ':')
4091 *command_p[j-1]++; /* remove dodgy ":" */
4093 /* parameter like this marks end of the sequence */
4097 return j; /* returns total number of items in the list */
4100 void process_command(userrec *user, char* cmd)
4104 char *command_p[127];
4105 char p[MAXBUF], temp[MAXBUF];
4106 int i, j, items, cmd_found;
4108 for (int i = 0; i < 127; i++)
4109 command_p[i] = NULL;
4119 if (!strcmp(cmd,""))
4126 FOREACH_MOD OnServerRaw(tmp,true);
4127 const char* cmd2 = tmp.c_str();
4128 snprintf(cmd,512,"%s",cmd2);
4130 if (!strchr(cmd,' '))
4132 /* no parameters, lets skip the formalities and not chop up
4135 command_p[0] = NULL;
4137 for (int i = 0; i <= strlen(cmd); i++)
4139 cmd[i] = toupper(cmd[i]);
4146 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4147 for (i = 0; i < strlen(temp); i++)
4149 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4155 /* split the full string into a command plus parameters */
4159 if (strchr(cmd,' '))
4161 for (i = 0; i <= strlen(cmd); i++)
4163 /* capitalise the command ONLY, leave params intact */
4164 cmd[i] = toupper(cmd[i]);
4165 /* are we nearly there yet?! :P */
4169 parameters = cmd+i+1;
4177 for (i = 0; i <= strlen(cmd); i++)
4179 cmd[i] = toupper(cmd[i]);
4187 for (i = 0; i != cmdlist.size(); i++)
4189 if (strcmp(cmdlist[i].command,""))
4191 if (!strcmp(command, cmdlist[i].command))
4195 if (strcmp(parameters,""))
4197 items = process_parameters(command_p,parameters);
4202 command_p[0] = NULL;
4208 command_p[0] = NULL;
4213 user->idle_lastmsg = time(NULL);
4214 /* activity resets the ping pending timer */
4215 user->nping = time(NULL) + 120;
4216 if ((items) < cmdlist[i].min_params)
4218 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4219 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4222 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4224 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4225 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4229 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4231 if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4233 if ((!isnick(user->nick)) || (user->registered != 7))
4235 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4236 WriteServ(user->fd,"451 %s :You have not registered",command);
4240 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4242 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4243 if (cmdlist[i].handler_function)
4245 /* ikky /stats counters */
4250 user->bytes_in += strlen(temp);
4253 cmdlist[i].use_count++;
4254 cmdlist[i].total_bytes+=strlen(temp);
4257 /* WARNING: nothing may come after the
4258 * command handler call, as the handler
4259 * may free the user structure! */
4261 cmdlist[i].handler_function(command_p,items,user);
4267 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4268 WriteServ(user->fd,"451 %s :You have not registered",command);
4276 if ((!cmd_found) && (user))
4278 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4279 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4284 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4287 /* create the command and push it onto the table */
4288 strcpy(comm.command,cmd);
4289 comm.handler_function = f;
4290 comm.flags_needed = flags;
4291 comm.min_params = minparams;
4293 comm.total_bytes = 0;
4294 cmdlist.push_back(comm);
4295 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4298 void SetupCommandTable(void)
4300 createcommand("USER",handle_user,0,4);
4301 createcommand("NICK",handle_nick,0,1);
4302 createcommand("QUIT",handle_quit,0,0);
4303 createcommand("VERSION",handle_version,0,0);
4304 createcommand("PING",handle_ping,0,1);
4305 createcommand("PONG",handle_pong,0,1);
4306 createcommand("ADMIN",handle_admin,0,0);
4307 createcommand("PRIVMSG",handle_privmsg,0,2);
4308 createcommand("INFO",handle_info,0,0);
4309 createcommand("TIME",handle_time,0,0);
4310 createcommand("WHOIS",handle_whois,0,1);
4311 createcommand("WALLOPS",handle_wallops,'o',1);
4312 createcommand("NOTICE",handle_notice,0,2);
4313 createcommand("JOIN",handle_join,0,1);
4314 createcommand("NAMES",handle_names,0,1);
4315 createcommand("PART",handle_part,0,1);
4316 createcommand("KICK",handle_kick,0,2);
4317 createcommand("MODE",handle_mode,0,1);
4318 createcommand("TOPIC",handle_topic,0,1);
4319 createcommand("WHO",handle_who,0,1);
4320 createcommand("MOTD",handle_motd,0,0);
4321 createcommand("RULES",handle_join,0,0);
4322 createcommand("OPER",handle_oper,0,2);
4323 createcommand("LIST",handle_list,0,0);
4324 createcommand("DIE",handle_die,'o',1);
4325 createcommand("RESTART",handle_restart,'o',1);
4326 createcommand("KILL",handle_kill,'o',2);
4327 createcommand("REHASH",handle_rehash,'o',0);
4328 createcommand("LUSERS",handle_lusers,0,0);
4329 createcommand("STATS",handle_stats,0,1);
4330 createcommand("USERHOST",handle_userhost,0,1);
4331 createcommand("AWAY",handle_away,0,0);
4332 createcommand("ISON",handle_ison,0,0);
4333 createcommand("SUMMON",handle_summon,0,0);
4334 createcommand("USERS",handle_users,0,0);
4335 createcommand("INVITE",handle_invite,0,2);
4336 createcommand("PASS",handle_pass,0,1);
4337 createcommand("TRACE",handle_trace,'o',0);
4338 createcommand("WHOWAS",handle_whowas,0,1);
4339 createcommand("CONNECT",handle_connect,'o',1);
4340 createcommand("SQUIT",handle_squit,'o',1);
4343 void process_buffer(userrec *user)
4351 if (!strcmp(user->inbuf,""))
4355 strncpy(cmd,user->inbuf,MAXBUF);
4356 if (!strcmp(cmd,""))
4360 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4362 cmd[strlen(cmd)-1] = '\0';
4364 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4366 cmd[strlen(cmd)-1] = '\0';
4368 strcpy(user->inbuf,"");
4369 if (!strcmp(cmd,""))
4373 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4375 process_command(user,cmd);
4378 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4380 WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4384 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4386 char response[10240];
4387 char token = udp_msg[0];
4388 char* params = udp_msg + 2;
4389 char finalparam[1024];
4390 strcpy(finalparam," :xxxx");
4391 if (strstr(params," :")) {
4392 strncpy(finalparam,strstr(params," :"),1024);
4395 // S test.chatspike.net password :ChatSpike InspIRCd test server
4396 char* servername = strtok(params," ");
4397 char* password = strtok(NULL," ");
4398 char* serverdesc = finalparam+2;
4399 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4402 char Link_ServerName[1024];
4403 char Link_IPAddr[1024];
4404 char Link_Port[1024];
4405 char Link_Pass[1024];
4406 char Link_SendPass[1024];
4409 // search for a corresponding <link> block in the config files
4410 for (int i = 0; i < ConfValueEnum("link"); i++)
4412 ConfValue("link","name",i,Link_ServerName);
4413 ConfValue("link","ipaddr",i,Link_IPAddr);
4414 ConfValue("link","port",i,Link_Port);
4415 ConfValue("link","recvpass",i,Link_Pass);
4416 ConfValue("link","sendpass",i,Link_SendPass);
4417 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4418 LinkPort = atoi(Link_Port);
4419 if (!strcasecmp(Link_ServerName,servername)) {
4420 if (!strcasecmp(Link_IPAddr,udp_host)) {
4421 if (LinkPort == udp_port) {
4422 // we have a matching link line -
4423 // send a 'diminutive' server message back...
4424 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4425 serv->SendPacket(response,udp_host,udp_port,0);
4426 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4427 for (int j = 0; j < 255; j++) {
4428 if (servers[j] == NULL) {
4429 servers[j] = new serverrec;
4430 strcpy(servers[j]->internal_addr,udp_host);
4431 strcpy(servers[j]->name,servername);
4432 // create a server record for this server
4433 snprintf(response,10240,"O %d",MyKey);
4434 serv->SendPacket(response,udp_host,udp_port,0);
4438 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4442 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4446 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4450 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4453 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4454 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4459 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4460 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4461 // array, which is only added by an 'S' packet or BeginLink().
4462 for (int i = 0; i < 255; i++) {
4463 if (servers[i] != NULL) {
4464 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4465 servers[i]->key = atoi(params);
4466 log(DEBUG,"Key for this server is now %d",servers[i]->key);
4467 serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4472 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4476 // S test.chatspike.net password :ChatSpike InspIRCd test server
4477 char* servername = strtok(params," ");
4478 char* password = strtok(NULL," ");
4479 char* serverdesc = finalparam+2;
4481 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4482 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4483 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4484 // a connect, so put out an oper alert!
4489 // for now, just accept all, we'll fix that later.
4490 WriteOpers("%s accepted our link credentials ",servername);
4492 char Link_ServerName[1024];
4493 char Link_IPAddr[1024];
4494 char Link_Port[1024];
4495 char Link_Pass[1024];
4496 char Link_SendPass[1024];
4499 // search for a corresponding <link> block in the config files
4500 for (int i = 0; i < ConfValueEnum("link"); i++)
4502 ConfValue("link","name",i,Link_ServerName);
4503 ConfValue("link","ipaddr",i,Link_IPAddr);
4504 ConfValue("link","port",i,Link_Port);
4505 ConfValue("link","recvpass",i,Link_Pass);
4506 ConfValue("link","sendpass",i,Link_SendPass);
4507 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4508 LinkPort = atoi(Link_Port);
4509 if (!strcasecmp(Link_ServerName,servername)) {
4510 if (!strcasecmp(Link_IPAddr,udp_host)) {
4511 if (LinkPort == udp_port) {
4512 // matching link at this end too, we're all done!
4513 // at this point we must begin key exchange and insert this
4514 // server into our 'active' table.
4515 for (int j = 0; j < 255; j++) {
4516 if (servers[j] != NULL) {
4517 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4518 WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4519 snprintf(response,10240,"O %d",MyKey);
4520 serv->SendPacket(response,udp_host,udp_port,0);
4525 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4530 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4534 log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4538 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4541 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4542 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4547 char* error_message = finalparam+2;
4548 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4549 // remove this server from any lists
4550 for (int j = 0; j < 255; j++) {
4551 if (servers[j] != NULL) {
4552 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4562 serverrec* source_server = NULL;
4564 for (int j = 0; j < 255; j++) {
4565 if (servers[j] != NULL) {
4566 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4567 if (servers[j]->key == theirkey) {
4568 // found a valid key for this server, can process restricted stuff here
4569 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4577 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4581 int reap_counter = 0;
4585 struct sockaddr_in client, server;
4586 char addrs[MAXBUF][255];
4587 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4589 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4590 int selectResult = 0;
4591 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4592 char resolvedHost[MAXBUF];
4596 log(DEBUG,"InspIRCd: startup: begin");
4600 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4602 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4604 SetupCommandTable();
4605 log(DEBUG,"InspIRCd: startup: default command table set up");
4608 if (strcmp(DieValue,""))
4610 printf("WARNING: %s\n\n",DieValue);
4613 log(DEBUG,"InspIRCd: startup: read config");
4615 int count2 = 0, count3 = 0;
4616 for (count = 0; count < ConfValueEnum("bind"); count++)
4618 ConfValue("bind","port",count,configToken);
4619 ConfValue("bind","address",count,Addr);
4620 ConfValue("bind","type",count,Type);
4621 if (!strcmp(Type,"servers"))
4623 char Default[MAXBUF];
4624 strcpy(Default,"no");
4625 ConfValue("bind","default",count,Default);
4626 if (strchr(Default,'y'))
4628 defaultRoute = count3;
4629 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4631 me[count3] = new serverrec(ServerName,100L,false);
4632 me[count3]->CreateListener(Addr,atoi(configToken));
4637 ports[count2] = atoi(configToken);
4638 strcpy(addrs[count2],Addr);
4641 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4644 UDPportCount = count3;
4646 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4648 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4652 /* BugFix By Craig! :p */
4654 for (count = 0; count2 < ConfValueEnum("module"); count2++)
4656 char modfile[MAXBUF];
4657 ConfValue("module","name",count,configToken);
4658 sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4659 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4660 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4661 /* If The File Doesnt exist, Trying to load it
4662 * Will Segfault the IRCd.. So, check to see if
4663 * it Exists, Before Proceeding. */
4664 if (FileExists(modfile))
4666 factory[count] = new ircd_module(modfile);
4667 if (factory[count]->LastError())
4669 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4670 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4673 if (factory[count]->factory)
4675 modules[count] = factory[count]->factory->CreateModule();
4676 /* save the module and the module's classfactory, if
4677 * this isnt done, random crashes can occur :/ */
4681 log(DEBUG,"Unable to load %s",modfile);
4682 sprintf("Unable to load %s\nExiting...\n",modfile);
4685 /* Increase the Count */
4690 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4691 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4694 MODCOUNT = count - 1;
4695 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4697 printf("\nInspIRCd is now running!\n");
4699 startup_time = time(NULL);
4703 log(VERBOSE,"Not forking as -nofork was specified");
4707 if (DaemonSeed() == ERROR)
4709 log(DEBUG,"InspIRCd: startup: can't daemonise");
4710 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4716 /* setup select call */
4717 FD_ZERO(&selectFds);
4718 log(DEBUG,"InspIRCd: startup: zero selects");
4719 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4721 for (count = 0; count < portCount; count++)
4723 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4725 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4728 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4730 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4732 else /* well we at least bound to one socket so we'll continue */
4738 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4740 /* if we didn't bind to anything then abort */
4741 if (boundPortCount == 0)
4743 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4747 length = sizeof (client);
4748 int flip_flop = 0, udp_port = 0;
4749 char udp_msg[MAXBUF], udp_host[MAXBUF];
4751 /* main loop for multiplexing/resetting */
4754 /* set up select call */
4755 for (count = 0; count < boundPortCount; count++)
4757 FD_SET (openSockfd[count], &selectFds);
4760 /* added timeout! select was waiting forever... wank... :/ */
4771 vector<int>::iterator niterator;
4774 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4775 // them in a list, then reap the list every second or so.
4776 if (reap_counter>5000) {
4777 if (fd_reap.size() > 0) {
4778 for( int n = 0; n < fd_reap.size(); n++)
4780 Blocking(fd_reap[n]);
4782 NonBlocking(fd_reap[n]);
4791 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4793 for (int x = 0; x != UDPportCount; x++)
4796 if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
4798 if (strlen(udp_msg)<1) {
4799 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
4802 FOREACH_MOD OnPacketReceive(udp_msg);
4803 // Packets must go back via the route they arrived on :)
4804 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
4809 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
4813 if (!count2->second) break;
4816 if (count2->second->fd)
4818 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4820 if (!count2->second->lastping)
4822 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4823 kill_link(count2->second,"Ping timeout");
4826 Write(count2->second->fd,"PING :%s",ServerName);
4827 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4828 count2->second->lastping = 0;
4829 count2->second->nping = time(NULL)+120;
4832 result = read(count2->second->fd, data, 1);
4833 // result EAGAIN means nothing read
4834 if (result == EAGAIN)
4840 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
4841 kill_link(count2->second,"Client exited");
4843 else if (result > 0)
4845 strncat(count2->second->inbuf, data, result);
4846 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r'))
4848 /* at least one complete line is waiting to be processed */
4849 if (!count2->second->fd)
4853 process_buffer(count2->second);
4861 /* select is reporting a waiting socket. Poll them all to find out which */
4862 if (selectResult > 0)
4864 char target[MAXBUF], resolved[MAXBUF];
4865 for (count = 0; count < boundPortCount; count++)
4867 if (FD_ISSET (openSockfd[count], &selectFds))
4869 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4871 address_cache::iterator iter = IP.find(client.sin_addr);
4872 bool iscached = false;
4873 if (iter == IP.end())
4875 /* ip isn't in cache, add it */
4876 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4877 if(CleanAndResolve(resolved, target) != TRUE)
4879 strncpy(resolved,target,MAXBUF);
4881 /* hostname now in 'target' */
4882 IP[client.sin_addr] = new string(resolved);
4883 /* hostname in cache */
4887 /* found ip (cached) */
4888 strncpy(resolved, iter->second->c_str(), MAXBUF);
4892 if (incomingSockfd < 0)
4894 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4895 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4899 AddClient(incomingSockfd, resolved, ports[count], iscached);
4900 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4909 close (incomingSockfd);