]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
064259c06c1a60f8e949a40d84b1319130f30a34
[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,chan->key,MAXBUF);
1126         }
1127         if (chan->limit)
1128         {
1129                 char foo[24];
1130                 sprintf(foo," %d",chan->limit);
1131                 strncat(sparam,foo,MAXBUF);
1132         }
1133         if (strlen(chan->custom_modes))
1134         {
1135                 strncat(scratch,chan->custom_modes,MAXMODES);
1136                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1137                 {
1138                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1139                         if (extparam != "")
1140                         {
1141                                 strncat(sparam," ",MAXBUF);
1142                                 strncat(sparam,extparam.c_str(),MAXBUF);
1143                         }
1144                 }
1145         }
1146         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1147         strncat(scratch,sparam,MAXMODES);
1148         return scratch;
1149 }
1150
1151
1152 /* compile a userlist of a channel into a string, each nick seperated by
1153  * spaces and op, voice etc status shown as @ and + */
1154
1155 void userlist(userrec *user,chanrec *c)
1156 {
1157         if ((!c) || (!user))
1158         {
1159                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1160                 return;
1161         }
1162
1163         sprintf(list,"353 %s = %s :", user->nick, c->name);
1164         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1165         {
1166                 if (has_channel(i->second,c))
1167                 {
1168                         if (isnick(i->second->nick))
1169                         {
1170                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1171                                 {
1172                                         /* user is +i, and source not on the channel, does not show
1173                                          * nick in NAMES list */
1174                                         continue;
1175                                 }
1176                                 strcat(list,cmode(i->second,c));
1177                                 strcat(list,i->second->nick);
1178                                 strcat(list," ");
1179                                 if (strlen(list)>(480-NICKMAX))
1180                                 {
1181                                         /* list overflowed into
1182                                          * multiple numerics */
1183                                         WriteServ(user->fd,list);
1184                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1185                                 }
1186                         }
1187                 }
1188         }
1189         /* if whats left in the list isnt empty, send it */
1190         if (list[strlen(list)-1] != ':')
1191         {
1192                 WriteServ(user->fd,list);
1193         }
1194 }
1195
1196 /* return a count of the users on a specific channel accounting for
1197  * invisible users who won't increase the count. e.g. for /LIST */
1198
1199 int usercount_i(chanrec *c)
1200 {
1201         int i = 0;
1202         int count = 0;
1203         
1204         if (!c)
1205         {
1206                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1207                 return 0;
1208         }
1209
1210         strcpy(list,"");
1211         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1212         {
1213                 if (i->second)
1214                 {
1215                         if (has_channel(i->second,c))
1216                         {
1217                                 if (isnick(i->second->nick))
1218                                 {
1219                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1220                                         {
1221                                                 /* user is +i, and source not on the channel, does not show
1222                                                  * nick in NAMES list */
1223                                                 continue;
1224                                         }
1225                                         count++;
1226                                 }
1227                         }
1228                 }
1229         }
1230         log(DEBUG,"usercount_i: %s %d",c->name,count);
1231         return count;
1232 }
1233
1234
1235 int usercount(chanrec *c)
1236 {
1237         int i = 0;
1238         int count = 0;
1239         
1240         if (!c)
1241         {
1242                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1243                 return 0;
1244         }
1245
1246         strcpy(list,"");
1247         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1248         {
1249                 if (i->second)
1250                 {
1251                         if (has_channel(i->second,c))
1252                         {
1253                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1254                                 {
1255                                         count++;
1256                                 }
1257                         }
1258                 }
1259         }
1260         log(DEBUG,"usercount: %s %d",c->name,count);
1261         return count;
1262 }
1263
1264
1265 /* add a channel to a user, creating the record for it if needed and linking
1266  * it to the user record */
1267
1268 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1269 {
1270         if ((!user) || (!cn))
1271         {
1272                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1273                 return 0;
1274         }
1275
1276         int i = 0;
1277         chanrec* Ptr;
1278         int created = 0;
1279         char cname[MAXBUF];
1280
1281         strncpy(cname,cn,MAXBUF);
1282         
1283         // we MUST declare this wherever we use FOREACH_RESULT
1284         int MOD_RESULT = 0;
1285
1286         if (strlen(cname) > CHANMAX-1)
1287         {
1288                 cname[CHANMAX-1] = '\0';
1289         }
1290
1291         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1292         
1293         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1294         {
1295                 return NULL; // already on the channel!
1296         }
1297
1298
1299         if (!FindChan(cname))
1300         {
1301                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1302                 if (MOD_RESULT) {
1303                         return NULL;
1304                 }
1305
1306                 /* create a new one */
1307                 log(DEBUG,"add_channel: creating: %s",cname);
1308                 {
1309                         chanlist[cname] = new chanrec();
1310
1311                         strcpy(chanlist[cname]->name, cname);
1312                         chanlist[cname]->topiclock = 1;
1313                         chanlist[cname]->noexternal = 1;
1314                         chanlist[cname]->created = time(NULL);
1315                         strcpy(chanlist[cname]->topic, "");
1316                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1317                         chanlist[cname]->topicset = 0;
1318                         Ptr = chanlist[cname];
1319                         log(DEBUG,"add_channel: created: %s",cname);
1320                         /* set created to 2 to indicate user
1321                          * is the first in the channel
1322                          * and should be given ops */
1323                         created = 2;
1324                 }
1325         }
1326         else
1327         {
1328                 /* channel exists, just fish out a pointer to its struct */
1329                 Ptr = FindChan(cname);
1330                 if (Ptr)
1331                 {
1332                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1333                         
1334                         // the override flag allows us to bypass channel modes
1335                         // and bans (used by servers)
1336                         if (!override)
1337                         {
1338                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1339                                 if (MOD_RESULT) {
1340                                         return NULL;
1341                                 }
1342                                 
1343                                 if (strcmp(Ptr->key,""))
1344                                 {
1345                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1346                                         if (!key)
1347                                         {
1348                                                 log(DEBUG,"add_channel: no key given in JOIN");
1349                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1350                                                 return NULL;
1351                                         }
1352                                         else
1353                                         {
1354                                                 log(DEBUG,"key at %p is %s",key,key);
1355                                                 if (strcasecmp(key,Ptr->key))
1356                                                 {
1357                                                         log(DEBUG,"add_channel: bad key given in JOIN");
1358                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1359                                                         return NULL;
1360                                                 }
1361                                         }
1362                                 }
1363                                 log(DEBUG,"add_channel: no key");
1364         
1365                                 if (Ptr->inviteonly)
1366                                 {
1367                                         log(DEBUG,"add_channel: channel is +i");
1368                                         if (user->IsInvited(Ptr->name))
1369                                         {
1370                                                 /* user was invited to channel */
1371                                                 /* there may be an optional channel NOTICE here */
1372                                         }
1373                                         else
1374                                         {
1375                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1376                                                 return NULL;
1377                                         }
1378                                 }
1379                                 log(DEBUG,"add_channel: channel is not +i");
1380         
1381                                 if (Ptr->limit)
1382                                 {
1383                                         if (usercount(Ptr) == Ptr->limit)
1384                                         {
1385                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1386                                                 return NULL;
1387                                         }
1388                                 }
1389                                 
1390                                 log(DEBUG,"add_channel: about to walk banlist");
1391         
1392                                 /* check user against the channel banlist */
1393                                 if (Ptr)
1394                                 {
1395                                         if (Ptr->bans.size())
1396                                         {
1397                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1398                                                 {
1399                                                         if (match(user->GetFullHost(),i->data))
1400                                                         {
1401                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1402                                                                 return NULL;
1403                                                         }
1404                                                 }
1405                                         }
1406                                 }
1407                                 
1408                                 log(DEBUG,"add_channel: bans checked");
1409                                 
1410
1411                                 if ((Ptr) && (user))
1412                                 {
1413                                         user->RemoveInvite(Ptr->name);
1414                                 }
1415         
1416                                 log(DEBUG,"add_channel: invites removed");
1417
1418                         }
1419                         else
1420                         {
1421                                 log(DEBUG,"Overridden checks");
1422                         }
1423
1424                         
1425                 }
1426                 created = 1;
1427         }
1428
1429         log(DEBUG,"Passed channel checks");
1430         
1431         for (int i =0; i != MAXCHANS; i++)
1432         {
1433                 log(DEBUG,"Check location %d",i);
1434                 if (user->chans[i].channel == NULL)
1435                 {
1436                         log(DEBUG,"Adding into their channel list at location %d",i);
1437
1438                         if (created == 2) 
1439                         {
1440                                 /* first user in is given ops */
1441                                 user->chans[i].uc_modes = UCMODE_OP;
1442                         }
1443                         else
1444                         {
1445                                 user->chans[i].uc_modes = 0;
1446                         }
1447                         user->chans[i].channel = Ptr;
1448                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1449                         
1450                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1451                         {
1452                                 // use the stamdard J token with no privilages.
1453                                 char buffer[MAXBUF];
1454                                 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1455                                 NetSendToAll(buffer);
1456                         }
1457
1458                         log(DEBUG,"Sent JOIN to client");
1459
1460                         if (Ptr->topicset)
1461                         {
1462                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1463                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1464                         }
1465                         userlist(user,Ptr);
1466                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1467                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1468                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1469                         FOREACH_MOD OnUserJoin(user,Ptr);
1470                         return Ptr;
1471                 }
1472         }
1473         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1474         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1475         return NULL;
1476 }
1477
1478 /* remove a channel from a users record, and remove the record from memory
1479  * if the channel has become empty */
1480
1481 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1482 {
1483         if ((!user) || (!cname))
1484         {
1485                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1486                 return NULL;
1487         }
1488
1489         chanrec* Ptr;
1490         int created = 0;
1491
1492         if ((!cname) || (!user))
1493         {
1494                 return NULL;
1495         }
1496
1497         Ptr = FindChan(cname);
1498         
1499         if (!Ptr)
1500         {
1501                 return NULL;
1502         }
1503
1504         FOREACH_MOD OnUserPart(user,Ptr);
1505         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1506         
1507         for (int i =0; i != MAXCHANS; i++)
1508         {
1509                 /* zap it from the channel list of the user */
1510                 if (user->chans[i].channel == Ptr)
1511                 {
1512                         if (reason)
1513                         {
1514                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1515
1516                                 if (!local)
1517                                 {
1518                                         char buffer[MAXBUF];
1519                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1520                                         NetSendToAll(buffer);
1521                                 }
1522
1523                                 
1524                         }
1525                         else
1526                         {
1527                                 if (!local)
1528                                 {
1529                                         char buffer[MAXBUF];
1530                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1531                                         NetSendToAll(buffer);
1532                                 }
1533                         
1534                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1535                         }
1536                         user->chans[i].uc_modes = 0;
1537                         user->chans[i].channel = NULL;
1538                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1539                         break;
1540                 }
1541         }
1542         
1543         /* if there are no users left on the channel */
1544         if (!usercount(Ptr))
1545         {
1546                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1547
1548                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1549
1550                 /* kill the record */
1551                 if (iter != chanlist.end())
1552                 {
1553                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1554                         delete iter->second;
1555                         chanlist.erase(iter);
1556                 }
1557         }
1558 }
1559
1560
1561 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1562 {
1563         if ((!src) || (!user) || (!Ptr) || (!reason))
1564         {
1565                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1566                 return;
1567         }
1568
1569         int i = 0;
1570         int created = 0;
1571
1572         if ((!Ptr) || (!user) || (!src))
1573         {
1574                 return;
1575         }
1576
1577         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1578
1579         if (!has_channel(user,Ptr))
1580         {
1581                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1582                 return;
1583         }
1584         if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1585         {
1586                 if (cstatus(src,Ptr) == STATUS_HOP)
1587                 {
1588                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1589                 }
1590                 else
1591                 {
1592                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1593                 }
1594                 
1595                 return;
1596         }
1597         
1598         for (int i =0; i != MAXCHANS; i++)
1599         {
1600                 /* zap it from the channel list of the user */
1601                 if (user->chans[i].channel)
1602                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1603                 {
1604                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1605                         user->chans[i].uc_modes = 0;
1606                         user->chans[i].channel = NULL;
1607                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1608                         break;
1609                 }
1610         }
1611         
1612         /* if there are no users left on the channel */
1613         if (!usercount(Ptr))
1614         {
1615                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1616
1617                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1618
1619                 /* kill the record */
1620                 if (iter != chanlist.end())
1621                 {
1622                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1623                         delete iter->second;
1624                         chanlist.erase(iter);
1625                 }
1626         }
1627 }
1628
1629
1630
1631
1632 /* This function pokes and hacks at a parameter list like the following:
1633  *
1634  * PART #winbot, #darkgalaxy :m00!
1635  *
1636  * to turn it into a series of individual calls like this:
1637  *
1638  * PART #winbot :m00!
1639  * PART #darkgalaxy :m00!
1640  *
1641  * The seperate calls are sent to a callback function provided by the caller
1642  * (the caller will usually call itself recursively). The callback function
1643  * must be a command handler. Calling this function on a line with no list causes
1644  * no action to be taken. You must provide a starting and ending parameter number
1645  * where the range of the list can be found, useful if you have a terminating
1646  * parameter as above which is actually not part of the list, or parameters
1647  * before the actual list as well. This code is used by many functions which
1648  * can function as "one to list" (see the RFC) */
1649
1650 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1651 {
1652         char plist[MAXBUF];
1653         char *param;
1654         char *pars[32];
1655         char blog[32][MAXBUF];
1656         char blog2[32][MAXBUF];
1657         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1658         char keystr[MAXBUF];
1659         char moo[MAXBUF];
1660
1661         for (int i = 0; i <32; i++)
1662                 strcpy(blog[i],"");
1663
1664         for (int i = 0; i <32; i++)
1665                 strcpy(blog2[i],"");
1666
1667         strcpy(moo,"");
1668         for (int i = 0; i <10; i++)
1669         {
1670                 if (!parameters[i])
1671                 {
1672                         parameters[i] = moo;
1673                 }
1674         }
1675         if (joins)
1676         {
1677                 if (pcnt > 1) /* we have a key to copy */
1678                 {
1679                         strcpy(keystr,parameters[1]);
1680                 }
1681         }
1682
1683         if (!parameters[start])
1684         {
1685                 return 0;
1686         }
1687         if (!strchr(parameters[start],','))
1688         {
1689                 return 0;
1690         }
1691         strcpy(plist,"");
1692         for (int i = start; i <= end; i++)
1693         {
1694                 if (parameters[i])
1695                 {
1696                         strcat(plist,parameters[i]);
1697                 }
1698         }
1699         
1700         j = 0;
1701         param = plist;
1702
1703         t = strlen(plist);
1704         for (int i = 0; i < t; i++)
1705         {
1706                 if (plist[i] == ',')
1707                 {
1708                         plist[i] = '\0';
1709                         strcpy(blog[j++],param);
1710                         param = plist+i+1;
1711                         if (j>20)
1712                         {
1713                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1714                                 return 1;
1715                         }
1716                 }
1717         }
1718         strcpy(blog[j++],param);
1719         total = j;
1720
1721         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1722         {
1723                 strcat(keystr,",");
1724         }
1725         
1726         if ((joins) && (keystr))
1727         {
1728                 if (strchr(keystr,','))
1729                 {
1730                         j = 0;
1731                         param = keystr;
1732                         t2 = strlen(keystr);
1733                         for (int i = 0; i < t2; i++)
1734                         {
1735                                 if (keystr[i] == ',')
1736                                 {
1737                                         keystr[i] = '\0';
1738                                         strcpy(blog2[j++],param);
1739                                         param = keystr+i+1;
1740                                 }
1741                         }
1742                         strcpy(blog2[j++],param);
1743                         total2 = j;
1744                 }
1745         }
1746
1747         for (j = 0; j < total; j++)
1748         {
1749                 if (blog[j])
1750                 {
1751                         pars[0] = blog[j];
1752                 }
1753                 for (q = end; q < pcnt-1; q++)
1754                 {
1755                         if (parameters[q+1])
1756                         {
1757                                 pars[q-end+1] = parameters[q+1];
1758                         }
1759                 }
1760                 if ((joins) && (parameters[1]))
1761                 {
1762                         if (pcnt > 1)
1763                         {
1764                                 pars[1] = blog2[j];
1765                         }
1766                         else
1767                         {
1768                                 pars[1] = NULL;
1769                         }
1770                 }
1771                 /* repeatedly call the function with the hacked parameter list */
1772                 if ((joins) && (pcnt > 1))
1773                 {
1774                         if (pars[1])
1775                         {
1776                                 // pars[1] already set up and containing key from blog2[j]
1777                                 fn(pars,2,u);
1778                         }
1779                         else
1780                         {
1781                                 pars[1] = parameters[1];
1782                                 fn(pars,2,u);
1783                         }
1784                 }
1785                 else
1786                 {
1787                         fn(pars,pcnt-(end-start),u);
1788                 }
1789         }
1790
1791         return 1;
1792 }
1793
1794
1795
1796 void kill_link(userrec *user,const char* r)
1797 {
1798         user_hash::iterator iter = clientlist.find(user->nick);
1799         
1800         char reason[MAXBUF];
1801         
1802         strncpy(reason,r,MAXBUF);
1803
1804         if (strlen(reason)>MAXQUIT)
1805         {
1806                 reason[MAXQUIT-1] = '\0';
1807         }
1808
1809         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1810         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1811         log(DEBUG,"closing fd %d",user->fd);
1812
1813         /* bugfix, cant close() a nonblocking socket (sux!) */
1814         if (user->registered == 7) {
1815                 FOREACH_MOD OnUserQuit(user);
1816                 WriteCommonExcept(user,"QUIT :%s",reason);
1817
1818                 // Q token must go to ALL servers!!!
1819                 char buffer[MAXBUF];
1820                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1821                 NetSendToAll(buffer);
1822         }
1823
1824         /* push the socket on a stack of sockets due to be closed at the next opportunity
1825          * 'Client exited' is an exception to this as it means the client side has already
1826          * closed the socket, we don't need to do it.
1827          */
1828         fd_reap.push_back(user->fd);
1829         
1830         bool do_purge = false;
1831         
1832         if (user->registered == 7) {
1833                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1834                 AddWhoWas(user);
1835         }
1836
1837         if (iter != clientlist.end())
1838         {
1839                 log(DEBUG,"deleting user hash value %d",iter->second);
1840                 if ((iter->second) && (user->registered == 7)) {
1841                         delete iter->second;
1842                 }
1843                 clientlist.erase(iter);
1844         }
1845
1846         if (user->registered == 7) {
1847                 purge_empty_chans();
1848         }
1849 }
1850
1851 void kill_link_silent(userrec *user,const char* r)
1852 {
1853         user_hash::iterator iter = clientlist.find(user->nick);
1854         
1855         char reason[MAXBUF];
1856         
1857         strncpy(reason,r,MAXBUF);
1858
1859         if (strlen(reason)>MAXQUIT)
1860         {
1861                 reason[MAXQUIT-1] = '\0';
1862         }
1863
1864         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1865         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1866         log(DEBUG,"closing fd %d",user->fd);
1867
1868         /* bugfix, cant close() a nonblocking socket (sux!) */
1869         if (user->registered == 7) {
1870                 FOREACH_MOD OnUserQuit(user);
1871                 WriteCommonExcept(user,"QUIT :%s",reason);
1872
1873                 // Q token must go to ALL servers!!!
1874                 char buffer[MAXBUF];
1875                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1876                 NetSendToAll(buffer);
1877         }
1878
1879         /* push the socket on a stack of sockets due to be closed at the next opportunity
1880          * 'Client exited' is an exception to this as it means the client side has already
1881          * closed the socket, we don't need to do it.
1882          */
1883         fd_reap.push_back(user->fd);
1884         
1885         bool do_purge = false;
1886         
1887         if (iter != clientlist.end())
1888         {
1889                 log(DEBUG,"deleting user hash value %d",iter->second);
1890                 if ((iter->second) && (user->registered == 7)) {
1891                         delete iter->second;
1892                 }
1893                 clientlist.erase(iter);
1894         }
1895
1896         if (user->registered == 7) {
1897                 purge_empty_chans();
1898         }
1899 }
1900
1901
1902
1903 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1904
1905 char* Passwd(userrec *user)
1906 {
1907         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1908         {
1909                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1910                 {
1911                         return i->pass;
1912                 }
1913         }
1914         return "";
1915 }
1916
1917 bool IsDenied(userrec *user)
1918 {
1919         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1920         {
1921                 if (match(user->host,i->host) && (i->type == CC_DENY))
1922                 {
1923                         return true;
1924                 }
1925         }
1926         return false;
1927 }
1928
1929
1930
1931
1932 /* sends out an error notice to all connected clients (not to be used
1933  * lightly!) */
1934
1935 void send_error(char *s)
1936 {
1937         log(DEBUG,"send_error: %s",s);
1938         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1939         {
1940                 if (isnick(i->second->nick))
1941                 {
1942                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1943                 }
1944                 else
1945                 {
1946                         // fix - unregistered connections receive ERROR, not NOTICE
1947                         Write(i->second->fd,"ERROR :%s",s);
1948                 }
1949         }
1950 }
1951
1952 void Error(int status)
1953 {
1954         signal (SIGALRM, SIG_IGN);
1955         signal (SIGPIPE, SIG_IGN);
1956         signal (SIGTERM, SIG_IGN);
1957         signal (SIGABRT, SIG_IGN);
1958         signal (SIGSEGV, SIG_IGN);
1959         signal (SIGURG, SIG_IGN);
1960         signal (SIGKILL, SIG_IGN);
1961         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1962         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1963         exit(status);
1964 }
1965
1966
1967 int main(int argc, char *argv[])
1968 {
1969         Start();
1970         srand(time(NULL));
1971         log(DEBUG,"*** InspIRCd starting up!");
1972         if (!FileExists(CONFIG_FILE))
1973         {
1974                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1975                 log(DEBUG,"main: no config");
1976                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1977                 Exit(ERROR);
1978         }
1979         if (argc > 1) {
1980                 if (!strcmp(argv[1],"-nofork")) {
1981                         nofork = true;
1982                 }
1983         }
1984         if (InspIRCd() == ERROR)
1985         {
1986                 log(DEBUG,"main: daemon function bailed");
1987                 printf("ERROR: could not initialise. Shutting down.\n");
1988                 Exit(ERROR);
1989         }
1990         Exit(TRUE);
1991         return 0;
1992 }
1993
1994 template<typename T> inline string ConvToStr(const T &in)
1995 {
1996         stringstream tmp;
1997         if (!(tmp << in)) return string();
1998         return tmp.str();
1999 }
2000
2001 /* re-allocates a nick in the user_hash after they change nicknames,
2002  * returns a pointer to the new user as it may have moved */
2003
2004 userrec* ReHashNick(char* Old, char* New)
2005 {
2006         user_hash::iterator newnick;
2007         user_hash::iterator oldnick = clientlist.find(Old);
2008
2009         log(DEBUG,"ReHashNick: %s %s",Old,New);
2010         
2011         if (!strcasecmp(Old,New))
2012         {
2013                 log(DEBUG,"old nick is new nick, skipping");
2014                 return oldnick->second;
2015         }
2016         
2017         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2018
2019         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2020
2021         clientlist[New] = new userrec();
2022         clientlist[New] = oldnick->second;
2023         /*delete oldnick->second; */
2024         clientlist.erase(oldnick);
2025
2026         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2027         
2028         return clientlist[New];
2029 }
2030
2031 /* adds or updates an entry in the whowas list */
2032 void AddWhoWas(userrec* u)
2033 {
2034         user_hash::iterator iter = whowas.find(u->nick);
2035         userrec *a = new userrec();
2036         strcpy(a->nick,u->nick);
2037         strcpy(a->ident,u->ident);
2038         strcpy(a->dhost,u->dhost);
2039         strcpy(a->host,u->host);
2040         strcpy(a->fullname,u->fullname);
2041         strcpy(a->server,u->server);
2042         a->signon = u->signon;
2043
2044         /* MAX_WHOWAS:   max number of /WHOWAS items
2045          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2046          *               can be replaced by a newer one
2047          */
2048         
2049         if (iter == whowas.end())
2050         {
2051                 if (whowas.size() == WHOWAS_MAX)
2052                 {
2053                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2054                         {
2055                                 // 3600 seconds in an hour ;)
2056                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2057                                 {
2058                                         delete i->second;
2059                                         i->second = a;
2060                                         log(DEBUG,"added WHOWAS entry, purged an old record");
2061                                         return;
2062                                 }
2063                         }
2064                 }
2065                 else
2066                 {
2067                         log(DEBUG,"added fresh WHOWAS entry");
2068                         whowas[a->nick] = a;
2069                 }
2070         }
2071         else
2072         {
2073                 log(DEBUG,"updated WHOWAS entry");
2074                 delete iter->second;
2075                 iter->second = a;
2076         }
2077 }
2078
2079
2080 /* add a client connection to the sockets list */
2081 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2082 {
2083         int i;
2084         int blocking = 1;
2085         char resolved[MAXBUF];
2086         string tempnick;
2087         char tn2[MAXBUF];
2088         user_hash::iterator iter;
2089
2090         tempnick = ConvToStr(socket) + "-unknown";
2091         sprintf(tn2,"%d-unknown",socket);
2092
2093         iter = clientlist.find(tempnick);
2094
2095         if (iter != clientlist.end()) return;
2096
2097         /*
2098          * It is OK to access the value here this way since we know
2099          * it exists, we just created it above.
2100          *
2101          * At NO other time should you access a value in a map or a
2102          * hash_map this way.
2103          */
2104         clientlist[tempnick] = new userrec();
2105
2106         NonBlocking(socket);
2107         log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2108
2109         clientlist[tempnick]->fd = socket;
2110         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2111         strncpy(clientlist[tempnick]->host, host,160);
2112         strncpy(clientlist[tempnick]->dhost, host,160);
2113         strncpy(clientlist[tempnick]->server, ServerName,256);
2114         strncpy(clientlist[tempnick]->ident, "unknown",9);
2115         clientlist[tempnick]->registered = 0;
2116         clientlist[tempnick]->signon = time(NULL);
2117         clientlist[tempnick]->nping = time(NULL)+240;
2118         clientlist[tempnick]->lastping = 1;
2119         clientlist[tempnick]->port = port;
2120         strncpy(clientlist[tempnick]->ip,ip,32);
2121
2122         if (iscached)
2123         {
2124                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2125         }
2126         else
2127         {
2128                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2129         }
2130
2131         // set the registration timeout for this user
2132         unsigned long class_regtimeout = 90;
2133         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2134         {
2135                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2136                 {
2137                         class_regtimeout = (unsigned long)i->registration_timeout;
2138                         break;
2139                 }
2140         }
2141
2142         int class_flood = 0;
2143         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2144         {
2145                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2146                 {
2147                         class_flood = i->flood;
2148                         break;
2149                 }
2150         }
2151
2152         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2153         clientlist[tempnick]->flood = class_flood;
2154
2155         for (int i = 0; i < MAXCHANS; i++)
2156         {
2157                 clientlist[tempnick]->chans[i].channel = NULL;
2158                 clientlist[tempnick]->chans[i].uc_modes = 0;
2159         }
2160
2161         if (clientlist.size() == MAXCLIENTS)
2162                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2163                 
2164         char* r = matches_zline(ip);
2165         if (r)
2166         {
2167                 char reason[MAXBUF];
2168                 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2169                 kill_link(clientlist[tempnick],reason);
2170         }
2171 }
2172
2173
2174 int usercnt(void)
2175 {
2176         return clientlist.size();
2177 }
2178
2179
2180 int usercount_invisible(void)
2181 {
2182         int c = 0;
2183
2184         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2185         {
2186                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2187         }
2188         return c;
2189 }
2190
2191 int usercount_opers(void)
2192 {
2193         int c = 0;
2194
2195         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2196         {
2197                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2198         }
2199         return c;
2200 }
2201
2202 int usercount_unknown(void)
2203 {
2204         int c = 0;
2205
2206         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2207         {
2208                 if ((i->second->fd) && (i->second->registered != 7))
2209                         c++;
2210         }
2211         return c;
2212 }
2213
2214 long chancount(void)
2215 {
2216         return chanlist.size();
2217 }
2218
2219 long count_servs(void)
2220 {
2221         int c = 0;
2222         //for (int j = 0; j < 255; j++)
2223         //{
2224         //      if (servers[j] != NULL)
2225         //              c++;
2226         //}
2227         return c;
2228 }
2229
2230 long servercount(void)
2231 {
2232         return count_servs()+1;
2233 }
2234
2235 long local_count()
2236 {
2237         int c = 0;
2238         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2239         {
2240                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2241         }
2242         return c;
2243 }
2244
2245
2246 void ShowMOTD(userrec *user)
2247 {
2248         if (!MOTD.size())
2249         {
2250                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2251                 return;
2252         }
2253         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2254         for (int i = 0; i != MOTD.size(); i++)
2255         {
2256                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2257         }
2258         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2259 }
2260
2261 void ShowRULES(userrec *user)
2262 {
2263         if (!RULES.size())
2264         {
2265                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2266                 return;
2267         }
2268         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2269         for (int i = 0; i != RULES.size(); i++)
2270         {
2271                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2272         }
2273         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2274 }
2275
2276 /* shows the message of the day, and any other on-logon stuff */
2277 void ConnectUser(userrec *user)
2278 {
2279         user->registered = 7;
2280         user->idle_lastmsg = time(NULL);
2281         log(DEBUG,"ConnectUser: %s",user->nick);
2282
2283         if (strcmp(Passwd(user),"") && (!user->haspassed))
2284         {
2285                 kill_link(user,"Invalid password");
2286                 return;
2287         }
2288         if (IsDenied(user))
2289         {
2290                 kill_link(user,"Unauthorised connection");
2291                 return;
2292         }
2293
2294         char match_against[MAXBUF];
2295         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2296         char* r = matches_gline(match_against);
2297         if (r)
2298         {
2299                 char reason[MAXBUF];
2300                 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2301                 kill_link_silent(user,reason);
2302                 return;
2303         }
2304
2305         r = matches_kline(user->host);
2306         if (r)
2307         {
2308                 char reason[MAXBUF];
2309                 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2310                 kill_link_silent(user,reason);
2311                 return;
2312         }
2313
2314         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2315         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2316         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2317         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2318         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2319         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);
2320         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);
2321         ShowMOTD(user);
2322         FOREACH_MOD OnUserConnect(user);
2323         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2324         
2325         char buffer[MAXBUF];
2326         snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,ServerName,user->fullname);
2327         NetSendToAll(buffer);
2328 }
2329
2330 void handle_version(char **parameters, int pcnt, userrec *user)
2331 {
2332         char Revision[] = "$Revision$";
2333
2334         char *s1 = Revision;
2335         char *savept;
2336         char *v1 = strtok_r(s1," ",&savept);
2337         s1 = savept;
2338         char *v2 = strtok_r(s1," ",&savept);
2339         s1 = savept;
2340         
2341         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2342 }
2343
2344
2345 // calls a handler function for a command
2346
2347 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2348 {
2349                 for (int i = 0; i < cmdlist.size(); i++)
2350                 {
2351                         if (!strcasecmp(cmdlist[i].command,commandname))
2352                         {
2353                                 if (cmdlist[i].handler_function)
2354                                 {
2355                                         if (pcnt>=cmdlist[i].min_params)
2356                                         {
2357                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2358                                                 {
2359                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2360                                                 }
2361                                         }
2362                                 }
2363                         }
2364                 }
2365 }
2366
2367 void DoSplitEveryone()
2368 {
2369         bool go_again = true;
2370         while (go_again)
2371         {
2372                 go_again = false;
2373                 for (int i = 0; i < 32; i++)
2374                 {
2375                         if (me[i] != NULL)
2376                         {
2377                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2378                                 {
2379                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2380                                         {
2381                                                 j->routes.clear();
2382                                                 j->CloseConnection();
2383                                                 me[i]->connectors.erase(j);
2384                                                 go_again = true;
2385                                                 break;
2386                                         }
2387                                 }
2388                         }
2389                 }
2390         }
2391         log(DEBUG,"Removed server. Will remove clients...");
2392         // iterate through the userlist and remove all users on this server.
2393         // because we're dealing with a mesh, we dont have to deal with anything
2394         // "down-route" from this server (nice huh)
2395         go_again = true;
2396         char reason[MAXBUF];
2397         while (go_again)
2398         {
2399                 go_again = false;
2400                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2401                 {
2402                         if (strcasecmp(u->second->server,ServerName))
2403                         {
2404                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2405                                 kill_link(u->second,reason);
2406                                 go_again = true;
2407                                 break;
2408                         }
2409                 }
2410         }
2411 }
2412
2413
2414
2415 char islast(const char* s)
2416 {
2417         char c = '`';
2418         for (int j = 0; j < 32; j++)
2419         {
2420                 if (me[j] != NULL)
2421                 {
2422                         for (int k = 0; k < me[j]->connectors.size(); k++)
2423                         {
2424                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2425                                 {
2426                                         c = '|';
2427                                 }
2428                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2429                                 {
2430                                         c = '`';
2431                                 }
2432                         }
2433                 }
2434         }
2435         return c;
2436 }
2437
2438 long map_count(const char* s)
2439 {
2440         int c = 0;
2441         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2442         {
2443                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2444         }
2445         return c;
2446 }
2447
2448
2449 void force_nickchange(userrec* user,const char* newnick)
2450 {
2451         char nick[MAXBUF];
2452         int MOD_RESULT = 0;
2453         
2454         strcpy(nick,"");
2455
2456         FOREACH_RESULT(OnUserPreNick(user,newnick));
2457         if (MOD_RESULT) {
2458                 kill_link(user,"Nickname collision");
2459                 return;
2460         }
2461         if (matches_qline(newnick))
2462         {
2463                 kill_link(user,"Nickname collision");
2464                 return;
2465         }
2466         
2467         if (user)
2468         {
2469                 if (newnick)
2470                 {
2471                         strncpy(nick,newnick,MAXBUF);
2472                 }
2473                 if (user->registered == 7)
2474                 {
2475                         char* pars[1];
2476                         pars[0] = nick;
2477                         handle_nick(pars,1,user);
2478                 }
2479         }
2480 }
2481                                 
2482
2483 int process_parameters(char **command_p,char *parameters)
2484 {
2485         int i = 0;
2486         int j = 0;
2487         int q = 0;
2488         q = strlen(parameters);
2489         if (!q)
2490         {
2491                 /* no parameters, command_p invalid! */
2492                 return 0;
2493         }
2494         if (parameters[0] == ':')
2495         {
2496                 command_p[0] = parameters+1;
2497                 return 1;
2498         }
2499         if (q)
2500         {
2501                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2502                 {
2503                         /* only one parameter */
2504                         command_p[0] = parameters;
2505                         if (parameters[0] == ':')
2506                         {
2507                                 if (strchr(parameters,' ') != NULL)
2508                                 {
2509                                         command_p[0]++;
2510                                 }
2511                         }
2512                         return 1;
2513                 }
2514         }
2515         command_p[j++] = parameters;
2516         for (int i = 0; i <= q; i++)
2517         {
2518                 if (parameters[i] == ' ')
2519                 {
2520                         command_p[j++] = parameters+i+1;
2521                         parameters[i] = '\0';
2522                         if (command_p[j-1][0] == ':')
2523                         {
2524                                 *command_p[j-1]++; /* remove dodgy ":" */
2525                                 break;
2526                                 /* parameter like this marks end of the sequence */
2527                         }
2528                 }
2529         }
2530         return j; /* returns total number of items in the list */
2531 }
2532
2533 void process_command(userrec *user, char* cmd)
2534 {
2535         char *parameters;
2536         char *command;
2537         char *command_p[127];
2538         char p[MAXBUF], temp[MAXBUF];
2539         int i, j, items, cmd_found;
2540
2541         for (int i = 0; i < 127; i++)
2542                 command_p[i] = NULL;
2543
2544         if (!user)
2545         {
2546                 return;
2547         }
2548         if (!cmd)
2549         {
2550                 return;
2551         }
2552         if (!strcmp(cmd,""))
2553         {
2554                 return;
2555         }
2556         
2557         int total_params = 0;
2558         if (strlen(cmd)>2)
2559         {
2560                 for (int q = 0; q < strlen(cmd)-1; q++)
2561                 {
2562                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2563                         {
2564                                 total_params++;
2565                                 // found a 'trailing', we dont count them after this.
2566                                 break;
2567                         }
2568                         if (cmd[q] == ' ')
2569                                 total_params++;
2570                 }
2571         }
2572         
2573         // another phidjit bug...
2574         if (total_params > 126)
2575         {
2576                 kill_link(user,"Protocol violation (1)");
2577                 return;
2578         }
2579         
2580         strcpy(temp,cmd);
2581
2582         std::string tmp = cmd;
2583         for (int i = 0; i <= MODCOUNT; i++)
2584         {
2585                 std::string oldtmp = tmp;
2586                 modules[i]->OnServerRaw(tmp,true);
2587                 if (oldtmp != tmp)
2588                 {
2589                         log(DEBUG,"A Module changed the input string!");
2590                         log(DEBUG,"New string: %s",tmp.c_str());
2591                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2592                         break;
2593                 }
2594         }
2595         strncpy(cmd,tmp.c_str(),MAXBUF);
2596         strcpy(temp,cmd);
2597
2598         if (!strchr(cmd,' '))
2599         {
2600                 /* no parameters, lets skip the formalities and not chop up
2601                  * the string */
2602                 log(DEBUG,"About to preprocess command with no params");
2603                 items = 0;
2604                 command_p[0] = NULL;
2605                 parameters = NULL;
2606                 for (int i = 0; i <= strlen(cmd); i++)
2607                 {
2608                         cmd[i] = toupper(cmd[i]);
2609                 }
2610                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2611                 command = cmd;
2612         }
2613         else
2614         {
2615                 strcpy(cmd,"");
2616                 j = 0;
2617                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2618                 for (int i = 0; i < strlen(temp); i++)
2619                 {
2620                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2621                         {
2622                                 cmd[j++] = temp[i];
2623                                 cmd[j] = 0;
2624                         }
2625                 }
2626                 /* split the full string into a command plus parameters */
2627                 parameters = p;
2628                 strcpy(p," ");
2629                 command = cmd;
2630                 if (strchr(cmd,' '))
2631                 {
2632                         for (int i = 0; i <= strlen(cmd); i++)
2633                         {
2634                                 /* capitalise the command ONLY, leave params intact */
2635                                 cmd[i] = toupper(cmd[i]);
2636                                 /* are we nearly there yet?! :P */
2637                                 if (cmd[i] == ' ')
2638                                 {
2639                                         command = cmd;
2640                                         parameters = cmd+i+1;
2641                                         cmd[i] = '\0';
2642                                         break;
2643                                 }
2644                         }
2645                 }
2646                 else
2647                 {
2648                         for (int i = 0; i <= strlen(cmd); i++)
2649                         {
2650                                 cmd[i] = toupper(cmd[i]);
2651                         }
2652                 }
2653
2654         }
2655         cmd_found = 0;
2656         
2657         if (strlen(command)>MAXCOMMAND)
2658         {
2659                 kill_link(user,"Protocol violation (2)");
2660                 return;
2661         }
2662         
2663         for (int x = 0; x < strlen(command); x++)
2664         {
2665                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2666                 {
2667                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2668                         {
2669                                 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2670                                 {
2671                                         kill_link(user,"Protocol violation (3)");
2672                                         return;
2673                                 }
2674                         }
2675                 }
2676         }
2677
2678         for (int i = 0; i != cmdlist.size(); i++)
2679         {
2680                 if (strcmp(cmdlist[i].command,""))
2681                 {
2682                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2683                         {
2684                                 log(DEBUG,"Found matching command");
2685
2686                                 if (parameters)
2687                                 {
2688                                         if (strcmp(parameters,""))
2689                                         {
2690                                                 items = process_parameters(command_p,parameters);
2691                                         }
2692                                         else
2693                                         {
2694                                                 items = 0;
2695                                                 command_p[0] = NULL;
2696                                         }
2697                                 }
2698                                 else
2699                                 {
2700                                         items = 0;
2701                                         command_p[0] = NULL;
2702                                 }
2703                                 
2704                                 if (user)
2705                                 {
2706                                         log(DEBUG,"Processing command");
2707                                         
2708                                         /* activity resets the ping pending timer */
2709                                         user->nping = time(NULL) + 120;
2710                                         if ((items) < cmdlist[i].min_params)
2711                                         {
2712                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2713                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2714                                                 return;
2715                                         }
2716                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2717                                         {
2718                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2719                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2720                                                 cmd_found = 1;
2721                                                 return;
2722                                         }
2723                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2724                                          * deny command! */
2725                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2726                                         {
2727                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2728                                                 {
2729                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2730                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2731                                                         return;
2732                                                 }
2733                                         }
2734                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2735                                         {
2736                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2737                                                 if (cmdlist[i].handler_function)
2738                                                 {
2739                                                         /* ikky /stats counters */
2740                                                         if (temp)
2741                                                         {
2742                                                                 if (user)
2743                                                                 {
2744                                                                         user->bytes_in += strlen(temp);
2745                                                                         user->cmds_in++;
2746                                                                 }
2747                                                                 cmdlist[i].use_count++;
2748                                                                 cmdlist[i].total_bytes+=strlen(temp);
2749                                                         }
2750
2751                                                         /* WARNING: nothing may come after the
2752                                                          * command handler call, as the handler
2753                                                          * may free the user structure! */
2754
2755                                                         cmdlist[i].handler_function(command_p,items,user);
2756                                                 }
2757                                                 return;
2758                                         }
2759                                         else
2760                                         {
2761                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2762                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2763                                                 return;
2764                                         }
2765                                 }
2766                                 cmd_found = 1;
2767                         }
2768                 }
2769         }
2770         if ((!cmd_found) && (user))
2771         {
2772                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2773                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2774         }
2775 }
2776
2777
2778 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2779 {
2780         command_t comm;
2781         /* create the command and push it onto the table */     
2782         strcpy(comm.command,cmd);
2783         comm.handler_function = f;
2784         comm.flags_needed = flags;
2785         comm.min_params = minparams;
2786         comm.use_count = 0;
2787         comm.total_bytes = 0;
2788         cmdlist.push_back(comm);
2789         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2790 }
2791
2792 void SetupCommandTable(void)
2793 {
2794         createcommand("USER",handle_user,0,4);
2795         createcommand("NICK",handle_nick,0,1);
2796         createcommand("QUIT",handle_quit,0,0);
2797         createcommand("VERSION",handle_version,0,0);
2798         createcommand("PING",handle_ping,0,1);
2799         createcommand("PONG",handle_pong,0,1);
2800         createcommand("ADMIN",handle_admin,0,0);
2801         createcommand("PRIVMSG",handle_privmsg,0,2);
2802         createcommand("INFO",handle_info,0,0);
2803         createcommand("TIME",handle_time,0,0);
2804         createcommand("WHOIS",handle_whois,0,1);
2805         createcommand("WALLOPS",handle_wallops,'o',1);
2806         createcommand("NOTICE",handle_notice,0,2);
2807         createcommand("JOIN",handle_join,0,1);
2808         createcommand("NAMES",handle_names,0,1);
2809         createcommand("PART",handle_part,0,1);
2810         createcommand("KICK",handle_kick,0,2);
2811         createcommand("MODE",handle_mode,0,1);
2812         createcommand("TOPIC",handle_topic,0,1);
2813         createcommand("WHO",handle_who,0,1);
2814         createcommand("MOTD",handle_motd,0,0);
2815         createcommand("RULES",handle_rules,0,0);
2816         createcommand("OPER",handle_oper,0,2);
2817         createcommand("LIST",handle_list,0,0);
2818         createcommand("DIE",handle_die,'o',1);
2819         createcommand("RESTART",handle_restart,'o',1);
2820         createcommand("KILL",handle_kill,'o',2);
2821         createcommand("REHASH",handle_rehash,'o',0);
2822         createcommand("LUSERS",handle_lusers,0,0);
2823         createcommand("STATS",handle_stats,0,1);
2824         createcommand("USERHOST",handle_userhost,0,1);
2825         createcommand("AWAY",handle_away,0,0);
2826         createcommand("ISON",handle_ison,0,0);
2827         createcommand("SUMMON",handle_summon,0,0);
2828         createcommand("USERS",handle_users,0,0);
2829         createcommand("INVITE",handle_invite,0,2);
2830         createcommand("PASS",handle_pass,0,1);
2831         createcommand("TRACE",handle_trace,'o',0);
2832         createcommand("WHOWAS",handle_whowas,0,1);
2833         createcommand("CONNECT",handle_connect,'o',1);
2834         createcommand("SQUIT",handle_squit,'o',0);
2835         createcommand("MODULES",handle_modules,'o',0);
2836         createcommand("LINKS",handle_links,0,0);
2837         createcommand("MAP",handle_map,0,0);
2838         createcommand("KLINE",handle_kline,'o',1);
2839         createcommand("GLINE",handle_gline,'o',1);
2840         createcommand("ZLINE",handle_zline,'o',1);
2841         createcommand("QLINE",handle_qline,'o',1);
2842 }
2843
2844 void process_buffer(const char* cmdbuf,userrec *user)
2845 {
2846         if (!user)
2847         {
2848                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2849                 return;
2850         }
2851         char cmd[MAXBUF];
2852         int i;
2853         if (!cmdbuf)
2854         {
2855                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2856                 return;
2857         }
2858         if (!strcmp(cmdbuf,""))
2859         {
2860                 return;
2861         }
2862         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2863
2864         strncpy(cmd,cmdbuf,MAXBUF);
2865         if (!strcmp(cmd,""))
2866         {
2867                 return;
2868         }
2869         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2870         {
2871                 cmd[strlen(cmd)-1] = '\0';
2872         }
2873         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2874         {
2875                 cmd[strlen(cmd)-1] = '\0';
2876         }
2877
2878         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2879         {
2880                 cmd[strlen(cmd)-1] = '\0';
2881         }
2882
2883         if (!strcmp(cmd,""))
2884         {
2885                 return;
2886         }
2887         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2888         tidystring(cmd);
2889         if ((user) && (cmd))
2890         {
2891                 process_command(user,cmd);
2892         }
2893 }
2894
2895 void DoSync(serverrec* serv, char* tcp_host)
2896 {
2897         char data[MAXBUF];
2898         log(DEBUG,"Sending sync");
2899         // send start of sync marker: Y <timestamp>
2900         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2901         // except the ones its receiving it from.
2902         snprintf(data,MAXBUF,"Y %d",time(NULL));
2903         serv->SendPacket(data,tcp_host);
2904         // send users and channels
2905         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2906         {
2907                 snprintf(data,MAXBUF,"N %d %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->server,u->second->fullname);
2908                 serv->SendPacket(data,tcp_host);
2909                 if (strcmp(chlist(u->second),""))
2910                 {
2911                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2912                         serv->SendPacket(data,tcp_host);
2913                 }
2914         }
2915         // send channel modes, topics etc...
2916         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2917         {
2918                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2919                 serv->SendPacket(data,tcp_host);
2920                 if (strcmp(c->second->topic,""))
2921                 {
2922                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2923                         serv->SendPacket(data,tcp_host);
2924                 }
2925                 // send current banlist
2926                 
2927                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2928                 {
2929                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2930                         serv->SendPacket(data,tcp_host);
2931                 }
2932         }
2933         // sync global zlines, glines, etc
2934         sync_xlines(serv,tcp_host);
2935         snprintf(data,MAXBUF,"F %d",time(NULL));
2936         serv->SendPacket(data,tcp_host);
2937         log(DEBUG,"Sent sync");
2938         // ircd sends its serverlist after the end of sync here
2939 }
2940
2941
2942 void NetSendMyRoutingTable()
2943 {
2944         // send out a line saying what is reachable to us.
2945         // E.g. if A is linked to B C and D, send out:
2946         // $ A B C D
2947         // if its only linked to B and D send out:
2948         // $ A B D
2949         // if it has no links, dont even send out the line at all.
2950         char buffer[MAXBUF];
2951         sprintf(buffer,"$ %s",ServerName);
2952         bool sendit = false;
2953         for (int i = 0; i < 32; i++)
2954         {
2955                 if (me[i] != NULL)
2956                 {
2957                         for (int j = 0; j < me[i]->connectors.size(); j++)
2958                         {
2959                                 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2960                                 {
2961                                         strncat(buffer," ",MAXBUF);
2962                                         strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2963                                         sendit = true;
2964                                 }
2965                         }
2966                 }
2967         }
2968         if (sendit)
2969                 NetSendToAll(buffer);
2970 }
2971
2972
2973 void DoSplit(const char* params)
2974 {
2975         bool go_again = true;
2976         while (go_again)
2977         {
2978                 go_again = false;
2979                 for (int i = 0; i < 32; i++)
2980                 {
2981                         if (me[i] != NULL)
2982                         {
2983                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2984                                 {
2985                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2986                                         {
2987                                                 j->routes.clear();
2988                                                 j->CloseConnection();
2989                                                 me[i]->connectors.erase(j);
2990                                                 go_again = true;
2991                                                 break;
2992                                         }
2993                                 }
2994                         }
2995                 }
2996         }
2997         log(DEBUG,"Removed server. Will remove clients...");
2998         // iterate through the userlist and remove all users on this server.
2999         // because we're dealing with a mesh, we dont have to deal with anything
3000         // "down-route" from this server (nice huh)
3001         go_again = true;
3002         char reason[MAXBUF];
3003         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3004         while (go_again)
3005         {
3006                 go_again = false;
3007                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3008                 {
3009                         if (!strcasecmp(u->second->server,params))
3010                         {
3011                                 kill_link(u->second,reason);
3012                                 go_again = true;
3013                                 break;
3014                         }
3015                 }
3016         }
3017 }
3018
3019 // removes a server. Will NOT remove its users!
3020
3021 void RemoveServer(const char* name)
3022 {
3023         bool go_again = true;
3024         while (go_again)
3025         {
3026                 go_again = false;
3027                 for (int i = 0; i < 32; i++)
3028                 {
3029                         if (me[i] != NULL)
3030                         {
3031                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3032                                 {
3033                                         if (!strcasecmp(j->GetServerName().c_str(),name))
3034                                         {
3035                                                 j->routes.clear();
3036                                                 j->CloseConnection();
3037                                                 me[i]->connectors.erase(j);
3038                                                 go_again = true;
3039                                                 break;
3040                                         }
3041                                 }
3042                         }
3043                 }
3044         }
3045 }
3046
3047
3048 int reap_counter = 0;
3049
3050 int InspIRCd(void)
3051 {
3052         struct sockaddr_in client, server;
3053         char addrs[MAXBUF][255];
3054         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3055         socklen_t length;
3056         int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3057         int selectResult = 0, selectResult2 = 0;
3058         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3059         char resolvedHost[MAXBUF];
3060         fd_set selectFds;
3061         struct timeval tv;
3062
3063         log_file = fopen("ircd.log","a+");
3064         if (!log_file)
3065         {
3066                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3067                 Exit(ERROR);
3068         }
3069
3070         log(DEBUG,"InspIRCd: startup: begin");
3071         log(DEBUG,"$Id$");
3072         if (geteuid() == 0)
3073         {
3074                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3075                 Exit(ERROR);
3076                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3077         }
3078         SetupCommandTable();
3079         log(DEBUG,"InspIRCd: startup: default command table set up");
3080         
3081         ReadConfig();
3082         if (strcmp(DieValue,"")) 
3083         { 
3084                 printf("WARNING: %s\n\n",DieValue);
3085                 exit(0); 
3086         }  
3087         log(DEBUG,"InspIRCd: startup: read config");
3088           
3089         int count2 = 0, count3 = 0;
3090
3091         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3092         {
3093                 ConfValue("bind","port",count,configToken,&config_f);
3094                 ConfValue("bind","address",count,Addr,&config_f);
3095                 ConfValue("bind","type",count,Type,&config_f);
3096                 if (!strcmp(Type,"servers"))
3097                 {
3098                         char Default[MAXBUF];
3099                         strcpy(Default,"no");
3100                         ConfValue("bind","default",count,Default,&config_f);
3101                         if (strchr(Default,'y'))
3102                         {
3103                                 defaultRoute = count3;
3104                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3105                         }
3106                         me[count3] = new serverrec(ServerName,100L,false);
3107                         me[count3]->CreateListener(Addr,atoi(configToken));
3108                         count3++;
3109                 }
3110                 else
3111                 {
3112                         ports[count2] = atoi(configToken);
3113                         strcpy(addrs[count2],Addr);
3114                         count2++;
3115                 }
3116                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3117         }
3118         portCount = count2;
3119         UDPportCount = count3;
3120           
3121         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3122         
3123         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3124         
3125         printf("\n");
3126         
3127         /* BugFix By Craig! :p */
3128         count = 0;
3129         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3130         {
3131                 char modfile[MAXBUF];
3132                 ConfValue("module","name",count2,configToken,&config_f);
3133                 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3134                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3135                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3136                 /* If The File Doesnt exist, Trying to load it
3137                  * Will Segfault the IRCd.. So, check to see if
3138                  * it Exists, Before Proceeding. */
3139                 if (FileExists(modfile))
3140                 {
3141                         factory[count] = new ircd_module(modfile);
3142                         if (factory[count]->LastError())
3143                         {
3144                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3145                                 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3146                                 Exit(ERROR);
3147                         }
3148                         if (factory[count]->factory)
3149                         {
3150                                 modules[count] = factory[count]->factory->CreateModule();
3151                                 /* save the module and the module's classfactory, if
3152                                  * this isnt done, random crashes can occur :/ */
3153                                 module_names.push_back(modfile);        
3154                         }
3155                         else
3156                         {
3157                                 log(DEBUG,"Unable to load %s",modfile);
3158                                 sprintf("Unable to load %s\nExiting...\n",modfile);
3159                                 Exit(ERROR);
3160                         }
3161                         /* Increase the Count */
3162                         count++;
3163                 }
3164                 else
3165                 {
3166                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3167                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3168                 }
3169         }
3170         MODCOUNT = count - 1;
3171         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3172         
3173         printf("\nInspIRCd is now running!\n");
3174         
3175         startup_time = time(NULL);
3176           
3177         if (nofork)
3178         {
3179                 log(VERBOSE,"Not forking as -nofork was specified");
3180         }
3181         else
3182         {
3183                 if (DaemonSeed() == ERROR)
3184                 {
3185                         log(DEBUG,"InspIRCd: startup: can't daemonise");
3186                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3187                         Exit(ERROR);
3188                 }
3189         }
3190           
3191           
3192         /* setup select call */
3193         FD_ZERO(&selectFds);
3194         log(DEBUG,"InspIRCd: startup: zero selects");
3195         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3196         
3197         for (count = 0; count < portCount; count++)
3198         {
3199                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3200                 {
3201                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3202                         return(ERROR);
3203                 }
3204                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3205                 {
3206                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3207                 }
3208                 else    /* well we at least bound to one socket so we'll continue */
3209                 {
3210                         boundPortCount++;
3211                 }
3212         }
3213         
3214         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3215           
3216         /* if we didn't bind to anything then abort */
3217         if (boundPortCount == 0)
3218         {
3219                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3220                 return (ERROR);
3221         }
3222         
3223
3224         length = sizeof (client);
3225         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3226           
3227         /* main loop, this never returns */
3228         for (;;)
3229         {
3230 #ifdef _POSIX_PRIORITY_SCHEDULING
3231                 sched_yield();
3232 #endif
3233                 // update the status of klines, etc
3234                 expire_lines();
3235
3236                 fd_set sfd;
3237                 timeval tval;
3238                 FD_ZERO(&sfd);
3239
3240                 user_hash::iterator count2 = clientlist.begin();
3241
3242                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3243                 // them in a list, then reap the list every second or so.
3244                 if (reap_counter>300)
3245                 {
3246                         if (fd_reap.size() > 0)
3247                         {
3248                                 for( int n = 0; n < fd_reap.size(); n++)
3249                                 {
3250                                         Blocking(fd_reap[n]);
3251                                         close(fd_reap[n]);
3252                                         NonBlocking(fd_reap[n]);
3253                                 }
3254                         }
3255                         fd_reap.clear();
3256                         reap_counter=0;
3257                 }
3258                 reap_counter++;
3259
3260                 fd_set serverfds;
3261                 FD_ZERO(&serverfds);
3262                 timeval tvs;
3263                 
3264                 for (int x = 0; x != UDPportCount; x++)
3265                 {
3266                         FD_SET(me[x]->fd, &serverfds);
3267                 }
3268                 
3269                 tvs.tv_usec = 0;                
3270                 tvs.tv_sec = 0;
3271                 
3272                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3273                 if (servresult > 0)
3274                 {
3275                         for (int x = 0; x != UDPportCount; x++)
3276                         {
3277                                 if (FD_ISSET (me[x]->fd, &serverfds))
3278                                 {
3279                                         char remotehost[MAXBUF],resolved[MAXBUF];
3280                                         length = sizeof (client);
3281                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3282                                         strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3283                                         if(CleanAndResolve(resolved, remotehost) != TRUE)
3284                                         {
3285                                                 strncpy(resolved,remotehost,MAXBUF);
3286                                         }
3287                                         // add to this connections ircd_connector vector
3288                                         // *FIX* - we need the LOCAL port not the remote port in &client!
3289                                         me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3290                                 }
3291                         }
3292                 }
3293      
3294                 for (int x = 0; x < UDPportCount; x++)
3295                 {
3296                         std::deque<std::string> msgs;
3297                         msgs.clear();
3298                         if (me[x]->RecvPacket(msgs, tcp_host))
3299                         {
3300                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
3301                                 {
3302                                         char udp_msg[MAXBUF];
3303                                         strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3304                                         if (strlen(udp_msg)<1)
3305                                         {
3306                                                 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3307                                                 break;
3308                                         }
3309                                         // during a netburst, send all data to all other linked servers
3310                                         if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3311                                         {
3312                                                 if (is_uline(tcp_host))
3313                                                 {
3314                                                         if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3315                                                         {
3316                                                                 NetSendToAllExcept(tcp_host,udp_msg);
3317                                                         }
3318                                                 }
3319                                                 else
3320                                                         NetSendToAllExcept(tcp_host,udp_msg);
3321                                         }
3322                                         FOREACH_MOD OnPacketReceive(udp_msg);
3323                                         handle_link_packet(udp_msg, tcp_host, me[x]);
3324                                 }
3325                                 goto label;
3326                         }
3327                 }
3328         
3329
3330         while (count2 != clientlist.end())
3331         {
3332                 char data[10240];
3333                 tval.tv_usec = tval.tv_sec = 0;
3334                 FD_ZERO(&sfd);
3335                 int total_in_this_set = 0;
3336
3337                 user_hash::iterator xcount = count2;
3338                 user_hash::iterator endingiter = count2;
3339
3340                 if (!count2->second) break;
3341                 
3342                 if (count2->second)
3343                 if (count2->second->fd != 0)
3344                 {
3345                         // assemble up to 64 sockets into an fd_set
3346                         // to implement a pooling mechanism.
3347                         //
3348                         // This should be up to 64x faster than the
3349                         // old implementation.
3350                         while (total_in_this_set < 64)
3351                         {
3352                                 if (count2 != clientlist.end())
3353                                 {
3354                                         // we don't check the state of remote users.
3355                                         if (count2->second->fd > 0)
3356                                         {
3357                                                 FD_SET (count2->second->fd, &sfd);
3358
3359                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3360                                                 // their connection class.
3361                                                 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
3362                                                 {
3363                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3364                                                         kill_link(count2->second,"Registration timeout");
3365                                                         goto label;
3366                                                 }
3367                                                 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3368                                                 {
3369                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
3370                                                         {
3371                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3372                                                                 kill_link(count2->second,"Ping timeout");
3373                                                                 goto label;
3374                                                         }
3375                                                         Write(count2->second->fd,"PING :%s",ServerName);
3376                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3377                                                         count2->second->lastping = 0;
3378                                                         count2->second->nping = time(NULL)+120;
3379                                                 }
3380                                         }
3381                                         count2++;
3382                                         total_in_this_set++;
3383                                 }
3384                                 else break;
3385                         }
3386    
3387                         endingiter = count2;
3388                         count2 = xcount; // roll back to where we were
3389         
3390                         int v = 0;
3391
3392                         tval.tv_usec = 0;
3393                         tval.tv_sec = 0;
3394                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3395                         
3396                         // now loop through all of the items in this pool if any are waiting
3397                         //if (selectResult2 > 0)
3398                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3399                         {
3400
3401 #ifdef _POSIX_PRIORITY_SCHEDULING
3402                                 sched_yield();
3403 #endif
3404
3405                                 result = EAGAIN;
3406                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3407                                 {
3408                                         log(DEBUG,"Reading fd %d",count2a->second->fd);
3409                                         memset(data, 0, 10240);
3410                                         result = read(count2a->second->fd, data, 10240);
3411                                         
3412                                         if (result)
3413                                         {
3414                                                 if (result > 0)
3415                                                         log(DEBUG,"Read %d characters from socket",result);
3416                                                 userrec* current = count2a->second;
3417                                                 int currfd = current->fd;
3418                                                 char* l = strtok(data,"\n");
3419                                                 int floodlines = 0;
3420                                                 while (l)
3421                                                 {
3422                                                         floodlines++;
3423                                                         if ((floodlines > current->flood) && (current->flood != 0))
3424                                                         {
3425                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3426                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3427                                                                 kill_link(current,"Excess flood");
3428                                                                 goto label;
3429                                                         }
3430                                                         char sanitized[NetBufferSize];
3431                                                         memset(sanitized, 0, NetBufferSize);
3432                                                         int ptt = 0;
3433                                                         for (int pt = 0; pt < strlen(l); pt++)
3434                                                         {
3435                                                                 if (l[pt] != '\r')
3436                                                                 {
3437                                                                         sanitized[ptt++] = l[pt];
3438                                                                 }
3439                                                         }
3440                                                         sanitized[ptt] = '\0';
3441                                                         if (strlen(sanitized))
3442                                                         {
3443
3444
3445                                                                 // we're gonna re-scan to check if the nick is gone, after every
3446                                                                 // command - if it has, we're gonna bail
3447                                                                 bool find_again = false;
3448                                                                 process_buffer(sanitized,current);
3449         
3450                                                                 // look for the user's record in case it's changed
3451                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3452                                                                 {
3453                                                                         if (c2->second->fd == currfd)
3454                                                                         {
3455                                                                                 // found again, update pointer
3456                                                                                 current == c2->second;
3457                                                                                 find_again = true;
3458                                                                                 break;
3459                                                                         }
3460                                                                 }
3461                                                                 if (!find_again)
3462                                                                         goto label;
3463
3464                                                         }
3465                                                         l = strtok(NULL,"\n");
3466                                                 }
3467                                                 goto label;
3468                                         }
3469
3470                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3471                                         {
3472                                                 log(DEBUG,"killing: %s",count2a->second->nick);
3473                                                 kill_link(count2a->second,strerror(errno));
3474                                                 goto label;
3475                                         }
3476                                 }
3477                                 // result EAGAIN means nothing read
3478                                 if (result == EAGAIN)
3479                                 {
3480                                 }
3481                                 else
3482                                 if (result == 0)
3483                                 {
3484                                         if (count2->second)
3485                                         {
3486                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3487                                                 kill_link(count2a->second,"Client exited");
3488                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3489                                                 log(DEBUG,"Bailing from client exit");
3490                                                 goto label;
3491                                         }
3492                                 }
3493                                 else if (result > 0)
3494                                 {
3495                                 }
3496                         }
3497                 }
3498                 for (int q = 0; q < total_in_this_set; q++)
3499                 {
3500                         // there is no iterator += operator :(
3501                         //if (count2 != clientlist.end())
3502                         //{
3503                                 count2++;
3504                         //}
3505                 }
3506         }
3507         
3508         // set up select call
3509         for (count = 0; count < boundPortCount; count++)
3510         {
3511                 FD_SET (openSockfd[count], &selectFds);
3512         }
3513
3514         tv.tv_usec = 1;
3515         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3516
3517         /* select is reporting a waiting socket. Poll them all to find out which */
3518         if (selectResult > 0)
3519         {
3520                 char target[MAXBUF], resolved[MAXBUF];
3521                 for (count = 0; count < boundPortCount; count++)                
3522                 {
3523                         if (FD_ISSET (openSockfd[count], &selectFds))
3524                         {
3525                                 length = sizeof (client);
3526                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3527                               
3528                                 address_cache::iterator iter = IP.find(client.sin_addr);
3529                                 bool iscached = false;
3530                                 if (iter == IP.end())
3531                                 {
3532                                         /* ip isn't in cache, add it */
3533                                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3534                                         if(CleanAndResolve(resolved, target) != TRUE)
3535                                         {
3536                                                 strncpy(resolved,target,MAXBUF);
3537                                         }
3538                                         /* hostname now in 'target' */
3539                                         IP[client.sin_addr] = new string(resolved);
3540                                         /* hostname in cache */
3541                                 }
3542                                 else
3543                                 {
3544                                         /* found ip (cached) */
3545                                         strncpy(resolved, iter->second->c_str(), MAXBUF);
3546                                         iscached = true;
3547                                 }
3548                         
3549                                 if (incomingSockfd < 0)
3550                                 {
3551                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3552                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3553                                 }
3554                                 else
3555                                 {
3556                                         AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3557                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3558                                 }
3559                                 goto label;
3560                         }
3561                 }
3562         }
3563         label:
3564         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3565 }
3566 /* not reached */
3567 close (incomingSockfd);
3568 }
3569