]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fixed bug #15 - mode case sensitivity issue in mirc (glitch reported by strike and...
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 /* Now with added unF! ;) */
18
19 using namespace std;
20
21 #include "inspircd.h"
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
30 #include <cstdio>
31 #include <time.h>
32 #include <string>
33 #ifdef GCC3
34 #include <ext/hash_map>
35 #else
36 #include <hash_map>
37 #endif
38 #include <map>
39 #include <sstream>
40 #include <vector>
41 #include <errno.h>
42 #include <deque>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <sched.h>
46 #include "connection.h"
47 #include "users.h"
48 #include "servers.h"
49 #include "ctables.h"
50 #include "globals.h"
51 #include "modules.h"
52 #include "dynamic.h"
53 #include "wildcard.h"
54 #include "message.h"
55 #include "mode.h"
56 #include "commands.h"
57 #include "xline.h"
58
59 #ifdef GCC3
60 #define nspace __gnu_cxx
61 #else
62 #define nspace std
63 #endif
64
65 int LogLevel = DEFAULT;
66 char ServerName[MAXBUF];
67 char Network[MAXBUF];
68 char ServerDesc[MAXBUF];
69 char AdminName[MAXBUF];
70 char AdminEmail[MAXBUF];
71 char AdminNick[MAXBUF];
72 char diepass[MAXBUF];
73 char restartpass[MAXBUF];
74 char motd[MAXBUF];
75 char rules[MAXBUF];
76 char list[MAXBUF];
77 char PrefixQuit[MAXBUF];
78 char DieValue[MAXBUF];
79 int debugging =  0;
80 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
81 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
82 int DieDelay  =  5;
83 time_t startup_time = time(NULL);
84 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
85 extern int MaxWhoResults;
86 time_t nb_start = 0;
87
88 extern vector<Module*> modules;
89 std::vector<std::string> module_names;
90 extern vector<ircd_module*> factory;
91 std::vector<int> fd_reap;
92
93 extern int MODCOUNT;
94
95 bool nofork = false;
96
97 namespace nspace
98 {
99         template<> struct nspace::hash<in_addr>
100         {
101                 size_t operator()(const struct in_addr &a) const
102                 {
103                         size_t q;
104                         memcpy(&q,&a,sizeof(size_t));
105                         return q;
106                 }
107         };
108
109         template<> struct nspace::hash<string>
110         {
111                 size_t operator()(const string &s) const
112                 {
113                         char a[MAXBUF];
114                         static struct hash<const char *> strhash;
115                         strcpy(a,s.c_str());
116                         strlower(a);
117                         return strhash(a);
118                 }
119         };
120 }       
121
122
123 struct StrHashComp
124 {
125
126         bool operator()(const string& s1, const string& s2) const
127         {
128                 char a[MAXBUF],b[MAXBUF];
129                 strcpy(a,s1.c_str());
130                 strcpy(b,s2.c_str());
131                 return (strcasecmp(a,b) == 0);
132         }
133
134 };
135
136 struct InAddr_HashComp
137 {
138
139         bool operator()(const in_addr &s1, const in_addr &s2) const
140         {
141                 size_t q;
142                 size_t p;
143                 
144                 memcpy(&q,&s1,sizeof(size_t));
145                 memcpy(&p,&s2,sizeof(size_t));
146                 
147                 return (q == p);
148         }
149
150 };
151
152
153 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
154 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
155 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
156 typedef std::deque<command_t> command_table;
157
158 serverrec* me[32];
159
160 FILE *log_file;
161
162 user_hash clientlist;
163 chan_hash chanlist;
164 user_hash whowas;
165 command_table cmdlist;
166 file_cache MOTD;
167 file_cache RULES;
168 address_cache IP;
169
170 ClassVector Classes;
171
172 struct linger linger = { 0 };
173 char bannerBuffer[MAXBUF];
174 int boundPortCount = 0;
175 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
176 int defaultRoute = 0;
177
178 connection C;
179
180 long MyKey = C.GenKey();
181
182 /* prototypes */
183
184 int has_channel(userrec *u, chanrec *c);
185 int usercount(chanrec *c);
186 int usercount_i(chanrec *c);
187 void update_stats_l(int fd,int data_out);
188 char* Passwd(userrec *user);
189 bool IsDenied(userrec *user);
190 void AddWhoWas(userrec* u);
191
192 std::vector<long> auth_cookies;
193 std::stringstream config_f(stringstream::in | stringstream::out);
194
195
196
197 long GetRevision()
198 {
199         char Revision[] = "$Revision$";
200         char *s1 = Revision;
201         char *savept;
202         char *v1 = strtok_r(s1," ",&savept);
203         s1 = savept;
204         char *v2 = strtok_r(s1," ",&savept);
205         s1 = savept;
206         return (long)(atof(v2)*10000);
207 }
208
209
210 std::string getservername()
211 {
212         return ServerName;
213 }
214
215 std::string getserverdesc()
216 {
217         return ServerDesc;
218 }
219
220 std::string getnetworkname()
221 {
222         return Network;
223 }
224
225 std::string getadminname()
226 {
227         return AdminName;
228 }
229
230 std::string getadminemail()
231 {
232         return AdminEmail;
233 }
234
235 std::string getadminnick()
236 {
237         return AdminNick;
238 }
239
240 void log(int level,char *text, ...)
241 {
242         char textbuffer[MAXBUF];
243         va_list argsPtr;
244         time_t rawtime;
245         struct tm * timeinfo;
246         if (level < LogLevel)
247                 return;
248
249         time(&rawtime);
250         timeinfo = localtime (&rawtime);
251
252         if (log_file)
253         {
254                 char b[MAXBUF];
255                 va_start (argsPtr, text);
256                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
257                 va_end(argsPtr);
258                 strcpy(b,asctime(timeinfo));
259                 b[strlen(b)-1] = ':';
260                 fprintf(log_file,"%s %s\n",b,textbuffer);
261                 if (nofork)
262                 {
263                         // nofork enabled? display it on terminal too
264                         printf("%s %s\n",b,textbuffer);
265                 }
266         }
267 }
268
269 void readfile(file_cache &F, const char* fname)
270 {
271         FILE* file;
272         char linebuf[MAXBUF];
273         
274         log(DEBUG,"readfile: loading %s",fname);
275         F.clear();
276         file =  fopen(fname,"r");
277         if (file)
278         {
279                 while (!feof(file))
280                 {
281                         fgets(linebuf,sizeof(linebuf),file);
282                         linebuf[strlen(linebuf)-1]='\0';
283                         if (!strcmp(linebuf,""))
284                         {
285                                 strcpy(linebuf,"  ");
286                         }
287                         if (!feof(file))
288                         {
289                                 F.push_back(linebuf);
290                         }
291                 }
292                 fclose(file);
293         }
294         else
295         {
296                 log(DEBUG,"readfile: failed to load file: %s",fname);
297         }
298         log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
299 }
300
301 void ReadConfig(void)
302 {
303         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
304         ConnectClass c;
305         
306         LoadConf(CONFIG_FILE,&config_f);
307           
308         ConfValue("server","name",0,ServerName,&config_f);
309         ConfValue("server","description",0,ServerDesc,&config_f);
310         ConfValue("server","network",0,Network,&config_f);
311         ConfValue("admin","name",0,AdminName,&config_f);
312         ConfValue("admin","email",0,AdminEmail,&config_f);
313         ConfValue("admin","nick",0,AdminNick,&config_f);
314         ConfValue("files","motd",0,motd,&config_f);
315         ConfValue("files","rules",0,rules,&config_f);
316         ConfValue("power","diepass",0,diepass,&config_f);
317         ConfValue("power","pause",0,pauseval,&config_f);
318         ConfValue("power","restartpass",0,restartpass,&config_f);
319         ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
320         ConfValue("die","value",0,DieValue,&config_f);
321         ConfValue("options","loglevel",0,dbg,&config_f);
322         ConfValue("options","netbuffersize",0,NB,&config_f);
323         ConfValue("options","maxwho",0,MW,&config_f);
324         NetBufferSize = atoi(NB);
325         MaxWhoResults = atoi(MW);
326         if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
327         {
328                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
329                 NetBufferSize = 10240;
330         }
331         if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
332         {
333                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
334                 MaxWhoResults = 128;
335         }
336         if (!strcmp(dbg,"debug"))
337                 LogLevel = DEBUG;
338         if (!strcmp(dbg,"verbose"))
339                 LogLevel = VERBOSE;
340         if (!strcmp(dbg,"default"))
341                 LogLevel = DEFAULT;
342         if (!strcmp(dbg,"sparse"))
343                 LogLevel = SPARSE;
344         if (!strcmp(dbg,"none"))
345                 LogLevel = NONE;
346         readfile(MOTD,motd);
347         log(DEFAULT,"Reading message of the day...");
348         readfile(RULES,rules);
349         log(DEFAULT,"Reading connect classes...");
350         Classes.clear();
351         for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
352         {
353                 strcpy(Value,"");
354                 ConfValue("connect","allow",i,Value,&config_f);
355                 ConfValue("connect","timeout",i,timeout,&config_f);
356                 ConfValue("connect","flood",i,flood,&config_f);
357                 if (strcmp(Value,""))
358                 {
359                         strcpy(c.host,Value);
360                         c.type = CC_ALLOW;
361                         strcpy(Value,"");
362                         ConfValue("connect","password",i,Value,&config_f);
363                         strcpy(c.pass,Value);
364                         c.registration_timeout = 90; // default is 2 minutes
365                         c.flood = atoi(flood);
366                         if (atoi(timeout)>0)
367                         {
368                                 c.registration_timeout = atoi(timeout);
369                         }
370                         Classes.push_back(c);
371                         log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
372                 }
373                 else
374                 {
375                         ConfValue("connect","deny",i,Value,&config_f);
376                         strcpy(c.host,Value);
377                         c.type = CC_DENY;
378                         Classes.push_back(c);
379                         log(DEBUG,"Read connect class type DENY, host=%s",c.host);
380                 }
381         
382         }
383         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
384         read_xline_defaults();
385         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
386         apply_lines();
387         log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
388 }
389
390 /* write formatted text to a socket, in same format as printf */
391
392 void Write(int sock,char *text, ...)
393 {
394         if (!text)
395         {
396                 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
397                 return;
398         }
399         char textbuffer[MAXBUF];
400         va_list argsPtr;
401         char tb[MAXBUF];
402         
403         va_start (argsPtr, text);
404         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
405         va_end(argsPtr);
406         sprintf(tb,"%s\r\n",textbuffer);
407         chop(tb);
408         if (sock != -1)
409         {
410                 write(sock,tb,strlen(tb));
411                 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
412         }
413 }
414
415 /* write a server formatted numeric response to a single socket */
416
417 void WriteServ(int sock, char* text, ...)
418 {
419         if (!text)
420         {
421                 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
422                 return;
423         }
424         char textbuffer[MAXBUF],tb[MAXBUF];
425         va_list argsPtr;
426         va_start (argsPtr, text);
427         
428         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
429         va_end(argsPtr);
430         sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
431         chop(tb);
432         if (sock != -1)
433         {
434                 write(sock,tb,strlen(tb));
435                 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
436         }
437 }
438
439 /* write text from an originating user to originating user */
440
441 void WriteFrom(int sock, userrec *user,char* text, ...)
442 {
443         if ((!text) || (!user))
444         {
445                 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
446                 return;
447         }
448         char textbuffer[MAXBUF],tb[MAXBUF];
449         va_list argsPtr;
450         va_start (argsPtr, text);
451         
452         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
453         va_end(argsPtr);
454         sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
455         chop(tb);
456         if (sock != -1)
457         {
458                 write(sock,tb,strlen(tb));
459                 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
460         }
461 }
462
463 /* write text to an destination user from a source user (e.g. user privmsg) */
464
465 void WriteTo(userrec *source, userrec *dest,char *data, ...)
466 {
467         if ((!dest) || (!data))
468         {
469                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
470                 return;
471         }
472         char textbuffer[MAXBUF],tb[MAXBUF];
473         va_list argsPtr;
474         va_start (argsPtr, data);
475         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
476         va_end(argsPtr);
477         chop(tb);
478
479         // if no source given send it from the server.
480         if (!source)
481         {
482                 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
483         }
484         else
485         {
486                 WriteFrom(dest->fd,source,"%s",textbuffer);
487         }
488 }
489
490 /* write formatted text from a source user to all users on a channel
491  * including the sender (NOT for privmsg, notice etc!) */
492
493 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
494 {
495         if ((!Ptr) || (!user) || (!text))
496         {
497                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
498                 return;
499         }
500         char textbuffer[MAXBUF];
501         va_list argsPtr;
502         va_start (argsPtr, text);
503         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
504         va_end(argsPtr);
505         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
506         {
507                 if (has_channel(i->second,Ptr))
508                 {
509                         WriteTo(user,i->second,"%s",textbuffer);
510                 }
511         }
512 }
513
514 /* write formatted text from a source user to all users on a channel
515  * including the sender (NOT for privmsg, notice etc!) doesnt send to
516  * users on remote servers */
517
518 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
519 {
520         if ((!Ptr) || (!text))
521         {
522                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
523                 return;
524         }
525         char textbuffer[MAXBUF];
526         va_list argsPtr;
527         va_start (argsPtr, text);
528         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
529         va_end(argsPtr);
530         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
531         {
532                 if (has_channel(i->second,Ptr))
533                 {
534                         if (i->second->fd != -1)
535                         {
536                                 if (!user)
537                                 {
538                                         WriteServ(i->second->fd,"%s",textbuffer);
539                                 }
540                                 else
541                                 {
542                                         WriteTo(user,i->second,"%s",textbuffer);
543                                 }
544                         }       
545                 }
546         }
547 }
548
549
550 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
551 {
552         if ((!Ptr) || (!user) || (!text))
553         {
554                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
555                 return;
556         }
557         char textbuffer[MAXBUF];
558         va_list argsPtr;
559         va_start (argsPtr, text);
560         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
561         va_end(argsPtr);
562         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
563         {
564                 if (i->second)
565                 {
566                         if (has_channel(i->second,Ptr))
567                         {
568                                 WriteServ(i->second->fd,"%s",textbuffer);
569                         }
570                 }
571         }
572 }
573
574
575 /* write formatted text from a source user to all users on a channel except
576  * for the sender (for privmsg etc) */
577
578 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
579 {
580         if ((!Ptr) || (!user) || (!text))
581         {
582                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
583                 return;
584         }
585         char textbuffer[MAXBUF];
586         va_list argsPtr;
587         va_start (argsPtr, text);
588         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
589         va_end(argsPtr);
590
591         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
592         {
593                 if (i->second)
594                 {
595                         if (has_channel(i->second,Ptr) && (user != i->second))
596                         {
597                                 WriteTo(user,i->second,"%s",textbuffer);
598                         }
599                 }
600         }
601 }
602
603
604 std::string GetServerDescription(char* servername)
605 {
606         for (int j = 0; j < 32; j++)
607         {
608                 if (me[j] != NULL)
609                 {
610                         for (int k = 0; k < me[j]->connectors.size(); k++)
611                         {
612                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
613                                 {
614                                         return me[j]->connectors[k].GetDescription();
615                                 }
616                         }
617                 }
618                 return ServerDesc; // not a remote server that can be found, it must be me.
619         }
620 }
621
622
623 /* write a formatted string to all users who share at least one common
624  * channel, including the source user e.g. for use in NICK */
625
626 void WriteCommon(userrec *u, char* text, ...)
627 {
628         if (!u)
629         {
630                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
631                 return;
632         }
633
634         if (u->registered != 7) {
635                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
636                 return;
637         }
638         
639         char textbuffer[MAXBUF];
640         va_list argsPtr;
641         va_start (argsPtr, text);
642         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
643         va_end(argsPtr);
644
645         WriteFrom(u->fd,u,"%s",textbuffer);
646
647         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
648         {
649                 if (i->second)
650                 {
651                         if (common_channels(u,i->second) && (i->second != u))
652                         {
653                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
654                         }
655                 }
656         }
657 }
658
659 /* write a formatted string to all users who share at least one common
660  * channel, NOT including the source user e.g. for use in QUIT */
661
662 void WriteCommonExcept(userrec *u, char* text, ...)
663 {
664         if (!u)
665         {
666                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
667                 return;
668         }
669
670         if (u->registered != 7) {
671                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
672                 return;
673         }
674
675         char textbuffer[MAXBUF];
676         va_list argsPtr;
677         va_start (argsPtr, text);
678         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
679         va_end(argsPtr);
680
681         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
682         {
683                 if (i->second)
684                 {
685                         if ((common_channels(u,i->second)) && (u != i->second))
686                         {
687                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
688                         }
689                 }
690         }
691 }
692
693 void WriteOpers(char* text, ...)
694 {
695         if (!text)
696         {
697                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
698                 return;
699         }
700
701         char textbuffer[MAXBUF];
702         va_list argsPtr;
703         va_start (argsPtr, text);
704         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
705         va_end(argsPtr);
706
707         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
708         {
709                 if (i->second)
710                 {
711                         if (strchr(i->second->modes,'o'))
712                         {
713                                 if (strchr(i->second->modes,'s'))
714                                 {
715                                         // send server notices to all with +s
716                                         // (TODO: needs SNOMASKs)
717                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
718                                 }
719                         }
720                 }
721         }
722 }
723
724 // returns TRUE of any users on channel C occupy server 'servername'.
725
726 bool ChanAnyOnThisServer(chanrec *c,char* servername)
727 {
728         log(DEBUG,"ChanAnyOnThisServer");
729         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
730         {
731                 if (has_channel(i->second,c))
732                 {
733                         if (!strcasecmp(i->second->server,servername))
734                         {
735                                 return true;
736                         }
737                 }
738         }
739         return false;
740 }
741
742 // returns true if user 'u' shares any common channels with any users on server 'servername'
743
744 bool CommonOnThisServer(userrec* u,const char* servername)
745 {
746         log(DEBUG,"ChanAnyOnThisServer");
747         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
748         {
749                 if ((common_channels(u,i->second)) && (u != i->second))
750                 {
751                         if (!strcasecmp(i->second->server,servername))
752                         {
753                                 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
754                                 return true;
755                         }
756                 }
757         }
758         return false;
759 }
760
761
762 void NetSendToCommon(userrec* u, char* s)
763 {
764         char buffer[MAXBUF];
765         snprintf(buffer,MAXBUF,"%s",s);
766         
767         log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
768
769         for (int j = 0; j < 32; j++)
770         {
771                 if (me[j] != NULL)
772                 {
773                         for (int k = 0; k < me[j]->connectors.size(); k++)
774                         {
775                                 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
776                                 {
777                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
778                                 }
779                         }
780                 }
781         }
782 }
783
784
785 void NetSendToAll(char* s)
786 {
787         char buffer[MAXBUF];
788         snprintf(buffer,MAXBUF,"%s",s);
789         
790         log(DEBUG,"NetSendToAll: '%s'",s);
791
792         for (int j = 0; j < 32; j++)
793         {
794                 if (me[j] != NULL)
795                 {
796                         for (int k = 0; k < me[j]->connectors.size(); k++)
797                         {
798                                 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
799                         }
800                 }
801         }
802 }
803
804 void NetSendToAllAlive(char* s)
805 {
806         char buffer[MAXBUF];
807         snprintf(buffer,MAXBUF,"%s",s);
808         
809         log(DEBUG,"NetSendToAllAlive: '%s'",s);
810
811         for (int j = 0; j < 32; j++)
812         {
813                 if (me[j] != NULL)
814                 {
815                         for (int k = 0; k < me[j]->connectors.size(); k++)
816                         {
817                                 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
818                                 {
819                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
820                                 }
821                                 else
822                                 {
823                                         log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
824                                 }
825                         }
826                 }
827         }
828 }
829
830
831 void NetSendToOne(char* target,char* s)
832 {
833         char buffer[MAXBUF];
834         snprintf(buffer,MAXBUF,"%s",s);
835         
836         log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
837
838         for (int j = 0; j < 32; j++)
839         {
840                 if (me[j] != NULL)
841                 {
842                         for (int k = 0; k < me[j]->connectors.size(); k++)
843                         {
844                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
845                                 {
846                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
847                                 }
848                         }
849                 }
850         }
851 }
852
853 void NetSendToAllExcept(const char* target,char* s)
854 {
855         char buffer[MAXBUF];
856         snprintf(buffer,MAXBUF,"%s",s);
857         
858         log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
859         
860         for (int j = 0; j < 32; j++)
861         {
862                 if (me[j] != NULL)
863                 {
864                         for (int k = 0; k < me[j]->connectors.size(); k++)
865                         {
866                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
867                                 {
868                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
869                                 }
870                         }
871                 }
872         }
873 }
874
875
876 void WriteMode(const char* modes, int flags, const char* text, ...)
877 {
878         if ((!text) || (!modes) || (!flags))
879         {
880                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
881                 return;
882         }
883
884         char textbuffer[MAXBUF];
885         va_list argsPtr;
886         va_start (argsPtr, text);
887         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
888         va_end(argsPtr);
889
890         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
891         {
892                 if (i->second)
893                 {
894                         bool send_to_user = false;
895                         
896                         if (flags == WM_AND)
897                         {
898                                 send_to_user = true;
899                                 for (int n = 0; n < strlen(modes); n++)
900                                 {
901                                         if (!hasumode(i->second,modes[n]))
902                                         {
903                                                 send_to_user = false;
904                                                 break;
905                                         }
906                                 }
907                         }
908                         else if (flags == WM_OR)
909                         {
910                                 send_to_user = false;
911                                 for (int n = 0; n < strlen(modes); n++)
912                                 {
913                                         if (hasumode(i->second,modes[n]))
914                                         {
915                                                 send_to_user = true;
916                                                 break;
917                                         }
918                                 }
919                         }
920
921                         if (send_to_user)
922                         {
923                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
924                         }
925                 }
926         }
927 }
928
929
930 void WriteWallOps(userrec *source, bool local_only, char* text, ...)  
931 {  
932         if ((!text) || (!source))
933         {
934                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
935                 return;
936         }
937
938         int i = 0;  
939         char textbuffer[MAXBUF];  
940         va_list argsPtr;  
941         va_start (argsPtr, text);  
942         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
943         va_end(argsPtr);  
944   
945         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
946         {
947                 if (i->second)
948                 {
949                         if (strchr(i->second->modes,'w'))
950                         {
951                                 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
952                         }
953                 }
954         }
955
956         if (!local_only)
957         {
958                 char buffer[MAXBUF];
959                 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
960                 NetSendToAll(buffer);
961         }
962 }  
963
964 /* convert a string to lowercase. Note following special circumstances
965  * taken from RFC 1459. Many "official" server branches still hold to this
966  * rule so i will too;
967  *
968  *  Because of IRC's scandanavian origin, the characters {}| are
969  *  considered to be the lower case equivalents of the characters []\,
970  *  respectively. This is a critical issue when determining the
971  *  equivalence of two nicknames.
972  */
973
974 void strlower(char *n)
975 {
976         if (!n)
977         {
978                 return;
979         }
980         for (int i = 0; i != strlen(n); i++)
981         {
982                 n[i] = tolower(n[i]);
983                 if (n[i] == '[')
984                         n[i] = '{';
985                 if (n[i] == ']')
986                         n[i] = '}';
987                 if (n[i] == '\\')
988                         n[i] = '|';
989         }
990 }
991
992
993
994 /* Find a user record by nickname and return a pointer to it */
995
996 userrec* Find(string nick)
997 {
998         user_hash::iterator iter = clientlist.find(nick);
999
1000         if (iter == clientlist.end())
1001                 /* Couldn't find it */
1002                 return NULL;
1003
1004         return iter->second;
1005 }
1006
1007 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1008 {
1009         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1010         {
1011                 if (i->second)
1012                 {
1013                         if (i->second->fd == fd)
1014                         {
1015                                 i->second->bytes_out+=data_out;
1016                                 i->second->cmds_out++;
1017                         }
1018                 }
1019         }
1020 }
1021
1022
1023 /* find a channel record by channel name and return a pointer to it */
1024
1025 chanrec* FindChan(const char* chan)
1026 {
1027         if (!chan)
1028         {
1029                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1030                 return NULL;
1031         }
1032
1033         chan_hash::iterator iter = chanlist.find(chan);
1034
1035         if (iter == chanlist.end())
1036                 /* Couldn't find it */
1037                 return NULL;
1038
1039         return iter->second;
1040 }
1041
1042
1043 void purge_empty_chans(void)
1044 {
1045         int go_again = 1, purge = 0;
1046         
1047         while (go_again)
1048         {
1049                 go_again = 0;
1050                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1051                 {
1052                         if (i->second) {
1053                                 if (!usercount(i->second))
1054                                 {
1055                                         /* kill the record */
1056                                         if (i != chanlist.end())
1057                                         {
1058                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1059                                                 delete i->second;
1060                                                 chanlist.erase(i);
1061                                                 go_again = 1;
1062                                                 purge++;
1063                                                 break;
1064                                         }
1065                                 }
1066                                 else
1067                                 {
1068                                         log(DEBUG,"skipped purge for %s",i->second->name);
1069                                 }
1070                         }
1071                 }
1072         }
1073         log(DEBUG,"completed channel purge, killed %d",purge);
1074 }
1075
1076
1077 char scratch[MAXBUF];
1078 char sparam[MAXBUF];
1079
1080 char* chanmodes(chanrec *chan)
1081 {
1082         if (!chan)
1083         {
1084                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1085                 strcpy(scratch,"");
1086                 return scratch;
1087         }
1088
1089         strcpy(scratch,"");
1090         strcpy(sparam,"");
1091         if (chan->noexternal)
1092         {
1093                 strncat(scratch,"n",MAXMODES);
1094         }
1095         if (chan->topiclock)
1096         {
1097                 strncat(scratch,"t",MAXMODES);
1098         }
1099         if (strcmp(chan->key,""))
1100         {
1101                 strncat(scratch,"k",MAXMODES);
1102         }
1103         if (chan->limit)
1104         {
1105                 strncat(scratch,"l",MAXMODES);
1106         }
1107         if (chan->inviteonly)
1108         {
1109                 strncat(scratch,"i",MAXMODES);
1110         }
1111         if (chan->moderated)
1112         {
1113                 strncat(scratch,"m",MAXMODES);
1114         }
1115         if (chan->secret)
1116         {
1117                 strncat(scratch,"s",MAXMODES);
1118         }
1119         if (chan->c_private)
1120         {
1121                 strncat(scratch,"p",MAXMODES);
1122         }
1123         if (strcmp(chan->key,""))
1124         {
1125                 strncat(sparam," ",MAXBUF);
1126                 strncat(sparam,chan->key,MAXBUF);
1127         }
1128         if (chan->limit)
1129         {
1130                 char foo[24];
1131                 sprintf(foo," %d",chan->limit);
1132                 strncat(sparam,foo,MAXBUF);
1133         }
1134         if (strlen(chan->custom_modes))
1135         {
1136                 strncat(scratch,chan->custom_modes,MAXMODES);
1137                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1138                 {
1139                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1140                         if (extparam != "")
1141                         {
1142                                 strncat(sparam," ",MAXBUF);
1143                                 strncat(sparam,extparam.c_str(),MAXBUF);
1144                         }
1145                 }
1146         }
1147         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1148         strncat(scratch,sparam,MAXMODES);
1149         return scratch;
1150 }
1151
1152
1153 /* compile a userlist of a channel into a string, each nick seperated by
1154  * spaces and op, voice etc status shown as @ and + */
1155
1156 void userlist(userrec *user,chanrec *c)
1157 {
1158         if ((!c) || (!user))
1159         {
1160                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1161                 return;
1162         }
1163
1164         sprintf(list,"353 %s = %s :", user->nick, c->name);
1165         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1166         {
1167                 if (has_channel(i->second,c))
1168                 {
1169                         if (isnick(i->second->nick))
1170                         {
1171                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1172                                 {
1173                                         /* user is +i, and source not on the channel, does not show
1174                                          * nick in NAMES list */
1175                                         continue;
1176                                 }
1177                                 strcat(list,cmode(i->second,c));
1178                                 strcat(list,i->second->nick);
1179                                 strcat(list," ");
1180                                 if (strlen(list)>(480-NICKMAX))
1181                                 {
1182                                         /* list overflowed into
1183                                          * multiple numerics */
1184                                         WriteServ(user->fd,list);
1185                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1186                                 }
1187                         }
1188                 }
1189         }
1190         /* if whats left in the list isnt empty, send it */
1191         if (list[strlen(list)-1] != ':')
1192         {
1193                 WriteServ(user->fd,list);
1194         }
1195 }
1196
1197 /* return a count of the users on a specific channel accounting for
1198  * invisible users who won't increase the count. e.g. for /LIST */
1199
1200 int usercount_i(chanrec *c)
1201 {
1202         int i = 0;
1203         int count = 0;
1204         
1205         if (!c)
1206         {
1207                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1208                 return 0;
1209         }
1210
1211         strcpy(list,"");
1212         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1213         {
1214                 if (i->second)
1215                 {
1216                         if (has_channel(i->second,c))
1217                         {
1218                                 if (isnick(i->second->nick))
1219                                 {
1220                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1221                                         {
1222                                                 /* user is +i, and source not on the channel, does not show
1223                                                  * nick in NAMES list */
1224                                                 continue;
1225                                         }
1226                                         count++;
1227                                 }
1228                         }
1229                 }
1230         }
1231         log(DEBUG,"usercount_i: %s %d",c->name,count);
1232         return count;
1233 }
1234
1235
1236 int usercount(chanrec *c)
1237 {
1238         int i = 0;
1239         int count = 0;
1240         
1241         if (!c)
1242         {
1243                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1244                 return 0;
1245         }
1246
1247         strcpy(list,"");
1248         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1249         {
1250                 if (i->second)
1251                 {
1252                         if (has_channel(i->second,c))
1253                         {
1254                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1255                                 {
1256                                         count++;
1257                                 }
1258                         }
1259                 }
1260         }
1261         log(DEBUG,"usercount: %s %d",c->name,count);
1262         return count;
1263 }
1264
1265
1266 /* add a channel to a user, creating the record for it if needed and linking
1267  * it to the user record */
1268
1269 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1270 {
1271         if ((!user) || (!cn))
1272         {
1273                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1274                 return 0;
1275         }
1276
1277         int i = 0;
1278         chanrec* Ptr;
1279         int created = 0;
1280         char cname[MAXBUF];
1281
1282         strncpy(cname,cn,MAXBUF);
1283         
1284         // we MUST declare this wherever we use FOREACH_RESULT
1285         int MOD_RESULT = 0;
1286
1287         if (strlen(cname) > CHANMAX-1)
1288         {
1289                 cname[CHANMAX-1] = '\0';
1290         }
1291
1292         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1293         
1294         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1295         {
1296                 return NULL; // already on the channel!
1297         }
1298
1299
1300         if (!FindChan(cname))
1301         {
1302                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1303                 if (MOD_RESULT) {
1304                         return NULL;
1305                 }
1306
1307                 /* create a new one */
1308                 log(DEBUG,"add_channel: creating: %s",cname);
1309                 {
1310                         chanlist[cname] = new chanrec();
1311
1312                         strcpy(chanlist[cname]->name, cname);
1313                         chanlist[cname]->topiclock = 1;
1314                         chanlist[cname]->noexternal = 1;
1315                         chanlist[cname]->created = time(NULL);
1316                         strcpy(chanlist[cname]->topic, "");
1317                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1318                         chanlist[cname]->topicset = 0;
1319                         Ptr = chanlist[cname];
1320                         log(DEBUG,"add_channel: created: %s",cname);
1321                         /* set created to 2 to indicate user
1322                          * is the first in the channel
1323                          * and should be given ops */
1324                         created = 2;
1325                 }
1326         }
1327         else
1328         {
1329                 /* channel exists, just fish out a pointer to its struct */
1330                 Ptr = FindChan(cname);
1331                 if (Ptr)
1332                 {
1333                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1334                         
1335                         // the override flag allows us to bypass channel modes
1336                         // and bans (used by servers)
1337                         if (!override)
1338                         {
1339                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1340                                 if (MOD_RESULT) {
1341                                         return NULL;
1342                                 }
1343                                 
1344                                 if (strcmp(Ptr->key,""))
1345                                 {
1346                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1347                                         if (!key)
1348                                         {
1349                                                 log(DEBUG,"add_channel: no key given in JOIN");
1350                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1351                                                 return NULL;
1352                                         }
1353                                         else
1354                                         {
1355                                                 log(DEBUG,"key at %p is %s",key,key);
1356                                                 if (strcasecmp(key,Ptr->key))
1357                                                 {
1358                                                         log(DEBUG,"add_channel: bad key given in JOIN");
1359                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1360                                                         return NULL;
1361                                                 }
1362                                         }
1363                                 }
1364                                 log(DEBUG,"add_channel: no key");
1365         
1366                                 if (Ptr->inviteonly)
1367                                 {
1368                                         log(DEBUG,"add_channel: channel is +i");
1369                                         if (user->IsInvited(Ptr->name))
1370                                         {
1371                                                 /* user was invited to channel */
1372                                                 /* there may be an optional channel NOTICE here */
1373                                         }
1374                                         else
1375                                         {
1376                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1377                                                 return NULL;
1378                                         }
1379                                 }
1380                                 log(DEBUG,"add_channel: channel is not +i");
1381         
1382                                 if (Ptr->limit)
1383                                 {
1384                                         if (usercount(Ptr) == Ptr->limit)
1385                                         {
1386                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1387                                                 return NULL;
1388                                         }
1389                                 }
1390                                 
1391                                 log(DEBUG,"add_channel: about to walk banlist");
1392         
1393                                 /* check user against the channel banlist */
1394                                 if (Ptr)
1395                                 {
1396                                         if (Ptr->bans.size())
1397                                         {
1398                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1399                                                 {
1400                                                         if (match(user->GetFullHost(),i->data))
1401                                                         {
1402                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1403                                                                 return NULL;
1404                                                         }
1405                                                 }
1406                                         }
1407                                 }
1408                                 
1409                                 log(DEBUG,"add_channel: bans checked");
1410                                 
1411
1412                                 if ((Ptr) && (user))
1413                                 {
1414                                         user->RemoveInvite(Ptr->name);
1415                                 }
1416         
1417                                 log(DEBUG,"add_channel: invites removed");
1418
1419                         }
1420                         else
1421                         {
1422                                 log(DEBUG,"Overridden checks");
1423                         }
1424
1425                         
1426                 }
1427                 created = 1;
1428         }
1429
1430         log(DEBUG,"Passed channel checks");
1431         
1432         for (int i =0; i != MAXCHANS; i++)
1433         {
1434                 log(DEBUG,"Check location %d",i);
1435                 if (user->chans[i].channel == NULL)
1436                 {
1437                         log(DEBUG,"Adding into their channel list at location %d",i);
1438
1439                         if (created == 2) 
1440                         {
1441                                 /* first user in is given ops */
1442                                 user->chans[i].uc_modes = UCMODE_OP;
1443                         }
1444                         else
1445                         {
1446                                 user->chans[i].uc_modes = 0;
1447                         }
1448                         user->chans[i].channel = Ptr;
1449                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1450                         
1451                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1452                         {
1453                                 // use the stamdard J token with no privilages.
1454                                 char buffer[MAXBUF];
1455                                 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1456                                 NetSendToAll(buffer);
1457                         }
1458
1459                         log(DEBUG,"Sent JOIN to client");
1460
1461                         if (Ptr->topicset)
1462                         {
1463                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1464                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1465                         }
1466                         userlist(user,Ptr);
1467                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1468                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1469                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1470                         FOREACH_MOD OnUserJoin(user,Ptr);
1471                         return Ptr;
1472                 }
1473         }
1474         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1475         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1476         return NULL;
1477 }
1478
1479 /* remove a channel from a users record, and remove the record from memory
1480  * if the channel has become empty */
1481
1482 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1483 {
1484         if ((!user) || (!cname))
1485         {
1486                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1487                 return NULL;
1488         }
1489
1490         chanrec* Ptr;
1491         int created = 0;
1492
1493         if ((!cname) || (!user))
1494         {
1495                 return NULL;
1496         }
1497
1498         Ptr = FindChan(cname);
1499         
1500         if (!Ptr)
1501         {
1502                 return NULL;
1503         }
1504
1505         FOREACH_MOD OnUserPart(user,Ptr);
1506         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1507         
1508         for (int i =0; i != MAXCHANS; i++)
1509         {
1510                 /* zap it from the channel list of the user */
1511                 if (user->chans[i].channel == Ptr)
1512                 {
1513                         if (reason)
1514                         {
1515                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1516
1517                                 if (!local)
1518                                 {
1519                                         char buffer[MAXBUF];
1520                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1521                                         NetSendToAll(buffer);
1522                                 }
1523
1524                                 
1525                         }
1526                         else
1527                         {
1528                                 if (!local)
1529                                 {
1530                                         char buffer[MAXBUF];
1531                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1532                                         NetSendToAll(buffer);
1533                                 }
1534                         
1535                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1536                         }
1537                         user->chans[i].uc_modes = 0;
1538                         user->chans[i].channel = NULL;
1539                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1540                         break;
1541                 }
1542         }
1543         
1544         /* if there are no users left on the channel */
1545         if (!usercount(Ptr))
1546         {
1547                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1548
1549                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1550
1551                 /* kill the record */
1552                 if (iter != chanlist.end())
1553                 {
1554                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1555                         delete iter->second;
1556                         chanlist.erase(iter);
1557                 }
1558         }
1559 }
1560
1561
1562 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1563 {
1564         if ((!src) || (!user) || (!Ptr) || (!reason))
1565         {
1566                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1567                 return;
1568         }
1569
1570         int i = 0;
1571         int created = 0;
1572
1573         if ((!Ptr) || (!user) || (!src))
1574         {
1575                 return;
1576         }
1577
1578         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1579
1580         if (!has_channel(user,Ptr))
1581         {
1582                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1583                 return;
1584         }
1585         if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1586         {
1587                 if (cstatus(src,Ptr) == STATUS_HOP)
1588                 {
1589                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1590                 }
1591                 else
1592                 {
1593                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1594                 }
1595                 
1596                 return;
1597         }
1598         
1599         for (int i =0; i != MAXCHANS; i++)
1600         {
1601                 /* zap it from the channel list of the user */
1602                 if (user->chans[i].channel)
1603                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1604                 {
1605                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1606                         user->chans[i].uc_modes = 0;
1607                         user->chans[i].channel = NULL;
1608                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1609                         break;
1610                 }
1611         }
1612         
1613         /* if there are no users left on the channel */
1614         if (!usercount(Ptr))
1615         {
1616                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1617
1618                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1619
1620                 /* kill the record */
1621                 if (iter != chanlist.end())
1622                 {
1623                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1624                         delete iter->second;
1625                         chanlist.erase(iter);
1626                 }
1627         }
1628 }
1629
1630
1631
1632
1633 /* This function pokes and hacks at a parameter list like the following:
1634  *
1635  * PART #winbot, #darkgalaxy :m00!
1636  *
1637  * to turn it into a series of individual calls like this:
1638  *
1639  * PART #winbot :m00!
1640  * PART #darkgalaxy :m00!
1641  *
1642  * The seperate calls are sent to a callback function provided by the caller
1643  * (the caller will usually call itself recursively). The callback function
1644  * must be a command handler. Calling this function on a line with no list causes
1645  * no action to be taken. You must provide a starting and ending parameter number
1646  * where the range of the list can be found, useful if you have a terminating
1647  * parameter as above which is actually not part of the list, or parameters
1648  * before the actual list as well. This code is used by many functions which
1649  * can function as "one to list" (see the RFC) */
1650
1651 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1652 {
1653         char plist[MAXBUF];
1654         char *param;
1655         char *pars[32];
1656         char blog[32][MAXBUF];
1657         char blog2[32][MAXBUF];
1658         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1659         char keystr[MAXBUF];
1660         char moo[MAXBUF];
1661
1662         for (int i = 0; i <32; i++)
1663                 strcpy(blog[i],"");
1664
1665         for (int i = 0; i <32; i++)
1666                 strcpy(blog2[i],"");
1667
1668         strcpy(moo,"");
1669         for (int i = 0; i <10; i++)
1670         {
1671                 if (!parameters[i])
1672                 {
1673                         parameters[i] = moo;
1674                 }
1675         }
1676         if (joins)
1677         {
1678                 if (pcnt > 1) /* we have a key to copy */
1679                 {
1680                         strcpy(keystr,parameters[1]);
1681                 }
1682         }
1683
1684         if (!parameters[start])
1685         {
1686                 return 0;
1687         }
1688         if (!strchr(parameters[start],','))
1689         {
1690                 return 0;
1691         }
1692         strcpy(plist,"");
1693         for (int i = start; i <= end; i++)
1694         {
1695                 if (parameters[i])
1696                 {
1697                         strcat(plist,parameters[i]);
1698                 }
1699         }
1700         
1701         j = 0;
1702         param = plist;
1703
1704         t = strlen(plist);
1705         for (int i = 0; i < t; i++)
1706         {
1707                 if (plist[i] == ',')
1708                 {
1709                         plist[i] = '\0';
1710                         strcpy(blog[j++],param);
1711                         param = plist+i+1;
1712                         if (j>20)
1713                         {
1714                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1715                                 return 1;
1716                         }
1717                 }
1718         }
1719         strcpy(blog[j++],param);
1720         total = j;
1721
1722         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1723         {
1724                 strcat(keystr,",");
1725         }
1726         
1727         if ((joins) && (keystr))
1728         {
1729                 if (strchr(keystr,','))
1730                 {
1731                         j = 0;
1732                         param = keystr;
1733                         t2 = strlen(keystr);
1734                         for (int i = 0; i < t2; i++)
1735                         {
1736                                 if (keystr[i] == ',')
1737                                 {
1738                                         keystr[i] = '\0';
1739                                         strcpy(blog2[j++],param);
1740                                         param = keystr+i+1;
1741                                 }
1742                         }
1743                         strcpy(blog2[j++],param);
1744                         total2 = j;
1745                 }
1746         }
1747
1748         for (j = 0; j < total; j++)
1749         {
1750                 if (blog[j])
1751                 {
1752                         pars[0] = blog[j];
1753                 }
1754                 for (q = end; q < pcnt-1; q++)
1755                 {
1756                         if (parameters[q+1])
1757                         {
1758                                 pars[q-end+1] = parameters[q+1];
1759                         }
1760                 }
1761                 if ((joins) && (parameters[1]))
1762                 {
1763                         if (pcnt > 1)
1764                         {
1765                                 pars[1] = blog2[j];
1766                         }
1767                         else
1768                         {
1769                                 pars[1] = NULL;
1770                         }
1771                 }
1772                 /* repeatedly call the function with the hacked parameter list */
1773                 if ((joins) && (pcnt > 1))
1774                 {
1775                         if (pars[1])
1776                         {
1777                                 // pars[1] already set up and containing key from blog2[j]
1778                                 fn(pars,2,u);
1779                         }
1780                         else
1781                         {
1782                                 pars[1] = parameters[1];
1783                                 fn(pars,2,u);
1784                         }
1785                 }
1786                 else
1787                 {
1788                         fn(pars,pcnt-(end-start),u);
1789                 }
1790         }
1791
1792         return 1;
1793 }
1794
1795
1796
1797 void kill_link(userrec *user,const char* r)
1798 {
1799         user_hash::iterator iter = clientlist.find(user->nick);
1800         
1801         char reason[MAXBUF];
1802         
1803         strncpy(reason,r,MAXBUF);
1804
1805         if (strlen(reason)>MAXQUIT)
1806         {
1807                 reason[MAXQUIT-1] = '\0';
1808         }
1809
1810         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1811         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1812         log(DEBUG,"closing fd %d",user->fd);
1813
1814         /* bugfix, cant close() a nonblocking socket (sux!) */
1815         if (user->registered == 7) {
1816                 FOREACH_MOD OnUserQuit(user);
1817                 WriteCommonExcept(user,"QUIT :%s",reason);
1818
1819                 // Q token must go to ALL servers!!!
1820                 char buffer[MAXBUF];
1821                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1822                 NetSendToAll(buffer);
1823         }
1824
1825         /* push the socket on a stack of sockets due to be closed at the next opportunity
1826          * 'Client exited' is an exception to this as it means the client side has already
1827          * closed the socket, we don't need to do it.
1828          */
1829         fd_reap.push_back(user->fd);
1830         
1831         bool do_purge = false;
1832         
1833         if (user->registered == 7) {
1834                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1835                 AddWhoWas(user);
1836         }
1837
1838         if (iter != clientlist.end())
1839         {
1840                 log(DEBUG,"deleting user hash value %d",iter->second);
1841                 if ((iter->second) && (user->registered == 7)) {
1842                         delete iter->second;
1843                 }
1844                 clientlist.erase(iter);
1845         }
1846
1847         if (user->registered == 7) {
1848                 purge_empty_chans();
1849         }
1850 }
1851
1852 void kill_link_silent(userrec *user,const char* r)
1853 {
1854         user_hash::iterator iter = clientlist.find(user->nick);
1855         
1856         char reason[MAXBUF];
1857         
1858         strncpy(reason,r,MAXBUF);
1859
1860         if (strlen(reason)>MAXQUIT)
1861         {
1862                 reason[MAXQUIT-1] = '\0';
1863         }
1864
1865         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1866         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1867         log(DEBUG,"closing fd %d",user->fd);
1868
1869         /* bugfix, cant close() a nonblocking socket (sux!) */
1870         if (user->registered == 7) {
1871                 FOREACH_MOD OnUserQuit(user);
1872                 WriteCommonExcept(user,"QUIT :%s",reason);
1873
1874                 // Q token must go to ALL servers!!!
1875                 char buffer[MAXBUF];
1876                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1877                 NetSendToAll(buffer);
1878         }
1879
1880         /* push the socket on a stack of sockets due to be closed at the next opportunity
1881          * 'Client exited' is an exception to this as it means the client side has already
1882          * closed the socket, we don't need to do it.
1883          */
1884         fd_reap.push_back(user->fd);
1885         
1886         bool do_purge = false;
1887         
1888         if (iter != clientlist.end())
1889         {
1890                 log(DEBUG,"deleting user hash value %d",iter->second);
1891                 if ((iter->second) && (user->registered == 7)) {
1892                         delete iter->second;
1893                 }
1894                 clientlist.erase(iter);
1895         }
1896
1897         if (user->registered == 7) {
1898                 purge_empty_chans();
1899         }
1900 }
1901
1902
1903
1904 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1905
1906 char* Passwd(userrec *user)
1907 {
1908         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1909         {
1910                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1911                 {
1912                         return i->pass;
1913                 }
1914         }
1915         return "";
1916 }
1917
1918 bool IsDenied(userrec *user)
1919 {
1920         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1921         {
1922                 if (match(user->host,i->host) && (i->type == CC_DENY))
1923                 {
1924                         return true;
1925                 }
1926         }
1927         return false;
1928 }
1929
1930
1931
1932
1933 /* sends out an error notice to all connected clients (not to be used
1934  * lightly!) */
1935
1936 void send_error(char *s)
1937 {
1938         log(DEBUG,"send_error: %s",s);
1939         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1940         {
1941                 if (isnick(i->second->nick))
1942                 {
1943                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1944                 }
1945                 else
1946                 {
1947                         // fix - unregistered connections receive ERROR, not NOTICE
1948                         Write(i->second->fd,"ERROR :%s",s);
1949                 }
1950         }
1951 }
1952
1953 void Error(int status)
1954 {
1955         signal (SIGALRM, SIG_IGN);
1956         signal (SIGPIPE, SIG_IGN);
1957         signal (SIGTERM, SIG_IGN);
1958         signal (SIGABRT, SIG_IGN);
1959         signal (SIGSEGV, SIG_IGN);
1960         signal (SIGURG, SIG_IGN);
1961         signal (SIGKILL, SIG_IGN);
1962         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1963         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1964         exit(status);
1965 }
1966
1967
1968 int main(int argc, char *argv[])
1969 {
1970         Start();
1971         srand(time(NULL));
1972         log(DEBUG,"*** InspIRCd starting up!");
1973         if (!FileExists(CONFIG_FILE))
1974         {
1975                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1976                 log(DEBUG,"main: no config");
1977                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1978                 Exit(ERROR);
1979         }
1980         if (argc > 1) {
1981                 if (!strcmp(argv[1],"-nofork")) {
1982                         nofork = true;
1983                 }
1984         }
1985         if (InspIRCd() == ERROR)
1986         {
1987                 log(DEBUG,"main: daemon function bailed");
1988                 printf("ERROR: could not initialise. Shutting down.\n");
1989                 Exit(ERROR);
1990         }
1991         Exit(TRUE);
1992         return 0;
1993 }
1994
1995 template<typename T> inline string ConvToStr(const T &in)
1996 {
1997         stringstream tmp;
1998         if (!(tmp << in)) return string();
1999         return tmp.str();
2000 }
2001
2002 /* re-allocates a nick in the user_hash after they change nicknames,
2003  * returns a pointer to the new user as it may have moved */
2004
2005 userrec* ReHashNick(char* Old, char* New)
2006 {
2007         user_hash::iterator newnick;
2008         user_hash::iterator oldnick = clientlist.find(Old);
2009
2010         log(DEBUG,"ReHashNick: %s %s",Old,New);
2011         
2012         if (!strcasecmp(Old,New))
2013         {
2014                 log(DEBUG,"old nick is new nick, skipping");
2015                 return oldnick->second;
2016         }
2017         
2018         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2019
2020         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2021
2022         clientlist[New] = new userrec();
2023         clientlist[New] = oldnick->second;
2024         /*delete oldnick->second; */
2025         clientlist.erase(oldnick);
2026
2027         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2028         
2029         return clientlist[New];
2030 }
2031
2032 /* adds or updates an entry in the whowas list */
2033 void AddWhoWas(userrec* u)
2034 {
2035         user_hash::iterator iter = whowas.find(u->nick);
2036         userrec *a = new userrec();
2037         strcpy(a->nick,u->nick);
2038         strcpy(a->ident,u->ident);
2039         strcpy(a->dhost,u->dhost);
2040         strcpy(a->host,u->host);
2041         strcpy(a->fullname,u->fullname);
2042         strcpy(a->server,u->server);
2043         a->signon = u->signon;
2044
2045         /* MAX_WHOWAS:   max number of /WHOWAS items
2046          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2047          *               can be replaced by a newer one
2048          */
2049         
2050         if (iter == whowas.end())
2051         {
2052                 if (whowas.size() == WHOWAS_MAX)
2053                 {
2054                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2055                         {
2056                                 // 3600 seconds in an hour ;)
2057                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2058                                 {
2059                                         delete i->second;
2060                                         i->second = a;
2061                                         log(DEBUG,"added WHOWAS entry, purged an old record");
2062                                         return;
2063                                 }
2064                         }
2065                 }
2066                 else
2067                 {
2068                         log(DEBUG,"added fresh WHOWAS entry");
2069                         whowas[a->nick] = a;
2070                 }
2071         }
2072         else
2073         {
2074                 log(DEBUG,"updated WHOWAS entry");
2075                 delete iter->second;
2076                 iter->second = a;
2077         }
2078 }
2079
2080
2081 /* add a client connection to the sockets list */
2082 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2083 {
2084         int i;
2085         int blocking = 1;
2086         char resolved[MAXBUF];
2087         string tempnick;
2088         char tn2[MAXBUF];
2089         user_hash::iterator iter;
2090
2091         tempnick = ConvToStr(socket) + "-unknown";
2092         sprintf(tn2,"%d-unknown",socket);
2093
2094         iter = clientlist.find(tempnick);
2095
2096         if (iter != clientlist.end()) return;
2097
2098         /*
2099          * It is OK to access the value here this way since we know
2100          * it exists, we just created it above.
2101          *
2102          * At NO other time should you access a value in a map or a
2103          * hash_map this way.
2104          */
2105         clientlist[tempnick] = new userrec();
2106
2107         NonBlocking(socket);
2108         log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2109
2110         clientlist[tempnick]->fd = socket;
2111         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2112         strncpy(clientlist[tempnick]->host, host,160);
2113         strncpy(clientlist[tempnick]->dhost, host,160);
2114         strncpy(clientlist[tempnick]->server, ServerName,256);
2115         strncpy(clientlist[tempnick]->ident, "unknown",9);
2116         clientlist[tempnick]->registered = 0;
2117         clientlist[tempnick]->signon = time(NULL);
2118         clientlist[tempnick]->nping = time(NULL)+240;
2119         clientlist[tempnick]->lastping = 1;
2120         clientlist[tempnick]->port = port;
2121         strncpy(clientlist[tempnick]->ip,ip,32);
2122
2123         if (iscached)
2124         {
2125                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2126         }
2127         else
2128         {
2129                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2130         }
2131
2132         // set the registration timeout for this user
2133         unsigned long class_regtimeout = 90;
2134         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2135         {
2136                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2137                 {
2138                         class_regtimeout = (unsigned long)i->registration_timeout;
2139                         break;
2140                 }
2141         }
2142
2143         int class_flood = 0;
2144         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2145         {
2146                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2147                 {
2148                         class_flood = i->flood;
2149                         break;
2150                 }
2151         }
2152
2153         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2154         clientlist[tempnick]->flood = class_flood;
2155
2156         for (int i = 0; i < MAXCHANS; i++)
2157         {
2158                 clientlist[tempnick]->chans[i].channel = NULL;
2159                 clientlist[tempnick]->chans[i].uc_modes = 0;
2160         }
2161
2162         if (clientlist.size() == MAXCLIENTS)
2163                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2164                 
2165         char* r = matches_zline(ip);
2166         if (r)
2167         {
2168                 char reason[MAXBUF];
2169                 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2170                 kill_link(clientlist[tempnick],reason);
2171         }
2172 }
2173
2174
2175 int usercnt(void)
2176 {
2177         return clientlist.size();
2178 }
2179
2180
2181 int usercount_invisible(void)
2182 {
2183         int c = 0;
2184
2185         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2186         {
2187                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2188         }
2189         return c;
2190 }
2191
2192 int usercount_opers(void)
2193 {
2194         int c = 0;
2195
2196         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2197         {
2198                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2199         }
2200         return c;
2201 }
2202
2203 int usercount_unknown(void)
2204 {
2205         int c = 0;
2206
2207         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2208         {
2209                 if ((i->second->fd) && (i->second->registered != 7))
2210                         c++;
2211         }
2212         return c;
2213 }
2214
2215 long chancount(void)
2216 {
2217         return chanlist.size();
2218 }
2219
2220 long count_servs(void)
2221 {
2222         int c = 0;
2223         //for (int j = 0; j < 255; j++)
2224         //{
2225         //      if (servers[j] != NULL)
2226         //              c++;
2227         //}
2228         return c;
2229 }
2230
2231 long servercount(void)
2232 {
2233         return count_servs()+1;
2234 }
2235
2236 long local_count()
2237 {
2238         int c = 0;
2239         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2240         {
2241                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2242         }
2243         return c;
2244 }
2245
2246
2247 void ShowMOTD(userrec *user)
2248 {
2249         if (!MOTD.size())
2250         {
2251                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2252                 return;
2253         }
2254         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2255         for (int i = 0; i != MOTD.size(); i++)
2256         {
2257                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2258         }
2259         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2260 }
2261
2262 void ShowRULES(userrec *user)
2263 {
2264         if (!RULES.size())
2265         {
2266                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2267                 return;
2268         }
2269         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2270         for (int i = 0; i != RULES.size(); i++)
2271         {
2272                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2273         }
2274         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2275 }
2276
2277 /* shows the message of the day, and any other on-logon stuff */
2278 void ConnectUser(userrec *user)
2279 {
2280         user->registered = 7;
2281         user->idle_lastmsg = time(NULL);
2282         log(DEBUG,"ConnectUser: %s",user->nick);
2283
2284         if (strcmp(Passwd(user),"") && (!user->haspassed))
2285         {
2286                 kill_link(user,"Invalid password");
2287                 return;
2288         }
2289         if (IsDenied(user))
2290         {
2291                 kill_link(user,"Unauthorised connection");
2292                 return;
2293         }
2294
2295         char match_against[MAXBUF];
2296         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2297         char* r = matches_gline(match_against);
2298         if (r)
2299         {
2300                 char reason[MAXBUF];
2301                 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2302                 kill_link_silent(user,reason);
2303                 return;
2304         }
2305
2306         r = matches_kline(user->host);
2307         if (r)
2308         {
2309                 char reason[MAXBUF];
2310                 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2311                 kill_link_silent(user,reason);
2312                 return;
2313         }
2314
2315         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2316         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2317         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2318         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2319         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2320         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);
2321         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);
2322         ShowMOTD(user);
2323         FOREACH_MOD OnUserConnect(user);
2324         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2325         
2326         char buffer[MAXBUF];
2327         snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2328         NetSendToAll(buffer);
2329 }
2330
2331 void handle_version(char **parameters, int pcnt, userrec *user)
2332 {
2333         char Revision[] = "$Revision$";
2334
2335         char *s1 = Revision;
2336         char *savept;
2337         char *v1 = strtok_r(s1," ",&savept);
2338         s1 = savept;
2339         char *v2 = strtok_r(s1," ",&savept);
2340         s1 = savept;
2341         
2342         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2343 }
2344
2345
2346 // calls a handler function for a command
2347
2348 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2349 {
2350                 for (int i = 0; i < cmdlist.size(); i++)
2351                 {
2352                         if (!strcasecmp(cmdlist[i].command,commandname))
2353                         {
2354                                 if (cmdlist[i].handler_function)
2355                                 {
2356                                         if (pcnt>=cmdlist[i].min_params)
2357                                         {
2358                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2359                                                 {
2360                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2361                                                 }
2362                                         }
2363                                 }
2364                         }
2365                 }
2366 }
2367
2368 void DoSplitEveryone()
2369 {
2370         bool go_again = true;
2371         while (go_again)
2372         {
2373                 go_again = false;
2374                 for (int i = 0; i < 32; i++)
2375                 {
2376                         if (me[i] != NULL)
2377                         {
2378                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2379                                 {
2380                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2381                                         {
2382                                                 j->routes.clear();
2383                                                 j->CloseConnection();
2384                                                 me[i]->connectors.erase(j);
2385                                                 go_again = true;
2386                                                 break;
2387                                         }
2388                                 }
2389                         }
2390                 }
2391         }
2392         log(DEBUG,"Removed server. Will remove clients...");
2393         // iterate through the userlist and remove all users on this server.
2394         // because we're dealing with a mesh, we dont have to deal with anything
2395         // "down-route" from this server (nice huh)
2396         go_again = true;
2397         char reason[MAXBUF];
2398         while (go_again)
2399         {
2400                 go_again = false;
2401                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2402                 {
2403                         if (strcasecmp(u->second->server,ServerName))
2404                         {
2405                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2406                                 kill_link(u->second,reason);
2407                                 go_again = true;
2408                                 break;
2409                         }
2410                 }
2411         }
2412 }
2413
2414
2415
2416 char islast(const char* s)
2417 {
2418         char c = '`';
2419         for (int j = 0; j < 32; j++)
2420         {
2421                 if (me[j] != NULL)
2422                 {
2423                         for (int k = 0; k < me[j]->connectors.size(); k++)
2424                         {
2425                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2426                                 {
2427                                         c = '|';
2428                                 }
2429                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2430                                 {
2431                                         c = '`';
2432                                 }
2433                         }
2434                 }
2435         }
2436         return c;
2437 }
2438
2439 long map_count(const char* s)
2440 {
2441         int c = 0;
2442         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2443         {
2444                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2445         }
2446         return c;
2447 }
2448
2449
2450 void force_nickchange(userrec* user,const char* newnick)
2451 {
2452         char nick[MAXBUF];
2453         int MOD_RESULT = 0;
2454         
2455         strcpy(nick,"");
2456
2457         FOREACH_RESULT(OnUserPreNick(user,newnick));
2458         if (MOD_RESULT) {
2459                 kill_link(user,"Nickname collision");
2460                 return;
2461         }
2462         if (matches_qline(newnick))
2463         {
2464                 kill_link(user,"Nickname collision");
2465                 return;
2466         }
2467         
2468         if (user)
2469         {
2470                 if (newnick)
2471                 {
2472                         strncpy(nick,newnick,MAXBUF);
2473                 }
2474                 if (user->registered == 7)
2475                 {
2476                         char* pars[1];
2477                         pars[0] = nick;
2478                         handle_nick(pars,1,user);
2479                 }
2480         }
2481 }
2482                                 
2483
2484 int process_parameters(char **command_p,char *parameters)
2485 {
2486         int i = 0;
2487         int j = 0;
2488         int q = 0;
2489         q = strlen(parameters);
2490         if (!q)
2491         {
2492                 /* no parameters, command_p invalid! */
2493                 return 0;
2494         }
2495         if (parameters[0] == ':')
2496         {
2497                 command_p[0] = parameters+1;
2498                 return 1;
2499         }
2500         if (q)
2501         {
2502                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2503                 {
2504                         /* only one parameter */
2505                         command_p[0] = parameters;
2506                         if (parameters[0] == ':')
2507                         {
2508                                 if (strchr(parameters,' ') != NULL)
2509                                 {
2510                                         command_p[0]++;
2511                                 }
2512                         }
2513                         return 1;
2514                 }
2515         }
2516         command_p[j++] = parameters;
2517         for (int i = 0; i <= q; i++)
2518         {
2519                 if (parameters[i] == ' ')
2520                 {
2521                         command_p[j++] = parameters+i+1;
2522                         parameters[i] = '\0';
2523                         if (command_p[j-1][0] == ':')
2524                         {
2525                                 *command_p[j-1]++; /* remove dodgy ":" */
2526                                 break;
2527                                 /* parameter like this marks end of the sequence */
2528                         }
2529                 }
2530         }
2531         return j; /* returns total number of items in the list */
2532 }
2533
2534 void process_command(userrec *user, char* cmd)
2535 {
2536         char *parameters;
2537         char *command;
2538         char *command_p[127];
2539         char p[MAXBUF], temp[MAXBUF];
2540         int i, j, items, cmd_found;
2541
2542         for (int i = 0; i < 127; i++)
2543                 command_p[i] = NULL;
2544
2545         if (!user)
2546         {
2547                 return;
2548         }
2549         if (!cmd)
2550         {
2551                 return;
2552         }
2553         if (!strcmp(cmd,""))
2554         {
2555                 return;
2556         }
2557         
2558         int total_params = 0;
2559         if (strlen(cmd)>2)
2560         {
2561                 for (int q = 0; q < strlen(cmd)-1; q++)
2562                 {
2563                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2564                         {
2565                                 total_params++;
2566                                 // found a 'trailing', we dont count them after this.
2567                                 break;
2568                         }
2569                         if (cmd[q] == ' ')
2570                                 total_params++;
2571                 }
2572         }
2573         
2574         // another phidjit bug...
2575         if (total_params > 126)
2576         {
2577                 kill_link(user,"Protocol violation (1)");
2578                 return;
2579         }
2580         
2581         strcpy(temp,cmd);
2582
2583         std::string tmp = cmd;
2584         for (int i = 0; i <= MODCOUNT; i++)
2585         {
2586                 std::string oldtmp = tmp;
2587                 modules[i]->OnServerRaw(tmp,true);
2588                 if (oldtmp != tmp)
2589                 {
2590                         log(DEBUG,"A Module changed the input string!");
2591                         log(DEBUG,"New string: %s",tmp.c_str());
2592                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2593                         break;
2594                 }
2595         }
2596         strncpy(cmd,tmp.c_str(),MAXBUF);
2597         strcpy(temp,cmd);
2598
2599         if (!strchr(cmd,' '))
2600         {
2601                 /* no parameters, lets skip the formalities and not chop up
2602                  * the string */
2603                 log(DEBUG,"About to preprocess command with no params");
2604                 items = 0;
2605                 command_p[0] = NULL;
2606                 parameters = NULL;
2607                 for (int i = 0; i <= strlen(cmd); i++)
2608                 {
2609                         cmd[i] = toupper(cmd[i]);
2610                 }
2611                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2612                 command = cmd;
2613         }
2614         else
2615         {
2616                 strcpy(cmd,"");
2617                 j = 0;
2618                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2619                 for (int i = 0; i < strlen(temp); i++)
2620                 {
2621                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2622                         {
2623                                 cmd[j++] = temp[i];
2624                                 cmd[j] = 0;
2625                         }
2626                 }
2627                 /* split the full string into a command plus parameters */
2628                 parameters = p;
2629                 strcpy(p," ");
2630                 command = cmd;
2631                 if (strchr(cmd,' '))
2632                 {
2633                         for (int i = 0; i <= strlen(cmd); i++)
2634                         {
2635                                 /* capitalise the command ONLY, leave params intact */
2636                                 cmd[i] = toupper(cmd[i]);
2637                                 /* are we nearly there yet?! :P */
2638                                 if (cmd[i] == ' ')
2639                                 {
2640                                         command = cmd;
2641                                         parameters = cmd+i+1;
2642                                         cmd[i] = '\0';
2643                                         break;
2644                                 }
2645                         }
2646                 }
2647                 else
2648                 {
2649                         for (int i = 0; i <= strlen(cmd); i++)
2650                         {
2651                                 cmd[i] = toupper(cmd[i]);
2652                         }
2653                 }
2654
2655         }
2656         cmd_found = 0;
2657         
2658         if (strlen(command)>MAXCOMMAND)
2659         {
2660                 kill_link(user,"Protocol violation (2)");
2661                 return;
2662         }
2663         
2664         for (int x = 0; x < strlen(command); x++)
2665         {
2666                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2667                 {
2668                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2669                         {
2670                                 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2671                                 {
2672                                         kill_link(user,"Protocol violation (3)");
2673                                         return;
2674                                 }
2675                         }
2676                 }
2677         }
2678
2679         for (int i = 0; i != cmdlist.size(); i++)
2680         {
2681                 if (strcmp(cmdlist[i].command,""))
2682                 {
2683                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2684                         {
2685                                 log(DEBUG,"Found matching command");
2686
2687                                 if (parameters)
2688                                 {
2689                                         if (strcmp(parameters,""))
2690                                         {
2691                                                 items = process_parameters(command_p,parameters);
2692                                         }
2693                                         else
2694                                         {
2695                                                 items = 0;
2696                                                 command_p[0] = NULL;
2697                                         }
2698                                 }
2699                                 else
2700                                 {
2701                                         items = 0;
2702                                         command_p[0] = NULL;
2703                                 }
2704                                 
2705                                 if (user)
2706                                 {
2707                                         log(DEBUG,"Processing command");
2708                                         
2709                                         /* activity resets the ping pending timer */
2710                                         user->nping = time(NULL) + 120;
2711                                         if ((items) < cmdlist[i].min_params)
2712                                         {
2713                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2714                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2715                                                 return;
2716                                         }
2717                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2718                                         {
2719                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2720                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2721                                                 cmd_found = 1;
2722                                                 return;
2723                                         }
2724                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2725                                          * deny command! */
2726                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2727                                         {
2728                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2729                                                 {
2730                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2731                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2732                                                         return;
2733                                                 }
2734                                         }
2735                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2736                                         {
2737                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2738                                                 if (cmdlist[i].handler_function)
2739                                                 {
2740                                                         /* ikky /stats counters */
2741                                                         if (temp)
2742                                                         {
2743                                                                 if (user)
2744                                                                 {
2745                                                                         user->bytes_in += strlen(temp);
2746                                                                         user->cmds_in++;
2747                                                                 }
2748                                                                 cmdlist[i].use_count++;
2749                                                                 cmdlist[i].total_bytes+=strlen(temp);
2750                                                         }
2751
2752                                                         /* WARNING: nothing may come after the
2753                                                          * command handler call, as the handler
2754                                                          * may free the user structure! */
2755
2756                                                         cmdlist[i].handler_function(command_p,items,user);
2757                                                 }
2758                                                 return;
2759                                         }
2760                                         else
2761                                         {
2762                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2763                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2764                                                 return;
2765                                         }
2766                                 }
2767                                 cmd_found = 1;
2768                         }
2769                 }
2770         }
2771         if ((!cmd_found) && (user))
2772         {
2773                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2774                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2775         }
2776 }
2777
2778
2779 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2780 {
2781         command_t comm;
2782         /* create the command and push it onto the table */     
2783         strcpy(comm.command,cmd);
2784         comm.handler_function = f;
2785         comm.flags_needed = flags;
2786         comm.min_params = minparams;
2787         comm.use_count = 0;
2788         comm.total_bytes = 0;
2789         cmdlist.push_back(comm);
2790         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2791 }
2792
2793 void SetupCommandTable(void)
2794 {
2795         createcommand("USER",handle_user,0,4);
2796         createcommand("NICK",handle_nick,0,1);
2797         createcommand("QUIT",handle_quit,0,0);
2798         createcommand("VERSION",handle_version,0,0);
2799         createcommand("PING",handle_ping,0,1);
2800         createcommand("PONG",handle_pong,0,1);
2801         createcommand("ADMIN",handle_admin,0,0);
2802         createcommand("PRIVMSG",handle_privmsg,0,2);
2803         createcommand("INFO",handle_info,0,0);
2804         createcommand("TIME",handle_time,0,0);
2805         createcommand("WHOIS",handle_whois,0,1);
2806         createcommand("WALLOPS",handle_wallops,'o',1);
2807         createcommand("NOTICE",handle_notice,0,2);
2808         createcommand("JOIN",handle_join,0,1);
2809         createcommand("NAMES",handle_names,0,1);
2810         createcommand("PART",handle_part,0,1);
2811         createcommand("KICK",handle_kick,0,2);
2812         createcommand("MODE",handle_mode,0,1);
2813         createcommand("TOPIC",handle_topic,0,1);
2814         createcommand("WHO",handle_who,0,1);
2815         createcommand("MOTD",handle_motd,0,0);
2816         createcommand("RULES",handle_rules,0,0);
2817         createcommand("OPER",handle_oper,0,2);
2818         createcommand("LIST",handle_list,0,0);
2819         createcommand("DIE",handle_die,'o',1);
2820         createcommand("RESTART",handle_restart,'o',1);
2821         createcommand("KILL",handle_kill,'o',2);
2822         createcommand("REHASH",handle_rehash,'o',0);
2823         createcommand("LUSERS",handle_lusers,0,0);
2824         createcommand("STATS",handle_stats,0,1);
2825         createcommand("USERHOST",handle_userhost,0,1);
2826         createcommand("AWAY",handle_away,0,0);
2827         createcommand("ISON",handle_ison,0,0);
2828         createcommand("SUMMON",handle_summon,0,0);
2829         createcommand("USERS",handle_users,0,0);
2830         createcommand("INVITE",handle_invite,0,2);
2831         createcommand("PASS",handle_pass,0,1);
2832         createcommand("TRACE",handle_trace,'o',0);
2833         createcommand("WHOWAS",handle_whowas,0,1);
2834         createcommand("CONNECT",handle_connect,'o',1);
2835         createcommand("SQUIT",handle_squit,'o',0);
2836         createcommand("MODULES",handle_modules,'o',0);
2837         createcommand("LINKS",handle_links,0,0);
2838         createcommand("MAP",handle_map,0,0);
2839         createcommand("KLINE",handle_kline,'o',1);
2840         createcommand("GLINE",handle_gline,'o',1);
2841         createcommand("ZLINE",handle_zline,'o',1);
2842         createcommand("QLINE",handle_qline,'o',1);
2843 }
2844
2845 void process_buffer(const char* cmdbuf,userrec *user)
2846 {
2847         if (!user)
2848         {
2849                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2850                 return;
2851         }
2852         char cmd[MAXBUF];
2853         int i;
2854         if (!cmdbuf)
2855         {
2856                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2857                 return;
2858         }
2859         if (!strcmp(cmdbuf,""))
2860         {
2861                 return;
2862         }
2863         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2864
2865         strncpy(cmd,cmdbuf,MAXBUF);
2866         if (!strcmp(cmd,""))
2867         {
2868                 return;
2869         }
2870         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2871         {
2872                 cmd[strlen(cmd)-1] = '\0';
2873         }
2874         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2875         {
2876                 cmd[strlen(cmd)-1] = '\0';
2877         }
2878
2879         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2880         {
2881                 cmd[strlen(cmd)-1] = '\0';
2882         }
2883
2884         if (!strcmp(cmd,""))
2885         {
2886                 return;
2887         }
2888         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2889         tidystring(cmd);
2890         if ((user) && (cmd))
2891         {
2892                 process_command(user,cmd);
2893         }
2894 }
2895
2896 void DoSync(serverrec* serv, char* tcp_host)
2897 {
2898         char data[MAXBUF];
2899         log(DEBUG,"Sending sync");
2900         // send start of sync marker: Y <timestamp>
2901         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2902         // except the ones its receiving it from.
2903         snprintf(data,MAXBUF,"Y %d",time(NULL));
2904         serv->SendPacket(data,tcp_host);
2905         // send users and channels
2906         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2907         {
2908                 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
2909                 serv->SendPacket(data,tcp_host);
2910                 if (strcmp(chlist(u->second),""))
2911                 {
2912                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2913                         serv->SendPacket(data,tcp_host);
2914                 }
2915         }
2916         // send channel modes, topics etc...
2917         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2918         {
2919                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2920                 serv->SendPacket(data,tcp_host);
2921                 if (strcmp(c->second->topic,""))
2922                 {
2923                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2924                         serv->SendPacket(data,tcp_host);
2925                 }
2926                 // send current banlist
2927                 
2928                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2929                 {
2930                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2931                         serv->SendPacket(data,tcp_host);
2932                 }
2933         }
2934         // sync global zlines, glines, etc
2935         sync_xlines(serv,tcp_host);
2936         snprintf(data,MAXBUF,"F %d",time(NULL));
2937         serv->SendPacket(data,tcp_host);
2938         log(DEBUG,"Sent sync");
2939         // ircd sends its serverlist after the end of sync here
2940 }
2941
2942
2943 void NetSendMyRoutingTable()
2944 {
2945         // send out a line saying what is reachable to us.
2946         // E.g. if A is linked to B C and D, send out:
2947         // $ A B C D
2948         // if its only linked to B and D send out:
2949         // $ A B D
2950         // if it has no links, dont even send out the line at all.
2951         char buffer[MAXBUF];
2952         sprintf(buffer,"$ %s",ServerName);
2953         bool sendit = false;
2954         for (int i = 0; i < 32; i++)
2955         {
2956                 if (me[i] != NULL)
2957                 {
2958                         for (int j = 0; j < me[i]->connectors.size(); j++)
2959                         {
2960                                 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2961                                 {
2962                                         strncat(buffer," ",MAXBUF);
2963                                         strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2964                                         sendit = true;
2965                                 }
2966                         }
2967                 }
2968         }
2969         if (sendit)
2970                 NetSendToAll(buffer);
2971 }
2972
2973
2974 void DoSplit(const char* params)
2975 {
2976         bool go_again = true;
2977         while (go_again)
2978         {
2979                 go_again = false;
2980                 for (int i = 0; i < 32; i++)
2981                 {
2982                         if (me[i] != NULL)
2983                         {
2984                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2985                                 {
2986                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2987                                         {
2988                                                 j->routes.clear();
2989                                                 j->CloseConnection();
2990                                                 me[i]->connectors.erase(j);
2991                                                 go_again = true;
2992                                                 break;
2993                                         }
2994                                 }
2995                         }
2996                 }
2997         }
2998         log(DEBUG,"Removed server. Will remove clients...");
2999         // iterate through the userlist and remove all users on this server.
3000         // because we're dealing with a mesh, we dont have to deal with anything
3001         // "down-route" from this server (nice huh)
3002         go_again = true;
3003         char reason[MAXBUF];
3004         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3005         while (go_again)
3006         {
3007                 go_again = false;
3008                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3009                 {
3010                         if (!strcasecmp(u->second->server,params))
3011                         {
3012                                 kill_link(u->second,reason);
3013                                 go_again = true;
3014                                 break;
3015                         }
3016                 }
3017         }
3018 }
3019
3020 // removes a server. Will NOT remove its users!
3021
3022 void RemoveServer(const char* name)
3023 {
3024         bool go_again = true;
3025         while (go_again)
3026         {
3027                 go_again = false;
3028                 for (int i = 0; i < 32; i++)
3029                 {
3030                         if (me[i] != NULL)
3031                         {
3032                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3033                                 {
3034                                         if (!strcasecmp(j->GetServerName().c_str(),name))
3035                                         {
3036                                                 j->routes.clear();
3037                                                 j->CloseConnection();
3038                                                 me[i]->connectors.erase(j);
3039                                                 go_again = true;
3040                                                 break;
3041                                         }
3042                                 }
3043                         }
3044                 }
3045         }
3046 }
3047
3048
3049 int reap_counter = 0;
3050
3051 int InspIRCd(void)
3052 {
3053         struct sockaddr_in client, server;
3054         char addrs[MAXBUF][255];
3055         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3056         socklen_t length;
3057         int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3058         int selectResult = 0, selectResult2 = 0;
3059         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3060         char resolvedHost[MAXBUF];
3061         fd_set selectFds;
3062         struct timeval tv;
3063
3064         log_file = fopen("ircd.log","a+");
3065         if (!log_file)
3066         {
3067                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3068                 Exit(ERROR);
3069         }
3070
3071         log(DEBUG,"InspIRCd: startup: begin");
3072         log(DEBUG,"$Id$");
3073         if (geteuid() == 0)
3074         {
3075                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3076                 Exit(ERROR);
3077                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3078         }
3079         SetupCommandTable();
3080         log(DEBUG,"InspIRCd: startup: default command table set up");
3081         
3082         ReadConfig();
3083         if (strcmp(DieValue,"")) 
3084         { 
3085                 printf("WARNING: %s\n\n",DieValue);
3086                 exit(0); 
3087         }  
3088         log(DEBUG,"InspIRCd: startup: read config");
3089           
3090         int count2 = 0, count3 = 0;
3091
3092         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3093         {
3094                 ConfValue("bind","port",count,configToken,&config_f);
3095                 ConfValue("bind","address",count,Addr,&config_f);
3096                 ConfValue("bind","type",count,Type,&config_f);
3097                 if (!strcmp(Type,"servers"))
3098                 {
3099                         char Default[MAXBUF];
3100                         strcpy(Default,"no");
3101                         ConfValue("bind","default",count,Default,&config_f);
3102                         if (strchr(Default,'y'))
3103                         {
3104                                 defaultRoute = count3;
3105                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3106                         }
3107                         me[count3] = new serverrec(ServerName,100L,false);
3108                         me[count3]->CreateListener(Addr,atoi(configToken));
3109                         count3++;
3110                 }
3111                 else
3112                 {
3113                         ports[count2] = atoi(configToken);
3114                         strcpy(addrs[count2],Addr);
3115                         count2++;
3116                 }
3117                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3118         }
3119         portCount = count2;
3120         UDPportCount = count3;
3121           
3122         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3123         
3124         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3125         
3126         printf("\n");
3127         
3128         /* BugFix By Craig! :p */
3129         count = 0;
3130         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3131         {
3132                 char modfile[MAXBUF];
3133                 ConfValue("module","name",count2,configToken,&config_f);
3134                 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3135                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3136                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3137                 /* If The File Doesnt exist, Trying to load it
3138                  * Will Segfault the IRCd.. So, check to see if
3139                  * it Exists, Before Proceeding. */
3140                 if (FileExists(modfile))
3141                 {
3142                         factory[count] = new ircd_module(modfile);
3143                         if (factory[count]->LastError())
3144                         {
3145                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3146                                 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3147                                 Exit(ERROR);
3148                         }
3149                         if (factory[count]->factory)
3150                         {
3151                                 modules[count] = factory[count]->factory->CreateModule();
3152                                 /* save the module and the module's classfactory, if
3153                                  * this isnt done, random crashes can occur :/ */
3154                                 module_names.push_back(modfile);        
3155                         }
3156                         else
3157                         {
3158                                 log(DEBUG,"Unable to load %s",modfile);
3159                                 sprintf("Unable to load %s\nExiting...\n",modfile);
3160                                 Exit(ERROR);
3161                         }
3162                         /* Increase the Count */
3163                         count++;
3164                 }
3165                 else
3166                 {
3167                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3168                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3169                 }
3170         }
3171         MODCOUNT = count - 1;
3172         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3173         
3174         printf("\nInspIRCd is now running!\n");
3175         
3176         startup_time = time(NULL);
3177           
3178         if (nofork)
3179         {
3180                 log(VERBOSE,"Not forking as -nofork was specified");
3181         }
3182         else
3183         {
3184                 if (DaemonSeed() == ERROR)
3185                 {
3186                         log(DEBUG,"InspIRCd: startup: can't daemonise");
3187                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3188                         Exit(ERROR);
3189                 }
3190         }
3191           
3192           
3193         /* setup select call */
3194         FD_ZERO(&selectFds);
3195         log(DEBUG,"InspIRCd: startup: zero selects");
3196         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3197         
3198         for (count = 0; count < portCount; count++)
3199         {
3200                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3201                 {
3202                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3203                         return(ERROR);
3204                 }
3205                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3206                 {
3207                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3208                 }
3209                 else    /* well we at least bound to one socket so we'll continue */
3210                 {
3211                         boundPortCount++;
3212                 }
3213         }
3214         
3215         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3216           
3217         /* if we didn't bind to anything then abort */
3218         if (boundPortCount == 0)
3219         {
3220                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3221                 return (ERROR);
3222         }
3223         
3224
3225         length = sizeof (client);
3226         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3227           
3228         /* main loop, this never returns */
3229         for (;;)
3230         {
3231 #ifdef _POSIX_PRIORITY_SCHEDULING
3232                 sched_yield();
3233 #endif
3234                 // update the status of klines, etc
3235                 expire_lines();
3236
3237                 fd_set sfd;
3238                 timeval tval;
3239                 FD_ZERO(&sfd);
3240
3241                 user_hash::iterator count2 = clientlist.begin();
3242
3243                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3244                 // them in a list, then reap the list every second or so.
3245                 if (reap_counter>300)
3246                 {
3247                         if (fd_reap.size() > 0)
3248                         {
3249                                 for( int n = 0; n < fd_reap.size(); n++)
3250                                 {
3251                                         Blocking(fd_reap[n]);
3252                                         close(fd_reap[n]);
3253                                         NonBlocking(fd_reap[n]);
3254                                 }
3255                         }
3256                         fd_reap.clear();
3257                         reap_counter=0;
3258                 }
3259                 reap_counter++;
3260
3261                 fd_set serverfds;
3262                 FD_ZERO(&serverfds);
3263                 timeval tvs;
3264                 
3265                 for (int x = 0; x != UDPportCount; x++)
3266                 {
3267                         FD_SET(me[x]->fd, &serverfds);
3268                 }
3269                 
3270                 tvs.tv_usec = 0;                
3271                 tvs.tv_sec = 0;
3272                 
3273                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3274                 if (servresult > 0)
3275                 {
3276                         for (int x = 0; x != UDPportCount; x++)
3277                         {
3278                                 if (FD_ISSET (me[x]->fd, &serverfds))
3279                                 {
3280                                         char remotehost[MAXBUF],resolved[MAXBUF];
3281                                         length = sizeof (client);
3282                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3283                                         strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3284                                         if(CleanAndResolve(resolved, remotehost) != TRUE)
3285                                         {
3286                                                 strncpy(resolved,remotehost,MAXBUF);
3287                                         }
3288                                         // add to this connections ircd_connector vector
3289                                         // *FIX* - we need the LOCAL port not the remote port in &client!
3290                                         me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3291                                 }
3292                         }
3293                 }
3294      
3295                 for (int x = 0; x < UDPportCount; x++)
3296                 {
3297                         std::deque<std::string> msgs;
3298                         msgs.clear();
3299                         if (me[x]->RecvPacket(msgs, tcp_host))
3300                         {
3301                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
3302                                 {
3303                                         char udp_msg[MAXBUF];
3304                                         strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3305                                         if (strlen(udp_msg)<1)
3306                                         {
3307                                                 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3308                                                 break;
3309                                         }
3310                                         // during a netburst, send all data to all other linked servers
3311                                         if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3312                                         {
3313                                                 if (is_uline(tcp_host))
3314                                                 {
3315                                                         if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3316                                                         {
3317                                                                 NetSendToAllExcept(tcp_host,udp_msg);
3318                                                         }
3319                                                 }
3320                                                 else
3321                                                         NetSendToAllExcept(tcp_host,udp_msg);
3322                                         }
3323                                         FOREACH_MOD OnPacketReceive(udp_msg);
3324                                         handle_link_packet(udp_msg, tcp_host, me[x]);
3325                                 }
3326                                 goto label;
3327                         }
3328                 }
3329         
3330
3331         while (count2 != clientlist.end())
3332         {
3333                 char data[10240];
3334                 tval.tv_usec = tval.tv_sec = 0;
3335                 FD_ZERO(&sfd);
3336                 int total_in_this_set = 0;
3337
3338                 user_hash::iterator xcount = count2;
3339                 user_hash::iterator endingiter = count2;
3340
3341                 if (!count2->second) break;
3342                 
3343                 if (count2->second)
3344                 if (count2->second->fd != 0)
3345                 {
3346                         // assemble up to 64 sockets into an fd_set
3347                         // to implement a pooling mechanism.
3348                         //
3349                         // This should be up to 64x faster than the
3350                         // old implementation.
3351                         while (total_in_this_set < 64)
3352                         {
3353                                 if (count2 != clientlist.end())
3354                                 {
3355                                         // we don't check the state of remote users.
3356                                         if (count2->second->fd > 0)
3357                                         {
3358                                                 FD_SET (count2->second->fd, &sfd);
3359
3360                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3361                                                 // their connection class.
3362                                                 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
3363                                                 {
3364                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3365                                                         kill_link(count2->second,"Registration timeout");
3366                                                         goto label;
3367                                                 }
3368                                                 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3369                                                 {
3370                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
3371                                                         {
3372                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3373                                                                 kill_link(count2->second,"Ping timeout");
3374                                                                 goto label;
3375                                                         }
3376                                                         Write(count2->second->fd,"PING :%s",ServerName);
3377                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3378                                                         count2->second->lastping = 0;
3379                                                         count2->second->nping = time(NULL)+120;
3380                                                 }
3381                                         }
3382                                         count2++;
3383                                         total_in_this_set++;
3384                                 }
3385                                 else break;
3386                         }
3387    
3388                         endingiter = count2;
3389                         count2 = xcount; // roll back to where we were
3390         
3391                         int v = 0;
3392
3393                         tval.tv_usec = 0;
3394                         tval.tv_sec = 0;
3395                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3396                         
3397                         // now loop through all of the items in this pool if any are waiting
3398                         //if (selectResult2 > 0)
3399                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3400                         {
3401
3402 #ifdef _POSIX_PRIORITY_SCHEDULING
3403                                 sched_yield();
3404 #endif
3405
3406                                 result = EAGAIN;
3407                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3408                                 {
3409                                         log(DEBUG,"Reading fd %d",count2a->second->fd);
3410                                         memset(data, 0, 10240);
3411                                         result = read(count2a->second->fd, data, 10240);
3412                                         
3413                                         if (result)
3414                                         {
3415                                                 if (result > 0)
3416                                                         log(DEBUG,"Read %d characters from socket",result);
3417                                                 userrec* current = count2a->second;
3418                                                 int currfd = current->fd;
3419                                                 char* l = strtok(data,"\n");
3420                                                 int floodlines = 0;
3421                                                 while (l)
3422                                                 {
3423                                                         floodlines++;
3424                                                         if ((floodlines > current->flood) && (current->flood != 0))
3425                                                         {
3426                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3427                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3428                                                                 kill_link(current,"Excess flood");
3429                                                                 goto label;
3430                                                         }
3431                                                         char sanitized[NetBufferSize];
3432                                                         memset(sanitized, 0, NetBufferSize);
3433                                                         int ptt = 0;
3434                                                         for (int pt = 0; pt < strlen(l); pt++)
3435                                                         {
3436                                                                 if (l[pt] != '\r')
3437                                                                 {
3438                                                                         sanitized[ptt++] = l[pt];
3439                                                                 }
3440                                                         }
3441                                                         sanitized[ptt] = '\0';
3442                                                         if (strlen(sanitized))
3443                                                         {
3444
3445
3446                                                                 // we're gonna re-scan to check if the nick is gone, after every
3447                                                                 // command - if it has, we're gonna bail
3448                                                                 bool find_again = false;
3449                                                                 process_buffer(sanitized,current);
3450         
3451                                                                 // look for the user's record in case it's changed
3452                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3453                                                                 {
3454                                                                         if (c2->second->fd == currfd)
3455                                                                         {
3456                                                                                 // found again, update pointer
3457                                                                                 current == c2->second;
3458                                                                                 find_again = true;
3459                                                                                 break;
3460                                                                         }
3461                                                                 }
3462                                                                 if (!find_again)
3463                                                                         goto label;
3464
3465                                                         }
3466                                                         l = strtok(NULL,"\n");
3467                                                 }
3468                                                 goto label;
3469                                         }
3470
3471                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3472                                         {
3473                                                 log(DEBUG,"killing: %s",count2a->second->nick);
3474                                                 kill_link(count2a->second,strerror(errno));
3475                                                 goto label;
3476                                         }
3477                                 }
3478                                 // result EAGAIN means nothing read
3479                                 if (result == EAGAIN)
3480                                 {
3481                                 }
3482                                 else
3483                                 if (result == 0)
3484                                 {
3485                                         if (count2->second)
3486                                         {
3487                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3488                                                 kill_link(count2a->second,"Client exited");
3489                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3490                                                 log(DEBUG,"Bailing from client exit");
3491                                                 goto label;
3492                                         }
3493                                 }
3494                                 else if (result > 0)
3495                                 {
3496                                 }
3497                         }
3498                 }
3499                 for (int q = 0; q < total_in_this_set; q++)
3500                 {
3501                         // there is no iterator += operator :(
3502                         //if (count2 != clientlist.end())
3503                         //{
3504                                 count2++;
3505                         //}
3506                 }
3507         }
3508         
3509         // set up select call
3510         for (count = 0; count < boundPortCount; count++)
3511         {
3512                 FD_SET (openSockfd[count], &selectFds);
3513         }
3514
3515         tv.tv_usec = 1;
3516         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3517
3518         /* select is reporting a waiting socket. Poll them all to find out which */
3519         if (selectResult > 0)
3520         {
3521                 char target[MAXBUF], resolved[MAXBUF];
3522                 for (count = 0; count < boundPortCount; count++)                
3523                 {
3524                         if (FD_ISSET (openSockfd[count], &selectFds))
3525                         {
3526                                 length = sizeof (client);
3527                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3528                               
3529                                 address_cache::iterator iter = IP.find(client.sin_addr);
3530                                 bool iscached = false;
3531                                 if (iter == IP.end())
3532                                 {
3533                                         /* ip isn't in cache, add it */
3534                                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3535                                         if(CleanAndResolve(resolved, target) != TRUE)
3536                                         {
3537                                                 strncpy(resolved,target,MAXBUF);
3538                                         }
3539                                         /* hostname now in 'target' */
3540                                         IP[client.sin_addr] = new string(resolved);
3541                                         /* hostname in cache */
3542                                 }
3543                                 else
3544                                 {
3545                                         /* found ip (cached) */
3546                                         strncpy(resolved, iter->second->c_str(), MAXBUF);
3547                                         iscached = true;
3548                                 }
3549                         
3550                                 if (incomingSockfd < 0)
3551                                 {
3552                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3553                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3554                                 }
3555                                 else
3556                                 {
3557                                         AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3558                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3559                                 }
3560                                 goto label;
3561                         }
3562                 }
3563         }
3564         label:
3565         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3566 }
3567 /* not reached */
3568 close (incomingSockfd);
3569 }
3570