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