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